content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from configuration import configuration, dbName, debugEverythingNeedsRolling
from optionChain import OptionChain
from statistics import median
from tinydb import TinyDB, Query
import datetime
import time
import alert
import support
class Cc:
def __init__(self, asset):
self.asset = asset
def findNew(self, api, existing, existingPremium):
asset = self.asset
newccExpDate = support.getNewCcExpirationDate()
# get option chain of third thursday and friday of the month
optionChain = OptionChain(api, asset, newccExpDate, 1)
chain = optionChain.get()
if not chain:
return alert.botFailed(asset, 'No chain found on the third thursday OR friday')
# get closest chain to days
# it will get friday most of the time, but if a friday is a holiday f.ex. the chain will only return a thursday date chain
closestChain = chain[-1]
minStrike = configuration[asset]['minStrike']
atmPrice = api.getATMPrice(asset)
strikePrice = atmPrice + configuration[asset]['minGapToATM']
if existing and configuration[asset]['rollWithoutDebit']:
# prevent paying debit with setting the minYield to the current price of existing
minYield = existingPremium
else:
minYield = configuration[asset]['minYield']
if minStrike > strikePrice:
strikePrice = minStrike
# get the best matching contract
contract = optionChain.getContractFromDateChain(strikePrice, closestChain['contracts'])
if not contract:
return alert.botFailed(asset, 'No contract over minStrike found')
# check minYield
projectedPremium = median([contract['bid'], contract['ask']])
if projectedPremium < minYield:
if existing and configuration[asset]['rollWithoutDebit']:
print('Failed to write contract for CREDIT with ATM price + minGapToATM (' + str(strikePrice) + '), now trying to get a lower strike ...')
# we need to get a lower strike instead to not pay debit
# this works with overwritten minStrike and minYield config settings. the minGapToATM is only used for max price (ATM price + minGapToATM)
contract = optionChain.getContractFromDateChainByMinYield(existing['strike'], strikePrice, minYield, closestChain['contracts'])
# edge case where this new contract fails: If even a calendar roll wouldn't result in a credit
if not contract:
return alert.botFailed(asset, 'minYield not met')
projectedPremium = median([contract['bid'], contract['ask']])
else:
# the contract we want has not enough premium
return alert.botFailed(asset, 'minYield not met')
return {
'date': closestChain['date'],
'days': closestChain['days'],
'contract': contract,
'projectedPremium': projectedPremium
}
def existing(self):
db = TinyDB(dbName)
ret = db.search(Query().stockSymbol == self.asset)
db.close()
return ret
def writeCcs(api):
for asset in configuration:
asset = asset.upper()
cc = Cc(asset)
try:
existing = cc.existing()[0]
except IndexError:
existing = None
if (existing and needsRolling(existing)) or not existing:
amountToSell = configuration[asset]['amountOfHundreds']
if existing:
existingSymbol = existing['optionSymbol']
amountToBuyBack = existing['count']
existingPremium = api.getATMPrice(existing['optionSymbol'])
else:
existingSymbol = None
amountToBuyBack = 0
existingPremium = 0
new = cc.findNew(api, existing, existingPremium)
print('The bot wants to write the following contract:')
print(new)
if not api.checkAccountHasEnoughToCover(asset, existingSymbol, amountToBuyBack, amountToSell, new['contract']['strike'], new['date']):
return alert.botFailed(asset, 'The account doesn\'t have enough shares or options to cover selling '
+ str(amountToSell) + ' cc(\'s)')
writeCc(api, asset, new, existing, existingPremium, amountToBuyBack, amountToSell)
else:
print('Nothing to write ...')
def needsRolling(cc):
if debugEverythingNeedsRolling:
return True
# needs rolling on date BEFORE expiration (if the market is closed, it will trigger ON expiration date)
nowPlusOffset = (datetime.datetime.utcnow() + datetime.timedelta(days=support.ccExpDaysOffset)).strftime('%Y-%m-%d')
return nowPlusOffset >= cc['expiration']
def writeCc(api, asset, new, existing, existingPremium, amountToBuyBack, amountToSell, retry=0, partialContractsSold=0):
maxRetries = configuration[asset]['allowedPriceReductionPercent']
# lower the price by 1% for each retry if we couldn't get filled
orderPricePercentage = 100 - retry
if retry > maxRetries:
return alert.botFailed(asset, 'Order cant be filled, tried with ' + str(orderPricePercentage + 1) + '% of the price.')
if existing and existingPremium:
orderId = api.writeNewContracts(
existing['optionSymbol'],
amountToBuyBack,
existingPremium,
new['contract']['symbol'],
amountToSell,
new['projectedPremium'],
orderPricePercentage
)
else:
orderId = api.writeNewContracts(
None,
0,
0,
new['contract']['symbol'],
amountToSell,
new['projectedPremium'],
orderPricePercentage
)
checkFillXTimes = 12
if retry > 0:
# go faster through it
# todo maybe define a max time for writeCc function, as this can run well past 1 hour with dumb config settings and many assets
checkFillXTimes = 6
for x in range(checkFillXTimes):
# try to fill it for x * 5 seconds
print('Waiting for order to be filled ...')
time.sleep(5)
checkedOrder = api.checkOrder(orderId)
if checkedOrder['filled']:
print('Order has been filled!')
break
if not checkedOrder['filled']:
api.cancelOrder(orderId)
print('Cant fill order, retrying with lower price ...')
if checkedOrder['partialFills'] > 0:
if checkedOrder['complexOrderStrategyType'] is None or (checkedOrder['complexOrderStrategyType'] and checkedOrder['complexOrderStrategyType'] != 'DIAGONAL'):
# partial fills are only possible on DIAGONAL orders, so this should never happen
return alert.botFailed(asset, 'Partial fill on custom order, manual review required: ' + str(checkedOrder['partialFills']))
# on diagonal fill is per leg, 1 fill = 1 bought back and 1 sold
# quick verification, this should never be true
if not (amountToBuyBack == amountToSell and amountToBuyBack > checkedOrder['partialFills']):
return alert.botFailed(asset, 'Partial fill amounts do not match, manual review required')
diagonalAmountBothWays = amountToBuyBack - checkedOrder['partialFills']
receivedPremium = checkedOrder['price'] * checkedOrder['partialFills']
alert.alert(asset, 'Partial fill: Bought back ' + str(checkedOrder['partialFills']) + 'x ' + existing['optionSymbol'] + ' and sold ' + str(
checkedOrder['partialFills']) + 'x ' +
new['contract']['symbol'] + ' for ' + str(receivedPremium))
return writeCc(api, asset, new, existing, existingPremium, diagonalAmountBothWays, diagonalAmountBothWays, retry + 1,
partialContractsSold + checkedOrder['partialFills'])
return writeCc(api, asset, new, existing, existingPremium, amountToBuyBack, amountToSell, retry + 1, partialContractsSold)
receivedPremium = checkedOrder['price'] * amountToSell
if existing:
if amountToBuyBack != amountToSell:
# custom order, price is not per contract
receivedPremium = checkedOrder['price']
alert.alert(asset, 'Bought back ' + str(amountToBuyBack) + 'x ' + existing['optionSymbol'] + ' and sold ' + str(amountToSell) + 'x ' +
new['contract']['symbol'] + ' for ' + str(receivedPremium))
else:
alert.alert(asset, 'Sold ' + str(amountToSell) + 'x ' + new['contract']['symbol'] + ' for ' + str(receivedPremium))
if partialContractsSold > 0:
amountHasSold = partialContractsSold + amountToSell
receivedPremium = receivedPremium + checkedOrder['price'] * partialContractsSold
# shouldn't happen
if amountHasSold != configuration[asset]['amountOfHundreds']:
return alert.botFailed(asset, 'Unexpected amount of contracts sold: ' + str(amountHasSold))
else:
amountHasSold = amountToSell
soldOption = {
'stockSymbol': asset,
'optionSymbol': new['contract']['symbol'],
'expiration': new['date'],
'count': amountHasSold,
'strike': new['contract']['strike'],
'receivedPremium': receivedPremium
}
db = TinyDB(dbName)
db.remove(Query().stockSymbol == asset)
db.insert(soldOption)
db.close()
return soldOption
| nilq/baby-python | python |
"""Plotting Module."""
from scphylo.pl._data import heatmap
from scphylo.pl._trees import clonal_tree, dendro_tree, networkx_tree, newick_tree
__all__ = (heatmap, clonal_tree, dendro_tree, networkx_tree, newick_tree)
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-03-05 02:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('storehouse', '0002_supplier'),
]
operations = [
migrations.CreateModel(
name='Store',
fields=[
('name', models.TextField(primary_key=True, serialize=False)),
],
),
]
| nilq/baby-python | python |
import json
from pathlib import Path
from types import SimpleNamespace
from typing import NamedTuple, Any, Optional
from flask.testing import FlaskClient
from numpy.testing import assert_almost_equal
from osgeo_utils.auxiliary.base import PathLikeOrStr
test_env = SimpleNamespace()
test_env.root = Path('.')
test_env.talos = 'http://localhost:5000'
test_env.tasc = test_env.talos
test_env.talos_wps = test_env.talos + '/wps/'
test_env.tasc_api1 = test_env.tasc + '/api/1.0'
test_env.talos_api1 = test_env.talos + '/api/1.0'
class TalosTest(NamedTuple):
c: FlaskClient
url: str
request: Any
response: Any
dump_response: Optional[PathLikeOrStr] = None
def assert_response(self, other):
assert self.response == other
def run_test(self, is_json=True):
if is_json:
rv = self.c.post(self.url, json=self.request)
else:
rv = self.c.post(self.url, data=self.request)
assert rv.status_code == 200
json_data = rv.get_json()
if self.dump_response:
with open(self.dump_response, 'w') as f:
json.dump(json_data, f, indent=4)
self.assert_response(json_data)
class ProfileTest(TalosTest):
def assert_response(self, other):
c1 = self.response['features'][0]['geometry']['coordinates']
c2 = other['features'][0]['geometry']['coordinates']
assert_almost_equal(c1, c2)
self.response['features'][0]['geometry']['coordinates'] = None
other['features'][0]['geometry']['coordinates'] = None
super().assert_response(other)
class CzmlTest(TalosTest):
def assert_response(self, other):
self.response[1]['name'] = None
other[1]['name'] = None
super().assert_response(other)
def read_file(filename):
with open(filename) as f:
data = f.read()
return data
| nilq/baby-python | python |
#!/usr/bin/python
import smtplib
import subprocess
import urllib2
from email.mime.text import MIMEText
smtp_address="YOUR SMTP LOGIN"
sender="YOUR SMTP LOGIN "
receiver="YOUR EMAIL DESTINATION"
password="YOURU SMTP PASSWORD"
uptime = subprocess.check_output('uptime')
ip_ext = urllib2.urlopen("http://ifconfig.me/ip").read()
print ip_ext
#ip_ext = subprocess.check_output(['curl','ifconfig.me'])
msg = MIMEText(uptime+ip_ext)
msg ["Subject"] = "Onion Report"
server = smtplib.SMTP(smtp_address)
server.starttls()
server.login(sender,password)
server.sendmail(sender,receiver,msg.as_string())
server.quit()
| nilq/baby-python | python |
from scipy.stats import norm
import math
def dice_test(stat, alfa, mode_speed):
# add parametrs for normal distribution
if mode_speed == "plt_6":
critical_const = norm.ppf(alfa, loc=0.2700502, scale=math.sqrt(0.0002832429))
p_value = norm.cdf(stat, loc=0.2700502, scale=math.sqrt(0.0002832429))
if mode_speed == "plt_13.5":
critical_const = norm.ppf(alfa, loc=0.27328, scale=math.sqrt(0.0009519578))
p_value = norm.cdf(stat, loc=0.27328, scale=math.sqrt(0.0009519578))
if mode_speed == "plt_21":
critical_const = norm.ppf(alfa, loc=0.4341689, scale=math.sqrt(0.001787848))
p_value = norm.cdf(stat, loc=0.4341689, scale=math.sqrt(0.001787848))
if mode_speed == "qpz_13.5":
critical_const = norm.ppf(alfa, loc=0.4889668, scale=math.sqrt(0.00203925))
p_value = norm.cdf(stat, loc=0.4889668, scale=math.sqrt(0.00203925))
if mode_speed == "str_13.5":
critical_const = norm.ppf(alfa, loc=0.4008677, scale=math.sqrt(0.001664502))
p_value = norm.cdf(stat, loc=0.4008677, scale=math.sqrt(0.001664502))
if mode_speed == "str_21":
critical_const = norm.ppf(alfa, loc=0.4732636, scale=math.sqrt(0.002565701))
p_value = norm.cdf(stat, loc=0.4732636, scale=math.sqrt(0.002565701))
if mode_speed == "toe_13.5":
critical_const = norm.ppf(alfa)
p_value = norm.cdf(stat)
if mode_speed == "air_13.5":
critical_const = norm.ppf(alfa)
p_value = norm.cdf(stat)
return critical_const, p_value | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from clickhouse_mysql.observable import Observable
class Reader(Observable):
"""Read data from source and notify observers"""
converter = None
event_handlers = {
# called on each WriteRowsEvent
'WriteRowsEvent': [],
# called on each row inside WriteRowsEvent (thus can be called multiple times per WriteRowsEvent)
'WriteRowsEvent.EachRow': [],
# called when Reader has no data to read
'ReaderIdleEvent': [],
# called on each DeleteRowsEvent
'DeleteRowsEvent': [],
# called on each UpdateRowsEvent
'UpdateRowsEvent': [],
}
def __init__(self, converter=None, callbacks={}):
self.converter = converter
self.subscribe(callbacks)
def read(self):
pass
| nilq/baby-python | python |
"""
Call two arms equally strong if the heaviest weights they each are able
to lift are equal.
Call two people equally strong if their strongest arms are equally strong
(the strongest arm can be both the right and the left), and so are their
weakest arms.
Given your and your friend's arms' lifting capabilities find out if you
two are equally strong.
Example
For yourLeft = 10, yourRight = 15, friendsLeft = 15, and friendsRight = 10,
the output should be
areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true;
For yourLeft = 15, yourRight = 10, friendsLeft = 15, and friendsRight = 10,
the output should be
areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true;
For yourLeft = 15, yourRight = 10, friendsLeft = 15, and friendsRight = 9,
the output should be
areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = false.
"""
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
# if (a == c or a == d) and (b == c or b == d):
# return true
# else:
# return False
# creates a set of list wit hordered numbers -> set([10, 15])
return {yourLeft, yourRight} == {friendsLeft, friendsRight}
a = 15
b = 10
c = 10
d = 15
print(areEquallyStrong(a, b, c, d))
| nilq/baby-python | python |
import setuptools
setuptools.setup(
name="confluent_schema_registry_client",
version="1.1.0",
author="Tom Leach",
author_email="tom@gc.com",
description="A simple client Confluent's Avro Schema Registry",
license="MIT",
keywords="confluent schema registry client avro http rest",
url="http://github.com/gamechanger/confluent_schema_registry_client",
packages=["confluent_schema_registry_client"],
install_requires=['requests>=2.3.0'],
tests_require=['nose', 'requests_mock']
)
| nilq/baby-python | python |
#!/usr/bin/env python2
"""
Dump ranks into a JS file, to be included by index.html.
The JS file contains a global "raw_data" object, with fields:
- contests: list of included contests. Each is an object with:
- name: name of the contest.
- tasks: list of tasks to include in this contest.
- scores: map each username to an object with {task_name: score}.
"""
import argparse
import json
import sys
import time
import yaml
from cms.db import SessionGen
from cms.grading import task_score
from server_utils.cms.scripts.DatabaseUtils import get_contests, get_tasks, \
get_users
def create_ranks_object(included_contests=None, excluded_contests=None,
included_tasks=None, excluded_tasks=None,
included_users=None, excluded_users=None):
"""
Create a ranks object with the given parameters.
"""
with SessionGen() as session:
# Fetch all relevant data.
contests = get_contests(session, included_contests, excluded_contests)
tasks = get_tasks(session, included_tasks, excluded_tasks)
name_to_task = {task.name: task for task in tasks}
users = get_users(session, included_users, excluded_users)
usernames_set = set(user.username for user in users)
result = {"contests": [], "scores": {}}
# Initialize users info.
for username in usernames_set:
result["scores"][username] = {}
# Fill the result according to each contest.
for contest in contests:
# Relevant tasks only.
contest_tasks = [task.name for task in contest.tasks
if task.name in name_to_task]
# Don't include empty contests (where all tasks were excluded).
if not contest_tasks:
continue
# Contest information.
result["contests"] += [{
"name": contest.name,
"tasks": contest_tasks
}]
# Submission information for each user and each task.
for participation in contest.participations:
username = participation.user.username
# Skip irrelevant users.
if username not in usernames_set:
continue
# Get the tasks this user submitted to.
submitted_task_names = set(submission.task.name for submission
in participation.submissions)
for task_name in contest_tasks:
# If the user did not submit to this task, we don't write
# anything (this is distinct from getting 0).
if task_name not in submitted_task_names:
continue
task = name_to_task[task_name]
score, partial = task_score(participation, task)
score = round(score, task.score_precision)
score_string = str(score)
if partial:
score_string += "*"
result["scores"][username][task_name] = score_string
return result
def dump_ranks_js(path, ranks_object):
"""
Dump the given ranks object to the given path as a JS file.
The JS file contains only "var raw_data = <object>;".
"""
js_str = "var raw_data = %s;" % json.dumps(ranks_object) + \
"var scores_timestamp = %d;" % int(time.time())
with open(path, "w") as stream:
stream.write(js_str)
def main():
"""
Read settings file and dump ranks to a JS file.
"""
parser = argparse.ArgumentParser()
parser.add_argument("settings", help="settings file to use")
args = parser.parse_args()
settings_path = args.settings
with open(settings_path) as stream:
settings = yaml.safe_load(stream)
target_path = settings["target_path"]
if not target_path.endswith("scores.js"):
raise Exception("Expected scores.js: %s" % target_path)
ranks_object = create_ranks_object(
settings.get("included_contests"),
settings.get("excluded_contests"),
settings.get("included_tasks"),
settings.get("excluded_tasks"),
settings.get("included_users"),
settings.get("excluded_users"))
dump_ranks_js(target_path, ranks_object)
if __name__ == "__main__":
sys.exit(main())
| nilq/baby-python | python |
"""Responses provided by the iov42 platform."""
import json
from dataclasses import dataclass
from typing import List
from typing import Union
from ._entity import Identifier
from ._request import Request
@dataclass(frozen=True)
class BaseResponse:
"""Base class for successful platform responses."""
request: Request
# TODO: what information are we going to provide form the HTTP response.
# Note: we do not want to leak out the HTTP response itself.
content: bytes
@dataclass(frozen=True)
class EntityCreated(BaseResponse):
"""Entity was successfully created."""
proof: str
resources: List[str]
@dataclass(frozen=True)
class Endorsement(BaseResponse):
"""Endorsement against a subject claim of the given endorser exists."""
proof: str
endorser_id: Identifier
endorsement: str
Response = Union[EntityCreated, Endorsement]
def deserialize(request: Request, content: bytes) -> Response:
"""Deserializes the HTTP response content to a Response."""
content_json = json.loads(content.decode())
if request.method == "PUT":
return EntityCreated(
request,
content,
content_json["proof"],
resources=content_json["resources"],
)
else:
if "/endorsements/" in request.resource: # pragma: no cover
return Endorsement(
request,
content,
content_json["proof"],
content_json["endorserId"],
content_json["endorsement"],
)
raise NotImplementedError(
"Response deserialize not implemented"
) # pragma: no cover
| nilq/baby-python | python |
# -*- coding:utf-8 -*-
__author__ = 'shichao'
import platform
import tensorflow as tf
import numpy as np
import time
def iterator_demo():
'''
python iterator demo
:return:
'''
class numIter: #
def __init__(self, n):
self.n = n
def __iter__(self):
self.x = -1
return self
if platform.python_version().startswith('2.'):
def next(self):
self.x += 1
if self.x < self.n:
return self.x
else:
raise StopIteration
else:
def __next__(self): # Python 3.x version Python 2.x version uses next()
self.x += 1
if self.x < self.n:
return self.x
else:
raise StopIteration
for i in numIter(5):
print(i)
print(isinstance(numIter(1),))
print(isinstance(numIter,list))
def generator_demo():
'''
the generator demo
:return:
'''
def numGen(n): # generator
try:
x = 0
while x < n:
y = yield x
print(y)
x += 1
except ValueError:
yield 'error'
finally:
print('finally')
num = numGen(5)
print(num.next())
print(num.next())
print(num.send(999))
num.close()
# print(num.throw(ValueError))
print(num.next())
# print(num.next())
def bubblesort(array,length):
'''
the largest number will first down to the bottom, then the second largest, etc
:param array:
:param length:
:return:
'''
sorted = False
while not sorted:
sorted = True
for i in range(1,length):
if array[i-1] > array[i]:
[array[i-1],array[i]] = swap(array[i-1],array[i])
sorted = False
print(array)
def swap(a,b):
tmp = a
a = b
b = tmp
return [a,b]
def reverse_1(array,lo,hi):
if lo<hi:
array[lo],array[hi] = swap(array[lo],array[hi])
reverse_1(array,lo+1,hi-1)
return array
def reverse_2(array):
pass
def power2(n):
if n==0:
return 1
else:
return power2(n>>1)**2<<1 if n&1 else power2(n>>1)**2
def power1(n):
tmp = 1
for i in range(n):
tmp *= 2
return tmp
def simple_decorater(f):
def wrapper():
print('enter')
# f()
int('exit')
return wrapper
@ simple_decorater
def hello():
print('hello')
def main():
##########
# iterator and generator
# iterator_demo()
# generator_demo()
#########
# array operation
# array = np.array([3,1,6,2,5,10,8,9,4,7])
# # bubblesort(array,len(array))
# array = reverse_1(array,0,len(array)-1)
# print(array)
#
# #############
# recursion vs for loop
start = time.time()
print('%E'%power2(1000))
end = time.time()
print('power2 elapsed time: {0}'.format(end-start))
# print('power2 elapsed time: %E'%(end-start))
start = time.time()
print('%E'%power1(1000))
end = time.time()
# print('power1 elapsed time: %E'%(end-start))
print('power1 elpased time: {0}'.format(end-start))
if __name__ == '__main__':
# main()
hello() | nilq/baby-python | python |
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QMessageBox, QFileDialog, QGridLayout, QHBoxLayout, \
QVBoxLayout, QGroupBox, QCheckBox, QPushButton, QAction
from PatchEdit import *
from collections import OrderedDict
import copy
class PatchGUI(QMainWindow):
def __init__(self):
self.app = QApplication(sys.argv)
super(PatchGUI, self).__init__()
self.file_dic = OrderedDict()
self.orig_patch_obj_dic = OrderedDict()
self.patch_obj_dic = OrderedDict()
self.cb_dic = OrderedDict()
self.vBox_list = []
self.apply_button = None
self.disable_all_button = None
self.defaults_button = None
self.choose_files()
def choose_files(self):
fn_list, file_type = QFileDialog.getOpenFileNames(caption='Open File', filter='Kobo Patch (*.patch)')
if fn_list:
fd = {fn: None for fn in fn_list}
self.file_dic, error = read_patch_files(fd)
if error:
QMessageBox.critical(self, 'Read Error!', error)
else:
for (fn, patch_text) in iterDic(self.file_dic):
self.orig_patch_obj_dic[fn] = gen_patch_obj_list(fn, patch_text)
self.initialize()
else:
self.close()
def initialize(self):
self.patch_obj_dic = copy.deepcopy(self.orig_patch_obj_dic)
cont_index = 0
vBox = QVBoxLayout(self)
for (fn, patch_obj_list) in iterDic(self.patch_obj_dic):
self.cb_dic[fn] = []
gb = QGroupBox(fn)
cb_grid = QGridLayout(self)
# Create and add checkboxes to appropriate LabelFrame
for (cb_index, obj) in enumerate(patch_obj_list):
# Create checkbox variable and checkbox label for display
cb_name = ''
if obj.group:
cb_name = obj.name + '\n(' + obj.group + ')'
else:
cb_name = obj.name
# Create and add checkboxes to the LabelFrame, using the grid geometry manager
self.cb_dic[fn].append(QCheckBox(cb_name))
# Set initial state of checkboxes
if 'yes' in obj.status:
self.cb_dic[fn][cb_index].setCheckState(Qt.Checked)
else:
self.cb_dic[fn][cb_index].setCheckState(Qt.Unchecked)
self.cb_dic[fn][cb_index].stateChanged.connect(self.toggle_check)
self.cb_dic[fn][cb_index].setToolTip(self.patch_obj_dic[fn][cb_index].help_text)
grid_pos = calc_grid_pos(cb_index, cols=3)
cb_grid.addWidget(self.cb_dic[fn][cb_index], grid_pos[0], grid_pos[1])
gb.setLayout(cb_grid)
vBox.addWidget(gb)
cont_index += 1
self.apply_button = QPushButton('Apply Changes')
self.apply_button.clicked.connect(self.app_chgs)
self.disable_all_button = QPushButton("Disable All")
self.disable_all_button.clicked.connect(self.disable_all_patches)
self.defaults_button = QPushButton('Restore Settings')
self.defaults_button.clicked.connect(self.restore_defaults)
button_box = QHBoxLayout()
button_box.addStretch()
button_box.addWidget(self.apply_button)
button_box.addWidget(self.disable_all_button)
button_box.addWidget(self.defaults_button)
button_box.addStretch()
vBox.addLayout(button_box)
self.setCentralWidget(QWidget(self))
self.centralWidget().setLayout(vBox)
self.setWindowTitle('Kobo Patch GUI')
self.show()
sys.exit(self.app.exec_())
def disable_all_patches(self):
"""
Does what it says on the tin :p
Deselects all checkboxes and sets each objects status to 'no'
:return:
"""
for chk_list in self.cb_dic.values():
for cb in chk_list:
cb.setCheckState(Qt.Unchecked)
for (fn, patch_obj_list) in iterDic(self.patch_obj_dic):
for patch_obj in patch_obj_list:
patch_obj.status = '`no`'
def restore_defaults(self):
"""
Restores the state of the patch objects and checkboxes back to their original state of when the file was loaded
:return:
"""
self.patch_obj_dic = copy.deepcopy(self.orig_patch_obj_dic)
for (cb_list, patch_obj_list) in zip(self.cb_dic.values(), self.patch_obj_dic.values()):
for (cb, patch_obj) in zip(cb_list, patch_obj_list):
if 'yes' in patch_obj.status:
cb.setCheckState(Qt.Checked)
else:
cb.setCheckState(Qt.Unchecked)
def toggle_check(self, event):
cb = self.sender()
name = cb.text()
for patch_list in self.patch_obj_dic.values():
for obj in patch_list:
if obj.name in name:
if cb.isChecked():
obj.status = '`yes`'
else:
obj.status = '`no`'
def app_chgs(self, event):
ask_confirm = QMessageBox.question(self, 'Are you sure?', 'Are you sure you wish to write the changes to the '
'patch files?', QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if ask_confirm == QMessageBox.Yes:
success, error_title, error_msg = apply_changes(self.patch_obj_dic, self.file_dic)
if not success:
QMessageBox.critical(self, error_title, error_msg)
else:
QMessageBox.information(self, 'Sussess!', 'The files were successfully written.')
def edit(self):
pass
if __name__ == '__main__':
pg = PatchGUI()
| nilq/baby-python | python |
import typer
INFO = typer.style("INFO", fg=typer.colors.GREEN) + ": "
HELP = typer.style("HELP", fg=typer.colors.BLUE) + ": "
FAIL = typer.style("FAIL", fg=typer.colors.RED) + ": "
SUCCESS = typer.style("SUCCESS", fg=typer.colors.BLUE) + ": "
typer.echo(f"{INFO} Importing modules, please wait")
import os
import uvicorn
import forest_lite.server.main as _main
from forest_lite.server import config, user_db
app = typer.Typer()
def scan_port(initial_port):
"""Helper to detect available port"""
port = initial_port
typer.echo(f"{INFO} Scanning ports")
while in_use(port):
typer.echo(f"{FAIL} Port {port} in use")
port += 1
typer.echo(f"{SUCCESS} Port {port} available")
return port
def in_use(port):
"""Check if port is accessible"""
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', port)) == 0
def get_settings(file_name, driver_name, palette):
def fn():
return config.Settings(datasets=[
{
"label": file_name,
"palettes": {
"default": {
"name": palette,
"number": 256,
"reverse": True,
"low": 200,
"high": 300
}
},
"driver": {
"name": driver_name,
"settings": {
"pattern": file_name
}
}
}
])
return fn
def browser_thread(url):
import threading
import webbrowser
typer.echo(f"{INFO} Opening browser: {url}")
return threading.Thread(target=webbrowser.open, args=(url,))
@app.command()
def view(file_name: str, driver: str = "eida50", open_tab: bool = True,
palette: str = "Viridis",
port: int = 1234):
"""
FOREST Lite viewer
A simplified interface to the FOREST Lite server tool
"""
port = scan_port(port)
if open_tab:
url = f"http://localhost:{port}"
thread = browser_thread(url)
thread.start()
callback = get_settings(file_name, driver, palette)
_main.app.dependency_overrides[config.get_settings] = callback
uvicorn.run(_main.app, port=port)
@app.command()
def serve(config_file: str,
open_tab: bool = True,
port: int = 1234):
"""
FOREST Lite server
A simplified interface to uvicorn and configuration files
used to serve the app
"""
if not os.path.exists(config_file):
typer.echo(f"{FAIL} {config_file} not found on file system")
if os.path.isabs(config_file):
helper = f"{HELP} Looks like an absolute path, is there a typo?"
else:
helper = (f"{HELP} Looks like a relative path, "
"are you in the right directory?")
typer.echo(helper)
raise typer.Exit()
port = scan_port(port)
def get_settings():
import yaml
with open(config_file) as stream:
data = yaml.safe_load(stream)
return config.Settings(**data)
if open_tab:
url = f"http://localhost:{port}"
thread = browser_thread(url)
thread.start()
_main.app.dependency_overrides[config.get_settings] = get_settings
uvicorn.run(_main.app, port=port)
@app.command()
def database(user_name: str, password: str, db_file: str,
user_group: str = "anonymous"):
print(f"save: {user_name} to {db_file}")
user_db.save_user(user_name, password, db_file,
user_group=user_group)
| nilq/baby-python | python |
#!/usr/bin/env python3.7
# Copyright 2021 DataStax, Inc.
#
# 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
#
# https://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.
# Delete bucket function is used to delete the state files bucket.
# This bucket will be created at make init run.
# To delete
from google.cloud import storage
import os
import sys
def delete_bucket(bucket_name):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
try:
bucket.delete()
print("Bucket {} deleted".format(bucket.name))
except:
print("buckeet does not exists")
bucket_name = os.getenv("bucket_name")
delete_bucket(bucket_name)
| nilq/baby-python | python |
import torch
import onnx
from pathlib import Path
import sys
def convert2onnx(model_path,input_size,out_path=None):
if out_path is None:
out_path=Path(model_path).with_suffix('.onnx')
model=torch.load(model_path)
out_path=export2onnx(model,input_size,out_path)
return out_path
def export2onnx(model,input_size,onnx_path,if_check=True,if_simplify=True):
model.eval()
c,h,w=tuple(input_size)
device='cuda' if torch.cuda.is_available() else 'cpu'
model.to(device)
dummy_input = torch.randn(1,c,h,w).to(device)
assert onnx_path.endswith('.onnx')
torch.onnx._export(model,dummy_input,onnx_path,
verbose=False)
print('onnx exported')
if if_check:
onnx_path=check_onnx(onnx_path)
if if_simplify:
out_path=simplify_onnx(onnx_path)
Path(onnx_path).unlink()
else:
out_path=onnx_path
return out_path
def check_onnx(onnx_path):
onnx_model=onnx.load(onnx_path)
onnx.checker.check_model(onnx_model)
print('valid onnx model')
return onnx_path
def simplify_onnx(onnx_path):
from onnxsim import simplify
onnx_path=str(onnx_path)
onnx_model=onnx.load(onnx_path)
model_simp, check = simplify(onnx_model)
assert check, "Simplified ONNX model could not be validated"
out_path=onnx_path.replace('.onnx','_simp.onnx')
onnx.save(model_simp,out_path)
print('simplify done')
return out_path
if __name__ == '__main__':
# model_path,c,w,h=sys.path[1:5]
# convert2onnx(model_path,c,w,h)
simply_onnx('model/model_Number_aus_bin.onnx')
| nilq/baby-python | python |
from caffe2.python import core
import numpy as np
class ParameterTags(object):
BIAS = 'BIAS'
WEIGHT = 'WEIGHT'
COMPUTED_PARAM = 'COMPUTED_PARAM'
class ParameterInfo(object):
def __init__(
self, param_id, param, key=None, shape=None, length=None,
grad=None, blob_copy=None):
assert isinstance(param, core.BlobReference)
self.param_id = param_id
self.name = str(param)
self.blob = param
self.key = key
self.shape = shape
self.size = None if shape is None else np.prod(shape)
self.length = max(1, length if length is not None else 1)
self.grad = grad
self._cloned_init_net = None
# Optionally store equivalent copies of the blob
# in different precisions (i.e. half and float copies)
# stored as a dict of TensorProto.DataType -> BlobReference
self.blob_copy = blob_copy
# each param_info can have its own optimizer. It can be set within
# OptimizerContext (caffe2/python/optimizer.py)
self._optimizer = None
@property
def parameter(self):
return self.blob
@property
def optimizer(self):
return self._optimizer
@optimizer.setter
def optimizer(self, value):
assert self._optimizer is None, "optimizer has already been set"
self._optimizer = value
def __str__(self):
return self.name
| nilq/baby-python | python |
# Criar e modificar arquivos txt
'''
'r' = Usado somente para ler algo
'w' = Usado somente para escrever algo
'r+' = Usado para ler e escrever algo
'a' = Usado para acrescentar algo
'''
numeros = [0, 15, 10, 20, 15, 45]
# Criar um arquivo e colocar as informações da lista numeros dentro dele
with open('numeros.txt', 'w') as arquivo:
for numero in numeros:
arquivo.write(str(f"{numero}\n"))
# Adicionar ao arquivo as informações da lista numeros dentro dele
with open('numeros.txt', 'a') as arquivo:
for numero in numeros:
arquivo.write(f'{numero}\n')
# Ler as informações dentro do arquivo de texto
with open('numeros.txt', 'r') as arquivo:
for linha in arquivo:
print(linha)
| nilq/baby-python | python |
"""
Copyright Tiyab KONLAMBIGUE
"""
from gce import client
import logging
import time
from model import job as jobmodel
import configuration
JSON_KEY_FOLDER = configuration.JSON_KEY_FOLDER
# Google instance image project configs
IMAGES_PROJECT = configuration.IMAGES_PROJECT
class instance():
GCE_TERMINATED_STATUS = "TERMINATED"
GCE_RUNNING_STATUS = "RUNNING"
GCE_STOPPING_STATUS = "STOPPING"
def __init__(self, project_id):
self.project_id =project_id
self.json_key_path = JSON_KEY_FOLDER + project_id + ".json"
client.GCE_DEFAULT_ZONE=configuration.GCE_DEFAULT_ZONE
client.GCE_DEFAULT_MACHINE_TYPE=configuration.GCE_DEFAULT_MACHINE_TYPE
client.GCE_DEFAULT_IMAGE_NAME=configuration.GCE_DEFAULT_IMAGE_NAME
client.GCE_DEFAULT_IMAGE_PROJECT=configuration.GCE_DEFAULT_IMAGE_PROJECT
client.GCE_DEFAULT_FULL_SCOPE=configuration.GCE_DEFAULT_FULL_SCOPE
self.gce_client = client.get_client(json_key_file=self.json_key_path, readonly=False)
# Check if instance exist
def exist(self, instance_name, project):
logging.info("Run instance exist at > %s" % time.strftime("%c"))
instance_metadata = self.get(instance_name, project)
if instance_metadata:
return True
return False
# Check if machine is running
def get(self, instance_name, project):
logging.info("Run instance get at > %s" % time.strftime("%c"))
instances = self.gce_client.list_instances(project)
for instance in instances:
if instance['name']== instance_name:
return instance
return None
# Get instance status
def status_of(self, instance_name, project):
logging.info("Run instance status_of at > %s" % time.strftime("%c"))
instance_metadata = self.get(instance_name, project)
if instance_metadata:
return instance_metadata["status"]
return None
# Create a new machine if not exist
def create(self,project, instance_name, startup_script_path,shutdown_script_path,
bucket_id, zone, image_project, image_name,type_machine
):
logging.info("Run instance create at > %s" % time.strftime("%c"))
if not self.exist(instance_name, project):
#Create machine
#startup_script_path= SCRIPT_FOLDER + startup_scrip_name
self.gce_client.create_instance(project, instance_name, startup_script_path,shutdown_script_path,
bucket_id, zone, image_project, image_name,type_machine)
#Check if machine is created
if self.exist(instance_name, project):
return True
else:
logging.info("Unexpected error, instance is not created...")
else:
logging.info("Instance "+instance_name+" already exist...")
return False
# Stop running instance
def stop(self, instance_name, project, zone):
if self.exist(instance_name, project):
current_status = self.status_of(instance_name, project)
if current_status != "STOPPING" and \
current_status != "TERMINATED":
self.gce_client.stop_instance(project, instance_name, zone)
#Check is instance is stopped correctly
if self.status_of(instance_name, project) == "TERMINATED":
return True
else:
logging.info("Instance " + instance_name + " not exist...")
return False
# Start instance stopped
def start(self, instance_name, project, zone):
if self.exist(instance_name, project):
current_status = self.status_of(instance_name, project)
if current_status == "TERMINATED":
self.gce_client.start_instance(project, instance_name, zone)
# Check is instance is stopped correctly
if self.status_of(instance_name, project) == "RUNNING":
return True
else:
logging.info("Instance " + instance_name + " not exist...")
return False
# Remove instance
def delete(self, instance_name, project, zone):
if self.exist(instance_name, project):
self.gce_client.delete_instance(project, instance_name, zone)
# Check is instance is removed correctly
if not self.exist(instance_name, project):
return True
else:
logging.info("Instance " + instance_name + " not exist...")
return False
#####################################################################################################
# JOB
#####################################################################################################
# Run job
def run_job(self, job):
creation = job.creation
updated = job.updated
emails = job.emails
project_id = job.project_id
bucket_id = job.bucket_id
machine_name = job.machine_name
startup_script = job.startup_script
shutdown_script = job.shutdown_script
machine_type = job.machine_type
machine_zone = job.machine_zone
machine_os = job.machine_os
cron_schedule = job.cron_schedule
after_run = job.after_run
max_running_time = job.max_running_time
job_name = job.job_name
job_status = job.job_status
last_run = job.last_run
# Check if instance exist
# If instance exist - It's an stopped instance
if self.exist(machine_name, project_id):
status = self.status_of(machine_name, project_id)
print('>>>>>> Status is ' + str(status))
if status!="RUNNING":
# Create job by starting instance
# By starting up instance, startup script will do the job
new_instance_running = self.start(machine_name, project_id, machine_zone)
if new_instance_running:
# Update Datastore
self.update_datastore_running_job(job)
else:
# If instance not exist create new one
#Find image project by machine_os
os_project = None
for image in IMAGES_PROJECT:
if image["key-word"] in machine_os:
os_project = image["image-project"]
# Create instance if we have image project
if not os_project is None:
new_instance_running = self.create(project_id,machine_name,startup_script,shutdown_script,
bucket_id,machine_zone, os_project, machine_os, machine_type)
if new_instance_running:
# Update Datastore
self.update_datastore_running_job(job)
# Stop job
def stop_job(self, job):
creation = job.creation
updated = job.updated
emails = job.emails
project_id = job.project_id
bucket_id = job.bucket_id
machine_name = job.machine_name
startup_script = job.startup_script
shutdown_script = job.shutdown_script
machine_type = job.machine_type
machine_zone = job.machine_zone
machine_os = job.machine_os
cron_schedule = job.cron_schedule
after_run = job.after_run
max_running_time = job.max_running_time
job_name = job.job_name
job_status = job.job_status
last_run = job.last_run
if self.exist(machine_name, project_id):
if after_run =="stop":
self.stop(machine_name, project_id, machine_zone)
if after_run =="delete":
self.delete(machine_name, project_id, machine_zone)
current_status = self.status_of(machine_name, project_id)
if current_status == self.GCE_STOPPING_STATUS or \
current_status == self.GCE_TERMINATED_STATUS \
or current_status ==None:
# Update Datastore
self.update_datastore_stopping_job(job)
#################################################################################################
######## DATASTORE
#################################################################################################
#Update datastore and indicate a running job
def update_datastore_running_job(self, job):
# Check if job exist
my_filter = "WHERE job_name='" + job.job_name + "'"
existing_job = jobmodel.Job().get(my_filter)
if len(existing_job) > 0:
logging.info("update_job: Update job " + job.job_name + " to datastore ...")
#Update existing job
old_job = existing_job[0]
old_job.emails = job.emails
old_job.project_id = job.project_id
old_job.bucket_id = job.bucket_id
old_job.machine_name = job.machine_name
old_job.startup_script = job.startup_script
old_job.shutdown_script = job.shutdown_script
old_job.machine_type = job.machine_type
old_job.machine_zone = job.machine_zone
old_job.after_run=job.after_run
old_job.machine_os = job.machine_os
old_job.cron_schedule = job.cron_schedule
old_job.max_running_time = job.max_running_time
old_job.job_name = job.job_name
old_job.job_status = "running"
old_job.put()
else:
#Redirect to list
logging.info("Unable to update job " + job.job_name + ", job not found ...")
#Update datastore and indicate a stopped job
def update_datastore_stopping_job(self, job):
# Check if job exist
my_filter = "WHERE job_name='" + job.job_name + "'"
existing_job = jobmodel.Job().get(my_filter)
if len(existing_job) > 0:
logging.info("update_job: Update job " + job.job_name + " to datastore ...")
#Update existing job
old_job = existing_job[0]
old_job.emails = job.emails
old_job.project_id = job.project_id
old_job.bucket_id = job.bucket_id
old_job.machine_name = job.machine_name
old_job.startup_script = job.startup_script
old_job.shutdown_script = job.shutdown_script
old_job.machine_type = job.machine_type
old_job.machine_zone = job.machine_zone
old_job.after_run=job.after_run
old_job.machine_os = job.machine_os
old_job.cron_schedule = job.cron_schedule
old_job.max_running_time = job.max_running_time
old_job.job_name = job.job_name
old_job.job_status = "standby"
old_job.put()
else:
#Redirect to list
logging.info("Unable to update job " + job.job_name + ", job not found ...") | nilq/baby-python | python |
import datapackage
from datapackage_pipelines.wrapper import ingest, spew, get_dependency_datapackage_url
dep_prefix = 'dependency://'
parameters, dp, res_iter = ingest()
url = parameters['url']
if url.startswith(dep_prefix):
dependency = url[len(dep_prefix):].strip()
url = get_dependency_datapackage_url(dependency)
assert url is not None, "Failed to fetch output datapackage for dependency '%s'" % dependency
datapackage = datapackage.DataPackage(url)
for k, v in datapackage.descriptor.items():
if k != 'resources':
dp[k] = v
spew(dp, res_iter)
| nilq/baby-python | python |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from functools import reduce
import operator
import math
import dolfin as dl
import mshr
def sort_points_in_anti_clockwise_order(coords):
coords=coords.T
center = tuple(map(operator.truediv, reduce(lambda x, y: map(operator.add, x, y), coords), [len(coords)] * 2))
sorted_coords = sorted(coords, key=lambda coord: (-135 - math.degrees(math.atan2(*tuple(map(operator.sub, coord, center))[::-1]))) % 360)
sorted_coords = np.array(sorted_coords)[::-1].T
return sorted_coords, center
def numpy_to_dolfin_points(points):
vertices=[]
for ii in range(points.shape[1]):
point = points[:,ii]
vertices.append(dl.Point(point[0],point[1]))
return vertices
from scipy import io
import os
def generate_blade_domain():
path = os.path.abspath(os.path.dirname(__file__))
data = io.loadmat(os.path.join(path,'data','blade_geometry.mat'))
bedge = data['bedge']
xy = data['xy']
points,bndry = [],[]
for ii in range(bedge.shape[1]):
kn1 = bedge[0,ii]-1
kn2 = bedge[1,ii]-1
points.append(xy[:,kn1])
points.append(xy[:,kn2])
bndry.append(bedge[2,ii])
bndry.append(bedge[2,ii])
points = np.asarray(points).T
bndry = np.asarray(bndry)
coords = points[:,bndry==0]
sorted_coords,center=sort_points_in_anti_clockwise_order(coords)
vertices = numpy_to_dolfin_points(sorted_coords)
airfoil_domain = mshr.Polygon(vertices)
cooling_domains = []
domain = airfoil_domain
for ii in range(1,3):
coords = points[:,bndry==ii]
sorted_coords,center=sort_points_in_anti_clockwise_order(coords)
vertices = numpy_to_dolfin_points(sorted_coords)
cooling_domains.append(mshr.Polygon(vertices))
domain-=cooling_domains[-1]
#last cooling domain requires special treatment
coords = points[:,bndry==3]
coords = coords[:,(coords[0]>=0.45)&(coords[0]<=0.7)]
sorted_coords,center=sort_points_in_anti_clockwise_order(coords)
vertices = numpy_to_dolfin_points(sorted_coords)
cooling_domains.append(mshr.Polygon(vertices))
domain-=cooling_domains[-1]
coords = points[:,bndry==3]
coords = coords[:,(np.absolute(coords[1])<=0.01)&(coords[0]>=0.7)]
sorted_coords,center=sort_points_in_anti_clockwise_order(coords)
vertices = numpy_to_dolfin_points(sorted_coords)
cooling_domains.append(mshr.Polygon(vertices))
domain-=cooling_domains[-1]
return domain
class CoolingPassage1(dl.SubDomain):
def inside(self, x, on_boundary):
cond1 = ((abs(x[1])<=0.045+1e-12) and (x[0]>=0.1-1e-12) and (x[0]<=0.2+1e-12))
cond2 = ((abs(x[1])<=0.035+1e-12) and (x[0]<=0.1+1e-12) and (x[0]>=0.05-1e-12))
cond3 = ((abs(x[1])<=0.02+1e-12) and (x[0]<=0.05+1e-12) and (x[0]>=0.025-1e-12))
return ((cond1 or cond2 or cond3) and on_boundary)
class CoolingPassage2(dl.SubDomain):
def inside(self, x, on_boundary):
cond1 = ((abs(x[1])<=0.045+1e-12) and (x[0]<=0.45+1e-12) and (x[0]>=0.25-1e-12))
return (cond1 and on_boundary)
class CoolingPassage3(dl.SubDomain):
def inside(self, x, on_boundary):
cond1 = ((abs(x[1])<=0.01+1e-12) and (x[0]>=0.5))
cond2 = ((abs(x[1])<0.035) and (x[0]>=0.5) and (x[0]<=0.7))
cond3 = ((abs(x[1])<0.04+1e-12) and (x[0]>=0.5) and (x[0]<=0.6))
return ((cond1 or cond2 or cond3) and on_boundary)
class Airfoil(dl.SubDomain):
def inside(self, x, on_boundary):
return on_boundary
from pyapprox.fenics_models.advection_diffusion import run_steady_state_model
class AirfoilHeatTransferModel(object):
def __init__(self,degree):
self.degree=degree
self.num_config_vars=1
self.domain = generate_blade_domain()
def get_boundary_conditions_and_function_space(self,random_sample):
function_space = dl.FunctionSpace(self.mesh, "Lagrange", degree)
t_c1,t_c2,t_c3,thermal_conductivity,h_le,h_te=random_sample
airfoil_expr = dl.Expression(
'h_te+(h_le-h_te)*std::exp(-4*std::pow(x[0]/(chord*lhot),2))',
degree=self.degree,h_le=h_le,h_te=h_te,lhot=0.05,chord=0.04)
boundary_conditions = [
['dirichlet',Airfoil(),airfoil_expr],
['dirichlet',CoolingPassage1(),dl.Constant(t_c1)],
['dirichlet',CoolingPassage2(),dl.Constant(t_c2)],
['dirichlet',CoolingPassage3(),dl.Constant(t_c3)]]
return boundary_conditions,function_space
def initialize_random_expressions(self,random_sample):
"""
Parameters
----------
random_sample : np.ndarray (6)
Realization of model uncertainties. The uncertainties are listed
below in the order they appear in ``random_sample``
h_le : float
Leading edge heat transfer coefficient
h_lt : float
Tail edge heat transfer coefficient
thermal_conductivity : float
Blade thermal conductivity
t_c1 : float
First passage coolant temperature
t_c2 : float
Second passage coolant temperature
t_c3 : float
Thrid passage coolant temperature
"""
t_c1,t_c2,t_c3,thermal_conductivity,h_le,h_te=random_sample
kappa = dl.Constant(thermal_conductivity)
forcing = dl.Constant(0)
boundary_conditions, function_space = \
self.get_boundary_conditions_and_function_space(random_sample)
return kappa,forcing,boundary_conditions,function_space
def get_mesh_resolution(self,resolution_level):
resolution = 10*(2**resolution_level)
return int(resolution)
def solve(self,samples):
assert samples.ndim==2
assert samples.shape[1]==1
resolution_levels = samples[-self.num_config_vars:,0]
self.mesh = self.get_mesh(
self.get_mesh_resolution(resolution_levels[-1]))
random_sample = samples[:-self.num_config_vars,0]
kappa,forcing,boundary_conditions,function_space=\
self.initialize_random_expressions(random_sample)
sol = run_steady_state_model(
function_space,kappa,forcing,boundary_conditions)
return sol
def qoi_functional(self,sol):
vol = dl.assemble(dl.Constant(1)*dl.dx(sol.function_space().mesh()))
bulk_temperature=dl.assemble(sol*dl.dx(sol.function_space().mesh()))/vol
print('Bulk (average) temperature',bulk_temperature)
return bulk_temperature
def __call__(self,samples):
sol = self.solve(samples)
vals = np.atleast_1d(self.qoi_functional(sol))
if vals.ndim==1:
vals = vals[:,np.newaxis]
return vals
def get_mesh(self,resolution):
mesh = mshr.generate_mesh(self.domain,resolution)
return mesh
if __name__=='__main__':
degree=1
model = AirfoilHeatTransferModel(degree)
sample = np.array([595,645,705,29,1025,1000,0])
sol = model.solve(sample[:,np.newaxis])
qoi = model(sample[:,np.newaxis])
fig,axs=plt.subplots(1,1)
p=dl.plot(sol)
plt.colorbar(p)
plt.show()
# #check boundary
# from pyapprox.fenics_models.fenics_utilities import mark_boundaries, collect_dirichlet_boundaries
# boundaries = mark_boundaries(mesh,boundary_conditions)
# dirichlet_bcs = collect_dirichlet_boundaries(
# function_space,boundary_conditions, boundaries)
# temp = dl.Function(function_space)
# temp.vector()[:]=-1
# for bc in dirichlet_bcs:
# bc.apply(temp.vector())
# fig,axs=plt.subplots(1,1)
# p=dl.plot(temp)
# plt.colorbar(p)
# #dl.plot(mesh)
# plt.show()
| nilq/baby-python | python |
from fractions import Fraction
from src.seq import fibonacci, stern_diatomic_seq, fib_seq, stern_brocot
from src.graph import stern_brocot_graph
from itertools import islice
import pytest
def test_returns_first_5_numbers_of_stern_brocot():
assert take(stern_brocot, 5) == [
Fraction(1, 1),
Fraction(1, 2),
Fraction(2, 1),
Fraction(1, 3),
Fraction(3, 2)]
@pytest.mark.skip(reason="WIP")
def test_returns_first_5_numbers_of_stern_brocot_via_graph():
assert take(stern_brocot_graph, 5) == [
Fraction(1, 1),
Fraction(1, 2),
Fraction(2, 1),
Fraction(1, 3),
Fraction(3, 2)]
def test_stern_diatomic_seq_appends_previous_fib_result():
assert take(stern_diatomic_seq, 5) == [0, 1, 1, 2, 1]
def test_stern_diatomic_seq_appends_previous_fib_result_for_higher_n():
assert take(stern_diatomic_seq, 10) == [0, 1, 1, 2, 1, 3, 2, 3, 1, 4]
def test_stern_diatomic_seq_appends_previous_fib_result_for_much_higher_n():
assert take(stern_diatomic_seq, 16) == [
0, 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4]
def test_fibonacci_seq_correct_for_zero():
assert take(fib_seq, 1) == [0]
def test_fibonacci_seq_correct_for_one():
assert take(fib_seq, 2) == [0, 1]
def test_fibonacci_seq_correct_for_n():
assert take(fib_seq, 8) == [0, 1, 1, 2, 3, 5, 8, 13]
def test_fibonacci_correct_for_zero():
assert fibonacci(0) == 0
def test_fibonacci_correct_for_one():
assert fibonacci(1) == 1
def test_fibonacci_correct_for_n():
assert fibonacci(7) == 13
def take(func, n):
return list(islice(func(), n))
| nilq/baby-python | python |
# Copyright 2020 Thiago Teixeira
#
# 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 unittest
from htbuilder.units import px, em, percent
class TestUnits(unittest.TestCase):
def test_basic_usage(self):
self.assertEqual(px(10), ('10px',))
self.assertEqual(px(0), ('0',))
self.assertEqual(em(5), ('5em',))
self.assertEqual(percent(99), ('99%',))
def test_varargs(self):
self.assertEqual(px(10, 9, 8), ('10px', '9px', '8px'))
self.assertEqual(px(0, 1), ('0', '1px'))
self.assertEqual(em(5, 7), ('5em', '7em'))
self.assertEqual(percent(99, 99.9), ('99%', '99.9%'))
if __name__ == '__main__':
unittest.main()
| nilq/baby-python | python |
from datetime import datetime
from importers.e_trac_importer import ETracImporter
from importers.nmea_importer import NMEAImporter
from pepys_import.core.formats import rep_line
def test_nmea_timestamp_parsing():
parse_timestamp = NMEAImporter.parse_timestamp
# Invalid day in date
result = parse_timestamp("20201045", "111456")
assert not result
# Invalid hour in time
result = parse_timestamp("20201006", "340738")
assert not result
def test_etrac_timestamp_parsing():
parse_timestamp = ETracImporter.parse_timestamp
# Invalid day in date
result = parse_timestamp("2020/04/57", "11:46:23")
assert not result
# Invalid hour in time
result = parse_timestamp("2020/04/07", "34:07:38")
assert not result
def test_rep_timestamp_parsing():
parse_timestamp = rep_line.parse_timestamp
date = "20201001"
time = "12010" # missing minute in time
result = parse_timestamp(date, time)
assert not result
time = "340100" # invalid hour in time
result = parse_timestamp(date, time)
assert not result
time = "120105"
result = parse_timestamp(date, time)
assert result == datetime(2020, 10, 1, 12, 1, 5)
time = "120105.1"
result = parse_timestamp(date, time)
assert result == datetime(2020, 10, 1, 12, 1, 5, 100000)
time = "120105.11"
result = parse_timestamp(date, time)
assert result == datetime(2020, 10, 1, 12, 1, 5, 110000)
time = "120105.111"
result = parse_timestamp(date, time)
assert result == datetime(2020, 10, 1, 12, 1, 5, 111000)
time = "120105.1111"
result = parse_timestamp(date, time)
assert result == datetime(2020, 10, 1, 12, 1, 5, 111100)
time = "120105.11111"
result = parse_timestamp(date, time)
assert result == datetime(2020, 10, 1, 12, 1, 5, 111110)
time = "120105.111111"
result = parse_timestamp(date, time)
assert result == datetime(2020, 10, 1, 12, 1, 5, 111111)
time = "120101.1234567" # invalid decimals in time
result = parse_timestamp(date, time)
assert not result
| nilq/baby-python | python |
from flask_wtf import FlaskForm
from wtforms import IntegerField
from wtforms import SelectField
from wtforms import SubmitField
from wtforms import StringField
from wtforms import FileField
from wtforms import SelectField
from wtforms import PasswordField
from wtforms.validators import Email, Length, Required
from wtforms.fields.html5 import DateField
class registroCliente(FlaskForm):
numeroIdCliente = IntegerField('Numero Identificacion', validators=[
Required(message='El campo es obligatorio'),
Length(max=10, min=6, message='El campo debe tener entre 6 y 10 caracteres')
])
tipoId = SelectField('Tipo Idenficacion', choices=[
('CC','Cedula de Ciudadania'),
('CE','Cedula de Extrangeria'),
('PA','Pasaporte'),
('RC','Registro Civil'),
('TI','Tarjeta de Identidad')], validators=[
Required(message='El campo es obligatorio'),
])
fechaExpIdCliente = DateField('Fecha Expedicion Documento Identidad', format='%Y,%M,%D')
lugarExpIdCliente = SelectField('Ciudad Expedicion Documento Identidad', choices=[
(5001,'Medellín'),
(5002,'Abejorral'),
(5004,'Abriaquí'),
(5021,'Alejandría'),
(5030,'Amagá'),
(5031,'Amalfi'),
(5034,'Andes'),
(5036,'Angelópolis'),
(5038,'Angostura'),
(5040,'Anorí'),
(5042,'Santafé De Antioquia'),
(5044,'Anza'),
(5045,'Apartadó'),
(5051,'Arboletes'),
(5055,'Argelia'),
(5059,'Armenia'),
(5079,'Barbosa'),
(5086,'Belmira'),
(5088,'Bello'),
(5091,'Betania'),
(5093,'Betulia'),
(5101,'Ciudad Bolívar'),
(5107,'Briceño'),
(5113,'Buriticá'),
(5120,'Cáceres'),
(5125,'Caicedo'),
(5129,'Caldas'),
(5134,'Campamento'),
(5138,'Cañasgordas'),
(5142,'Caracolí'),
(5145,'Caramanta'),
(5147,'Carepa'),
(5148,'El Carmen De Viboral'),
(5150,'Carolina'),
(5154,'Caucasia'),
(5172,'Chigorodó'),
(5190,'Cisneros'),
(5197,'Cocorná'),
(5206,'Concepción'),
(5209,'Concordia'),
(5212,'Copacabana'),
(5234,'Dabeiba'),
(5237,'Don Matías'),
(5240,'Ebéjico'),
(5250,'El Bagre'),
(5264,'Entrerrios'),
(5266,'Envigado'),
(5282,'Fredonia'),
(5284,'Frontino'),
(5306,'Giraldo'),
(5308,'Girardota'),
(5310,'Gómez Plata'),
(5313,'Granada'),
(5315,'Guadalupe'),
(5318,'Guarne'),
(5321,'Guatape'),
(5347,'Heliconia'),
(5353,'Hispania'),
(5360,'Itagui'),
(5361,'Ituango'),
(5364,'Jardín'),
(5368,'Jericó'),
(5376,'La Ceja'),
(5380,'La Estrella'),
(5390,'La Pintada'),
(5400,'La Unión'),
(5411,'Liborina'),
(5425,'Maceo'),
(5440,'Marinilla'),
(5467,'Montebello'),
(5475,'Murindó'),
(5480,'Mutatá'),
(5483,'Nariño'),
(5490,'Necoclí'),
(5495,'Nechí'),
(5501,'Olaya'),
(5541,'Peñol'),
(5543,'Peque'),
(5576,'Pueblorrico'),
(5579,'Puerto Berrío'),
(5585,'Puerto Nare'),
(5591,'Puerto Triunfo'),
(5604,'Remedios'),
(5607,'Retiro'),
(5615,'Rionegro'),
(5628,'Sabanalarga'),
(5631,'Sabaneta'),
(5642,'Salgar'),
(5647,'San Andrés De Cuerquía'),
(5649,'San Carlos'),
(5652,'San Francisco'),
(5656,'San Jerónimo'),
(5658,'San José De La Montaña'),
(5659,'San Juan De Urabá'),
(5660,'San Luis'),
(5664,'San Pedro'),
(5665,'San Pedro De Uraba'),
(5667,'San Rafael'),
(5670,'San Roque'),
(5674,'San Vicente'),
(5679,'Santa Bárbara'),
(5686,'Santa Rosa De Osos'),
(5690,'Santo Domingo'),
(5697,'El Santuario'),
(5736,'Segovia'),
(5756,'Sonson'),
(5761,'Sopetrán'),
(5789,'Támesis'),
(5790,'Tarazá'),
(5792,'Tarso'),
(5809,'Titiribí'),
(5819,'Toledo'),
(5837,'Turbo'),
(5842,'Uramita'),
(5847,'Urrao'),
(5854,'Valdivia'),
(5856,'Valparaíso'),
(5858,'Vegachí'),
(5861,'Venecia'),
(5873,'Vigía Del Fuerte'),
(5885,'Yalí'),
(5887,'Yarumal'),
(5890,'Yolombó'),
(5893,'Yondó'),
(5895,'Zaragoza'),
(8001,'Barranquilla'),
(8078,'Baranoa'),
(8137,'Campo De La Cruz'),
(8141,'Candelaria'),
(8296,'Galapa'),
(8372,'Juan De Acosta'),
(8421,'Luruaco'),
(8433,'Malambo'),
(8436,'Manatí'),
(8520,'Palmar De Varela'),
(8549,'Piojó'),
(8558,'Polonuevo'),
(8560,'Ponedera'),
(8573,'Puerto Colombia'),
(8606,'Repelón'),
(8634,'Sabanagrande'),
(8638,'Sabanalarga'),
(8675,'Santa Lucía'),
(8685,'Santo Tomás'),
(8758,'Soledad'),
(8770,'Suan'),
(8832,'Tubará'),
(8849,'Usiacurí'),
(11001,'Bogota DC'),
(13001,'Cartagena'),
(13006,'Choachí'),
(13030,'Altos Del Rosario'),
(13042,'Arenal'),
(13052,'Arjona'),
(13062,'Arroyohondo'),
(13074,'Barranco De Loba'),
(13140,'Calamar'),
(13160,'Cantagallo'),
(13188,'Cicuco'),
(13212,'Córdoba'),
(13222,'Clemencia'),
(13244,'El Carmen De Bolívar'),
(13248,'El Guamo'),
(13268,'El Peñón'),
(13300,'Hatillo De Loba'),
(13430,'Magangué'),
(13433,'Mahates'),
(13440,'Margarita'),
(13442,'María La Baja'),
(13458,'Montecristo'),
(13468,'Mompós'),
(13473,'Morales'),
(13549,'Pinillos'),
(13580,'Regidor'),
(13600,'Río Viejo'),
(13620,'San Cristóbal'),
(13647,'San Estanislao'),
(13650,'San Fernando'),
(13654,'San Jacinto'),
(13655,'San Jacinto Del Cauca'),
(13657,'San Juan Nepomuceno'),
(13667,'San Martín De Loba'),
(13670,'San Pablo'),
(13673,'Santa Catalina'),
(13683,'Santa Rosa'),
(13688,'Santa Rosa Del Sur'),
(13744,'Simití'),
(13760,'Soplaviento'),
(13780,'Talaigua Nuevo'),
(13810,'Tiquisio'),
(13836,'Turbaco'),
(13838,'Turbaná'),
(13873,'Villanueva'),
(13894,'Zambrano'),
(15001,'Tunja'),
(15022,'Almeida'),
(15047,'Aquitania'),
(15051,'Arcabuco'),
(15087,'Belén'),
(15090,'Berbeo'),
(15092,'Betéitiva'),
(15097,'Boavita'),
(15104,'Boyacá'),
(15106,'Briceño'),
(15109,'Buenavista'),
(15114,'Busbanzá'),
(15131,'Caldas'),
(15135,'Campohermoso'),
(15162,'Cerinza'),
(15172,'Chinavita'),
(15176,'Chiquinquirá'),
(15180,'Chiscas'),
(15183,'Chita'),
(15185,'Chitaraque'),
(15187,'Chivatá'),
(15189,'Ciénega'),
(15204,'Cómbita'),
(15212,'Coper'),
(15215,'Corrales'),
(15218,'Covarachía'),
(15223,'Cubará'),
(15224,'Cucaita'),
(15226,'Cuítiva'),
(15232,'Chíquiza'),
(15236,'Chivor'),
(15238,'Duitama'),
(15244,'El Cocuy'),
(15248,'El6Aspino'),
(15272,'Firavitoba'),
(15276,'Floresta'),
(15293,'Gachantivá'),
(15296,'Gameza'),
(15299,'Garagoa'),
(15317,'Guacamayas'),
(15322,'Guateque'),
(15325,'Guayatá'),
(15332,'Guican'),
(15362,'Iza'),
(15367,'Jenesano'),
(15368,'Jericó'),
(15377,'Labranzagrande'),
(15380,'La Capilla'),
(15401,'La Victoria'),
(15403,'La Uvita'),
(15407,'Villa De Leyva'),
(15425,'Macanal'),
(15442,'Maripí'),
(15455,'Miraflores'),
(15464,'Mongua'),
(15466,'Monguí'),
(15469,'Moniquirá'),
(15476,'Motavita'),
(15480,'Muzo'),
(15491,'Nobsa'),
(15494,'Nuevo Colón'),
(15500,'Oicatá'),
(15507,'Otanche'),
(15511,'Pachavita'),
(15514,'Páez'),
(15516,'Paipa'),
(15518,'Pajarito'),
(15522,'Panqueba'),
(15531,'Pauna'),
(15533,'Paya'),
(15537,'Paz De Río'),
(15542,'Pesca'),
(15550,'Pisba'),
(15572,'Puerto Boyacá'),
(15580,'Quípama'),
(15599,'Ramiriquí'),
(15600,'Ráquira'),
(15621,'Rondón'),
(15632,'Saboyá'),
(15638,'Sáchica'),
(15646,'Samacá'),
(15660,'San Eduardo'),
(15664,'San José De Pare'),
(15667,'San Luis De Gaceno'),
(15673,'San Mateo'),
(15676,'San Miguel De Sema'),
(15681,'San Pablo De Borbur'),
(15686,'Santana'),
(15690,'Santa María'),
(15693,'Santa Rosa De Viterbo'),
(15696,'Santa Sofía'),
(15720,'Sativanorte'),
(15723,'Sativasur'),
(15740,'Siachoque'),
(15753,'Soatá'),
(15755,'Socotá'),
(15757,'Socha'),
(15759,'Sogamoso'),
(15761,'Somondoco'),
(15762,'Sora'),
(15763,'Sotaquirá'),
(15764,'Soracá'),
(15774,'Susacón'),
(15776,'Sutamarchán'),
(15778,'Sutatenza'),
(15790,'Tasco'),
(15798,'Tenza'),
(15804,'Tibaná'),
(15806,'Tibasosa'),
(15808,'Tinjacá'),
(15810,'Tipacoque'),
(15814,'Toca'),
(15816,'Togüí'),
(15820,'Tópaga'),
(15822,'Tota'),
(15832,'Tununguá'),
(15835,'Turmequé'),
(15837,'Tuta'),
(15839,'Tutazá'),
(15842,'Umbita'),
(15861,'Ventaquemada'),
(15879,'Viracachá'),
(15897,'Zetaquira'),
(17001,'Manizales'),
(17013,'Aguadas'),
(17042,'Anserma'),
(17050,'Aranzazu'),
(17088,'Belalcázar'),
(17174,'Chinchiná'),
(17272,'Filadelfia'),
(17380,'La Dorada'),
(17388,'La Merced'),
(17433,'Manzanares'),
(17442,'Marmato'),
(17444,'Marquetalia'),
(17446,'Marulanda'),
(17486,'Neira'),
(17495,'Norcasia'),
(17513,'Pácora'),
(17524,'Palestina'),
(17541,'Pensilvania'),
(17614,'Riosucio'),
(17616,'Risaralda'),
(17653,'Salamina'),
(17662,'Samaná'),
(17665,'San José'),
(17777,'Supía'),
(17867,'Victoria'),
(17873,'Villamaría'),
(17877,'Viterbo'),
(18001,'Florencia'),
(18029,'Albania'),
(18094,'Belén De Los Andaquies'),
(18150,'Cartagena Del Chairá'),
(18205,'Curillo'),
(18247,'El Doncello'),
(18256,'El Paujil'),
(18410,'La Montañita'),
(18460,'Milán'),
(18479,'Morelia'),
(18592,'Puerto Rico'),
(18610,'San José Del Fragua'),
(18753,'San Vicente Del Caguán'),
(18756,'Solano'),
(18785,'Solita'),
(18860,'Valparaíso'),
(19001,'Popayán'),
(19022,'Almaguer'),
(19050,'Argelia'),
(19075,'Balboa'),
(19100,'Bolívar'),
(19110,'Buenos Aires'),
(19130,'Cajibío'),
(19137,'Caldono'),
(19142,'Caloto'),
(19212,'Corinto'),
(19256,'El Tambo'),
(19290,'Florencia'),
(19300,'Guachené'),
(19318,'Guapi'),
(19355,'Inzá'),
(19364,'Jambaló'),
(19392,'La Sierra'),
(19397,'La Vega'),
(19418,'López'),
(19450,'Mercaderes'),
(19455,'Miranda'),
(19473,'Morales'),
(19513,'Padilla'),
(19517,'Paez'),
(19532,'Patía'),
(19533,'Piamonte'),
(19548,'Piendamó'),
(19573,'Puerto Tejada'),
(19585,'Puracé'),
(19622,'Rosas'),
(19693,'San Sebastián'),
(19698,'Santander De Quilichao'),
(19701,'Santa Rosa'),
(19743,'Silvia'),
(19760,'Sotara'),
(19780,'Suárez'),
(19785,'Sucre'),
(19807,'Timbío'),
(19809,'Timbiquí'),
(19821,'Toribio'),
(19824,'Totoró'),
(19845,'Villa Rica'),
(20001,'Valledupar'),
(20011,'Aguachica'),
(20013,'Agustín Codazzi'),
(20032,'Astrea'),
(20045,'Becerril'),
(20060,'Bosconia'),
(20175,'Chimichagua'),
(20178,'Chiriguaná'),
(20228,'Curumaní'),
(20238,'El Copey'),
(20250,'El Paso'),
(20295,'Gamarra'),
(20310,'González'),
(20383,'La Gloria'),
(20400,'La Jagua De Ibirico'),
(20443,'Manaure'),
(20517,'Pailitas'),
(20550,'Pelaya'),
(20570,'Pueblo Bello'),
(20614,'Río De Oro'),
(20621,'La Paz'),
(20710,'San Alberto'),
(20750,'San Diego'),
(20770,'San Martín'),
(20787,'Tamalameque'),
(23001,'Montería'),
(23068,'Ayapel'),
(23079,'Buenavista'),
(23090,'Canalete'),
(23162,'Cereté'),
(23168,'Chimá'),
(23182,'Chinú'),
(23189,'Ciénaga De Oro'),
(23300,'Cotorra'),
(23350,'La Apartada'),
(23417,'Lorica'),
(23419,'Los Córdobas'),
(23464,'Momil'),
(23466,'Montelíbano'),
(23500,'Moñitos'),
(23555,'Planeta Rica'),
(23570,'Pueblo Nuevo'),
(23574,'Puerto Escondido'),
(23580,'Puerto Libertador'),
(23586,'Purísima'),
(23660,'Sahagún'),
(23670,'San Andrés Sotavento'),
(23672,'San Antero'),
(23675,'San Bernardo Del Viento'),
(23678,'San Carlos'),
(23686,'San Pelayo'),
(23807,'Tierralta'),
(23855,'Valencia'),
(25001,'Agua De Dios'),
(25019,'Albán'),
(25035,'Anapoima'),
(25040,'Anolaima'),
(25053,'Arbeláez'),
(25086,'Beltrán'),
(25095,'Bituima'),
(25099,'Bojacá'),
(25120,'Cabrera'),
(25123,'Cachipay'),
(25126,'Cajicá'),
(25148,'Caparrapí'),
(25151,'Caqueza'),
(25154,'Carmen De Carupa'),
(25168,'Chaguaní'),
(25175,'Chía'),
(25178,'Chipaque'),
(25181,'Choachí'),
(25183,'Chocontá'),
(25200,'Cogua'),
(25214,'Cota'),
(25224,'Cucunuba'),
(25245,'El Colegio'),
(25258,'El Peñón'),
(25260,'El Rosal'),
(25269,'Facatativá'),
(25279,'Fomeque'),
(25281,'Fosca'),
(25286,'Funza'),
(25288,'Fúquene'),
(25290,'Fusagasugá'),
(25293,'Gachala'),
(25295,'Gachancipá'),
(25297,'Gachetá'),
(25299,'Gama'),
(25307,'Girardot'),
(25312,'Granada'),
(25317,'Guachetá'),
(25320,'Guaduas'),
(25322,'Guasca'),
(25324,'Guataquí'),
(25326,'Guatavita'),
(25328,'Guayabal De Siquima'),
(25335,'Guayabetal'),
(25339,'Gutiérrez'),
(25368,'Jerusalén'),
(25372,'Junín'),
(25377,'La Calera'),
(25386,'La Mesa'),
(25394,'La Palma'),
(25398,'La Peña'),
(25402,'La Vega'),
(25407,'Lenguazaque'),
(25426,'Macheta'),
(25430,'Madrid'),
(25436,'Manta'),
(25438,'Medina'),
(25473,'Mosquera'),
(25483,'Nariño'),
(25486,'Nemocón'),
(25488,'Nilo'),
(25489,'Nimaima'),
(25491,'Nocaima'),
(25506,'Venecia'),
(25513,'Pacho'),
(25518,'Paime'),
(25524,'Pandi'),
(25530,'Paratebueno'),
(25535,'Pasca'),
(25572,'Puerto Salgar'),
(25580,'Pulí'),
(25592,'Quebradanegra'),
(25594,'Quetame'),
(25596,'Quipile'),
(25599,'Apulo'),
(25612,'Ricaurte'),
(25645,'San Antonio Del Tequendama'),
(25649,'San Bernardo'),
(25653,'San Cayetano'),
(25658,'San Francisco'),
(25662,'San Juan De Río Seco'),
(25718,'Sasaima'),
(25736,'Sesquilé'),
(25740,'Sibaté'),
(25743,'Silvania'),
(25745,'Simijaca'),
(25754,'Soacha'),
(25758,'Sopó'),
(25769,'Subachoque'),
(25772,'Suesca'),
(25777,'Supatá'),
(25779,'Susa'),
(25781,'Sutatausa'),
(25785,'Tabio'),
(25793,'Tausa'),
(25797,'Tena'),
(25799,'Tenjo'),
(25805,'Tibacuy'),
(25807,'Tibirita'),
(25815,'Tocaima'),
(25817,'Tocancipá'),
(25823,'Topaipi'),
(25839,'Ubalá'),
(25841,'Ubaque'),
(25843,'Villa De San Diego De Ubate'),
(25845,'Une'),
(25851,'Útica'),
(25862,'Vergara'),
(25867,'Vianí'),
(25871,'Villagómez'),
(25873,'Villapinzón'),
(25875,'Villeta'),
(25878,'Viotá'),
(25885,'Yacopí'),
(25898,'Zipacón'),
(25899,'Zipaquirá'),
(27001,'Quibdó'),
(27006,'Acandí'),
(27025,'Alto Baudo'),
(27050,'Atrato'),
(27073,'Bagadó'),
(27075,'Bahía Solano'),
(27077,'Bajo Baudó'),
(27086,'Belén De Bajirá'),
(27099,'Bojaya'),
(27135,'El Cantón Del San Pablo'),
(27150,'Carmen Del Darien'),
(27160,'Cértegui'),
(27205,'Condoto'),
(27245,'El Carmen De Atrato'),
(27250,'El Litoral Del San Juan'),
(27361,'Istmina'),
(27372,'Juradó'),
(27413,'Lloró'),
(27425,'Medio Atrato'),
(27430,'Medio Baudó'),
(27450,'Medio San Juan'),
(27491,'Nóvita'),
(27495,'Nuquí'),
(27580,'Río Iro'),
(27600,'Río Quito'),
(27615,'Riosucio'),
(27660,'San José Del Palmar'),
(27745,'Sipí'),
(27787,'Tadó'),
(27800,'Unguía'),
(27810,'Unión Panamericana'),
(41001,'Neiva'),
(41006,'Acevedo'),
(41013,'Agrado'),
(41016,'Aipe'),
(41020,'Algeciras'),
(41026,'Altamira'),
(41078,'Baraya'),
(41132,'Campoalegre'),
(41206,'Colombia'),
(41244,'Elías'),
(41298,'Garzón'),
(41306,'Gigante'),
(41319,'Guadalupe'),
(41349,'Hobo'),
(41357,'Iquira'),
(41359,'Isnos'),
(41378,'La Argentina'),
(41396,'La Plata'),
(41483,'Nátaga'),
(41503,'Oporapa'),
(41518,'Paicol'),
(41524,'Palermo'),
(41530,'Palestina'),
(41548,'Pital'),
(41551,'Pitalito'),
(41615,'Rivera'),
(41660,'Saladoblanco'),
(41668,'San Agustín'),
(41676,'Santa María'),
(41770,'Suaza'),
(41791,'Tarqui'),
(41797,'Tesalia'),
(41799,'Tello'),
(41801,'Teruel'),
(41807,'Timana'),
(41872,'Villavieja'),
(41885,'Yaguará'),
(44001,'Riohacha'),
(44035,'Albania'),
(44078,'Barrancas'),
(44090,'Dibulla'),
(44098,'Distracción'),
(44110,'El Molino'),
(44279,'Fonseca'),
(44378,'Hatonuevo'),
(44420,'La Jagua Del Pilar'),
(44430,'Maicao'),
(44560,'Manaure'),
(44650,'San Juan Del Cesar'),
(44847,'Uribia'),
(44855,'Urumita'),
(44874,'Villanueva'),
(47001,'Santa Marta'),
(47030,'Algarrobo'),
(47053,'Aracataca'),
(47058,'Ariguaní'),
(47161,'Cerro San Antonio'),
(47170,'Chibolo'),
(47189,'Ciénaga'),
(47205,'Concordia'),
(47245,'El Banco'),
(47258,'El Piñon'),
(47268,'El Retén'),
(47288,'Fundación'),
(47318,'Guamal'),
(47460,'Nueva Granada'),
(47541,'Pedraza'),
(47545,'Pijiño Del Carmen'),
(47551,'Pivijay'),
(47555,'Plato'),
(47570,'Puebloviejo'),
(47605,'Remolino'),
(47660,'Sabanas De San Angel'),
(47675,'Salamina'),
(47692,'San Sebastián De Buenavista'),
(47703,'San Zenón'),
(47707,'Santa Ana'),
(47720,'Santa Bárbara De Pinto'),
(47745,'Sitionuevo'),
(47798,'Tenerife'),
(47960,'Zapayán'),
(47980,'Zona Bananera'),
(50001,'Villavicencio'),
(50006,'Acacías'),
(50110,'Barranca De Upía'),
(50124,'Cabuyaro'),
(50150,'Castilla La Nueva'),
(50223,'Cubarral'),
(50226,'Cumaral'),
(50245,'El Calvario'),
(50251,'El Castillo'),
(50270,'El Dorado'),
(50287,'Fuente De Oro'),
(50313,'Granada'),
(50318,'Guamal'),
(50325,'Mapiripán'),
(50330,'Mesetas'),
(50350,'La Macarena'),
(50370,'Uribe'),
(50400,'Lejanías'),
(50450,'Puerto Concordia'),
(50568,'Puerto Gaitán'),
(50573,'Puerto López'),
(50577,'Puerto Lleras'),
(50590,'Puerto Rico'),
(50606,'Restrepo'),
(50680,'San Carlos De Guaroa'),
(50683,'San Juan De Arama'),
(50686,'San Juanito'),
(50689,'San Martín'),
(50711,'Vistahermosa'),
(52001,'Pasto'),
(52019,'Albán'),
(52022,'Aldana'),
(52036,'Ancuya'),
(52051,'Arboleda'),
(52079,'Barbacoas'),
(52083,'Belén'),
(52110,'Buesaco'),
(52203,'Colón'),
(52207,'Consaca'),
(52210,'Contadero'),
(52215,'Córdoba'),
(52224,'Cuaspud'),
(52227,'Cumbal'),
(52233,'Cumbitara'),
(52240,'Chachagüí'),
(52250,'El Charco'),
(52254,'El Peñol'),
(52256,'El Rosario'),
(52258,'El Tablón De Gómez'),
(52260,'El Tambo'),
(52287,'Funes'),
(52317,'Guachucal'),
(52320,'Guaitarilla'),
(52323,'Gualmatán'),
(52352,'Iles'),
(52354,'Imués'),
(52356,'Ipiales'),
(52378,'La Cruz'),
(52381,'La Florida'),
(52385,'La Llanada'),
(52390,'La Tola'),
(52399,'La Unión'),
(52405,'Leiva'),
(52411,'Linares'),
(52418,'Los Andes'),
(52427,'Magüi'),
(52435,'Mallama'),
(52473,'Mosquera'),
(52480,'Nariño'),
(52490,'Olaya Herrera'),
(52506,'Ospina'),
(52520,'Francisco Pizarro'),
(52540,'Policarpa'),
(52560,'Potosí'),
(52565,'Providencia'),
(52573,'Puerres'),
(52585,'Pupiales'),
(52612,'Ricaurte'),
(52621,'Roberto Payán'),
(52678,'Samaniego'),
(52683,'Sandoná'),
(52685,'San Bernardo'),
(52687,'San Lorenzo'),
(52693,'San Pablo'),
(52694,'San Pedro De Cartago'),
(52696,'Santa Bárbara'),
(52699,'Santacruz'),
(52720,'Sapuyes'),
(52786,'Taminango'),
(52788,'Tangua'),
(52835,'San Andres De Tumaco'),
(52838,'Túquerres'),
(52885,'Yacuanquer'),
(54001,'Cúcuta'),
(54003,'Abrego'),
(54051,'Arboledas'),
(54099,'Bochalema'),
(54109,'Bucarasica'),
(54125,'Cácota'),
(54128,'Cachirá'),
(54172,'Chinácota'),
(54174,'Chitagá'),
(54206,'Convención'),
(54223,'Cucutilla'),
(54239,'Durania'),
(54245,'El Carmen'),
(54250,'El Tarra'),
(54261,'El Zulia'),
(54313,'Gramalote'),
(54344,'Hacarí'),
(54347,'Herrán'),
(54377,'Labateca'),
(54385,'La Esperanza'),
(54398,'La Playa'),
(54405,'Los Patios'),
(54418,'Lourdes'),
(54480,'Mutiscua'),
(54498,'Ocaña'),
(54518,'Pamplona'),
(54520,'Pamplonita'),
(54553,'Puerto Santander'),
(54599,'Ragonvalia'),
(54660,'Salazar'),
(54670,'San Calixto'),
(54673,'San Cayetano'),
(54680,'Santiago'),
(54720,'Sardinata'),
(54743,'Silos'),
(54800,'Teorama'),
(54810,'Tibú'),
(54820,'Toledo'),
(54871,'Villa Caro'),
(54874,'Villa Del Rosario'),
(63001,'Armenia'),
(63111,'Buenavista'),
(63130,'Calarca'),
(63190,'Circasia'),
(63212,'Córdoba'),
(63272,'Filandia'),
(63302,'Génova'),
(63401,'La Tebaida'),
(63470,'Montenegro'),
(63548,'Pijao'),
(63594,'Quimbaya'),
(63690,'Salento'),
(66001,'Pereira'),
(66045,'Apía'),
(66075,'Balboa'),
(66088,'Belén De Umbría'),
(66170,'Dosquebradas'),
(66318,'Guática'),
(66383,'La Celia'),
(66400,'La Virginia'),
(66440,'Marsella'),
(66456,'Mistrató'),
(66572,'Pueblo Rico'),
(66594,'Quinchía'),
(66682,'Santa Rosa De Cabal'),
(66687,'Santuario'),
(68001,'Bucaramanga'),
(68013,'Aguada'),
(68020,'Albania'),
(68051,'Aratoca'),
(68077,'Barbosa'),
(68079,'Barichara'),
(68081,'Barrancabermeja'),
(68092,'Betulia'),
(68101,'Bolívar'),
(68121,'Cabrera'),
(68132,'California'),
(68147,'Capitanejo'),
(68152,'Carcasí'),
(68160,'Cepitá'),
(68162,'Cerrito'),
(68167,'Charalá'),
(68169,'Charta'),
(68176,'Chima'),
(68179,'Chipatá'),
(68190,'Cimitarra'),
(68207,'Concepción'),
(68209,'Confines'),
(68211,'Contratación'),
(68217,'Coromoro'),
(68229,'Curití'),
(68235,'El Carmen De Chucurí'),
(68245,'El Guacamayo'),
(68250,'El Peñón'),
(68255,'El Playón'),
(68264,'Encino'),
(68266,'Enciso'),
(68271,'Florián'),
(68276,'Floridablanca'),
(68296,'Galan'),
(68298,'Gambita'),
(68307,'Girón'),
(68318,'Guaca'),
(68320,'Guadalupe'),
(68322,'Guapotá'),
(68324,'Guavatá'),
(68327,'Güepsa'),
(68344,'Hato'),
(68368,'Jesús María'),
(68370,'Jordán'),
(68377,'La Belleza'),
(68385,'Landázuri'),
(68397,'La Paz'),
(68406,'Lebríja'),
(68418,'Los Santos'),
(68425,'Macaravita'),
(68432,'Málaga'),
(68444,'Matanza'),
(68464,'Mogotes'),
(68468,'Molagavita'),
(68498,'Ocamonte'),
(68500,'Oiba'),
(68502,'Onzaga'),
(68522,'Palmar'),
(68524,'Palmas Del Socorro'),
(68533,'Páramo'),
(68547,'Piedecuesta'),
(68549,'Pinchote'),
(68572,'Puente Nacional'),
(68573,'Puerto Parra'),
(68575,'Puerto Wilches'),
(68615,'Rionegro'),
(68655,'Sabana De Torres'),
(68669,'San Andrés'),
(68673,'San Benito'),
(68679,'San Gil'),
(68682,'San Joaquín'),
(68684,'San José De Miranda'),
(68686,'San Miguel'),
(68689,'San Vicente De Chucurí'),
(68705,'Santa Bárbara'),
(68720,'Santa Helena Del Opón'),
(68745,'Simacota'),
(68755,'Socorro'),
(68770,'Suaita'),
(68773,'Sucre'),
(68780,'Suratá'),
(68820,'Tona'),
(68855,'Valle De San José'),
(68861,'Vélez'),
(68867,'Vetas'),
(68872,'Villanueva'),
(68895,'Zapatoca'),
(70001,'Sincelejo'),
(70110,'Buenavista'),
(70124,'Caimito'),
(70204,'Coloso'),
(70215,'Corozal'),
(70221,'Coveñas'),
(70230,'Chalán'),
(70233,'El Roble'),
(70235,'Galeras'),
(70265,'Guaranda'),
(70400,'La Unión'),
(70418,'Los Palmitos'),
(70429,'Majagual'),
(70473,'Morroa'),
(70508,'Ovejas'),
(70523,'Palmito'),
(70670,'Sampués'),
(70678,'San Benito Abad'),
(70702,'San Juan De Betulia'),
(70708,'San Marcos'),
(70713,'San Onofre'),
(70717,'San Pedro'),
(70742,'San Luis De Sincé'),
(70771,'Sucre'),
(70820,'Santiago De Tolú'),
(70823,'Tolú Viejo'),
(73001,'Ibague'),
(73024,'Alpujarra'),
(73026,'Alvarado'),
(73030,'Ambalema'),
(73043,'Anzoátegui'),
(73055,'Armero'),
(73067,'Ataco'),
(73124,'Cajamarca'),
(73148,'Carmen De Apicalá'),
(73152,'Casabianca'),
(73168,'Chaparral'),
(73200,'Coello'),
(73217,'Coyaima'),
(73226,'Cunday'),
(73236,'Dolores'),
(73268,'Espinal'),
(73270,'Falan'),
(73275,'Flandes'),
(73283,'Fresno'),
(73319,'Guamo'),
(73347,'Herveo'),
(73349,'Honda'),
(73352,'Icononzo'),
(73408,'Lérida'),
(73411,'Líbano'),
(73443,'Mariquita'),
(73449,'Melgar'),
(73461,'Murillo'),
(73483,'Natagaima'),
(73504,'Ortega'),
(73520,'Palocabildo'),
(73547,'Piedras'),
(73555,'Planadas'),
(73563,'Prado'),
(73585,'Purificación'),
(73616,'Rioblanco'),
(73622,'Roncesvalles'),
(73624,'Rovira'),
(73671,'Saldaña'),
(73675,'San Antonio'),
(73678,'San Luis'),
(73686,'Santa Isabel'),
(73770,'Suárez'),
(73854,'Valle De San Juan'),
(73861,'Venadillo'),
(73870,'Villahermosa'),
(73873,'Villarrica'),
(76001,'Cali'),
(76020,'Alcalá'),
(76036,'Andalucía'),
(76041,'Ansermanuevo'),
(76054,'Argelia'),
(76100,'Bolívar'),
(76109,'Buenaventura'),
(76111,'Guadalajara De Buga'),
(76113,'Bugalagrande'),
(76122,'Caicedonia'),
(76126,'Calima'),
(76130,'Candelaria'),
(76147,'Cartago'),
(76233,'Dagua'),
(76243,'El Águila'),
(76246,'El Cairo'),
(76248,'El Cerrito'),
(76250,'El Dovio'),
(76275,'Florida'),
(76306,'Ginebra'),
(76318,'Guacarí'),
(76364,'Jamundí'),
(76377,'La Cumbre'),
(76400,'La Unión'),
(76403,'La Victoria'),
(76497,'Obando'),
(76520,'Palmira'),
(76563,'Pradera'),
(76606,'Restrepo'),
(76616,'Riofrío'),
(76622,'Roldanillo'),
(76670,'San Pedro'),
(76736,'Sevilla'),
(76823,'Toro'),
(76828,'Trujillo'),
(76834,'Tuluá'),
(76845,'Ulloa'),
(76863,'Versalles'),
(76869,'Vijes'),
(76890,'Yotoco'),
(76892,'Yumbo'),
(76895,'Zarzal'),
(81001,'Arauca'),
(81065,'Arauquita'),
(81220,'Cravo Norte'),
(81300,'Fortul'),
(81591,'Puerto Rondón'),
(81736,'Saravena'),
(81794,'Tame'),
(85001,'Yopal'),
(85010,'Aguazul'),
(85015,'Chameza'),
(85125,'Hato Corozal'),
(85136,'La Salina'),
(85139,'Maní'),
(85162,'Monterrey'),
(85225,'Nunchía'),
(85230,'Orocué'),
(85250,'Paz De Ariporo'),
(85263,'Pore'),
(85279,'Recetor'),
(85300,'Sabanalarga'),
(85315,'Sácama'),
(85325,'San Luis De Palenque'),
(85400,'Támara'),
(85410,'Tauramena'),
(85430,'Trinidad'),
(85440,'Villanueva'),
(86001,'Mocoa'),
(86219,'Colón'),
(86320,'Orito'),
(86568,'Puerto Asís'),
(86569,'Puerto Caicedo'),
(86571,'Puerto Guzmán'),
(86573,'Leguízamo'),
(86749,'Sibundoy'),
(86755,'San Francisco'),
(86757,'San Miguel'),
(86760,'Santiago'),
(86865,'Valle Del Guamuez'),
(86885,'Villagarzón'),
(88001,'San Andrés'),
(88564,'Providencia'),
(91001,'Leticia'),
(91263,'El Encanto'),
(91405,'La Chorrera'),
(91407,'La Pedrera'),
(91430,'La Victoria'),
(91460,'Miriti - Paraná'),
(91530,'Puerto Alegría'),
(91536,'Puerto Arica'),
(91540,'Puerto Nariño'),
(91669,'Puerto Santander'),
(91798,'Tarapacá'),
(94001,'Inírida'),
(94343,'Barranco Minas'),
(94663,'Mapiripana'),
(94883,'San Felipe'),
(94884,'Puerto Colombia'),
(94885,'La Guadalupe'),
(94886,'Cacahual'),
(94887,'Pana Pana'),
(94888,'Morichal'),
(95001,'San José Del Guaviare'),
(95015,'Calamar'),
(95025,'El Retorno'),
(95200,'Miraflores'),
(97001,'Mitú'),
(97161,'Caruru'),
(97511,'Pacoa'),
(97666,'Taraira'),
(97777,'Papunaua'),
(97889,'Yavaraté'),
(99001,'Puerto Carreño'),
(99524,'La Primavera'),
(99624,'Santa Rosalía'),
(99773,'Cumaribo')
], validators=[
Required()
])
primerNombreCliente = StringField('Primer Nombre', validators=[
Required(message='El campo es obligatorio'),
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
segundoNombreCliente = StringField('Segundo Nombre', validators=[
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
primerApellidoCliente = StringField('Primer Apellido', validators=[
Required(message='El campo es obligatorio'),
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
segundoApellidoCliente = StringField('Segundo Apellido', validators=[
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
fechaNacimientoCliente = DateField('Fecha de Nacimiento', format='%Y,%M,%D', validators=[])
direccionCliente = StringField('Direccion Residencia', validators=[
Required(message='El campo es obligatorio'),
Length(max=50, min=20, message='El campo debe tener entre 20 y 50 caracteres')
])
barrioCliente = StringField('Barrio Residencia', validators=[
Required(message='El campo es obligatorio'),
Length(max=20, min=10, message='El campo debe tener entre 10 y 20 caracteres')
])
idPais = SelectField('Pais Residencia', choices=[
('AD','Andorra'),
('AE','Emiratos Arabes Unid'),
('AF','Afganistan'),
('AG','Antigua Y Barbuda'),
('AI','Anguilla'),
('AL','Albania'),
('AM','Armenia'),
('AN','Antillas Holandesas'),
('AO','Angola'),
('AR','Argentina'),
('AS','Samoa Norteamericana'),
('AT','Austria'),
('AU','Australia'),
('AW','Aruba'),
('AZ','Azerbaijan'),
('BA','Bosnia-Herzegovina'),
('BB','Barbados'),
('BD','Bangladesh'),
('BE','Belgica'),
('BF','Burkina Fasso'),
('BG','Bulgaria'),
('BH','Bahrein'),
('BI','Burundi'),
('BJ','Benin'),
('BM','Bermudas'),
('BN','Brunei Darussalam'),
('BO','Bolivia'),
('BR','Brasil'),
('BS','Bahamas'),
('BT','Butan'),
('BW','Botswana'),
('BY','Belorus'),
('BZ','Belice'),
('CA','Canada'),
('CC','Cocos (Keeling) Islas'),
('CD','Republica Democratica Del Congo'),
('CF','Republica Centroafri'),
('CG','Congo'),
('CH','Suiza'),
('CI','Costa De Marfil'),
('CK','Cook Islas'),
('CL','Chile'),
('CM','Camerun Republica U'),
('CN','China'),
('CO','Colombia'),
('CR','Costa Rica'),
('CU','Cuba'),
('CV','Cabo Verde'),
('CX','Navidad (Christmas)'),
('CY','Chipre'),
('CZ','Republica Checa'),
('DE','Alemania'),
('DJ','Djibouti'),
('DK','Dinamarca'),
('DM','Dominica'),
('DO','Republica Dominicana'),
('DZ','Argelia'),
('EC','Ecuador'),
('EE','Estonia'),
('EG','Egipto'),
('EH','Sahara Occidental'),
('ER','Eritrea'),
('ES','España'),
('ET','Etiopia'),
('EU','Comunidad Europea'),
('FI','Finlandia'),
('FJ','Fiji'),
('FM','Micronesia Estados F'),
('FO','Feroe Islas'),
('FR','Francia'),
('GA','Gabon'),
('GB','Reino Unido'),
('GD','Granada'),
('GE','Georgia'),
('GF','Guayana Francesa'),
('GH','Ghana'),
('GI','Gibraltar'),
('GL','Groenlandia'),
('GM','Gambia'),
('GN','Guinea'),
('GP','Guadalupe'),
('GQ','Guinea Ecuatorial'),
('GR','Grecia'),
('GT','Guatemala'),
('GU','Guam'),
('GW','Guinea - Bissau'),
('GY','Guyana'),
('HK','Hong Kong'),
('HN','Honduras'),
('HR','Croacia'),
('HT','Haiti'),
('HU','Hungria'),
('ID','Indonesia'),
('IE','Irlanda (Eire)'),
('IL','Israel'),
('IM','Isla De Man'),
('IN','India'),
('IO','Territori Britanico'),
('IQ','Irak'),
('IR','Iran Republica Islamica'),
('IS','Islandia'),
('IT','Italia'),
('JM','Jamaica'),
('JO','Jordania'),
('JP','Japon'),
('KE','Kenya'),
('KG','Kirguizistan'),
('KH','Kampuchea (Camboya)'),
('KI','Kiribati'),
('KM','Comoras'),
('KN','San Cristobal Y Nieves'),
('KP','Corea Del Norte Republica'),
('KR','Corea Del Sur Republica'),
('KW','Kuwait'),
('KY','Caiman Islas'),
('KZ','Kazajstan'),
('LA','Laos Republica Popular'),
('LB','Libano'),
('LC','Santa Lucia'),
('LI','Liechtenstein'),
('LK','Sri Lanka'),
('LR','Liberia'),
('LS','Lesotho'),
('LT','Lituania'),
('LU','Luxemburgo'),
('LV','Letonia'),
('LY','Libia(Incluye Fezzan'),
('MA','Marruecos'),
('MC','Monaco'),
('MD','Moldavia'),
('MG','Madagascar'),
('MH','Marshall Islas'),
('MK','Macedonia'),
('ML','Mali'),
('MM','Birmania (Myanmar)'),
('MN','Mongolia'),
('MO','Macao'),
('MP','Marianas Del Norte Islas'),
('MQ','Martinica'),
('MR','Mauritania'),
('MS','Monserrat Islas'),
('MT','Malta'),
('MU','Mauricio'),
('MV','Maldivas'),
('MW','Malawi'),
('MX','Mexico'),
('MY','Malasia'),
('MZ','Mozambique'),
('NA','Namibia'),
('NC','Nueva Caledonia'),
('NE','Niger'),
('NF','Norfolk Isla'),
('NG','Nigeria'),
('NI','Nicaragua'),
('NL','Paises Bajos(Holanda'),
('NO','Noruega'),
('NP','Nepal'),
('NR','Nauru'),
('NU','Nive Isla'),
('NZ','Nueva Zelandia'),
('OM','Oman'),
('PA','Panama'),
('PE','Peru'),
('PF','Polinesia Francesa'),
('PG','Papuasia Nuev Guinea'),
('PH','Filipinas'),
('PK','Pakistan'),
('PL','Polonia'),
('PM','San Pedro Y Miguelon'),
('PN','Pitcairn Isla'),
('PR','Puerto Rico'),
('PS','Palestina'),
('PT','Portugal'),
('PW','Palau Islas'),
('PY','Paraguay'),
('QA','Qatar'),
('RE','Reunion'),
('RO','Rumania'),
('RS','Serbia'),
('RU','Rusia'),
('RW','Rwanda'),
('SA','Arabia Saudita'),
('SB','Salomsn Islas'),
('SC','Seychelles'),
('SD','Sudan'),
('SE','Suecia'),
('SG','Singapur'),
('SH','Santa Elena'),
('SI','Eslovenia'),
('SK','Eslovaquia'),
('SL','Sierra Leona'),
('SM','San Marino'),
('SN','Senegal'),
('SO','Somalia'),
('SR','Surinam'),
('ST','Santo Tome Y Princip'),
('SV','El Salvador'),
('SY','Siria Republica Arabe'),
('SZ','Swazilandia'),
('TC','Turcas Y Caicos Isla'),
('TD','Chad'),
('TG','Togo'),
('TH','Tailandia'),
('TJ','Tadjikistan'),
('TK','Tokelau'),
('TL','Timor Del Este'),
('TM','Turkmenistan'),
('TN','Tunicia'),
('TO','Tonga'),
('TR','Turquia'),
('TT','Trinidad Y Tobago'),
('TV','Tuvalu'),
('TW','Taiwan (Formosa)'),
('TZ','Tanzania Republica'),
('UA','Ucrania'),
('UG','Uganda'),
('UM','Islas Menores De Estados Unidos'),
('UN','Niue Isla'),
('US','Estados Unidos'),
('UY','Uruguay'),
('UZ','Uzbekistan'),
('VA','Ciudad Del Vaticano'),
('VC','San Vicente Y Las Gr'),
('VE','Venezuela'),
('VG','Virgenes Islas Britanicas'),
('VI','Virgenes Islas'),
('VN','Vietnam'),
('VU','Vanuatu'),
('WF','Wallis Y Fortuna Islas'),
('WS','Samoa'),
('YE','Yemen'),
('YU','Yugoslavia'),
('ZA','Sudafrica Republica'),
('ZM','Zambia'),
('ZW','Zimbabwe')
], validate_choice=True)
idDepartamento = SelectField('Departamento Residencia', choices=[
(5,'Antioquia'),
(8,'Atlántico'),
(11,'Bogotá DC'),
(13,'Bolívar'),
(15,'Boyacá'),
(17,'Caldas'),
(18,'Caquetá'),
(19,'Cauca'),
(20,'Cesar'),
(23,'Córdoba'),
(25,'Cundinamarca'),
(27,'Chocó'),
(41,'Huila'),
(44,'La Guajira'),
(47,'Magdalena'),
(50,'Meta'),
(52,'Nariño'),
(54,'Norte de Santander'),
(63,'Quindío'),
(66,'Risaralda'),
(68,'Santander'),
(70,'Sucre'),
(73,'Tolima'),
(76,'Valle del Cauca'),
(81,'Arauca'),
(85,'Casanare'),
(86,'Putumayo'),
(88,'San Andres'),
(91,'Amazonas'),
(94,'Guainía'),
(95,'Guaviare'),
(97,'Vaupés'),
(99,'Vichada'),
], validate_choice=True)
idMunicipio = SelectField('Municipio Residencia', choices=[
(5001,'Medellín'),
(5002,'Abejorral'),
(5004,'Abriaquí'),
(5021,'Alejandría'),
(5030,'Amagá'),
(5031,'Amalfi'),
(5034,'Andes'),
(5036,'Angelópolis'),
(5038,'Angostura'),
(5040,'Anorí'),
(5042,'Santafé De Antioquia'),
(5044,'Anza'),
(5045,'Apartadó'),
(5051,'Arboletes'),
(5055,'Argelia'),
(5059,'Armenia'),
(5079,'Barbosa'),
(5086,'Belmira'),
(5088,'Bello'),
(5091,'Betania'),
(5093,'Betulia'),
(5101,'Ciudad Bolívar'),
(5107,'Briceño'),
(5113,'Buriticá'),
(5120,'Cáceres'),
(5125,'Caicedo'),
(5129,'Caldas'),
(5134,'Campamento'),
(5138,'Cañasgordas'),
(5142,'Caracolí'),
(5145,'Caramanta'),
(5147,'Carepa'),
(5148,'El Carmen De Viboral'),
(5150,'Carolina'),
(5154,'Caucasia'),
(5172,'Chigorodó'),
(5190,'Cisneros'),
(5197,'Cocorná'),
(5206,'Concepción'),
(5209,'Concordia'),
(5212,'Copacabana'),
(5234,'Dabeiba'),
(5237,'Don Matías'),
(5240,'Ebéjico'),
(5250,'El Bagre'),
(5264,'Entrerrios'),
(5266,'Envigado'),
(5282,'Fredonia'),
(5284,'Frontino'),
(5306,'Giraldo'),
(5308,'Girardota'),
(5310,'Gómez Plata'),
(5313,'Granada'),
(5315,'Guadalupe'),
(5318,'Guarne'),
(5321,'Guatape'),
(5347,'Heliconia'),
(5353,'Hispania'),
(5360,'Itagui'),
(5361,'Ituango'),
(5364,'Jardín'),
(5368,'Jericó'),
(5376,'La Ceja'),
(5380,'La Estrella'),
(5390,'La Pintada'),
(5400,'La Unión'),
(5411,'Liborina'),
(5425,'Maceo'),
(5440,'Marinilla'),
(5467,'Montebello'),
(5475,'Murindó'),
(5480,'Mutatá'),
(5483,'Nariño'),
(5490,'Necoclí'),
(5495,'Nechí'),
(5501,'Olaya'),
(5541,'Peñol'),
(5543,'Peque'),
(5576,'Pueblorrico'),
(5579,'Puerto Berrío'),
(5585,'Puerto Nare'),
(5591,'Puerto Triunfo'),
(5604,'Remedios'),
(5607,'Retiro'),
(5615,'Rionegro'),
(5628,'Sabanalarga'),
(5631,'Sabaneta'),
(5642,'Salgar'),
(5647,'San Andrés De Cuerquía'),
(5649,'San Carlos'),
(5652,'San Francisco'),
(5656,'San Jerónimo'),
(5658,'San José De La Montaña'),
(5659,'San Juan De Urabá'),
(5660,'San Luis'),
(5664,'San Pedro'),
(5665,'San Pedro De Uraba'),
(5667,'San Rafael'),
(5670,'San Roque'),
(5674,'San Vicente'),
(5679,'Santa Bárbara'),
(5686,'Santa Rosa De Osos'),
(5690,'Santo Domingo'),
(5697,'El Santuario'),
(5736,'Segovia'),
(5756,'Sonson'),
(5761,'Sopetrán'),
(5789,'Támesis'),
(5790,'Tarazá'),
(5792,'Tarso'),
(5809,'Titiribí'),
(5819,'Toledo'),
(5837,'Turbo'),
(5842,'Uramita'),
(5847,'Urrao'),
(5854,'Valdivia'),
(5856,'Valparaíso'),
(5858,'Vegachí'),
(5861,'Venecia'),
(5873,'Vigía Del Fuerte'),
(5885,'Yalí'),
(5887,'Yarumal'),
(5890,'Yolombó'),
(5893,'Yondó'),
(5895,'Zaragoza'),
(8001,'Barranquilla'),
(8078,'Baranoa'),
(8137,'Campo De La Cruz'),
(8141,'Candelaria'),
(8296,'Galapa'),
(8372,'Juan De Acosta'),
(8421,'Luruaco'),
(8433,'Malambo'),
(8436,'Manatí'),
(8520,'Palmar De Varela'),
(8549,'Piojó'),
(8558,'Polonuevo'),
(8560,'Ponedera'),
(8573,'Puerto Colombia'),
(8606,'Repelón'),
(8634,'Sabanagrande'),
(8638,'Sabanalarga'),
(8675,'Santa Lucía'),
(8685,'Santo Tomás'),
(8758,'Soledad'),
(8770,'Suan'),
(8832,'Tubará'),
(8849,'Usiacurí'),
(11001,'Bogota DC'),
(13001,'Cartagena'),
(13006,'Choachí'),
(13030,'Altos Del Rosario'),
(13042,'Arenal'),
(13052,'Arjona'),
(13062,'Arroyohondo'),
(13074,'Barranco De Loba'),
(13140,'Calamar'),
(13160,'Cantagallo'),
(13188,'Cicuco'),
(13212,'Córdoba'),
(13222,'Clemencia'),
(13244,'El Carmen De Bolívar'),
(13248,'El Guamo'),
(13268,'El Peñón'),
(13300,'Hatillo De Loba'),
(13430,'Magangué'),
(13433,'Mahates'),
(13440,'Margarita'),
(13442,'María La Baja'),
(13458,'Montecristo'),
(13468,'Mompós'),
(13473,'Morales'),
(13549,'Pinillos'),
(13580,'Regidor'),
(13600,'Río Viejo'),
(13620,'San Cristóbal'),
(13647,'San Estanislao'),
(13650,'San Fernando'),
(13654,'San Jacinto'),
(13655,'San Jacinto Del Cauca'),
(13657,'San Juan Nepomuceno'),
(13667,'San Martín De Loba'),
(13670,'San Pablo'),
(13673,'Santa Catalina'),
(13683,'Santa Rosa'),
(13688,'Santa Rosa Del Sur'),
(13744,'Simití'),
(13760,'Soplaviento'),
(13780,'Talaigua Nuevo'),
(13810,'Tiquisio'),
(13836,'Turbaco'),
(13838,'Turbaná'),
(13873,'Villanueva'),
(13894,'Zambrano'),
(15001,'Tunja'),
(15022,'Almeida'),
(15047,'Aquitania'),
(15051,'Arcabuco'),
(15087,'Belén'),
(15090,'Berbeo'),
(15092,'Betéitiva'),
(15097,'Boavita'),
(15104,'Boyacá'),
(15106,'Briceño'),
(15109,'Buenavista'),
(15114,'Busbanzá'),
(15131,'Caldas'),
(15135,'Campohermoso'),
(15162,'Cerinza'),
(15172,'Chinavita'),
(15176,'Chiquinquirá'),
(15180,'Chiscas'),
(15183,'Chita'),
(15185,'Chitaraque'),
(15187,'Chivatá'),
(15189,'Ciénega'),
(15204,'Cómbita'),
(15212,'Coper'),
(15215,'Corrales'),
(15218,'Covarachía'),
(15223,'Cubará'),
(15224,'Cucaita'),
(15226,'Cuítiva'),
(15232,'Chíquiza'),
(15236,'Chivor'),
(15238,'Duitama'),
(15244,'El Cocuy'),
(15248,'El6Aspino'),
(15272,'Firavitoba'),
(15276,'Floresta'),
(15293,'Gachantivá'),
(15296,'Gameza'),
(15299,'Garagoa'),
(15317,'Guacamayas'),
(15322,'Guateque'),
(15325,'Guayatá'),
(15332,'Guican'),
(15362,'Iza'),
(15367,'Jenesano'),
(15368,'Jericó'),
(15377,'Labranzagrande'),
(15380,'La Capilla'),
(15401,'La Victoria'),
(15403,'La Uvita'),
(15407,'Villa De Leyva'),
(15425,'Macanal'),
(15442,'Maripí'),
(15455,'Miraflores'),
(15464,'Mongua'),
(15466,'Monguí'),
(15469,'Moniquirá'),
(15476,'Motavita'),
(15480,'Muzo'),
(15491,'Nobsa'),
(15494,'Nuevo Colón'),
(15500,'Oicatá'),
(15507,'Otanche'),
(15511,'Pachavita'),
(15514,'Páez'),
(15516,'Paipa'),
(15518,'Pajarito'),
(15522,'Panqueba'),
(15531,'Pauna'),
(15533,'Paya'),
(15537,'Paz De Río'),
(15542,'Pesca'),
(15550,'Pisba'),
(15572,'Puerto Boyacá'),
(15580,'Quípama'),
(15599,'Ramiriquí'),
(15600,'Ráquira'),
(15621,'Rondón'),
(15632,'Saboyá'),
(15638,'Sáchica'),
(15646,'Samacá'),
(15660,'San Eduardo'),
(15664,'San José De Pare'),
(15667,'San Luis De Gaceno'),
(15673,'San Mateo'),
(15676,'San Miguel De Sema'),
(15681,'San Pablo De Borbur'),
(15686,'Santana'),
(15690,'Santa María'),
(15693,'Santa Rosa De Viterbo'),
(15696,'Santa Sofía'),
(15720,'Sativanorte'),
(15723,'Sativasur'),
(15740,'Siachoque'),
(15753,'Soatá'),
(15755,'Socotá'),
(15757,'Socha'),
(15759,'Sogamoso'),
(15761,'Somondoco'),
(15762,'Sora'),
(15763,'Sotaquirá'),
(15764,'Soracá'),
(15774,'Susacón'),
(15776,'Sutamarchán'),
(15778,'Sutatenza'),
(15790,'Tasco'),
(15798,'Tenza'),
(15804,'Tibaná'),
(15806,'Tibasosa'),
(15808,'Tinjacá'),
(15810,'Tipacoque'),
(15814,'Toca'),
(15816,'Togüí'),
(15820,'Tópaga'),
(15822,'Tota'),
(15832,'Tununguá'),
(15835,'Turmequé'),
(15837,'Tuta'),
(15839,'Tutazá'),
(15842,'Umbita'),
(15861,'Ventaquemada'),
(15879,'Viracachá'),
(15897,'Zetaquira'),
(17001,'Manizales'),
(17013,'Aguadas'),
(17042,'Anserma'),
(17050,'Aranzazu'),
(17088,'Belalcázar'),
(17174,'Chinchiná'),
(17272,'Filadelfia'),
(17380,'La Dorada'),
(17388,'La Merced'),
(17433,'Manzanares'),
(17442,'Marmato'),
(17444,'Marquetalia'),
(17446,'Marulanda'),
(17486,'Neira'),
(17495,'Norcasia'),
(17513,'Pácora'),
(17524,'Palestina'),
(17541,'Pensilvania'),
(17614,'Riosucio'),
(17616,'Risaralda'),
(17653,'Salamina'),
(17662,'Samaná'),
(17665,'San José'),
(17777,'Supía'),
(17867,'Victoria'),
(17873,'Villamaría'),
(17877,'Viterbo'),
(18001,'Florencia'),
(18029,'Albania'),
(18094,'Belén De Los Andaquies'),
(18150,'Cartagena Del Chairá'),
(18205,'Curillo'),
(18247,'El Doncello'),
(18256,'El Paujil'),
(18410,'La Montañita'),
(18460,'Milán'),
(18479,'Morelia'),
(18592,'Puerto Rico'),
(18610,'San José Del Fragua'),
(18753,'San Vicente Del Caguán'),
(18756,'Solano'),
(18785,'Solita'),
(18860,'Valparaíso'),
(19001,'Popayán'),
(19022,'Almaguer'),
(19050,'Argelia'),
(19075,'Balboa'),
(19100,'Bolívar'),
(19110,'Buenos Aires'),
(19130,'Cajibío'),
(19137,'Caldono'),
(19142,'Caloto'),
(19212,'Corinto'),
(19256,'El Tambo'),
(19290,'Florencia'),
(19300,'Guachené'),
(19318,'Guapi'),
(19355,'Inzá'),
(19364,'Jambaló'),
(19392,'La Sierra'),
(19397,'La Vega'),
(19418,'López'),
(19450,'Mercaderes'),
(19455,'Miranda'),
(19473,'Morales'),
(19513,'Padilla'),
(19517,'Paez'),
(19532,'Patía'),
(19533,'Piamonte'),
(19548,'Piendamó'),
(19573,'Puerto Tejada'),
(19585,'Puracé'),
(19622,'Rosas'),
(19693,'San Sebastián'),
(19698,'Santander De Quilichao'),
(19701,'Santa Rosa'),
(19743,'Silvia'),
(19760,'Sotara'),
(19780,'Suárez'),
(19785,'Sucre'),
(19807,'Timbío'),
(19809,'Timbiquí'),
(19821,'Toribio'),
(19824,'Totoró'),
(19845,'Villa Rica'),
(20001,'Valledupar'),
(20011,'Aguachica'),
(20013,'Agustín Codazzi'),
(20032,'Astrea'),
(20045,'Becerril'),
(20060,'Bosconia'),
(20175,'Chimichagua'),
(20178,'Chiriguaná'),
(20228,'Curumaní'),
(20238,'El Copey'),
(20250,'El Paso'),
(20295,'Gamarra'),
(20310,'González'),
(20383,'La Gloria'),
(20400,'La Jagua De Ibirico'),
(20443,'Manaure'),
(20517,'Pailitas'),
(20550,'Pelaya'),
(20570,'Pueblo Bello'),
(20614,'Río De Oro'),
(20621,'La Paz'),
(20710,'San Alberto'),
(20750,'San Diego'),
(20770,'San Martín'),
(20787,'Tamalameque'),
(23001,'Montería'),
(23068,'Ayapel'),
(23079,'Buenavista'),
(23090,'Canalete'),
(23162,'Cereté'),
(23168,'Chimá'),
(23182,'Chinú'),
(23189,'Ciénaga De Oro'),
(23300,'Cotorra'),
(23350,'La Apartada'),
(23417,'Lorica'),
(23419,'Los Córdobas'),
(23464,'Momil'),
(23466,'Montelíbano'),
(23500,'Moñitos'),
(23555,'Planeta Rica'),
(23570,'Pueblo Nuevo'),
(23574,'Puerto Escondido'),
(23580,'Puerto Libertador'),
(23586,'Purísima'),
(23660,'Sahagún'),
(23670,'San Andrés Sotavento'),
(23672,'San Antero'),
(23675,'San Bernardo Del Viento'),
(23678,'San Carlos'),
(23686,'San Pelayo'),
(23807,'Tierralta'),
(23855,'Valencia'),
(25001,'Agua De Dios'),
(25019,'Albán'),
(25035,'Anapoima'),
(25040,'Anolaima'),
(25053,'Arbeláez'),
(25086,'Beltrán'),
(25095,'Bituima'),
(25099,'Bojacá'),
(25120,'Cabrera'),
(25123,'Cachipay'),
(25126,'Cajicá'),
(25148,'Caparrapí'),
(25151,'Caqueza'),
(25154,'Carmen De Carupa'),
(25168,'Chaguaní'),
(25175,'Chía'),
(25178,'Chipaque'),
(25181,'Choachí'),
(25183,'Chocontá'),
(25200,'Cogua'),
(25214,'Cota'),
(25224,'Cucunuba'),
(25245,'El Colegio'),
(25258,'El Peñón'),
(25260,'El Rosal'),
(25269,'Facatativá'),
(25279,'Fomeque'),
(25281,'Fosca'),
(25286,'Funza'),
(25288,'Fúquene'),
(25290,'Fusagasugá'),
(25293,'Gachala'),
(25295,'Gachancipá'),
(25297,'Gachetá'),
(25299,'Gama'),
(25307,'Girardot'),
(25312,'Granada'),
(25317,'Guachetá'),
(25320,'Guaduas'),
(25322,'Guasca'),
(25324,'Guataquí'),
(25326,'Guatavita'),
(25328,'Guayabal De Siquima'),
(25335,'Guayabetal'),
(25339,'Gutiérrez'),
(25368,'Jerusalén'),
(25372,'Junín'),
(25377,'La Calera'),
(25386,'La Mesa'),
(25394,'La Palma'),
(25398,'La Peña'),
(25402,'La Vega'),
(25407,'Lenguazaque'),
(25426,'Macheta'),
(25430,'Madrid'),
(25436,'Manta'),
(25438,'Medina'),
(25473,'Mosquera'),
(25483,'Nariño'),
(25486,'Nemocón'),
(25488,'Nilo'),
(25489,'Nimaima'),
(25491,'Nocaima'),
(25506,'Venecia'),
(25513,'Pacho'),
(25518,'Paime'),
(25524,'Pandi'),
(25530,'Paratebueno'),
(25535,'Pasca'),
(25572,'Puerto Salgar'),
(25580,'Pulí'),
(25592,'Quebradanegra'),
(25594,'Quetame'),
(25596,'Quipile'),
(25599,'Apulo'),
(25612,'Ricaurte'),
(25645,'San Antonio Del Tequendama'),
(25649,'San Bernardo'),
(25653,'San Cayetano'),
(25658,'San Francisco'),
(25662,'San Juan De Río Seco'),
(25718,'Sasaima'),
(25736,'Sesquilé'),
(25740,'Sibaté'),
(25743,'Silvania'),
(25745,'Simijaca'),
(25754,'Soacha'),
(25758,'Sopó'),
(25769,'Subachoque'),
(25772,'Suesca'),
(25777,'Supatá'),
(25779,'Susa'),
(25781,'Sutatausa'),
(25785,'Tabio'),
(25793,'Tausa'),
(25797,'Tena'),
(25799,'Tenjo'),
(25805,'Tibacuy'),
(25807,'Tibirita'),
(25815,'Tocaima'),
(25817,'Tocancipá'),
(25823,'Topaipi'),
(25839,'Ubalá'),
(25841,'Ubaque'),
(25843,'Villa De San Diego De Ubate'),
(25845,'Une'),
(25851,'Útica'),
(25862,'Vergara'),
(25867,'Vianí'),
(25871,'Villagómez'),
(25873,'Villapinzón'),
(25875,'Villeta'),
(25878,'Viotá'),
(25885,'Yacopí'),
(25898,'Zipacón'),
(25899,'Zipaquirá'),
(27001,'Quibdó'),
(27006,'Acandí'),
(27025,'Alto Baudo'),
(27050,'Atrato'),
(27073,'Bagadó'),
(27075,'Bahía Solano'),
(27077,'Bajo Baudó'),
(27086,'Belén De Bajirá'),
(27099,'Bojaya'),
(27135,'El Cantón Del San Pablo'),
(27150,'Carmen Del Darien'),
(27160,'Cértegui'),
(27205,'Condoto'),
(27245,'El Carmen De Atrato'),
(27250,'El Litoral Del San Juan'),
(27361,'Istmina'),
(27372,'Juradó'),
(27413,'Lloró'),
(27425,'Medio Atrato'),
(27430,'Medio Baudó'),
(27450,'Medio San Juan'),
(27491,'Nóvita'),
(27495,'Nuquí'),
(27580,'Río Iro'),
(27600,'Río Quito'),
(27615,'Riosucio'),
(27660,'San José Del Palmar'),
(27745,'Sipí'),
(27787,'Tadó'),
(27800,'Unguía'),
(27810,'Unión Panamericana'),
(41001,'Neiva'),
(41006,'Acevedo'),
(41013,'Agrado'),
(41016,'Aipe'),
(41020,'Algeciras'),
(41026,'Altamira'),
(41078,'Baraya'),
(41132,'Campoalegre'),
(41206,'Colombia'),
(41244,'Elías'),
(41298,'Garzón'),
(41306,'Gigante'),
(41319,'Guadalupe'),
(41349,'Hobo'),
(41357,'Iquira'),
(41359,'Isnos'),
(41378,'La Argentina'),
(41396,'La Plata'),
(41483,'Nátaga'),
(41503,'Oporapa'),
(41518,'Paicol'),
(41524,'Palermo'),
(41530,'Palestina'),
(41548,'Pital'),
(41551,'Pitalito'),
(41615,'Rivera'),
(41660,'Saladoblanco'),
(41668,'San Agustín'),
(41676,'Santa María'),
(41770,'Suaza'),
(41791,'Tarqui'),
(41797,'Tesalia'),
(41799,'Tello'),
(41801,'Teruel'),
(41807,'Timana'),
(41872,'Villavieja'),
(41885,'Yaguará'),
(44001,'Riohacha'),
(44035,'Albania'),
(44078,'Barrancas'),
(44090,'Dibulla'),
(44098,'Distracción'),
(44110,'El Molino'),
(44279,'Fonseca'),
(44378,'Hatonuevo'),
(44420,'La Jagua Del Pilar'),
(44430,'Maicao'),
(44560,'Manaure'),
(44650,'San Juan Del Cesar'),
(44847,'Uribia'),
(44855,'Urumita'),
(44874,'Villanueva'),
(47001,'Santa Marta'),
(47030,'Algarrobo'),
(47053,'Aracataca'),
(47058,'Ariguaní'),
(47161,'Cerro San Antonio'),
(47170,'Chibolo'),
(47189,'Ciénaga'),
(47205,'Concordia'),
(47245,'El Banco'),
(47258,'El Piñon'),
(47268,'El Retén'),
(47288,'Fundación'),
(47318,'Guamal'),
(47460,'Nueva Granada'),
(47541,'Pedraza'),
(47545,'Pijiño Del Carmen'),
(47551,'Pivijay'),
(47555,'Plato'),
(47570,'Puebloviejo'),
(47605,'Remolino'),
(47660,'Sabanas De San Angel'),
(47675,'Salamina'),
(47692,'San Sebastián De Buenavista'),
(47703,'San Zenón'),
(47707,'Santa Ana'),
(47720,'Santa Bárbara De Pinto'),
(47745,'Sitionuevo'),
(47798,'Tenerife'),
(47960,'Zapayán'),
(47980,'Zona Bananera'),
(50001,'Villavicencio'),
(50006,'Acacías'),
(50110,'Barranca De Upía'),
(50124,'Cabuyaro'),
(50150,'Castilla La Nueva'),
(50223,'Cubarral'),
(50226,'Cumaral'),
(50245,'El Calvario'),
(50251,'El Castillo'),
(50270,'El Dorado'),
(50287,'Fuente De Oro'),
(50313,'Granada'),
(50318,'Guamal'),
(50325,'Mapiripán'),
(50330,'Mesetas'),
(50350,'La Macarena'),
(50370,'Uribe'),
(50400,'Lejanías'),
(50450,'Puerto Concordia'),
(50568,'Puerto Gaitán'),
(50573,'Puerto López'),
(50577,'Puerto Lleras'),
(50590,'Puerto Rico'),
(50606,'Restrepo'),
(50680,'San Carlos De Guaroa'),
(50683,'San Juan De Arama'),
(50686,'San Juanito'),
(50689,'San Martín'),
(50711,'Vistahermosa'),
(52001,'Pasto'),
(52019,'Albán'),
(52022,'Aldana'),
(52036,'Ancuya'),
(52051,'Arboleda'),
(52079,'Barbacoas'),
(52083,'Belén'),
(52110,'Buesaco'),
(52203,'Colón'),
(52207,'Consaca'),
(52210,'Contadero'),
(52215,'Córdoba'),
(52224,'Cuaspud'),
(52227,'Cumbal'),
(52233,'Cumbitara'),
(52240,'Chachagüí'),
(52250,'El Charco'),
(52254,'El Peñol'),
(52256,'El Rosario'),
(52258,'El Tablón De Gómez'),
(52260,'El Tambo'),
(52287,'Funes'),
(52317,'Guachucal'),
(52320,'Guaitarilla'),
(52323,'Gualmatán'),
(52352,'Iles'),
(52354,'Imués'),
(52356,'Ipiales'),
(52378,'La Cruz'),
(52381,'La Florida'),
(52385,'La Llanada'),
(52390,'La Tola'),
(52399,'La Unión'),
(52405,'Leiva'),
(52411,'Linares'),
(52418,'Los Andes'),
(52427,'Magüi'),
(52435,'Mallama'),
(52473,'Mosquera'),
(52480,'Nariño'),
(52490,'Olaya Herrera'),
(52506,'Ospina'),
(52520,'Francisco Pizarro'),
(52540,'Policarpa'),
(52560,'Potosí'),
(52565,'Providencia'),
(52573,'Puerres'),
(52585,'Pupiales'),
(52612,'Ricaurte'),
(52621,'Roberto Payán'),
(52678,'Samaniego'),
(52683,'Sandoná'),
(52685,'San Bernardo'),
(52687,'San Lorenzo'),
(52693,'San Pablo'),
(52694,'San Pedro De Cartago'),
(52696,'Santa Bárbara'),
(52699,'Santacruz'),
(52720,'Sapuyes'),
(52786,'Taminango'),
(52788,'Tangua'),
(52835,'San Andres De Tumaco'),
(52838,'Túquerres'),
(52885,'Yacuanquer'),
(54001,'Cúcuta'),
(54003,'Abrego'),
(54051,'Arboledas'),
(54099,'Bochalema'),
(54109,'Bucarasica'),
(54125,'Cácota'),
(54128,'Cachirá'),
(54172,'Chinácota'),
(54174,'Chitagá'),
(54206,'Convención'),
(54223,'Cucutilla'),
(54239,'Durania'),
(54245,'El Carmen'),
(54250,'El Tarra'),
(54261,'El Zulia'),
(54313,'Gramalote'),
(54344,'Hacarí'),
(54347,'Herrán'),
(54377,'Labateca'),
(54385,'La Esperanza'),
(54398,'La Playa'),
(54405,'Los Patios'),
(54418,'Lourdes'),
(54480,'Mutiscua'),
(54498,'Ocaña'),
(54518,'Pamplona'),
(54520,'Pamplonita'),
(54553,'Puerto Santander'),
(54599,'Ragonvalia'),
(54660,'Salazar'),
(54670,'San Calixto'),
(54673,'San Cayetano'),
(54680,'Santiago'),
(54720,'Sardinata'),
(54743,'Silos'),
(54800,'Teorama'),
(54810,'Tibú'),
(54820,'Toledo'),
(54871,'Villa Caro'),
(54874,'Villa Del Rosario'),
(63001,'Armenia'),
(63111,'Buenavista'),
(63130,'Calarca'),
(63190,'Circasia'),
(63212,'Córdoba'),
(63272,'Filandia'),
(63302,'Génova'),
(63401,'La Tebaida'),
(63470,'Montenegro'),
(63548,'Pijao'),
(63594,'Quimbaya'),
(63690,'Salento'),
(66001,'Pereira'),
(66045,'Apía'),
(66075,'Balboa'),
(66088,'Belén De Umbría'),
(66170,'Dosquebradas'),
(66318,'Guática'),
(66383,'La Celia'),
(66400,'La Virginia'),
(66440,'Marsella'),
(66456,'Mistrató'),
(66572,'Pueblo Rico'),
(66594,'Quinchía'),
(66682,'Santa Rosa De Cabal'),
(66687,'Santuario'),
(68001,'Bucaramanga'),
(68013,'Aguada'),
(68020,'Albania'),
(68051,'Aratoca'),
(68077,'Barbosa'),
(68079,'Barichara'),
(68081,'Barrancabermeja'),
(68092,'Betulia'),
(68101,'Bolívar'),
(68121,'Cabrera'),
(68132,'California'),
(68147,'Capitanejo'),
(68152,'Carcasí'),
(68160,'Cepitá'),
(68162,'Cerrito'),
(68167,'Charalá'),
(68169,'Charta'),
(68176,'Chima'),
(68179,'Chipatá'),
(68190,'Cimitarra'),
(68207,'Concepción'),
(68209,'Confines'),
(68211,'Contratación'),
(68217,'Coromoro'),
(68229,'Curití'),
(68235,'El Carmen De Chucurí'),
(68245,'El Guacamayo'),
(68250,'El Peñón'),
(68255,'El Playón'),
(68264,'Encino'),
(68266,'Enciso'),
(68271,'Florián'),
(68276,'Floridablanca'),
(68296,'Galan'),
(68298,'Gambita'),
(68307,'Girón'),
(68318,'Guaca'),
(68320,'Guadalupe'),
(68322,'Guapotá'),
(68324,'Guavatá'),
(68327,'Güepsa'),
(68344,'Hato'),
(68368,'Jesús María'),
(68370,'Jordán'),
(68377,'La Belleza'),
(68385,'Landázuri'),
(68397,'La Paz'),
(68406,'Lebríja'),
(68418,'Los Santos'),
(68425,'Macaravita'),
(68432,'Málaga'),
(68444,'Matanza'),
(68464,'Mogotes'),
(68468,'Molagavita'),
(68498,'Ocamonte'),
(68500,'Oiba'),
(68502,'Onzaga'),
(68522,'Palmar'),
(68524,'Palmas Del Socorro'),
(68533,'Páramo'),
(68547,'Piedecuesta'),
(68549,'Pinchote'),
(68572,'Puente Nacional'),
(68573,'Puerto Parra'),
(68575,'Puerto Wilches'),
(68615,'Rionegro'),
(68655,'Sabana De Torres'),
(68669,'San Andrés'),
(68673,'San Benito'),
(68679,'San Gil'),
(68682,'San Joaquín'),
(68684,'San José De Miranda'),
(68686,'San Miguel'),
(68689,'San Vicente De Chucurí'),
(68705,'Santa Bárbara'),
(68720,'Santa Helena Del Opón'),
(68745,'Simacota'),
(68755,'Socorro'),
(68770,'Suaita'),
(68773,'Sucre'),
(68780,'Suratá'),
(68820,'Tona'),
(68855,'Valle De San José'),
(68861,'Vélez'),
(68867,'Vetas'),
(68872,'Villanueva'),
(68895,'Zapatoca'),
(70001,'Sincelejo'),
(70110,'Buenavista'),
(70124,'Caimito'),
(70204,'Coloso'),
(70215,'Corozal'),
(70221,'Coveñas'),
(70230,'Chalán'),
(70233,'El Roble'),
(70235,'Galeras'),
(70265,'Guaranda'),
(70400,'La Unión'),
(70418,'Los Palmitos'),
(70429,'Majagual'),
(70473,'Morroa'),
(70508,'Ovejas'),
(70523,'Palmito'),
(70670,'Sampués'),
(70678,'San Benito Abad'),
(70702,'San Juan De Betulia'),
(70708,'San Marcos'),
(70713,'San Onofre'),
(70717,'San Pedro'),
(70742,'San Luis De Sincé'),
(70771,'Sucre'),
(70820,'Santiago De Tolú'),
(70823,'Tolú Viejo'),
(73001,'Ibague'),
(73024,'Alpujarra'),
(73026,'Alvarado'),
(73030,'Ambalema'),
(73043,'Anzoátegui'),
(73055,'Armero'),
(73067,'Ataco'),
(73124,'Cajamarca'),
(73148,'Carmen De Apicalá'),
(73152,'Casabianca'),
(73168,'Chaparral'),
(73200,'Coello'),
(73217,'Coyaima'),
(73226,'Cunday'),
(73236,'Dolores'),
(73268,'Espinal'),
(73270,'Falan'),
(73275,'Flandes'),
(73283,'Fresno'),
(73319,'Guamo'),
(73347,'Herveo'),
(73349,'Honda'),
(73352,'Icononzo'),
(73408,'Lérida'),
(73411,'Líbano'),
(73443,'Mariquita'),
(73449,'Melgar'),
(73461,'Murillo'),
(73483,'Natagaima'),
(73504,'Ortega'),
(73520,'Palocabildo'),
(73547,'Piedras'),
(73555,'Planadas'),
(73563,'Prado'),
(73585,'Purificación'),
(73616,'Rioblanco'),
(73622,'Roncesvalles'),
(73624,'Rovira'),
(73671,'Saldaña'),
(73675,'San Antonio'),
(73678,'San Luis'),
(73686,'Santa Isabel'),
(73770,'Suárez'),
(73854,'Valle De San Juan'),
(73861,'Venadillo'),
(73870,'Villahermosa'),
(73873,'Villarrica'),
(76001,'Cali'),
(76020,'Alcalá'),
(76036,'Andalucía'),
(76041,'Ansermanuevo'),
(76054,'Argelia'),
(76100,'Bolívar'),
(76109,'Buenaventura'),
(76111,'Guadalajara De Buga'),
(76113,'Bugalagrande'),
(76122,'Caicedonia'),
(76126,'Calima'),
(76130,'Candelaria'),
(76147,'Cartago'),
(76233,'Dagua'),
(76243,'El Águila'),
(76246,'El Cairo'),
(76248,'El Cerrito'),
(76250,'El Dovio'),
(76275,'Florida'),
(76306,'Ginebra'),
(76318,'Guacarí'),
(76364,'Jamundí'),
(76377,'La Cumbre'),
(76400,'La Unión'),
(76403,'La Victoria'),
(76497,'Obando'),
(76520,'Palmira'),
(76563,'Pradera'),
(76606,'Restrepo'),
(76616,'Riofrío'),
(76622,'Roldanillo'),
(76670,'San Pedro'),
(76736,'Sevilla'),
(76823,'Toro'),
(76828,'Trujillo'),
(76834,'Tuluá'),
(76845,'Ulloa'),
(76863,'Versalles'),
(76869,'Vijes'),
(76890,'Yotoco'),
(76892,'Yumbo'),
(76895,'Zarzal'),
(81001,'Arauca'),
(81065,'Arauquita'),
(81220,'Cravo Norte'),
(81300,'Fortul'),
(81591,'Puerto Rondón'),
(81736,'Saravena'),
(81794,'Tame'),
(85001,'Yopal'),
(85010,'Aguazul'),
(85015,'Chameza'),
(85125,'Hato Corozal'),
(85136,'La Salina'),
(85139,'Maní'),
(85162,'Monterrey'),
(85225,'Nunchía'),
(85230,'Orocué'),
(85250,'Paz De Ariporo'),
(85263,'Pore'),
(85279,'Recetor'),
(85300,'Sabanalarga'),
(85315,'Sácama'),
(85325,'San Luis De Palenque'),
(85400,'Támara'),
(85410,'Tauramena'),
(85430,'Trinidad'),
(85440,'Villanueva'),
(86001,'Mocoa'),
(86219,'Colón'),
(86320,'Orito'),
(86568,'Puerto Asís'),
(86569,'Puerto Caicedo'),
(86571,'Puerto Guzmán'),
(86573,'Leguízamo'),
(86749,'Sibundoy'),
(86755,'San Francisco'),
(86757,'San Miguel'),
(86760,'Santiago'),
(86865,'Valle Del Guamuez'),
(86885,'Villagarzón'),
(88001,'San Andrés'),
(88564,'Providencia'),
(91001,'Leticia'),
(91263,'El Encanto'),
(91405,'La Chorrera'),
(91407,'La Pedrera'),
(91430,'La Victoria'),
(91460,'Miriti - Paraná'),
(91530,'Puerto Alegría'),
(91536,'Puerto Arica'),
(91540,'Puerto Nariño'),
(91669,'Puerto Santander'),
(91798,'Tarapacá'),
(94001,'Inírida'),
(94343,'Barranco Minas'),
(94663,'Mapiripana'),
(94883,'San Felipe'),
(94884,'Puerto Colombia'),
(94885,'La Guadalupe'),
(94886,'Cacahual'),
(94887,'Pana Pana'),
(94888,'Morichal'),
(95001,'San José Del Guaviare'),
(95015,'Calamar'),
(95025,'El Retorno'),
(95200,'Miraflores'),
(97001,'Mitú'),
(97161,'Caruru'),
(97511,'Pacoa'),
(97666,'Taraira'),
(97777,'Papunaua'),
(97889,'Yavaraté'),
(99001,'Puerto Carreño'),
(99524,'La Primavera'),
(99624,'Santa Rosalía'),
(99773,'Cumaribo')
], validate_choice=True)
celularCliente = IntegerField('Numero Telefono Movil', validators=[
Required(message='El campo es obligatorio'),
Length(max=10, min=10, message='El campo debe tener 10 caracteres')
])
correoElectronicoCliente = StringField('Correo Electronico Principal', validators=[
Required(message='El campo es obligatorio'),
Email()
])
contraseñaCliente = PasswordField('Contraseña')
enviar = SubmitField("Enviar")
class ingresoCliente(FlaskForm):
correoElectronicoCliente = StringField('Correo Electronico Principal', validators=[
Required(message='El campo es obligatorio'),
Email()
])
contraseñaCliente = PasswordField('Contraseña')
enviar = SubmitField("Enviar")
class registrarEmpleado(FlaskForm):
numeroIdEmpleado = IntegerField('Numero Identificacion', validators=[
Required(message='El campo es obligatorio'),
Length(max=10, min=6, message='El campo debe tener entre 6 y 10 caracteres')
])
tipoId = SelectField('Tipo Idenficacion', choices=[
('CC','Cedula de Ciudadania'),
('CE','Cedula de Extrangeria'),
('PA','Pasaporte'),
('RC','Registro Civil'),
('TI','Tarjeta de Identidad')], validators=[
Required(message='El campo es obligatorio'),
])
fechaExpIdEmpleado = DateField('Fecha Expedicion Documento Identidad', format='%Y,%M,%D')
lugarExpIdEmpleado = SelectField('Ciudad Expedicion Documento Identidad', choices=[
(5001,'Medellín'),
(5002,'Abejorral'),
(5004,'Abriaquí'),
(5021,'Alejandría'),
(5030,'Amagá'),
(5031,'Amalfi'),
(5034,'Andes'),
(5036,'Angelópolis'),
(5038,'Angostura'),
(5040,'Anorí'),
(5042,'Santafé De Antioquia'),
(5044,'Anza'),
(5045,'Apartadó'),
(5051,'Arboletes'),
(5055,'Argelia'),
(5059,'Armenia'),
(5079,'Barbosa'),
(5086,'Belmira'),
(5088,'Bello'),
(5091,'Betania'),
(5093,'Betulia'),
(5101,'Ciudad Bolívar'),
(5107,'Briceño'),
(5113,'Buriticá'),
(5120,'Cáceres'),
(5125,'Caicedo'),
(5129,'Caldas'),
(5134,'Campamento'),
(5138,'Cañasgordas'),
(5142,'Caracolí'),
(5145,'Caramanta'),
(5147,'Carepa'),
(5148,'El Carmen De Viboral'),
(5150,'Carolina'),
(5154,'Caucasia'),
(5172,'Chigorodó'),
(5190,'Cisneros'),
(5197,'Cocorná'),
(5206,'Concepción'),
(5209,'Concordia'),
(5212,'Copacabana'),
(5234,'Dabeiba'),
(5237,'Don Matías'),
(5240,'Ebéjico'),
(5250,'El Bagre'),
(5264,'Entrerrios'),
(5266,'Envigado'),
(5282,'Fredonia'),
(5284,'Frontino'),
(5306,'Giraldo'),
(5308,'Girardota'),
(5310,'Gómez Plata'),
(5313,'Granada'),
(5315,'Guadalupe'),
(5318,'Guarne'),
(5321,'Guatape'),
(5347,'Heliconia'),
(5353,'Hispania'),
(5360,'Itagui'),
(5361,'Ituango'),
(5364,'Jardín'),
(5368,'Jericó'),
(5376,'La Ceja'),
(5380,'La Estrella'),
(5390,'La Pintada'),
(5400,'La Unión'),
(5411,'Liborina'),
(5425,'Maceo'),
(5440,'Marinilla'),
(5467,'Montebello'),
(5475,'Murindó'),
(5480,'Mutatá'),
(5483,'Nariño'),
(5490,'Necoclí'),
(5495,'Nechí'),
(5501,'Olaya'),
(5541,'Peñol'),
(5543,'Peque'),
(5576,'Pueblorrico'),
(5579,'Puerto Berrío'),
(5585,'Puerto Nare'),
(5591,'Puerto Triunfo'),
(5604,'Remedios'),
(5607,'Retiro'),
(5615,'Rionegro'),
(5628,'Sabanalarga'),
(5631,'Sabaneta'),
(5642,'Salgar'),
(5647,'San Andrés De Cuerquía'),
(5649,'San Carlos'),
(5652,'San Francisco'),
(5656,'San Jerónimo'),
(5658,'San José De La Montaña'),
(5659,'San Juan De Urabá'),
(5660,'San Luis'),
(5664,'San Pedro'),
(5665,'San Pedro De Uraba'),
(5667,'San Rafael'),
(5670,'San Roque'),
(5674,'San Vicente'),
(5679,'Santa Bárbara'),
(5686,'Santa Rosa De Osos'),
(5690,'Santo Domingo'),
(5697,'El Santuario'),
(5736,'Segovia'),
(5756,'Sonson'),
(5761,'Sopetrán'),
(5789,'Támesis'),
(5790,'Tarazá'),
(5792,'Tarso'),
(5809,'Titiribí'),
(5819,'Toledo'),
(5837,'Turbo'),
(5842,'Uramita'),
(5847,'Urrao'),
(5854,'Valdivia'),
(5856,'Valparaíso'),
(5858,'Vegachí'),
(5861,'Venecia'),
(5873,'Vigía Del Fuerte'),
(5885,'Yalí'),
(5887,'Yarumal'),
(5890,'Yolombó'),
(5893,'Yondó'),
(5895,'Zaragoza'),
(8001,'Barranquilla'),
(8078,'Baranoa'),
(8137,'Campo De La Cruz'),
(8141,'Candelaria'),
(8296,'Galapa'),
(8372,'Juan De Acosta'),
(8421,'Luruaco'),
(8433,'Malambo'),
(8436,'Manatí'),
(8520,'Palmar De Varela'),
(8549,'Piojó'),
(8558,'Polonuevo'),
(8560,'Ponedera'),
(8573,'Puerto Colombia'),
(8606,'Repelón'),
(8634,'Sabanagrande'),
(8638,'Sabanalarga'),
(8675,'Santa Lucía'),
(8685,'Santo Tomás'),
(8758,'Soledad'),
(8770,'Suan'),
(8832,'Tubará'),
(8849,'Usiacurí'),
(11001,'Bogota DC'),
(13001,'Cartagena'),
(13006,'Choachí'),
(13030,'Altos Del Rosario'),
(13042,'Arenal'),
(13052,'Arjona'),
(13062,'Arroyohondo'),
(13074,'Barranco De Loba'),
(13140,'Calamar'),
(13160,'Cantagallo'),
(13188,'Cicuco'),
(13212,'Córdoba'),
(13222,'Clemencia'),
(13244,'El Carmen De Bolívar'),
(13248,'El Guamo'),
(13268,'El Peñón'),
(13300,'Hatillo De Loba'),
(13430,'Magangué'),
(13433,'Mahates'),
(13440,'Margarita'),
(13442,'María La Baja'),
(13458,'Montecristo'),
(13468,'Mompós'),
(13473,'Morales'),
(13549,'Pinillos'),
(13580,'Regidor'),
(13600,'Río Viejo'),
(13620,'San Cristóbal'),
(13647,'San Estanislao'),
(13650,'San Fernando'),
(13654,'San Jacinto'),
(13655,'San Jacinto Del Cauca'),
(13657,'San Juan Nepomuceno'),
(13667,'San Martín De Loba'),
(13670,'San Pablo'),
(13673,'Santa Catalina'),
(13683,'Santa Rosa'),
(13688,'Santa Rosa Del Sur'),
(13744,'Simití'),
(13760,'Soplaviento'),
(13780,'Talaigua Nuevo'),
(13810,'Tiquisio'),
(13836,'Turbaco'),
(13838,'Turbaná'),
(13873,'Villanueva'),
(13894,'Zambrano'),
(15001,'Tunja'),
(15022,'Almeida'),
(15047,'Aquitania'),
(15051,'Arcabuco'),
(15087,'Belén'),
(15090,'Berbeo'),
(15092,'Betéitiva'),
(15097,'Boavita'),
(15104,'Boyacá'),
(15106,'Briceño'),
(15109,'Buenavista'),
(15114,'Busbanzá'),
(15131,'Caldas'),
(15135,'Campohermoso'),
(15162,'Cerinza'),
(15172,'Chinavita'),
(15176,'Chiquinquirá'),
(15180,'Chiscas'),
(15183,'Chita'),
(15185,'Chitaraque'),
(15187,'Chivatá'),
(15189,'Ciénega'),
(15204,'Cómbita'),
(15212,'Coper'),
(15215,'Corrales'),
(15218,'Covarachía'),
(15223,'Cubará'),
(15224,'Cucaita'),
(15226,'Cuítiva'),
(15232,'Chíquiza'),
(15236,'Chivor'),
(15238,'Duitama'),
(15244,'El Cocuy'),
(15248,'El6Aspino'),
(15272,'Firavitoba'),
(15276,'Floresta'),
(15293,'Gachantivá'),
(15296,'Gameza'),
(15299,'Garagoa'),
(15317,'Guacamayas'),
(15322,'Guateque'),
(15325,'Guayatá'),
(15332,'Guican'),
(15362,'Iza'),
(15367,'Jenesano'),
(15368,'Jericó'),
(15377,'Labranzagrande'),
(15380,'La Capilla'),
(15401,'La Victoria'),
(15403,'La Uvita'),
(15407,'Villa De Leyva'),
(15425,'Macanal'),
(15442,'Maripí'),
(15455,'Miraflores'),
(15464,'Mongua'),
(15466,'Monguí'),
(15469,'Moniquirá'),
(15476,'Motavita'),
(15480,'Muzo'),
(15491,'Nobsa'),
(15494,'Nuevo Colón'),
(15500,'Oicatá'),
(15507,'Otanche'),
(15511,'Pachavita'),
(15514,'Páez'),
(15516,'Paipa'),
(15518,'Pajarito'),
(15522,'Panqueba'),
(15531,'Pauna'),
(15533,'Paya'),
(15537,'Paz De Río'),
(15542,'Pesca'),
(15550,'Pisba'),
(15572,'Puerto Boyacá'),
(15580,'Quípama'),
(15599,'Ramiriquí'),
(15600,'Ráquira'),
(15621,'Rondón'),
(15632,'Saboyá'),
(15638,'Sáchica'),
(15646,'Samacá'),
(15660,'San Eduardo'),
(15664,'San José De Pare'),
(15667,'San Luis De Gaceno'),
(15673,'San Mateo'),
(15676,'San Miguel De Sema'),
(15681,'San Pablo De Borbur'),
(15686,'Santana'),
(15690,'Santa María'),
(15693,'Santa Rosa De Viterbo'),
(15696,'Santa Sofía'),
(15720,'Sativanorte'),
(15723,'Sativasur'),
(15740,'Siachoque'),
(15753,'Soatá'),
(15755,'Socotá'),
(15757,'Socha'),
(15759,'Sogamoso'),
(15761,'Somondoco'),
(15762,'Sora'),
(15763,'Sotaquirá'),
(15764,'Soracá'),
(15774,'Susacón'),
(15776,'Sutamarchán'),
(15778,'Sutatenza'),
(15790,'Tasco'),
(15798,'Tenza'),
(15804,'Tibaná'),
(15806,'Tibasosa'),
(15808,'Tinjacá'),
(15810,'Tipacoque'),
(15814,'Toca'),
(15816,'Togüí'),
(15820,'Tópaga'),
(15822,'Tota'),
(15832,'Tununguá'),
(15835,'Turmequé'),
(15837,'Tuta'),
(15839,'Tutazá'),
(15842,'Umbita'),
(15861,'Ventaquemada'),
(15879,'Viracachá'),
(15897,'Zetaquira'),
(17001,'Manizales'),
(17013,'Aguadas'),
(17042,'Anserma'),
(17050,'Aranzazu'),
(17088,'Belalcázar'),
(17174,'Chinchiná'),
(17272,'Filadelfia'),
(17380,'La Dorada'),
(17388,'La Merced'),
(17433,'Manzanares'),
(17442,'Marmato'),
(17444,'Marquetalia'),
(17446,'Marulanda'),
(17486,'Neira'),
(17495,'Norcasia'),
(17513,'Pácora'),
(17524,'Palestina'),
(17541,'Pensilvania'),
(17614,'Riosucio'),
(17616,'Risaralda'),
(17653,'Salamina'),
(17662,'Samaná'),
(17665,'San José'),
(17777,'Supía'),
(17867,'Victoria'),
(17873,'Villamaría'),
(17877,'Viterbo'),
(18001,'Florencia'),
(18029,'Albania'),
(18094,'Belén De Los Andaquies'),
(18150,'Cartagena Del Chairá'),
(18205,'Curillo'),
(18247,'El Doncello'),
(18256,'El Paujil'),
(18410,'La Montañita'),
(18460,'Milán'),
(18479,'Morelia'),
(18592,'Puerto Rico'),
(18610,'San José Del Fragua'),
(18753,'San Vicente Del Caguán'),
(18756,'Solano'),
(18785,'Solita'),
(18860,'Valparaíso'),
(19001,'Popayán'),
(19022,'Almaguer'),
(19050,'Argelia'),
(19075,'Balboa'),
(19100,'Bolívar'),
(19110,'Buenos Aires'),
(19130,'Cajibío'),
(19137,'Caldono'),
(19142,'Caloto'),
(19212,'Corinto'),
(19256,'El Tambo'),
(19290,'Florencia'),
(19300,'Guachené'),
(19318,'Guapi'),
(19355,'Inzá'),
(19364,'Jambaló'),
(19392,'La Sierra'),
(19397,'La Vega'),
(19418,'López'),
(19450,'Mercaderes'),
(19455,'Miranda'),
(19473,'Morales'),
(19513,'Padilla'),
(19517,'Paez'),
(19532,'Patía'),
(19533,'Piamonte'),
(19548,'Piendamó'),
(19573,'Puerto Tejada'),
(19585,'Puracé'),
(19622,'Rosas'),
(19693,'San Sebastián'),
(19698,'Santander De Quilichao'),
(19701,'Santa Rosa'),
(19743,'Silvia'),
(19760,'Sotara'),
(19780,'Suárez'),
(19785,'Sucre'),
(19807,'Timbío'),
(19809,'Timbiquí'),
(19821,'Toribio'),
(19824,'Totoró'),
(19845,'Villa Rica'),
(20001,'Valledupar'),
(20011,'Aguachica'),
(20013,'Agustín Codazzi'),
(20032,'Astrea'),
(20045,'Becerril'),
(20060,'Bosconia'),
(20175,'Chimichagua'),
(20178,'Chiriguaná'),
(20228,'Curumaní'),
(20238,'El Copey'),
(20250,'El Paso'),
(20295,'Gamarra'),
(20310,'González'),
(20383,'La Gloria'),
(20400,'La Jagua De Ibirico'),
(20443,'Manaure'),
(20517,'Pailitas'),
(20550,'Pelaya'),
(20570,'Pueblo Bello'),
(20614,'Río De Oro'),
(20621,'La Paz'),
(20710,'San Alberto'),
(20750,'San Diego'),
(20770,'San Martín'),
(20787,'Tamalameque'),
(23001,'Montería'),
(23068,'Ayapel'),
(23079,'Buenavista'),
(23090,'Canalete'),
(23162,'Cereté'),
(23168,'Chimá'),
(23182,'Chinú'),
(23189,'Ciénaga De Oro'),
(23300,'Cotorra'),
(23350,'La Apartada'),
(23417,'Lorica'),
(23419,'Los Córdobas'),
(23464,'Momil'),
(23466,'Montelíbano'),
(23500,'Moñitos'),
(23555,'Planeta Rica'),
(23570,'Pueblo Nuevo'),
(23574,'Puerto Escondido'),
(23580,'Puerto Libertador'),
(23586,'Purísima'),
(23660,'Sahagún'),
(23670,'San Andrés Sotavento'),
(23672,'San Antero'),
(23675,'San Bernardo Del Viento'),
(23678,'San Carlos'),
(23686,'San Pelayo'),
(23807,'Tierralta'),
(23855,'Valencia'),
(25001,'Agua De Dios'),
(25019,'Albán'),
(25035,'Anapoima'),
(25040,'Anolaima'),
(25053,'Arbeláez'),
(25086,'Beltrán'),
(25095,'Bituima'),
(25099,'Bojacá'),
(25120,'Cabrera'),
(25123,'Cachipay'),
(25126,'Cajicá'),
(25148,'Caparrapí'),
(25151,'Caqueza'),
(25154,'Carmen De Carupa'),
(25168,'Chaguaní'),
(25175,'Chía'),
(25178,'Chipaque'),
(25181,'Choachí'),
(25183,'Chocontá'),
(25200,'Cogua'),
(25214,'Cota'),
(25224,'Cucunuba'),
(25245,'El Colegio'),
(25258,'El Peñón'),
(25260,'El Rosal'),
(25269,'Facatativá'),
(25279,'Fomeque'),
(25281,'Fosca'),
(25286,'Funza'),
(25288,'Fúquene'),
(25290,'Fusagasugá'),
(25293,'Gachala'),
(25295,'Gachancipá'),
(25297,'Gachetá'),
(25299,'Gama'),
(25307,'Girardot'),
(25312,'Granada'),
(25317,'Guachetá'),
(25320,'Guaduas'),
(25322,'Guasca'),
(25324,'Guataquí'),
(25326,'Guatavita'),
(25328,'Guayabal De Siquima'),
(25335,'Guayabetal'),
(25339,'Gutiérrez'),
(25368,'Jerusalén'),
(25372,'Junín'),
(25377,'La Calera'),
(25386,'La Mesa'),
(25394,'La Palma'),
(25398,'La Peña'),
(25402,'La Vega'),
(25407,'Lenguazaque'),
(25426,'Macheta'),
(25430,'Madrid'),
(25436,'Manta'),
(25438,'Medina'),
(25473,'Mosquera'),
(25483,'Nariño'),
(25486,'Nemocón'),
(25488,'Nilo'),
(25489,'Nimaima'),
(25491,'Nocaima'),
(25506,'Venecia'),
(25513,'Pacho'),
(25518,'Paime'),
(25524,'Pandi'),
(25530,'Paratebueno'),
(25535,'Pasca'),
(25572,'Puerto Salgar'),
(25580,'Pulí'),
(25592,'Quebradanegra'),
(25594,'Quetame'),
(25596,'Quipile'),
(25599,'Apulo'),
(25612,'Ricaurte'),
(25645,'San Antonio Del Tequendama'),
(25649,'San Bernardo'),
(25653,'San Cayetano'),
(25658,'San Francisco'),
(25662,'San Juan De Río Seco'),
(25718,'Sasaima'),
(25736,'Sesquilé'),
(25740,'Sibaté'),
(25743,'Silvania'),
(25745,'Simijaca'),
(25754,'Soacha'),
(25758,'Sopó'),
(25769,'Subachoque'),
(25772,'Suesca'),
(25777,'Supatá'),
(25779,'Susa'),
(25781,'Sutatausa'),
(25785,'Tabio'),
(25793,'Tausa'),
(25797,'Tena'),
(25799,'Tenjo'),
(25805,'Tibacuy'),
(25807,'Tibirita'),
(25815,'Tocaima'),
(25817,'Tocancipá'),
(25823,'Topaipi'),
(25839,'Ubalá'),
(25841,'Ubaque'),
(25843,'Villa De San Diego De Ubate'),
(25845,'Une'),
(25851,'Útica'),
(25862,'Vergara'),
(25867,'Vianí'),
(25871,'Villagómez'),
(25873,'Villapinzón'),
(25875,'Villeta'),
(25878,'Viotá'),
(25885,'Yacopí'),
(25898,'Zipacón'),
(25899,'Zipaquirá'),
(27001,'Quibdó'),
(27006,'Acandí'),
(27025,'Alto Baudo'),
(27050,'Atrato'),
(27073,'Bagadó'),
(27075,'Bahía Solano'),
(27077,'Bajo Baudó'),
(27086,'Belén De Bajirá'),
(27099,'Bojaya'),
(27135,'El Cantón Del San Pablo'),
(27150,'Carmen Del Darien'),
(27160,'Cértegui'),
(27205,'Condoto'),
(27245,'El Carmen De Atrato'),
(27250,'El Litoral Del San Juan'),
(27361,'Istmina'),
(27372,'Juradó'),
(27413,'Lloró'),
(27425,'Medio Atrato'),
(27430,'Medio Baudó'),
(27450,'Medio San Juan'),
(27491,'Nóvita'),
(27495,'Nuquí'),
(27580,'Río Iro'),
(27600,'Río Quito'),
(27615,'Riosucio'),
(27660,'San José Del Palmar'),
(27745,'Sipí'),
(27787,'Tadó'),
(27800,'Unguía'),
(27810,'Unión Panamericana'),
(41001,'Neiva'),
(41006,'Acevedo'),
(41013,'Agrado'),
(41016,'Aipe'),
(41020,'Algeciras'),
(41026,'Altamira'),
(41078,'Baraya'),
(41132,'Campoalegre'),
(41206,'Colombia'),
(41244,'Elías'),
(41298,'Garzón'),
(41306,'Gigante'),
(41319,'Guadalupe'),
(41349,'Hobo'),
(41357,'Iquira'),
(41359,'Isnos'),
(41378,'La Argentina'),
(41396,'La Plata'),
(41483,'Nátaga'),
(41503,'Oporapa'),
(41518,'Paicol'),
(41524,'Palermo'),
(41530,'Palestina'),
(41548,'Pital'),
(41551,'Pitalito'),
(41615,'Rivera'),
(41660,'Saladoblanco'),
(41668,'San Agustín'),
(41676,'Santa María'),
(41770,'Suaza'),
(41791,'Tarqui'),
(41797,'Tesalia'),
(41799,'Tello'),
(41801,'Teruel'),
(41807,'Timana'),
(41872,'Villavieja'),
(41885,'Yaguará'),
(44001,'Riohacha'),
(44035,'Albania'),
(44078,'Barrancas'),
(44090,'Dibulla'),
(44098,'Distracción'),
(44110,'El Molino'),
(44279,'Fonseca'),
(44378,'Hatonuevo'),
(44420,'La Jagua Del Pilar'),
(44430,'Maicao'),
(44560,'Manaure'),
(44650,'San Juan Del Cesar'),
(44847,'Uribia'),
(44855,'Urumita'),
(44874,'Villanueva'),
(47001,'Santa Marta'),
(47030,'Algarrobo'),
(47053,'Aracataca'),
(47058,'Ariguaní'),
(47161,'Cerro San Antonio'),
(47170,'Chibolo'),
(47189,'Ciénaga'),
(47205,'Concordia'),
(47245,'El Banco'),
(47258,'El Piñon'),
(47268,'El Retén'),
(47288,'Fundación'),
(47318,'Guamal'),
(47460,'Nueva Granada'),
(47541,'Pedraza'),
(47545,'Pijiño Del Carmen'),
(47551,'Pivijay'),
(47555,'Plato'),
(47570,'Puebloviejo'),
(47605,'Remolino'),
(47660,'Sabanas De San Angel'),
(47675,'Salamina'),
(47692,'San Sebastián De Buenavista'),
(47703,'San Zenón'),
(47707,'Santa Ana'),
(47720,'Santa Bárbara De Pinto'),
(47745,'Sitionuevo'),
(47798,'Tenerife'),
(47960,'Zapayán'),
(47980,'Zona Bananera'),
(50001,'Villavicencio'),
(50006,'Acacías'),
(50110,'Barranca De Upía'),
(50124,'Cabuyaro'),
(50150,'Castilla La Nueva'),
(50223,'Cubarral'),
(50226,'Cumaral'),
(50245,'El Calvario'),
(50251,'El Castillo'),
(50270,'El Dorado'),
(50287,'Fuente De Oro'),
(50313,'Granada'),
(50318,'Guamal'),
(50325,'Mapiripán'),
(50330,'Mesetas'),
(50350,'La Macarena'),
(50370,'Uribe'),
(50400,'Lejanías'),
(50450,'Puerto Concordia'),
(50568,'Puerto Gaitán'),
(50573,'Puerto López'),
(50577,'Puerto Lleras'),
(50590,'Puerto Rico'),
(50606,'Restrepo'),
(50680,'San Carlos De Guaroa'),
(50683,'San Juan De Arama'),
(50686,'San Juanito'),
(50689,'San Martín'),
(50711,'Vistahermosa'),
(52001,'Pasto'),
(52019,'Albán'),
(52022,'Aldana'),
(52036,'Ancuya'),
(52051,'Arboleda'),
(52079,'Barbacoas'),
(52083,'Belén'),
(52110,'Buesaco'),
(52203,'Colón'),
(52207,'Consaca'),
(52210,'Contadero'),
(52215,'Córdoba'),
(52224,'Cuaspud'),
(52227,'Cumbal'),
(52233,'Cumbitara'),
(52240,'Chachagüí'),
(52250,'El Charco'),
(52254,'El Peñol'),
(52256,'El Rosario'),
(52258,'El Tablón De Gómez'),
(52260,'El Tambo'),
(52287,'Funes'),
(52317,'Guachucal'),
(52320,'Guaitarilla'),
(52323,'Gualmatán'),
(52352,'Iles'),
(52354,'Imués'),
(52356,'Ipiales'),
(52378,'La Cruz'),
(52381,'La Florida'),
(52385,'La Llanada'),
(52390,'La Tola'),
(52399,'La Unión'),
(52405,'Leiva'),
(52411,'Linares'),
(52418,'Los Andes'),
(52427,'Magüi'),
(52435,'Mallama'),
(52473,'Mosquera'),
(52480,'Nariño'),
(52490,'Olaya Herrera'),
(52506,'Ospina'),
(52520,'Francisco Pizarro'),
(52540,'Policarpa'),
(52560,'Potosí'),
(52565,'Providencia'),
(52573,'Puerres'),
(52585,'Pupiales'),
(52612,'Ricaurte'),
(52621,'Roberto Payán'),
(52678,'Samaniego'),
(52683,'Sandoná'),
(52685,'San Bernardo'),
(52687,'San Lorenzo'),
(52693,'San Pablo'),
(52694,'San Pedro De Cartago'),
(52696,'Santa Bárbara'),
(52699,'Santacruz'),
(52720,'Sapuyes'),
(52786,'Taminango'),
(52788,'Tangua'),
(52835,'San Andres De Tumaco'),
(52838,'Túquerres'),
(52885,'Yacuanquer'),
(54001,'Cúcuta'),
(54003,'Abrego'),
(54051,'Arboledas'),
(54099,'Bochalema'),
(54109,'Bucarasica'),
(54125,'Cácota'),
(54128,'Cachirá'),
(54172,'Chinácota'),
(54174,'Chitagá'),
(54206,'Convención'),
(54223,'Cucutilla'),
(54239,'Durania'),
(54245,'El Carmen'),
(54250,'El Tarra'),
(54261,'El Zulia'),
(54313,'Gramalote'),
(54344,'Hacarí'),
(54347,'Herrán'),
(54377,'Labateca'),
(54385,'La Esperanza'),
(54398,'La Playa'),
(54405,'Los Patios'),
(54418,'Lourdes'),
(54480,'Mutiscua'),
(54498,'Ocaña'),
(54518,'Pamplona'),
(54520,'Pamplonita'),
(54553,'Puerto Santander'),
(54599,'Ragonvalia'),
(54660,'Salazar'),
(54670,'San Calixto'),
(54673,'San Cayetano'),
(54680,'Santiago'),
(54720,'Sardinata'),
(54743,'Silos'),
(54800,'Teorama'),
(54810,'Tibú'),
(54820,'Toledo'),
(54871,'Villa Caro'),
(54874,'Villa Del Rosario'),
(63001,'Armenia'),
(63111,'Buenavista'),
(63130,'Calarca'),
(63190,'Circasia'),
(63212,'Córdoba'),
(63272,'Filandia'),
(63302,'Génova'),
(63401,'La Tebaida'),
(63470,'Montenegro'),
(63548,'Pijao'),
(63594,'Quimbaya'),
(63690,'Salento'),
(66001,'Pereira'),
(66045,'Apía'),
(66075,'Balboa'),
(66088,'Belén De Umbría'),
(66170,'Dosquebradas'),
(66318,'Guática'),
(66383,'La Celia'),
(66400,'La Virginia'),
(66440,'Marsella'),
(66456,'Mistrató'),
(66572,'Pueblo Rico'),
(66594,'Quinchía'),
(66682,'Santa Rosa De Cabal'),
(66687,'Santuario'),
(68001,'Bucaramanga'),
(68013,'Aguada'),
(68020,'Albania'),
(68051,'Aratoca'),
(68077,'Barbosa'),
(68079,'Barichara'),
(68081,'Barrancabermeja'),
(68092,'Betulia'),
(68101,'Bolívar'),
(68121,'Cabrera'),
(68132,'California'),
(68147,'Capitanejo'),
(68152,'Carcasí'),
(68160,'Cepitá'),
(68162,'Cerrito'),
(68167,'Charalá'),
(68169,'Charta'),
(68176,'Chima'),
(68179,'Chipatá'),
(68190,'Cimitarra'),
(68207,'Concepción'),
(68209,'Confines'),
(68211,'Contratación'),
(68217,'Coromoro'),
(68229,'Curití'),
(68235,'El Carmen De Chucurí'),
(68245,'El Guacamayo'),
(68250,'El Peñón'),
(68255,'El Playón'),
(68264,'Encino'),
(68266,'Enciso'),
(68271,'Florián'),
(68276,'Floridablanca'),
(68296,'Galan'),
(68298,'Gambita'),
(68307,'Girón'),
(68318,'Guaca'),
(68320,'Guadalupe'),
(68322,'Guapotá'),
(68324,'Guavatá'),
(68327,'Güepsa'),
(68344,'Hato'),
(68368,'Jesús María'),
(68370,'Jordán'),
(68377,'La Belleza'),
(68385,'Landázuri'),
(68397,'La Paz'),
(68406,'Lebríja'),
(68418,'Los Santos'),
(68425,'Macaravita'),
(68432,'Málaga'),
(68444,'Matanza'),
(68464,'Mogotes'),
(68468,'Molagavita'),
(68498,'Ocamonte'),
(68500,'Oiba'),
(68502,'Onzaga'),
(68522,'Palmar'),
(68524,'Palmas Del Socorro'),
(68533,'Páramo'),
(68547,'Piedecuesta'),
(68549,'Pinchote'),
(68572,'Puente Nacional'),
(68573,'Puerto Parra'),
(68575,'Puerto Wilches'),
(68615,'Rionegro'),
(68655,'Sabana De Torres'),
(68669,'San Andrés'),
(68673,'San Benito'),
(68679,'San Gil'),
(68682,'San Joaquín'),
(68684,'San José De Miranda'),
(68686,'San Miguel'),
(68689,'San Vicente De Chucurí'),
(68705,'Santa Bárbara'),
(68720,'Santa Helena Del Opón'),
(68745,'Simacota'),
(68755,'Socorro'),
(68770,'Suaita'),
(68773,'Sucre'),
(68780,'Suratá'),
(68820,'Tona'),
(68855,'Valle De San José'),
(68861,'Vélez'),
(68867,'Vetas'),
(68872,'Villanueva'),
(68895,'Zapatoca'),
(70001,'Sincelejo'),
(70110,'Buenavista'),
(70124,'Caimito'),
(70204,'Coloso'),
(70215,'Corozal'),
(70221,'Coveñas'),
(70230,'Chalán'),
(70233,'El Roble'),
(70235,'Galeras'),
(70265,'Guaranda'),
(70400,'La Unión'),
(70418,'Los Palmitos'),
(70429,'Majagual'),
(70473,'Morroa'),
(70508,'Ovejas'),
(70523,'Palmito'),
(70670,'Sampués'),
(70678,'San Benito Abad'),
(70702,'San Juan De Betulia'),
(70708,'San Marcos'),
(70713,'San Onofre'),
(70717,'San Pedro'),
(70742,'San Luis De Sincé'),
(70771,'Sucre'),
(70820,'Santiago De Tolú'),
(70823,'Tolú Viejo'),
(73001,'Ibague'),
(73024,'Alpujarra'),
(73026,'Alvarado'),
(73030,'Ambalema'),
(73043,'Anzoátegui'),
(73055,'Armero'),
(73067,'Ataco'),
(73124,'Cajamarca'),
(73148,'Carmen De Apicalá'),
(73152,'Casabianca'),
(73168,'Chaparral'),
(73200,'Coello'),
(73217,'Coyaima'),
(73226,'Cunday'),
(73236,'Dolores'),
(73268,'Espinal'),
(73270,'Falan'),
(73275,'Flandes'),
(73283,'Fresno'),
(73319,'Guamo'),
(73347,'Herveo'),
(73349,'Honda'),
(73352,'Icononzo'),
(73408,'Lérida'),
(73411,'Líbano'),
(73443,'Mariquita'),
(73449,'Melgar'),
(73461,'Murillo'),
(73483,'Natagaima'),
(73504,'Ortega'),
(73520,'Palocabildo'),
(73547,'Piedras'),
(73555,'Planadas'),
(73563,'Prado'),
(73585,'Purificación'),
(73616,'Rioblanco'),
(73622,'Roncesvalles'),
(73624,'Rovira'),
(73671,'Saldaña'),
(73675,'San Antonio'),
(73678,'San Luis'),
(73686,'Santa Isabel'),
(73770,'Suárez'),
(73854,'Valle De San Juan'),
(73861,'Venadillo'),
(73870,'Villahermosa'),
(73873,'Villarrica'),
(76001,'Cali'),
(76020,'Alcalá'),
(76036,'Andalucía'),
(76041,'Ansermanuevo'),
(76054,'Argelia'),
(76100,'Bolívar'),
(76109,'Buenaventura'),
(76111,'Guadalajara De Buga'),
(76113,'Bugalagrande'),
(76122,'Caicedonia'),
(76126,'Calima'),
(76130,'Candelaria'),
(76147,'Cartago'),
(76233,'Dagua'),
(76243,'El Águila'),
(76246,'El Cairo'),
(76248,'El Cerrito'),
(76250,'El Dovio'),
(76275,'Florida'),
(76306,'Ginebra'),
(76318,'Guacarí'),
(76364,'Jamundí'),
(76377,'La Cumbre'),
(76400,'La Unión'),
(76403,'La Victoria'),
(76497,'Obando'),
(76520,'Palmira'),
(76563,'Pradera'),
(76606,'Restrepo'),
(76616,'Riofrío'),
(76622,'Roldanillo'),
(76670,'San Pedro'),
(76736,'Sevilla'),
(76823,'Toro'),
(76828,'Trujillo'),
(76834,'Tuluá'),
(76845,'Ulloa'),
(76863,'Versalles'),
(76869,'Vijes'),
(76890,'Yotoco'),
(76892,'Yumbo'),
(76895,'Zarzal'),
(81001,'Arauca'),
(81065,'Arauquita'),
(81220,'Cravo Norte'),
(81300,'Fortul'),
(81591,'Puerto Rondón'),
(81736,'Saravena'),
(81794,'Tame'),
(85001,'Yopal'),
(85010,'Aguazul'),
(85015,'Chameza'),
(85125,'Hato Corozal'),
(85136,'La Salina'),
(85139,'Maní'),
(85162,'Monterrey'),
(85225,'Nunchía'),
(85230,'Orocué'),
(85250,'Paz De Ariporo'),
(85263,'Pore'),
(85279,'Recetor'),
(85300,'Sabanalarga'),
(85315,'Sácama'),
(85325,'San Luis De Palenque'),
(85400,'Támara'),
(85410,'Tauramena'),
(85430,'Trinidad'),
(85440,'Villanueva'),
(86001,'Mocoa'),
(86219,'Colón'),
(86320,'Orito'),
(86568,'Puerto Asís'),
(86569,'Puerto Caicedo'),
(86571,'Puerto Guzmán'),
(86573,'Leguízamo'),
(86749,'Sibundoy'),
(86755,'San Francisco'),
(86757,'San Miguel'),
(86760,'Santiago'),
(86865,'Valle Del Guamuez'),
(86885,'Villagarzón'),
(88001,'San Andrés'),
(88564,'Providencia'),
(91001,'Leticia'),
(91263,'El Encanto'),
(91405,'La Chorrera'),
(91407,'La Pedrera'),
(91430,'La Victoria'),
(91460,'Miriti - Paraná'),
(91530,'Puerto Alegría'),
(91536,'Puerto Arica'),
(91540,'Puerto Nariño'),
(91669,'Puerto Santander'),
(91798,'Tarapacá'),
(94001,'Inírida'),
(94343,'Barranco Minas'),
(94663,'Mapiripana'),
(94883,'San Felipe'),
(94884,'Puerto Colombia'),
(94885,'La Guadalupe'),
(94886,'Cacahual'),
(94887,'Pana Pana'),
(94888,'Morichal'),
(95001,'San José Del Guaviare'),
(95015,'Calamar'),
(95025,'El Retorno'),
(95200,'Miraflores'),
(97001,'Mitú'),
(97161,'Caruru'),
(97511,'Pacoa'),
(97666,'Taraira'),
(97777,'Papunaua'),
(97889,'Yavaraté'),
(99001,'Puerto Carreño'),
(99524,'La Primavera'),
(99624,'Santa Rosalía'),
(99773,'Cumaribo')
], validators=[
Required()
])
primerNombreEmpleado = StringField('Primer Nombre', validators=[
Required(message='El campo es obligatorio'),
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
segundoNombreEmpleado = StringField('Segundo Nombre', validators=[
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
primerApellidoEmpleado = StringField('Primer Apellido', validators=[
Required(message='El campo es obligatorio'),
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
segundoApellidoEmpleado = StringField('Segundo Apellido', validators=[
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
fechaNacimientoEmpleado = DateField('Fecha de Nacimiento', format='%Y,%M,%D', validators=[])
direccionEmpleado = StringField('Direccion Residencia', validators=[
Required(message='El campo es obligatorio'),
Length(max=50, min=20, message='El campo debe tener entre 20 y 50 caracteres')
])
barrioEmpleado = StringField('Barrio Residencia', validators=[
Required(message='El campo es obligatorio'),
Length(max=20, min=10, message='El campo debe tener entre 10 y 20 caracteres')
])
idPais = SelectField('Pais Residencia', choices=[
('AD','Andorra'),
('AE','Emiratos Arabes Unid'),
('AF','Afganistan'),
('AG','Antigua Y Barbuda'),
('AI','Anguilla'),
('AL','Albania'),
('AM','Armenia'),
('AN','Antillas Holandesas'),
('AO','Angola'),
('AR','Argentina'),
('AS','Samoa Norteamericana'),
('AT','Austria'),
('AU','Australia'),
('AW','Aruba'),
('AZ','Azerbaijan'),
('BA','Bosnia-Herzegovina'),
('BB','Barbados'),
('BD','Bangladesh'),
('BE','Belgica'),
('BF','Burkina Fasso'),
('BG','Bulgaria'),
('BH','Bahrein'),
('BI','Burundi'),
('BJ','Benin'),
('BM','Bermudas'),
('BN','Brunei Darussalam'),
('BO','Bolivia'),
('BR','Brasil'),
('BS','Bahamas'),
('BT','Butan'),
('BW','Botswana'),
('BY','Belorus'),
('BZ','Belice'),
('CA','Canada'),
('CC','Cocos (Keeling) Islas'),
('CD','Republica Democratica Del Congo'),
('CF','Republica Centroafri'),
('CG','Congo'),
('CH','Suiza'),
('CI','Costa De Marfil'),
('CK','Cook Islas'),
('CL','Chile'),
('CM','Camerun Republica U'),
('CN','China'),
('CO','Colombia'),
('CR','Costa Rica'),
('CU','Cuba'),
('CV','Cabo Verde'),
('CX','Navidad (Christmas)'),
('CY','Chipre'),
('CZ','Republica Checa'),
('DE','Alemania'),
('DJ','Djibouti'),
('DK','Dinamarca'),
('DM','Dominica'),
('DO','Republica Dominicana'),
('DZ','Argelia'),
('EC','Ecuador'),
('EE','Estonia'),
('EG','Egipto'),
('EH','Sahara Occidental'),
('ER','Eritrea'),
('ES','España'),
('ET','Etiopia'),
('EU','Comunidad Europea'),
('FI','Finlandia'),
('FJ','Fiji'),
('FM','Micronesia Estados F'),
('FO','Feroe Islas'),
('FR','Francia'),
('GA','Gabon'),
('GB','Reino Unido'),
('GD','Granada'),
('GE','Georgia'),
('GF','Guayana Francesa'),
('GH','Ghana'),
('GI','Gibraltar'),
('GL','Groenlandia'),
('GM','Gambia'),
('GN','Guinea'),
('GP','Guadalupe'),
('GQ','Guinea Ecuatorial'),
('GR','Grecia'),
('GT','Guatemala'),
('GU','Guam'),
('GW','Guinea - Bissau'),
('GY','Guyana'),
('HK','Hong Kong'),
('HN','Honduras'),
('HR','Croacia'),
('HT','Haiti'),
('HU','Hungria'),
('ID','Indonesia'),
('IE','Irlanda (Eire)'),
('IL','Israel'),
('IM','Isla De Man'),
('IN','India'),
('IO','Territori Britanico'),
('IQ','Irak'),
('IR','Iran Republica Islamica'),
('IS','Islandia'),
('IT','Italia'),
('JM','Jamaica'),
('JO','Jordania'),
('JP','Japon'),
('KE','Kenya'),
('KG','Kirguizistan'),
('KH','Kampuchea (Camboya)'),
('KI','Kiribati'),
('KM','Comoras'),
('KN','San Cristobal Y Nieves'),
('KP','Corea Del Norte Republica'),
('KR','Corea Del Sur Republica'),
('KW','Kuwait'),
('KY','Caiman Islas'),
('KZ','Kazajstan'),
('LA','Laos Republica Popular'),
('LB','Libano'),
('LC','Santa Lucia'),
('LI','Liechtenstein'),
('LK','Sri Lanka'),
('LR','Liberia'),
('LS','Lesotho'),
('LT','Lituania'),
('LU','Luxemburgo'),
('LV','Letonia'),
('LY','Libia(Incluye Fezzan'),
('MA','Marruecos'),
('MC','Monaco'),
('MD','Moldavia'),
('MG','Madagascar'),
('MH','Marshall Islas'),
('MK','Macedonia'),
('ML','Mali'),
('MM','Birmania (Myanmar)'),
('MN','Mongolia'),
('MO','Macao'),
('MP','Marianas Del Norte Islas'),
('MQ','Martinica'),
('MR','Mauritania'),
('MS','Monserrat Islas'),
('MT','Malta'),
('MU','Mauricio'),
('MV','Maldivas'),
('MW','Malawi'),
('MX','Mexico'),
('MY','Malasia'),
('MZ','Mozambique'),
('NA','Namibia'),
('NC','Nueva Caledonia'),
('NE','Niger'),
('NF','Norfolk Isla'),
('NG','Nigeria'),
('NI','Nicaragua'),
('NL','Paises Bajos(Holanda'),
('NO','Noruega'),
('NP','Nepal'),
('NR','Nauru'),
('NU','Nive Isla'),
('NZ','Nueva Zelandia'),
('OM','Oman'),
('PA','Panama'),
('PE','Peru'),
('PF','Polinesia Francesa'),
('PG','Papuasia Nuev Guinea'),
('PH','Filipinas'),
('PK','Pakistan'),
('PL','Polonia'),
('PM','San Pedro Y Miguelon'),
('PN','Pitcairn Isla'),
('PR','Puerto Rico'),
('PS','Palestina'),
('PT','Portugal'),
('PW','Palau Islas'),
('PY','Paraguay'),
('QA','Qatar'),
('RE','Reunion'),
('RO','Rumania'),
('RS','Serbia'),
('RU','Rusia'),
('RW','Rwanda'),
('SA','Arabia Saudita'),
('SB','Salomsn Islas'),
('SC','Seychelles'),
('SD','Sudan'),
('SE','Suecia'),
('SG','Singapur'),
('SH','Santa Elena'),
('SI','Eslovenia'),
('SK','Eslovaquia'),
('SL','Sierra Leona'),
('SM','San Marino'),
('SN','Senegal'),
('SO','Somalia'),
('SR','Surinam'),
('ST','Santo Tome Y Princip'),
('SV','El Salvador'),
('SY','Siria Republica Arabe'),
('SZ','Swazilandia'),
('TC','Turcas Y Caicos Isla'),
('TD','Chad'),
('TG','Togo'),
('TH','Tailandia'),
('TJ','Tadjikistan'),
('TK','Tokelau'),
('TL','Timor Del Este'),
('TM','Turkmenistan'),
('TN','Tunicia'),
('TO','Tonga'),
('TR','Turquia'),
('TT','Trinidad Y Tobago'),
('TV','Tuvalu'),
('TW','Taiwan (Formosa)'),
('TZ','Tanzania Republica'),
('UA','Ucrania'),
('UG','Uganda'),
('UM','Islas Menores De Estados Unidos'),
('UN','Niue Isla'),
('US','Estados Unidos'),
('UY','Uruguay'),
('UZ','Uzbekistan'),
('VA','Ciudad Del Vaticano'),
('VC','San Vicente Y Las Gr'),
('VE','Venezuela'),
('VG','Virgenes Islas Britanicas'),
('VI','Virgenes Islas'),
('VN','Vietnam'),
('VU','Vanuatu'),
('WF','Wallis Y Fortuna Islas'),
('WS','Samoa'),
('YE','Yemen'),
('YU','Yugoslavia'),
('ZA','Sudafrica Republica'),
('ZM','Zambia'),
('ZW','Zimbabwe')
], validate_choice=True)
idDepartamento = SelectField('Departamento Residencia', choices=[
(5,'Antioquia'),
(8,'Atlántico'),
(11,'Bogotá DC'),
(13,'Bolívar'),
(15,'Boyacá'),
(17,'Caldas'),
(18,'Caquetá'),
(19,'Cauca'),
(20,'Cesar'),
(23,'Córdoba'),
(25,'Cundinamarca'),
(27,'Chocó'),
(41,'Huila'),
(44,'La Guajira'),
(47,'Magdalena'),
(50,'Meta'),
(52,'Nariño'),
(54,'Norte de Santander'),
(63,'Quindío'),
(66,'Risaralda'),
(68,'Santander'),
(70,'Sucre'),
(73,'Tolima'),
(76,'Valle del Cauca'),
(81,'Arauca'),
(85,'Casanare'),
(86,'Putumayo'),
(88,'San Andres'),
(91,'Amazonas'),
(94,'Guainía'),
(95,'Guaviare'),
(97,'Vaupés'),
(99,'Vichada'),
], validate_choice=True)
idMunicipio = SelectField('Municipio Residencia', choices=[
(5001,'Medellín'),
(5002,'Abejorral'),
(5004,'Abriaquí'),
(5021,'Alejandría'),
(5030,'Amagá'),
(5031,'Amalfi'),
(5034,'Andes'),
(5036,'Angelópolis'),
(5038,'Angostura'),
(5040,'Anorí'),
(5042,'Santafé De Antioquia'),
(5044,'Anza'),
(5045,'Apartadó'),
(5051,'Arboletes'),
(5055,'Argelia'),
(5059,'Armenia'),
(5079,'Barbosa'),
(5086,'Belmira'),
(5088,'Bello'),
(5091,'Betania'),
(5093,'Betulia'),
(5101,'Ciudad Bolívar'),
(5107,'Briceño'),
(5113,'Buriticá'),
(5120,'Cáceres'),
(5125,'Caicedo'),
(5129,'Caldas'),
(5134,'Campamento'),
(5138,'Cañasgordas'),
(5142,'Caracolí'),
(5145,'Caramanta'),
(5147,'Carepa'),
(5148,'El Carmen De Viboral'),
(5150,'Carolina'),
(5154,'Caucasia'),
(5172,'Chigorodó'),
(5190,'Cisneros'),
(5197,'Cocorná'),
(5206,'Concepción'),
(5209,'Concordia'),
(5212,'Copacabana'),
(5234,'Dabeiba'),
(5237,'Don Matías'),
(5240,'Ebéjico'),
(5250,'El Bagre'),
(5264,'Entrerrios'),
(5266,'Envigado'),
(5282,'Fredonia'),
(5284,'Frontino'),
(5306,'Giraldo'),
(5308,'Girardota'),
(5310,'Gómez Plata'),
(5313,'Granada'),
(5315,'Guadalupe'),
(5318,'Guarne'),
(5321,'Guatape'),
(5347,'Heliconia'),
(5353,'Hispania'),
(5360,'Itagui'),
(5361,'Ituango'),
(5364,'Jardín'),
(5368,'Jericó'),
(5376,'La Ceja'),
(5380,'La Estrella'),
(5390,'La Pintada'),
(5400,'La Unión'),
(5411,'Liborina'),
(5425,'Maceo'),
(5440,'Marinilla'),
(5467,'Montebello'),
(5475,'Murindó'),
(5480,'Mutatá'),
(5483,'Nariño'),
(5490,'Necoclí'),
(5495,'Nechí'),
(5501,'Olaya'),
(5541,'Peñol'),
(5543,'Peque'),
(5576,'Pueblorrico'),
(5579,'Puerto Berrío'),
(5585,'Puerto Nare'),
(5591,'Puerto Triunfo'),
(5604,'Remedios'),
(5607,'Retiro'),
(5615,'Rionegro'),
(5628,'Sabanalarga'),
(5631,'Sabaneta'),
(5642,'Salgar'),
(5647,'San Andrés De Cuerquía'),
(5649,'San Carlos'),
(5652,'San Francisco'),
(5656,'San Jerónimo'),
(5658,'San José De La Montaña'),
(5659,'San Juan De Urabá'),
(5660,'San Luis'),
(5664,'San Pedro'),
(5665,'San Pedro De Uraba'),
(5667,'San Rafael'),
(5670,'San Roque'),
(5674,'San Vicente'),
(5679,'Santa Bárbara'),
(5686,'Santa Rosa De Osos'),
(5690,'Santo Domingo'),
(5697,'El Santuario'),
(5736,'Segovia'),
(5756,'Sonson'),
(5761,'Sopetrán'),
(5789,'Támesis'),
(5790,'Tarazá'),
(5792,'Tarso'),
(5809,'Titiribí'),
(5819,'Toledo'),
(5837,'Turbo'),
(5842,'Uramita'),
(5847,'Urrao'),
(5854,'Valdivia'),
(5856,'Valparaíso'),
(5858,'Vegachí'),
(5861,'Venecia'),
(5873,'Vigía Del Fuerte'),
(5885,'Yalí'),
(5887,'Yarumal'),
(5890,'Yolombó'),
(5893,'Yondó'),
(5895,'Zaragoza'),
(8001,'Barranquilla'),
(8078,'Baranoa'),
(8137,'Campo De La Cruz'),
(8141,'Candelaria'),
(8296,'Galapa'),
(8372,'Juan De Acosta'),
(8421,'Luruaco'),
(8433,'Malambo'),
(8436,'Manatí'),
(8520,'Palmar De Varela'),
(8549,'Piojó'),
(8558,'Polonuevo'),
(8560,'Ponedera'),
(8573,'Puerto Colombia'),
(8606,'Repelón'),
(8634,'Sabanagrande'),
(8638,'Sabanalarga'),
(8675,'Santa Lucía'),
(8685,'Santo Tomás'),
(8758,'Soledad'),
(8770,'Suan'),
(8832,'Tubará'),
(8849,'Usiacurí'),
(11001,'Bogota DC'),
(13001,'Cartagena'),
(13006,'Choachí'),
(13030,'Altos Del Rosario'),
(13042,'Arenal'),
(13052,'Arjona'),
(13062,'Arroyohondo'),
(13074,'Barranco De Loba'),
(13140,'Calamar'),
(13160,'Cantagallo'),
(13188,'Cicuco'),
(13212,'Córdoba'),
(13222,'Clemencia'),
(13244,'El Carmen De Bolívar'),
(13248,'El Guamo'),
(13268,'El Peñón'),
(13300,'Hatillo De Loba'),
(13430,'Magangué'),
(13433,'Mahates'),
(13440,'Margarita'),
(13442,'María La Baja'),
(13458,'Montecristo'),
(13468,'Mompós'),
(13473,'Morales'),
(13549,'Pinillos'),
(13580,'Regidor'),
(13600,'Río Viejo'),
(13620,'San Cristóbal'),
(13647,'San Estanislao'),
(13650,'San Fernando'),
(13654,'San Jacinto'),
(13655,'San Jacinto Del Cauca'),
(13657,'San Juan Nepomuceno'),
(13667,'San Martín De Loba'),
(13670,'San Pablo'),
(13673,'Santa Catalina'),
(13683,'Santa Rosa'),
(13688,'Santa Rosa Del Sur'),
(13744,'Simití'),
(13760,'Soplaviento'),
(13780,'Talaigua Nuevo'),
(13810,'Tiquisio'),
(13836,'Turbaco'),
(13838,'Turbaná'),
(13873,'Villanueva'),
(13894,'Zambrano'),
(15001,'Tunja'),
(15022,'Almeida'),
(15047,'Aquitania'),
(15051,'Arcabuco'),
(15087,'Belén'),
(15090,'Berbeo'),
(15092,'Betéitiva'),
(15097,'Boavita'),
(15104,'Boyacá'),
(15106,'Briceño'),
(15109,'Buenavista'),
(15114,'Busbanzá'),
(15131,'Caldas'),
(15135,'Campohermoso'),
(15162,'Cerinza'),
(15172,'Chinavita'),
(15176,'Chiquinquirá'),
(15180,'Chiscas'),
(15183,'Chita'),
(15185,'Chitaraque'),
(15187,'Chivatá'),
(15189,'Ciénega'),
(15204,'Cómbita'),
(15212,'Coper'),
(15215,'Corrales'),
(15218,'Covarachía'),
(15223,'Cubará'),
(15224,'Cucaita'),
(15226,'Cuítiva'),
(15232,'Chíquiza'),
(15236,'Chivor'),
(15238,'Duitama'),
(15244,'El Cocuy'),
(15248,'El6Aspino'),
(15272,'Firavitoba'),
(15276,'Floresta'),
(15293,'Gachantivá'),
(15296,'Gameza'),
(15299,'Garagoa'),
(15317,'Guacamayas'),
(15322,'Guateque'),
(15325,'Guayatá'),
(15332,'Guican'),
(15362,'Iza'),
(15367,'Jenesano'),
(15368,'Jericó'),
(15377,'Labranzagrande'),
(15380,'La Capilla'),
(15401,'La Victoria'),
(15403,'La Uvita'),
(15407,'Villa De Leyva'),
(15425,'Macanal'),
(15442,'Maripí'),
(15455,'Miraflores'),
(15464,'Mongua'),
(15466,'Monguí'),
(15469,'Moniquirá'),
(15476,'Motavita'),
(15480,'Muzo'),
(15491,'Nobsa'),
(15494,'Nuevo Colón'),
(15500,'Oicatá'),
(15507,'Otanche'),
(15511,'Pachavita'),
(15514,'Páez'),
(15516,'Paipa'),
(15518,'Pajarito'),
(15522,'Panqueba'),
(15531,'Pauna'),
(15533,'Paya'),
(15537,'Paz De Río'),
(15542,'Pesca'),
(15550,'Pisba'),
(15572,'Puerto Boyacá'),
(15580,'Quípama'),
(15599,'Ramiriquí'),
(15600,'Ráquira'),
(15621,'Rondón'),
(15632,'Saboyá'),
(15638,'Sáchica'),
(15646,'Samacá'),
(15660,'San Eduardo'),
(15664,'San José De Pare'),
(15667,'San Luis De Gaceno'),
(15673,'San Mateo'),
(15676,'San Miguel De Sema'),
(15681,'San Pablo De Borbur'),
(15686,'Santana'),
(15690,'Santa María'),
(15693,'Santa Rosa De Viterbo'),
(15696,'Santa Sofía'),
(15720,'Sativanorte'),
(15723,'Sativasur'),
(15740,'Siachoque'),
(15753,'Soatá'),
(15755,'Socotá'),
(15757,'Socha'),
(15759,'Sogamoso'),
(15761,'Somondoco'),
(15762,'Sora'),
(15763,'Sotaquirá'),
(15764,'Soracá'),
(15774,'Susacón'),
(15776,'Sutamarchán'),
(15778,'Sutatenza'),
(15790,'Tasco'),
(15798,'Tenza'),
(15804,'Tibaná'),
(15806,'Tibasosa'),
(15808,'Tinjacá'),
(15810,'Tipacoque'),
(15814,'Toca'),
(15816,'Togüí'),
(15820,'Tópaga'),
(15822,'Tota'),
(15832,'Tununguá'),
(15835,'Turmequé'),
(15837,'Tuta'),
(15839,'Tutazá'),
(15842,'Umbita'),
(15861,'Ventaquemada'),
(15879,'Viracachá'),
(15897,'Zetaquira'),
(17001,'Manizales'),
(17013,'Aguadas'),
(17042,'Anserma'),
(17050,'Aranzazu'),
(17088,'Belalcázar'),
(17174,'Chinchiná'),
(17272,'Filadelfia'),
(17380,'La Dorada'),
(17388,'La Merced'),
(17433,'Manzanares'),
(17442,'Marmato'),
(17444,'Marquetalia'),
(17446,'Marulanda'),
(17486,'Neira'),
(17495,'Norcasia'),
(17513,'Pácora'),
(17524,'Palestina'),
(17541,'Pensilvania'),
(17614,'Riosucio'),
(17616,'Risaralda'),
(17653,'Salamina'),
(17662,'Samaná'),
(17665,'San José'),
(17777,'Supía'),
(17867,'Victoria'),
(17873,'Villamaría'),
(17877,'Viterbo'),
(18001,'Florencia'),
(18029,'Albania'),
(18094,'Belén De Los Andaquies'),
(18150,'Cartagena Del Chairá'),
(18205,'Curillo'),
(18247,'El Doncello'),
(18256,'El Paujil'),
(18410,'La Montañita'),
(18460,'Milán'),
(18479,'Morelia'),
(18592,'Puerto Rico'),
(18610,'San José Del Fragua'),
(18753,'San Vicente Del Caguán'),
(18756,'Solano'),
(18785,'Solita'),
(18860,'Valparaíso'),
(19001,'Popayán'),
(19022,'Almaguer'),
(19050,'Argelia'),
(19075,'Balboa'),
(19100,'Bolívar'),
(19110,'Buenos Aires'),
(19130,'Cajibío'),
(19137,'Caldono'),
(19142,'Caloto'),
(19212,'Corinto'),
(19256,'El Tambo'),
(19290,'Florencia'),
(19300,'Guachené'),
(19318,'Guapi'),
(19355,'Inzá'),
(19364,'Jambaló'),
(19392,'La Sierra'),
(19397,'La Vega'),
(19418,'López'),
(19450,'Mercaderes'),
(19455,'Miranda'),
(19473,'Morales'),
(19513,'Padilla'),
(19517,'Paez'),
(19532,'Patía'),
(19533,'Piamonte'),
(19548,'Piendamó'),
(19573,'Puerto Tejada'),
(19585,'Puracé'),
(19622,'Rosas'),
(19693,'San Sebastián'),
(19698,'Santander De Quilichao'),
(19701,'Santa Rosa'),
(19743,'Silvia'),
(19760,'Sotara'),
(19780,'Suárez'),
(19785,'Sucre'),
(19807,'Timbío'),
(19809,'Timbiquí'),
(19821,'Toribio'),
(19824,'Totoró'),
(19845,'Villa Rica'),
(20001,'Valledupar'),
(20011,'Aguachica'),
(20013,'Agustín Codazzi'),
(20032,'Astrea'),
(20045,'Becerril'),
(20060,'Bosconia'),
(20175,'Chimichagua'),
(20178,'Chiriguaná'),
(20228,'Curumaní'),
(20238,'El Copey'),
(20250,'El Paso'),
(20295,'Gamarra'),
(20310,'González'),
(20383,'La Gloria'),
(20400,'La Jagua De Ibirico'),
(20443,'Manaure'),
(20517,'Pailitas'),
(20550,'Pelaya'),
(20570,'Pueblo Bello'),
(20614,'Río De Oro'),
(20621,'La Paz'),
(20710,'San Alberto'),
(20750,'San Diego'),
(20770,'San Martín'),
(20787,'Tamalameque'),
(23001,'Montería'),
(23068,'Ayapel'),
(23079,'Buenavista'),
(23090,'Canalete'),
(23162,'Cereté'),
(23168,'Chimá'),
(23182,'Chinú'),
(23189,'Ciénaga De Oro'),
(23300,'Cotorra'),
(23350,'La Apartada'),
(23417,'Lorica'),
(23419,'Los Córdobas'),
(23464,'Momil'),
(23466,'Montelíbano'),
(23500,'Moñitos'),
(23555,'Planeta Rica'),
(23570,'Pueblo Nuevo'),
(23574,'Puerto Escondido'),
(23580,'Puerto Libertador'),
(23586,'Purísima'),
(23660,'Sahagún'),
(23670,'San Andrés Sotavento'),
(23672,'San Antero'),
(23675,'San Bernardo Del Viento'),
(23678,'San Carlos'),
(23686,'San Pelayo'),
(23807,'Tierralta'),
(23855,'Valencia'),
(25001,'Agua De Dios'),
(25019,'Albán'),
(25035,'Anapoima'),
(25040,'Anolaima'),
(25053,'Arbeláez'),
(25086,'Beltrán'),
(25095,'Bituima'),
(25099,'Bojacá'),
(25120,'Cabrera'),
(25123,'Cachipay'),
(25126,'Cajicá'),
(25148,'Caparrapí'),
(25151,'Caqueza'),
(25154,'Carmen De Carupa'),
(25168,'Chaguaní'),
(25175,'Chía'),
(25178,'Chipaque'),
(25181,'Choachí'),
(25183,'Chocontá'),
(25200,'Cogua'),
(25214,'Cota'),
(25224,'Cucunuba'),
(25245,'El Colegio'),
(25258,'El Peñón'),
(25260,'El Rosal'),
(25269,'Facatativá'),
(25279,'Fomeque'),
(25281,'Fosca'),
(25286,'Funza'),
(25288,'Fúquene'),
(25290,'Fusagasugá'),
(25293,'Gachala'),
(25295,'Gachancipá'),
(25297,'Gachetá'),
(25299,'Gama'),
(25307,'Girardot'),
(25312,'Granada'),
(25317,'Guachetá'),
(25320,'Guaduas'),
(25322,'Guasca'),
(25324,'Guataquí'),
(25326,'Guatavita'),
(25328,'Guayabal De Siquima'),
(25335,'Guayabetal'),
(25339,'Gutiérrez'),
(25368,'Jerusalén'),
(25372,'Junín'),
(25377,'La Calera'),
(25386,'La Mesa'),
(25394,'La Palma'),
(25398,'La Peña'),
(25402,'La Vega'),
(25407,'Lenguazaque'),
(25426,'Macheta'),
(25430,'Madrid'),
(25436,'Manta'),
(25438,'Medina'),
(25473,'Mosquera'),
(25483,'Nariño'),
(25486,'Nemocón'),
(25488,'Nilo'),
(25489,'Nimaima'),
(25491,'Nocaima'),
(25506,'Venecia'),
(25513,'Pacho'),
(25518,'Paime'),
(25524,'Pandi'),
(25530,'Paratebueno'),
(25535,'Pasca'),
(25572,'Puerto Salgar'),
(25580,'Pulí'),
(25592,'Quebradanegra'),
(25594,'Quetame'),
(25596,'Quipile'),
(25599,'Apulo'),
(25612,'Ricaurte'),
(25645,'San Antonio Del Tequendama'),
(25649,'San Bernardo'),
(25653,'San Cayetano'),
(25658,'San Francisco'),
(25662,'San Juan De Río Seco'),
(25718,'Sasaima'),
(25736,'Sesquilé'),
(25740,'Sibaté'),
(25743,'Silvania'),
(25745,'Simijaca'),
(25754,'Soacha'),
(25758,'Sopó'),
(25769,'Subachoque'),
(25772,'Suesca'),
(25777,'Supatá'),
(25779,'Susa'),
(25781,'Sutatausa'),
(25785,'Tabio'),
(25793,'Tausa'),
(25797,'Tena'),
(25799,'Tenjo'),
(25805,'Tibacuy'),
(25807,'Tibirita'),
(25815,'Tocaima'),
(25817,'Tocancipá'),
(25823,'Topaipi'),
(25839,'Ubalá'),
(25841,'Ubaque'),
(25843,'Villa De San Diego De Ubate'),
(25845,'Une'),
(25851,'Útica'),
(25862,'Vergara'),
(25867,'Vianí'),
(25871,'Villagómez'),
(25873,'Villapinzón'),
(25875,'Villeta'),
(25878,'Viotá'),
(25885,'Yacopí'),
(25898,'Zipacón'),
(25899,'Zipaquirá'),
(27001,'Quibdó'),
(27006,'Acandí'),
(27025,'Alto Baudo'),
(27050,'Atrato'),
(27073,'Bagadó'),
(27075,'Bahía Solano'),
(27077,'Bajo Baudó'),
(27086,'Belén De Bajirá'),
(27099,'Bojaya'),
(27135,'El Cantón Del San Pablo'),
(27150,'Carmen Del Darien'),
(27160,'Cértegui'),
(27205,'Condoto'),
(27245,'El Carmen De Atrato'),
(27250,'El Litoral Del San Juan'),
(27361,'Istmina'),
(27372,'Juradó'),
(27413,'Lloró'),
(27425,'Medio Atrato'),
(27430,'Medio Baudó'),
(27450,'Medio San Juan'),
(27491,'Nóvita'),
(27495,'Nuquí'),
(27580,'Río Iro'),
(27600,'Río Quito'),
(27615,'Riosucio'),
(27660,'San José Del Palmar'),
(27745,'Sipí'),
(27787,'Tadó'),
(27800,'Unguía'),
(27810,'Unión Panamericana'),
(41001,'Neiva'),
(41006,'Acevedo'),
(41013,'Agrado'),
(41016,'Aipe'),
(41020,'Algeciras'),
(41026,'Altamira'),
(41078,'Baraya'),
(41132,'Campoalegre'),
(41206,'Colombia'),
(41244,'Elías'),
(41298,'Garzón'),
(41306,'Gigante'),
(41319,'Guadalupe'),
(41349,'Hobo'),
(41357,'Iquira'),
(41359,'Isnos'),
(41378,'La Argentina'),
(41396,'La Plata'),
(41483,'Nátaga'),
(41503,'Oporapa'),
(41518,'Paicol'),
(41524,'Palermo'),
(41530,'Palestina'),
(41548,'Pital'),
(41551,'Pitalito'),
(41615,'Rivera'),
(41660,'Saladoblanco'),
(41668,'San Agustín'),
(41676,'Santa María'),
(41770,'Suaza'),
(41791,'Tarqui'),
(41797,'Tesalia'),
(41799,'Tello'),
(41801,'Teruel'),
(41807,'Timana'),
(41872,'Villavieja'),
(41885,'Yaguará'),
(44001,'Riohacha'),
(44035,'Albania'),
(44078,'Barrancas'),
(44090,'Dibulla'),
(44098,'Distracción'),
(44110,'El Molino'),
(44279,'Fonseca'),
(44378,'Hatonuevo'),
(44420,'La Jagua Del Pilar'),
(44430,'Maicao'),
(44560,'Manaure'),
(44650,'San Juan Del Cesar'),
(44847,'Uribia'),
(44855,'Urumita'),
(44874,'Villanueva'),
(47001,'Santa Marta'),
(47030,'Algarrobo'),
(47053,'Aracataca'),
(47058,'Ariguaní'),
(47161,'Cerro San Antonio'),
(47170,'Chibolo'),
(47189,'Ciénaga'),
(47205,'Concordia'),
(47245,'El Banco'),
(47258,'El Piñon'),
(47268,'El Retén'),
(47288,'Fundación'),
(47318,'Guamal'),
(47460,'Nueva Granada'),
(47541,'Pedraza'),
(47545,'Pijiño Del Carmen'),
(47551,'Pivijay'),
(47555,'Plato'),
(47570,'Puebloviejo'),
(47605,'Remolino'),
(47660,'Sabanas De San Angel'),
(47675,'Salamina'),
(47692,'San Sebastián De Buenavista'),
(47703,'San Zenón'),
(47707,'Santa Ana'),
(47720,'Santa Bárbara De Pinto'),
(47745,'Sitionuevo'),
(47798,'Tenerife'),
(47960,'Zapayán'),
(47980,'Zona Bananera'),
(50001,'Villavicencio'),
(50006,'Acacías'),
(50110,'Barranca De Upía'),
(50124,'Cabuyaro'),
(50150,'Castilla La Nueva'),
(50223,'Cubarral'),
(50226,'Cumaral'),
(50245,'El Calvario'),
(50251,'El Castillo'),
(50270,'El Dorado'),
(50287,'Fuente De Oro'),
(50313,'Granada'),
(50318,'Guamal'),
(50325,'Mapiripán'),
(50330,'Mesetas'),
(50350,'La Macarena'),
(50370,'Uribe'),
(50400,'Lejanías'),
(50450,'Puerto Concordia'),
(50568,'Puerto Gaitán'),
(50573,'Puerto López'),
(50577,'Puerto Lleras'),
(50590,'Puerto Rico'),
(50606,'Restrepo'),
(50680,'San Carlos De Guaroa'),
(50683,'San Juan De Arama'),
(50686,'San Juanito'),
(50689,'San Martín'),
(50711,'Vistahermosa'),
(52001,'Pasto'),
(52019,'Albán'),
(52022,'Aldana'),
(52036,'Ancuya'),
(52051,'Arboleda'),
(52079,'Barbacoas'),
(52083,'Belén'),
(52110,'Buesaco'),
(52203,'Colón'),
(52207,'Consaca'),
(52210,'Contadero'),
(52215,'Córdoba'),
(52224,'Cuaspud'),
(52227,'Cumbal'),
(52233,'Cumbitara'),
(52240,'Chachagüí'),
(52250,'El Charco'),
(52254,'El Peñol'),
(52256,'El Rosario'),
(52258,'El Tablón De Gómez'),
(52260,'El Tambo'),
(52287,'Funes'),
(52317,'Guachucal'),
(52320,'Guaitarilla'),
(52323,'Gualmatán'),
(52352,'Iles'),
(52354,'Imués'),
(52356,'Ipiales'),
(52378,'La Cruz'),
(52381,'La Florida'),
(52385,'La Llanada'),
(52390,'La Tola'),
(52399,'La Unión'),
(52405,'Leiva'),
(52411,'Linares'),
(52418,'Los Andes'),
(52427,'Magüi'),
(52435,'Mallama'),
(52473,'Mosquera'),
(52480,'Nariño'),
(52490,'Olaya Herrera'),
(52506,'Ospina'),
(52520,'Francisco Pizarro'),
(52540,'Policarpa'),
(52560,'Potosí'),
(52565,'Providencia'),
(52573,'Puerres'),
(52585,'Pupiales'),
(52612,'Ricaurte'),
(52621,'Roberto Payán'),
(52678,'Samaniego'),
(52683,'Sandoná'),
(52685,'San Bernardo'),
(52687,'San Lorenzo'),
(52693,'San Pablo'),
(52694,'San Pedro De Cartago'),
(52696,'Santa Bárbara'),
(52699,'Santacruz'),
(52720,'Sapuyes'),
(52786,'Taminango'),
(52788,'Tangua'),
(52835,'San Andres De Tumaco'),
(52838,'Túquerres'),
(52885,'Yacuanquer'),
(54001,'Cúcuta'),
(54003,'Abrego'),
(54051,'Arboledas'),
(54099,'Bochalema'),
(54109,'Bucarasica'),
(54125,'Cácota'),
(54128,'Cachirá'),
(54172,'Chinácota'),
(54174,'Chitagá'),
(54206,'Convención'),
(54223,'Cucutilla'),
(54239,'Durania'),
(54245,'El Carmen'),
(54250,'El Tarra'),
(54261,'El Zulia'),
(54313,'Gramalote'),
(54344,'Hacarí'),
(54347,'Herrán'),
(54377,'Labateca'),
(54385,'La Esperanza'),
(54398,'La Playa'),
(54405,'Los Patios'),
(54418,'Lourdes'),
(54480,'Mutiscua'),
(54498,'Ocaña'),
(54518,'Pamplona'),
(54520,'Pamplonita'),
(54553,'Puerto Santander'),
(54599,'Ragonvalia'),
(54660,'Salazar'),
(54670,'San Calixto'),
(54673,'San Cayetano'),
(54680,'Santiago'),
(54720,'Sardinata'),
(54743,'Silos'),
(54800,'Teorama'),
(54810,'Tibú'),
(54820,'Toledo'),
(54871,'Villa Caro'),
(54874,'Villa Del Rosario'),
(63001,'Armenia'),
(63111,'Buenavista'),
(63130,'Calarca'),
(63190,'Circasia'),
(63212,'Córdoba'),
(63272,'Filandia'),
(63302,'Génova'),
(63401,'La Tebaida'),
(63470,'Montenegro'),
(63548,'Pijao'),
(63594,'Quimbaya'),
(63690,'Salento'),
(66001,'Pereira'),
(66045,'Apía'),
(66075,'Balboa'),
(66088,'Belén De Umbría'),
(66170,'Dosquebradas'),
(66318,'Guática'),
(66383,'La Celia'),
(66400,'La Virginia'),
(66440,'Marsella'),
(66456,'Mistrató'),
(66572,'Pueblo Rico'),
(66594,'Quinchía'),
(66682,'Santa Rosa De Cabal'),
(66687,'Santuario'),
(68001,'Bucaramanga'),
(68013,'Aguada'),
(68020,'Albania'),
(68051,'Aratoca'),
(68077,'Barbosa'),
(68079,'Barichara'),
(68081,'Barrancabermeja'),
(68092,'Betulia'),
(68101,'Bolívar'),
(68121,'Cabrera'),
(68132,'California'),
(68147,'Capitanejo'),
(68152,'Carcasí'),
(68160,'Cepitá'),
(68162,'Cerrito'),
(68167,'Charalá'),
(68169,'Charta'),
(68176,'Chima'),
(68179,'Chipatá'),
(68190,'Cimitarra'),
(68207,'Concepción'),
(68209,'Confines'),
(68211,'Contratación'),
(68217,'Coromoro'),
(68229,'Curití'),
(68235,'El Carmen De Chucurí'),
(68245,'El Guacamayo'),
(68250,'El Peñón'),
(68255,'El Playón'),
(68264,'Encino'),
(68266,'Enciso'),
(68271,'Florián'),
(68276,'Floridablanca'),
(68296,'Galan'),
(68298,'Gambita'),
(68307,'Girón'),
(68318,'Guaca'),
(68320,'Guadalupe'),
(68322,'Guapotá'),
(68324,'Guavatá'),
(68327,'Güepsa'),
(68344,'Hato'),
(68368,'Jesús María'),
(68370,'Jordán'),
(68377,'La Belleza'),
(68385,'Landázuri'),
(68397,'La Paz'),
(68406,'Lebríja'),
(68418,'Los Santos'),
(68425,'Macaravita'),
(68432,'Málaga'),
(68444,'Matanza'),
(68464,'Mogotes'),
(68468,'Molagavita'),
(68498,'Ocamonte'),
(68500,'Oiba'),
(68502,'Onzaga'),
(68522,'Palmar'),
(68524,'Palmas Del Socorro'),
(68533,'Páramo'),
(68547,'Piedecuesta'),
(68549,'Pinchote'),
(68572,'Puente Nacional'),
(68573,'Puerto Parra'),
(68575,'Puerto Wilches'),
(68615,'Rionegro'),
(68655,'Sabana De Torres'),
(68669,'San Andrés'),
(68673,'San Benito'),
(68679,'San Gil'),
(68682,'San Joaquín'),
(68684,'San José De Miranda'),
(68686,'San Miguel'),
(68689,'San Vicente De Chucurí'),
(68705,'Santa Bárbara'),
(68720,'Santa Helena Del Opón'),
(68745,'Simacota'),
(68755,'Socorro'),
(68770,'Suaita'),
(68773,'Sucre'),
(68780,'Suratá'),
(68820,'Tona'),
(68855,'Valle De San José'),
(68861,'Vélez'),
(68867,'Vetas'),
(68872,'Villanueva'),
(68895,'Zapatoca'),
(70001,'Sincelejo'),
(70110,'Buenavista'),
(70124,'Caimito'),
(70204,'Coloso'),
(70215,'Corozal'),
(70221,'Coveñas'),
(70230,'Chalán'),
(70233,'El Roble'),
(70235,'Galeras'),
(70265,'Guaranda'),
(70400,'La Unión'),
(70418,'Los Palmitos'),
(70429,'Majagual'),
(70473,'Morroa'),
(70508,'Ovejas'),
(70523,'Palmito'),
(70670,'Sampués'),
(70678,'San Benito Abad'),
(70702,'San Juan De Betulia'),
(70708,'San Marcos'),
(70713,'San Onofre'),
(70717,'San Pedro'),
(70742,'San Luis De Sincé'),
(70771,'Sucre'),
(70820,'Santiago De Tolú'),
(70823,'Tolú Viejo'),
(73001,'Ibague'),
(73024,'Alpujarra'),
(73026,'Alvarado'),
(73030,'Ambalema'),
(73043,'Anzoátegui'),
(73055,'Armero'),
(73067,'Ataco'),
(73124,'Cajamarca'),
(73148,'Carmen De Apicalá'),
(73152,'Casabianca'),
(73168,'Chaparral'),
(73200,'Coello'),
(73217,'Coyaima'),
(73226,'Cunday'),
(73236,'Dolores'),
(73268,'Espinal'),
(73270,'Falan'),
(73275,'Flandes'),
(73283,'Fresno'),
(73319,'Guamo'),
(73347,'Herveo'),
(73349,'Honda'),
(73352,'Icononzo'),
(73408,'Lérida'),
(73411,'Líbano'),
(73443,'Mariquita'),
(73449,'Melgar'),
(73461,'Murillo'),
(73483,'Natagaima'),
(73504,'Ortega'),
(73520,'Palocabildo'),
(73547,'Piedras'),
(73555,'Planadas'),
(73563,'Prado'),
(73585,'Purificación'),
(73616,'Rioblanco'),
(73622,'Roncesvalles'),
(73624,'Rovira'),
(73671,'Saldaña'),
(73675,'San Antonio'),
(73678,'San Luis'),
(73686,'Santa Isabel'),
(73770,'Suárez'),
(73854,'Valle De San Juan'),
(73861,'Venadillo'),
(73870,'Villahermosa'),
(73873,'Villarrica'),
(76001,'Cali'),
(76020,'Alcalá'),
(76036,'Andalucía'),
(76041,'Ansermanuevo'),
(76054,'Argelia'),
(76100,'Bolívar'),
(76109,'Buenaventura'),
(76111,'Guadalajara De Buga'),
(76113,'Bugalagrande'),
(76122,'Caicedonia'),
(76126,'Calima'),
(76130,'Candelaria'),
(76147,'Cartago'),
(76233,'Dagua'),
(76243,'El Águila'),
(76246,'El Cairo'),
(76248,'El Cerrito'),
(76250,'El Dovio'),
(76275,'Florida'),
(76306,'Ginebra'),
(76318,'Guacarí'),
(76364,'Jamundí'),
(76377,'La Cumbre'),
(76400,'La Unión'),
(76403,'La Victoria'),
(76497,'Obando'),
(76520,'Palmira'),
(76563,'Pradera'),
(76606,'Restrepo'),
(76616,'Riofrío'),
(76622,'Roldanillo'),
(76670,'San Pedro'),
(76736,'Sevilla'),
(76823,'Toro'),
(76828,'Trujillo'),
(76834,'Tuluá'),
(76845,'Ulloa'),
(76863,'Versalles'),
(76869,'Vijes'),
(76890,'Yotoco'),
(76892,'Yumbo'),
(76895,'Zarzal'),
(81001,'Arauca'),
(81065,'Arauquita'),
(81220,'Cravo Norte'),
(81300,'Fortul'),
(81591,'Puerto Rondón'),
(81736,'Saravena'),
(81794,'Tame'),
(85001,'Yopal'),
(85010,'Aguazul'),
(85015,'Chameza'),
(85125,'Hato Corozal'),
(85136,'La Salina'),
(85139,'Maní'),
(85162,'Monterrey'),
(85225,'Nunchía'),
(85230,'Orocué'),
(85250,'Paz De Ariporo'),
(85263,'Pore'),
(85279,'Recetor'),
(85300,'Sabanalarga'),
(85315,'Sácama'),
(85325,'San Luis De Palenque'),
(85400,'Támara'),
(85410,'Tauramena'),
(85430,'Trinidad'),
(85440,'Villanueva'),
(86001,'Mocoa'),
(86219,'Colón'),
(86320,'Orito'),
(86568,'Puerto Asís'),
(86569,'Puerto Caicedo'),
(86571,'Puerto Guzmán'),
(86573,'Leguízamo'),
(86749,'Sibundoy'),
(86755,'San Francisco'),
(86757,'San Miguel'),
(86760,'Santiago'),
(86865,'Valle Del Guamuez'),
(86885,'Villagarzón'),
(88001,'San Andrés'),
(88564,'Providencia'),
(91001,'Leticia'),
(91263,'El Encanto'),
(91405,'La Chorrera'),
(91407,'La Pedrera'),
(91430,'La Victoria'),
(91460,'Miriti - Paraná'),
(91530,'Puerto Alegría'),
(91536,'Puerto Arica'),
(91540,'Puerto Nariño'),
(91669,'Puerto Santander'),
(91798,'Tarapacá'),
(94001,'Inírida'),
(94343,'Barranco Minas'),
(94663,'Mapiripana'),
(94883,'San Felipe'),
(94884,'Puerto Colombia'),
(94885,'La Guadalupe'),
(94886,'Cacahual'),
(94887,'Pana Pana'),
(94888,'Morichal'),
(95001,'San José Del Guaviare'),
(95015,'Calamar'),
(95025,'El Retorno'),
(95200,'Miraflores'),
(97001,'Mitú'),
(97161,'Caruru'),
(97511,'Pacoa'),
(97666,'Taraira'),
(97777,'Papunaua'),
(97889,'Yavaraté'),
(99001,'Puerto Carreño'),
(99524,'La Primavera'),
(99624,'Santa Rosalía'),
(99773,'Cumaribo')
], validate_choice=True)
celularEmpleado = IntegerField('Numero Telefono Movil', validators=[
Required(message='El campo es obligatorio'),
Length(max=10, min=10, message='El campo debe tener 10 caracteres')
])
correoElectronicoEmpleado = StringField('Correo Electronico Principal', validators=[
Required(message='El campo es obligatorio'),
Email()
])
enviar = SubmitField("Enviar")
class ingresoEmpleado(FlaskForm):
correoElectronicoEmpleado = StringField('Correo Electronico Principal', validators=[
Required(message='El campo es obligatorio'),
Email()
])
contraseñaEmpleado = PasswordField('Contraseña')
enviar = SubmitField("Enviar")
class editarEmpleado(FlaskForm):
numeroIdEmpleado = IntegerField('Numero Identificacion', validators=[
Required(message='El campo es obligatorio'),
Length(max=10, min=6, message='El campo debe tener entre 6 y 10 caracteres')
])
tipoId = SelectField('Tipo Idenficacion', choices=[
('CC','Cedula de Ciudadania'),
('CE','Cedula de Extrangeria'),
('PA','Pasaporte'),
('RC','Registro Civil'),
('TI','Tarjeta de Identidad')], validators=[
Required(message='El campo es obligatorio'),
])
fechaExpIdEmpleado = DateField('Fecha Expedicion Documento Identidad', format='%Y,%M,%D')
lugarExpIdEmpleado = SelectField('Ciudad Expedicion Documento Identidad', choices=[
(5001,'Medellín'),
(5002,'Abejorral'),
(5004,'Abriaquí'),
(5021,'Alejandría'),
(5030,'Amagá'),
(5031,'Amalfi'),
(5034,'Andes'),
(5036,'Angelópolis'),
(5038,'Angostura'),
(5040,'Anorí'),
(5042,'Santafé De Antioquia'),
(5044,'Anza'),
(5045,'Apartadó'),
(5051,'Arboletes'),
(5055,'Argelia'),
(5059,'Armenia'),
(5079,'Barbosa'),
(5086,'Belmira'),
(5088,'Bello'),
(5091,'Betania'),
(5093,'Betulia'),
(5101,'Ciudad Bolívar'),
(5107,'Briceño'),
(5113,'Buriticá'),
(5120,'Cáceres'),
(5125,'Caicedo'),
(5129,'Caldas'),
(5134,'Campamento'),
(5138,'Cañasgordas'),
(5142,'Caracolí'),
(5145,'Caramanta'),
(5147,'Carepa'),
(5148,'El Carmen De Viboral'),
(5150,'Carolina'),
(5154,'Caucasia'),
(5172,'Chigorodó'),
(5190,'Cisneros'),
(5197,'Cocorná'),
(5206,'Concepción'),
(5209,'Concordia'),
(5212,'Copacabana'),
(5234,'Dabeiba'),
(5237,'Don Matías'),
(5240,'Ebéjico'),
(5250,'El Bagre'),
(5264,'Entrerrios'),
(5266,'Envigado'),
(5282,'Fredonia'),
(5284,'Frontino'),
(5306,'Giraldo'),
(5308,'Girardota'),
(5310,'Gómez Plata'),
(5313,'Granada'),
(5315,'Guadalupe'),
(5318,'Guarne'),
(5321,'Guatape'),
(5347,'Heliconia'),
(5353,'Hispania'),
(5360,'Itagui'),
(5361,'Ituango'),
(5364,'Jardín'),
(5368,'Jericó'),
(5376,'La Ceja'),
(5380,'La Estrella'),
(5390,'La Pintada'),
(5400,'La Unión'),
(5411,'Liborina'),
(5425,'Maceo'),
(5440,'Marinilla'),
(5467,'Montebello'),
(5475,'Murindó'),
(5480,'Mutatá'),
(5483,'Nariño'),
(5490,'Necoclí'),
(5495,'Nechí'),
(5501,'Olaya'),
(5541,'Peñol'),
(5543,'Peque'),
(5576,'Pueblorrico'),
(5579,'Puerto Berrío'),
(5585,'Puerto Nare'),
(5591,'Puerto Triunfo'),
(5604,'Remedios'),
(5607,'Retiro'),
(5615,'Rionegro'),
(5628,'Sabanalarga'),
(5631,'Sabaneta'),
(5642,'Salgar'),
(5647,'San Andrés De Cuerquía'),
(5649,'San Carlos'),
(5652,'San Francisco'),
(5656,'San Jerónimo'),
(5658,'San José De La Montaña'),
(5659,'San Juan De Urabá'),
(5660,'San Luis'),
(5664,'San Pedro'),
(5665,'San Pedro De Uraba'),
(5667,'San Rafael'),
(5670,'San Roque'),
(5674,'San Vicente'),
(5679,'Santa Bárbara'),
(5686,'Santa Rosa De Osos'),
(5690,'Santo Domingo'),
(5697,'El Santuario'),
(5736,'Segovia'),
(5756,'Sonson'),
(5761,'Sopetrán'),
(5789,'Támesis'),
(5790,'Tarazá'),
(5792,'Tarso'),
(5809,'Titiribí'),
(5819,'Toledo'),
(5837,'Turbo'),
(5842,'Uramita'),
(5847,'Urrao'),
(5854,'Valdivia'),
(5856,'Valparaíso'),
(5858,'Vegachí'),
(5861,'Venecia'),
(5873,'Vigía Del Fuerte'),
(5885,'Yalí'),
(5887,'Yarumal'),
(5890,'Yolombó'),
(5893,'Yondó'),
(5895,'Zaragoza'),
(8001,'Barranquilla'),
(8078,'Baranoa'),
(8137,'Campo De La Cruz'),
(8141,'Candelaria'),
(8296,'Galapa'),
(8372,'Juan De Acosta'),
(8421,'Luruaco'),
(8433,'Malambo'),
(8436,'Manatí'),
(8520,'Palmar De Varela'),
(8549,'Piojó'),
(8558,'Polonuevo'),
(8560,'Ponedera'),
(8573,'Puerto Colombia'),
(8606,'Repelón'),
(8634,'Sabanagrande'),
(8638,'Sabanalarga'),
(8675,'Santa Lucía'),
(8685,'Santo Tomás'),
(8758,'Soledad'),
(8770,'Suan'),
(8832,'Tubará'),
(8849,'Usiacurí'),
(11001,'Bogota DC'),
(13001,'Cartagena'),
(13006,'Choachí'),
(13030,'Altos Del Rosario'),
(13042,'Arenal'),
(13052,'Arjona'),
(13062,'Arroyohondo'),
(13074,'Barranco De Loba'),
(13140,'Calamar'),
(13160,'Cantagallo'),
(13188,'Cicuco'),
(13212,'Córdoba'),
(13222,'Clemencia'),
(13244,'El Carmen De Bolívar'),
(13248,'El Guamo'),
(13268,'El Peñón'),
(13300,'Hatillo De Loba'),
(13430,'Magangué'),
(13433,'Mahates'),
(13440,'Margarita'),
(13442,'María La Baja'),
(13458,'Montecristo'),
(13468,'Mompós'),
(13473,'Morales'),
(13549,'Pinillos'),
(13580,'Regidor'),
(13600,'Río Viejo'),
(13620,'San Cristóbal'),
(13647,'San Estanislao'),
(13650,'San Fernando'),
(13654,'San Jacinto'),
(13655,'San Jacinto Del Cauca'),
(13657,'San Juan Nepomuceno'),
(13667,'San Martín De Loba'),
(13670,'San Pablo'),
(13673,'Santa Catalina'),
(13683,'Santa Rosa'),
(13688,'Santa Rosa Del Sur'),
(13744,'Simití'),
(13760,'Soplaviento'),
(13780,'Talaigua Nuevo'),
(13810,'Tiquisio'),
(13836,'Turbaco'),
(13838,'Turbaná'),
(13873,'Villanueva'),
(13894,'Zambrano'),
(15001,'Tunja'),
(15022,'Almeida'),
(15047,'Aquitania'),
(15051,'Arcabuco'),
(15087,'Belén'),
(15090,'Berbeo'),
(15092,'Betéitiva'),
(15097,'Boavita'),
(15104,'Boyacá'),
(15106,'Briceño'),
(15109,'Buenavista'),
(15114,'Busbanzá'),
(15131,'Caldas'),
(15135,'Campohermoso'),
(15162,'Cerinza'),
(15172,'Chinavita'),
(15176,'Chiquinquirá'),
(15180,'Chiscas'),
(15183,'Chita'),
(15185,'Chitaraque'),
(15187,'Chivatá'),
(15189,'Ciénega'),
(15204,'Cómbita'),
(15212,'Coper'),
(15215,'Corrales'),
(15218,'Covarachía'),
(15223,'Cubará'),
(15224,'Cucaita'),
(15226,'Cuítiva'),
(15232,'Chíquiza'),
(15236,'Chivor'),
(15238,'Duitama'),
(15244,'El Cocuy'),
(15248,'El6Aspino'),
(15272,'Firavitoba'),
(15276,'Floresta'),
(15293,'Gachantivá'),
(15296,'Gameza'),
(15299,'Garagoa'),
(15317,'Guacamayas'),
(15322,'Guateque'),
(15325,'Guayatá'),
(15332,'Guican'),
(15362,'Iza'),
(15367,'Jenesano'),
(15368,'Jericó'),
(15377,'Labranzagrande'),
(15380,'La Capilla'),
(15401,'La Victoria'),
(15403,'La Uvita'),
(15407,'Villa De Leyva'),
(15425,'Macanal'),
(15442,'Maripí'),
(15455,'Miraflores'),
(15464,'Mongua'),
(15466,'Monguí'),
(15469,'Moniquirá'),
(15476,'Motavita'),
(15480,'Muzo'),
(15491,'Nobsa'),
(15494,'Nuevo Colón'),
(15500,'Oicatá'),
(15507,'Otanche'),
(15511,'Pachavita'),
(15514,'Páez'),
(15516,'Paipa'),
(15518,'Pajarito'),
(15522,'Panqueba'),
(15531,'Pauna'),
(15533,'Paya'),
(15537,'Paz De Río'),
(15542,'Pesca'),
(15550,'Pisba'),
(15572,'Puerto Boyacá'),
(15580,'Quípama'),
(15599,'Ramiriquí'),
(15600,'Ráquira'),
(15621,'Rondón'),
(15632,'Saboyá'),
(15638,'Sáchica'),
(15646,'Samacá'),
(15660,'San Eduardo'),
(15664,'San José De Pare'),
(15667,'San Luis De Gaceno'),
(15673,'San Mateo'),
(15676,'San Miguel De Sema'),
(15681,'San Pablo De Borbur'),
(15686,'Santana'),
(15690,'Santa María'),
(15693,'Santa Rosa De Viterbo'),
(15696,'Santa Sofía'),
(15720,'Sativanorte'),
(15723,'Sativasur'),
(15740,'Siachoque'),
(15753,'Soatá'),
(15755,'Socotá'),
(15757,'Socha'),
(15759,'Sogamoso'),
(15761,'Somondoco'),
(15762,'Sora'),
(15763,'Sotaquirá'),
(15764,'Soracá'),
(15774,'Susacón'),
(15776,'Sutamarchán'),
(15778,'Sutatenza'),
(15790,'Tasco'),
(15798,'Tenza'),
(15804,'Tibaná'),
(15806,'Tibasosa'),
(15808,'Tinjacá'),
(15810,'Tipacoque'),
(15814,'Toca'),
(15816,'Togüí'),
(15820,'Tópaga'),
(15822,'Tota'),
(15832,'Tununguá'),
(15835,'Turmequé'),
(15837,'Tuta'),
(15839,'Tutazá'),
(15842,'Umbita'),
(15861,'Ventaquemada'),
(15879,'Viracachá'),
(15897,'Zetaquira'),
(17001,'Manizales'),
(17013,'Aguadas'),
(17042,'Anserma'),
(17050,'Aranzazu'),
(17088,'Belalcázar'),
(17174,'Chinchiná'),
(17272,'Filadelfia'),
(17380,'La Dorada'),
(17388,'La Merced'),
(17433,'Manzanares'),
(17442,'Marmato'),
(17444,'Marquetalia'),
(17446,'Marulanda'),
(17486,'Neira'),
(17495,'Norcasia'),
(17513,'Pácora'),
(17524,'Palestina'),
(17541,'Pensilvania'),
(17614,'Riosucio'),
(17616,'Risaralda'),
(17653,'Salamina'),
(17662,'Samaná'),
(17665,'San José'),
(17777,'Supía'),
(17867,'Victoria'),
(17873,'Villamaría'),
(17877,'Viterbo'),
(18001,'Florencia'),
(18029,'Albania'),
(18094,'Belén De Los Andaquies'),
(18150,'Cartagena Del Chairá'),
(18205,'Curillo'),
(18247,'El Doncello'),
(18256,'El Paujil'),
(18410,'La Montañita'),
(18460,'Milán'),
(18479,'Morelia'),
(18592,'Puerto Rico'),
(18610,'San José Del Fragua'),
(18753,'San Vicente Del Caguán'),
(18756,'Solano'),
(18785,'Solita'),
(18860,'Valparaíso'),
(19001,'Popayán'),
(19022,'Almaguer'),
(19050,'Argelia'),
(19075,'Balboa'),
(19100,'Bolívar'),
(19110,'Buenos Aires'),
(19130,'Cajibío'),
(19137,'Caldono'),
(19142,'Caloto'),
(19212,'Corinto'),
(19256,'El Tambo'),
(19290,'Florencia'),
(19300,'Guachené'),
(19318,'Guapi'),
(19355,'Inzá'),
(19364,'Jambaló'),
(19392,'La Sierra'),
(19397,'La Vega'),
(19418,'López'),
(19450,'Mercaderes'),
(19455,'Miranda'),
(19473,'Morales'),
(19513,'Padilla'),
(19517,'Paez'),
(19532,'Patía'),
(19533,'Piamonte'),
(19548,'Piendamó'),
(19573,'Puerto Tejada'),
(19585,'Puracé'),
(19622,'Rosas'),
(19693,'San Sebastián'),
(19698,'Santander De Quilichao'),
(19701,'Santa Rosa'),
(19743,'Silvia'),
(19760,'Sotara'),
(19780,'Suárez'),
(19785,'Sucre'),
(19807,'Timbío'),
(19809,'Timbiquí'),
(19821,'Toribio'),
(19824,'Totoró'),
(19845,'Villa Rica'),
(20001,'Valledupar'),
(20011,'Aguachica'),
(20013,'Agustín Codazzi'),
(20032,'Astrea'),
(20045,'Becerril'),
(20060,'Bosconia'),
(20175,'Chimichagua'),
(20178,'Chiriguaná'),
(20228,'Curumaní'),
(20238,'El Copey'),
(20250,'El Paso'),
(20295,'Gamarra'),
(20310,'González'),
(20383,'La Gloria'),
(20400,'La Jagua De Ibirico'),
(20443,'Manaure'),
(20517,'Pailitas'),
(20550,'Pelaya'),
(20570,'Pueblo Bello'),
(20614,'Río De Oro'),
(20621,'La Paz'),
(20710,'San Alberto'),
(20750,'San Diego'),
(20770,'San Martín'),
(20787,'Tamalameque'),
(23001,'Montería'),
(23068,'Ayapel'),
(23079,'Buenavista'),
(23090,'Canalete'),
(23162,'Cereté'),
(23168,'Chimá'),
(23182,'Chinú'),
(23189,'Ciénaga De Oro'),
(23300,'Cotorra'),
(23350,'La Apartada'),
(23417,'Lorica'),
(23419,'Los Córdobas'),
(23464,'Momil'),
(23466,'Montelíbano'),
(23500,'Moñitos'),
(23555,'Planeta Rica'),
(23570,'Pueblo Nuevo'),
(23574,'Puerto Escondido'),
(23580,'Puerto Libertador'),
(23586,'Purísima'),
(23660,'Sahagún'),
(23670,'San Andrés Sotavento'),
(23672,'San Antero'),
(23675,'San Bernardo Del Viento'),
(23678,'San Carlos'),
(23686,'San Pelayo'),
(23807,'Tierralta'),
(23855,'Valencia'),
(25001,'Agua De Dios'),
(25019,'Albán'),
(25035,'Anapoima'),
(25040,'Anolaima'),
(25053,'Arbeláez'),
(25086,'Beltrán'),
(25095,'Bituima'),
(25099,'Bojacá'),
(25120,'Cabrera'),
(25123,'Cachipay'),
(25126,'Cajicá'),
(25148,'Caparrapí'),
(25151,'Caqueza'),
(25154,'Carmen De Carupa'),
(25168,'Chaguaní'),
(25175,'Chía'),
(25178,'Chipaque'),
(25181,'Choachí'),
(25183,'Chocontá'),
(25200,'Cogua'),
(25214,'Cota'),
(25224,'Cucunuba'),
(25245,'El Colegio'),
(25258,'El Peñón'),
(25260,'El Rosal'),
(25269,'Facatativá'),
(25279,'Fomeque'),
(25281,'Fosca'),
(25286,'Funza'),
(25288,'Fúquene'),
(25290,'Fusagasugá'),
(25293,'Gachala'),
(25295,'Gachancipá'),
(25297,'Gachetá'),
(25299,'Gama'),
(25307,'Girardot'),
(25312,'Granada'),
(25317,'Guachetá'),
(25320,'Guaduas'),
(25322,'Guasca'),
(25324,'Guataquí'),
(25326,'Guatavita'),
(25328,'Guayabal De Siquima'),
(25335,'Guayabetal'),
(25339,'Gutiérrez'),
(25368,'Jerusalén'),
(25372,'Junín'),
(25377,'La Calera'),
(25386,'La Mesa'),
(25394,'La Palma'),
(25398,'La Peña'),
(25402,'La Vega'),
(25407,'Lenguazaque'),
(25426,'Macheta'),
(25430,'Madrid'),
(25436,'Manta'),
(25438,'Medina'),
(25473,'Mosquera'),
(25483,'Nariño'),
(25486,'Nemocón'),
(25488,'Nilo'),
(25489,'Nimaima'),
(25491,'Nocaima'),
(25506,'Venecia'),
(25513,'Pacho'),
(25518,'Paime'),
(25524,'Pandi'),
(25530,'Paratebueno'),
(25535,'Pasca'),
(25572,'Puerto Salgar'),
(25580,'Pulí'),
(25592,'Quebradanegra'),
(25594,'Quetame'),
(25596,'Quipile'),
(25599,'Apulo'),
(25612,'Ricaurte'),
(25645,'San Antonio Del Tequendama'),
(25649,'San Bernardo'),
(25653,'San Cayetano'),
(25658,'San Francisco'),
(25662,'San Juan De Río Seco'),
(25718,'Sasaima'),
(25736,'Sesquilé'),
(25740,'Sibaté'),
(25743,'Silvania'),
(25745,'Simijaca'),
(25754,'Soacha'),
(25758,'Sopó'),
(25769,'Subachoque'),
(25772,'Suesca'),
(25777,'Supatá'),
(25779,'Susa'),
(25781,'Sutatausa'),
(25785,'Tabio'),
(25793,'Tausa'),
(25797,'Tena'),
(25799,'Tenjo'),
(25805,'Tibacuy'),
(25807,'Tibirita'),
(25815,'Tocaima'),
(25817,'Tocancipá'),
(25823,'Topaipi'),
(25839,'Ubalá'),
(25841,'Ubaque'),
(25843,'Villa De San Diego De Ubate'),
(25845,'Une'),
(25851,'Útica'),
(25862,'Vergara'),
(25867,'Vianí'),
(25871,'Villagómez'),
(25873,'Villapinzón'),
(25875,'Villeta'),
(25878,'Viotá'),
(25885,'Yacopí'),
(25898,'Zipacón'),
(25899,'Zipaquirá'),
(27001,'Quibdó'),
(27006,'Acandí'),
(27025,'Alto Baudo'),
(27050,'Atrato'),
(27073,'Bagadó'),
(27075,'Bahía Solano'),
(27077,'Bajo Baudó'),
(27086,'Belén De Bajirá'),
(27099,'Bojaya'),
(27135,'El Cantón Del San Pablo'),
(27150,'Carmen Del Darien'),
(27160,'Cértegui'),
(27205,'Condoto'),
(27245,'El Carmen De Atrato'),
(27250,'El Litoral Del San Juan'),
(27361,'Istmina'),
(27372,'Juradó'),
(27413,'Lloró'),
(27425,'Medio Atrato'),
(27430,'Medio Baudó'),
(27450,'Medio San Juan'),
(27491,'Nóvita'),
(27495,'Nuquí'),
(27580,'Río Iro'),
(27600,'Río Quito'),
(27615,'Riosucio'),
(27660,'San José Del Palmar'),
(27745,'Sipí'),
(27787,'Tadó'),
(27800,'Unguía'),
(27810,'Unión Panamericana'),
(41001,'Neiva'),
(41006,'Acevedo'),
(41013,'Agrado'),
(41016,'Aipe'),
(41020,'Algeciras'),
(41026,'Altamira'),
(41078,'Baraya'),
(41132,'Campoalegre'),
(41206,'Colombia'),
(41244,'Elías'),
(41298,'Garzón'),
(41306,'Gigante'),
(41319,'Guadalupe'),
(41349,'Hobo'),
(41357,'Iquira'),
(41359,'Isnos'),
(41378,'La Argentina'),
(41396,'La Plata'),
(41483,'Nátaga'),
(41503,'Oporapa'),
(41518,'Paicol'),
(41524,'Palermo'),
(41530,'Palestina'),
(41548,'Pital'),
(41551,'Pitalito'),
(41615,'Rivera'),
(41660,'Saladoblanco'),
(41668,'San Agustín'),
(41676,'Santa María'),
(41770,'Suaza'),
(41791,'Tarqui'),
(41797,'Tesalia'),
(41799,'Tello'),
(41801,'Teruel'),
(41807,'Timana'),
(41872,'Villavieja'),
(41885,'Yaguará'),
(44001,'Riohacha'),
(44035,'Albania'),
(44078,'Barrancas'),
(44090,'Dibulla'),
(44098,'Distracción'),
(44110,'El Molino'),
(44279,'Fonseca'),
(44378,'Hatonuevo'),
(44420,'La Jagua Del Pilar'),
(44430,'Maicao'),
(44560,'Manaure'),
(44650,'San Juan Del Cesar'),
(44847,'Uribia'),
(44855,'Urumita'),
(44874,'Villanueva'),
(47001,'Santa Marta'),
(47030,'Algarrobo'),
(47053,'Aracataca'),
(47058,'Ariguaní'),
(47161,'Cerro San Antonio'),
(47170,'Chibolo'),
(47189,'Ciénaga'),
(47205,'Concordia'),
(47245,'El Banco'),
(47258,'El Piñon'),
(47268,'El Retén'),
(47288,'Fundación'),
(47318,'Guamal'),
(47460,'Nueva Granada'),
(47541,'Pedraza'),
(47545,'Pijiño Del Carmen'),
(47551,'Pivijay'),
(47555,'Plato'),
(47570,'Puebloviejo'),
(47605,'Remolino'),
(47660,'Sabanas De San Angel'),
(47675,'Salamina'),
(47692,'San Sebastián De Buenavista'),
(47703,'San Zenón'),
(47707,'Santa Ana'),
(47720,'Santa Bárbara De Pinto'),
(47745,'Sitionuevo'),
(47798,'Tenerife'),
(47960,'Zapayán'),
(47980,'Zona Bananera'),
(50001,'Villavicencio'),
(50006,'Acacías'),
(50110,'Barranca De Upía'),
(50124,'Cabuyaro'),
(50150,'Castilla La Nueva'),
(50223,'Cubarral'),
(50226,'Cumaral'),
(50245,'El Calvario'),
(50251,'El Castillo'),
(50270,'El Dorado'),
(50287,'Fuente De Oro'),
(50313,'Granada'),
(50318,'Guamal'),
(50325,'Mapiripán'),
(50330,'Mesetas'),
(50350,'La Macarena'),
(50370,'Uribe'),
(50400,'Lejanías'),
(50450,'Puerto Concordia'),
(50568,'Puerto Gaitán'),
(50573,'Puerto López'),
(50577,'Puerto Lleras'),
(50590,'Puerto Rico'),
(50606,'Restrepo'),
(50680,'San Carlos De Guaroa'),
(50683,'San Juan De Arama'),
(50686,'San Juanito'),
(50689,'San Martín'),
(50711,'Vistahermosa'),
(52001,'Pasto'),
(52019,'Albán'),
(52022,'Aldana'),
(52036,'Ancuya'),
(52051,'Arboleda'),
(52079,'Barbacoas'),
(52083,'Belén'),
(52110,'Buesaco'),
(52203,'Colón'),
(52207,'Consaca'),
(52210,'Contadero'),
(52215,'Córdoba'),
(52224,'Cuaspud'),
(52227,'Cumbal'),
(52233,'Cumbitara'),
(52240,'Chachagüí'),
(52250,'El Charco'),
(52254,'El Peñol'),
(52256,'El Rosario'),
(52258,'El Tablón De Gómez'),
(52260,'El Tambo'),
(52287,'Funes'),
(52317,'Guachucal'),
(52320,'Guaitarilla'),
(52323,'Gualmatán'),
(52352,'Iles'),
(52354,'Imués'),
(52356,'Ipiales'),
(52378,'La Cruz'),
(52381,'La Florida'),
(52385,'La Llanada'),
(52390,'La Tola'),
(52399,'La Unión'),
(52405,'Leiva'),
(52411,'Linares'),
(52418,'Los Andes'),
(52427,'Magüi'),
(52435,'Mallama'),
(52473,'Mosquera'),
(52480,'Nariño'),
(52490,'Olaya Herrera'),
(52506,'Ospina'),
(52520,'Francisco Pizarro'),
(52540,'Policarpa'),
(52560,'Potosí'),
(52565,'Providencia'),
(52573,'Puerres'),
(52585,'Pupiales'),
(52612,'Ricaurte'),
(52621,'Roberto Payán'),
(52678,'Samaniego'),
(52683,'Sandoná'),
(52685,'San Bernardo'),
(52687,'San Lorenzo'),
(52693,'San Pablo'),
(52694,'San Pedro De Cartago'),
(52696,'Santa Bárbara'),
(52699,'Santacruz'),
(52720,'Sapuyes'),
(52786,'Taminango'),
(52788,'Tangua'),
(52835,'San Andres De Tumaco'),
(52838,'Túquerres'),
(52885,'Yacuanquer'),
(54001,'Cúcuta'),
(54003,'Abrego'),
(54051,'Arboledas'),
(54099,'Bochalema'),
(54109,'Bucarasica'),
(54125,'Cácota'),
(54128,'Cachirá'),
(54172,'Chinácota'),
(54174,'Chitagá'),
(54206,'Convención'),
(54223,'Cucutilla'),
(54239,'Durania'),
(54245,'El Carmen'),
(54250,'El Tarra'),
(54261,'El Zulia'),
(54313,'Gramalote'),
(54344,'Hacarí'),
(54347,'Herrán'),
(54377,'Labateca'),
(54385,'La Esperanza'),
(54398,'La Playa'),
(54405,'Los Patios'),
(54418,'Lourdes'),
(54480,'Mutiscua'),
(54498,'Ocaña'),
(54518,'Pamplona'),
(54520,'Pamplonita'),
(54553,'Puerto Santander'),
(54599,'Ragonvalia'),
(54660,'Salazar'),
(54670,'San Calixto'),
(54673,'San Cayetano'),
(54680,'Santiago'),
(54720,'Sardinata'),
(54743,'Silos'),
(54800,'Teorama'),
(54810,'Tibú'),
(54820,'Toledo'),
(54871,'Villa Caro'),
(54874,'Villa Del Rosario'),
(63001,'Armenia'),
(63111,'Buenavista'),
(63130,'Calarca'),
(63190,'Circasia'),
(63212,'Córdoba'),
(63272,'Filandia'),
(63302,'Génova'),
(63401,'La Tebaida'),
(63470,'Montenegro'),
(63548,'Pijao'),
(63594,'Quimbaya'),
(63690,'Salento'),
(66001,'Pereira'),
(66045,'Apía'),
(66075,'Balboa'),
(66088,'Belén De Umbría'),
(66170,'Dosquebradas'),
(66318,'Guática'),
(66383,'La Celia'),
(66400,'La Virginia'),
(66440,'Marsella'),
(66456,'Mistrató'),
(66572,'Pueblo Rico'),
(66594,'Quinchía'),
(66682,'Santa Rosa De Cabal'),
(66687,'Santuario'),
(68001,'Bucaramanga'),
(68013,'Aguada'),
(68020,'Albania'),
(68051,'Aratoca'),
(68077,'Barbosa'),
(68079,'Barichara'),
(68081,'Barrancabermeja'),
(68092,'Betulia'),
(68101,'Bolívar'),
(68121,'Cabrera'),
(68132,'California'),
(68147,'Capitanejo'),
(68152,'Carcasí'),
(68160,'Cepitá'),
(68162,'Cerrito'),
(68167,'Charalá'),
(68169,'Charta'),
(68176,'Chima'),
(68179,'Chipatá'),
(68190,'Cimitarra'),
(68207,'Concepción'),
(68209,'Confines'),
(68211,'Contratación'),
(68217,'Coromoro'),
(68229,'Curití'),
(68235,'El Carmen De Chucurí'),
(68245,'El Guacamayo'),
(68250,'El Peñón'),
(68255,'El Playón'),
(68264,'Encino'),
(68266,'Enciso'),
(68271,'Florián'),
(68276,'Floridablanca'),
(68296,'Galan'),
(68298,'Gambita'),
(68307,'Girón'),
(68318,'Guaca'),
(68320,'Guadalupe'),
(68322,'Guapotá'),
(68324,'Guavatá'),
(68327,'Güepsa'),
(68344,'Hato'),
(68368,'Jesús María'),
(68370,'Jordán'),
(68377,'La Belleza'),
(68385,'Landázuri'),
(68397,'La Paz'),
(68406,'Lebríja'),
(68418,'Los Santos'),
(68425,'Macaravita'),
(68432,'Málaga'),
(68444,'Matanza'),
(68464,'Mogotes'),
(68468,'Molagavita'),
(68498,'Ocamonte'),
(68500,'Oiba'),
(68502,'Onzaga'),
(68522,'Palmar'),
(68524,'Palmas Del Socorro'),
(68533,'Páramo'),
(68547,'Piedecuesta'),
(68549,'Pinchote'),
(68572,'Puente Nacional'),
(68573,'Puerto Parra'),
(68575,'Puerto Wilches'),
(68615,'Rionegro'),
(68655,'Sabana De Torres'),
(68669,'San Andrés'),
(68673,'San Benito'),
(68679,'San Gil'),
(68682,'San Joaquín'),
(68684,'San José De Miranda'),
(68686,'San Miguel'),
(68689,'San Vicente De Chucurí'),
(68705,'Santa Bárbara'),
(68720,'Santa Helena Del Opón'),
(68745,'Simacota'),
(68755,'Socorro'),
(68770,'Suaita'),
(68773,'Sucre'),
(68780,'Suratá'),
(68820,'Tona'),
(68855,'Valle De San José'),
(68861,'Vélez'),
(68867,'Vetas'),
(68872,'Villanueva'),
(68895,'Zapatoca'),
(70001,'Sincelejo'),
(70110,'Buenavista'),
(70124,'Caimito'),
(70204,'Coloso'),
(70215,'Corozal'),
(70221,'Coveñas'),
(70230,'Chalán'),
(70233,'El Roble'),
(70235,'Galeras'),
(70265,'Guaranda'),
(70400,'La Unión'),
(70418,'Los Palmitos'),
(70429,'Majagual'),
(70473,'Morroa'),
(70508,'Ovejas'),
(70523,'Palmito'),
(70670,'Sampués'),
(70678,'San Benito Abad'),
(70702,'San Juan De Betulia'),
(70708,'San Marcos'),
(70713,'San Onofre'),
(70717,'San Pedro'),
(70742,'San Luis De Sincé'),
(70771,'Sucre'),
(70820,'Santiago De Tolú'),
(70823,'Tolú Viejo'),
(73001,'Ibague'),
(73024,'Alpujarra'),
(73026,'Alvarado'),
(73030,'Ambalema'),
(73043,'Anzoátegui'),
(73055,'Armero'),
(73067,'Ataco'),
(73124,'Cajamarca'),
(73148,'Carmen De Apicalá'),
(73152,'Casabianca'),
(73168,'Chaparral'),
(73200,'Coello'),
(73217,'Coyaima'),
(73226,'Cunday'),
(73236,'Dolores'),
(73268,'Espinal'),
(73270,'Falan'),
(73275,'Flandes'),
(73283,'Fresno'),
(73319,'Guamo'),
(73347,'Herveo'),
(73349,'Honda'),
(73352,'Icononzo'),
(73408,'Lérida'),
(73411,'Líbano'),
(73443,'Mariquita'),
(73449,'Melgar'),
(73461,'Murillo'),
(73483,'Natagaima'),
(73504,'Ortega'),
(73520,'Palocabildo'),
(73547,'Piedras'),
(73555,'Planadas'),
(73563,'Prado'),
(73585,'Purificación'),
(73616,'Rioblanco'),
(73622,'Roncesvalles'),
(73624,'Rovira'),
(73671,'Saldaña'),
(73675,'San Antonio'),
(73678,'San Luis'),
(73686,'Santa Isabel'),
(73770,'Suárez'),
(73854,'Valle De San Juan'),
(73861,'Venadillo'),
(73870,'Villahermosa'),
(73873,'Villarrica'),
(76001,'Cali'),
(76020,'Alcalá'),
(76036,'Andalucía'),
(76041,'Ansermanuevo'),
(76054,'Argelia'),
(76100,'Bolívar'),
(76109,'Buenaventura'),
(76111,'Guadalajara De Buga'),
(76113,'Bugalagrande'),
(76122,'Caicedonia'),
(76126,'Calima'),
(76130,'Candelaria'),
(76147,'Cartago'),
(76233,'Dagua'),
(76243,'El Águila'),
(76246,'El Cairo'),
(76248,'El Cerrito'),
(76250,'El Dovio'),
(76275,'Florida'),
(76306,'Ginebra'),
(76318,'Guacarí'),
(76364,'Jamundí'),
(76377,'La Cumbre'),
(76400,'La Unión'),
(76403,'La Victoria'),
(76497,'Obando'),
(76520,'Palmira'),
(76563,'Pradera'),
(76606,'Restrepo'),
(76616,'Riofrío'),
(76622,'Roldanillo'),
(76670,'San Pedro'),
(76736,'Sevilla'),
(76823,'Toro'),
(76828,'Trujillo'),
(76834,'Tuluá'),
(76845,'Ulloa'),
(76863,'Versalles'),
(76869,'Vijes'),
(76890,'Yotoco'),
(76892,'Yumbo'),
(76895,'Zarzal'),
(81001,'Arauca'),
(81065,'Arauquita'),
(81220,'Cravo Norte'),
(81300,'Fortul'),
(81591,'Puerto Rondón'),
(81736,'Saravena'),
(81794,'Tame'),
(85001,'Yopal'),
(85010,'Aguazul'),
(85015,'Chameza'),
(85125,'Hato Corozal'),
(85136,'La Salina'),
(85139,'Maní'),
(85162,'Monterrey'),
(85225,'Nunchía'),
(85230,'Orocué'),
(85250,'Paz De Ariporo'),
(85263,'Pore'),
(85279,'Recetor'),
(85300,'Sabanalarga'),
(85315,'Sácama'),
(85325,'San Luis De Palenque'),
(85400,'Támara'),
(85410,'Tauramena'),
(85430,'Trinidad'),
(85440,'Villanueva'),
(86001,'Mocoa'),
(86219,'Colón'),
(86320,'Orito'),
(86568,'Puerto Asís'),
(86569,'Puerto Caicedo'),
(86571,'Puerto Guzmán'),
(86573,'Leguízamo'),
(86749,'Sibundoy'),
(86755,'San Francisco'),
(86757,'San Miguel'),
(86760,'Santiago'),
(86865,'Valle Del Guamuez'),
(86885,'Villagarzón'),
(88001,'San Andrés'),
(88564,'Providencia'),
(91001,'Leticia'),
(91263,'El Encanto'),
(91405,'La Chorrera'),
(91407,'La Pedrera'),
(91430,'La Victoria'),
(91460,'Miriti - Paraná'),
(91530,'Puerto Alegría'),
(91536,'Puerto Arica'),
(91540,'Puerto Nariño'),
(91669,'Puerto Santander'),
(91798,'Tarapacá'),
(94001,'Inírida'),
(94343,'Barranco Minas'),
(94663,'Mapiripana'),
(94883,'San Felipe'),
(94884,'Puerto Colombia'),
(94885,'La Guadalupe'),
(94886,'Cacahual'),
(94887,'Pana Pana'),
(94888,'Morichal'),
(95001,'San José Del Guaviare'),
(95015,'Calamar'),
(95025,'El Retorno'),
(95200,'Miraflores'),
(97001,'Mitú'),
(97161,'Caruru'),
(97511,'Pacoa'),
(97666,'Taraira'),
(97777,'Papunaua'),
(97889,'Yavaraté'),
(99001,'Puerto Carreño'),
(99524,'La Primavera'),
(99624,'Santa Rosalía'),
(99773,'Cumaribo')
], validators=[
Required()
])
primerNombreEmpleado = StringField('Primer Nombre', validators=[
Required(message='El campo es obligatorio'),
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
segundoNombreEmpleado = StringField('Segundo Nombre', validators=[
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
primerApellidoEmpleado = StringField('Primer Apellido', validators=[
Required(message='El campo es obligatorio'),
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
segundoApellidoEmpleado = StringField('Segundo Apellido', validators=[
Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres')
])
fechaNacimientoEmpleado = DateField('Fecha de Nacimiento', format='%Y,%M,%D', validators=[])
direccionEmpleado = StringField('Direccion Residencia', validators=[
Required(message='El campo es obligatorio'),
Length(max=50, min=20, message='El campo debe tener entre 20 y 50 caracteres')
])
barrioEmpleado = StringField('Barrio Residencia', validators=[
Required(message='El campo es obligatorio'),
Length(max=20, min=10, message='El campo debe tener entre 10 y 20 caracteres')
])
idPais = SelectField('Pais Residencia', choices=[
('AD','Andorra'),
('AE','Emiratos Arabes Unid'),
('AF','Afganistan'),
('AG','Antigua Y Barbuda'),
('AI','Anguilla'),
('AL','Albania'),
('AM','Armenia'),
('AN','Antillas Holandesas'),
('AO','Angola'),
('AR','Argentina'),
('AS','Samoa Norteamericana'),
('AT','Austria'),
('AU','Australia'),
('AW','Aruba'),
('AZ','Azerbaijan'),
('BA','Bosnia-Herzegovina'),
('BB','Barbados'),
('BD','Bangladesh'),
('BE','Belgica'),
('BF','Burkina Fasso'),
('BG','Bulgaria'),
('BH','Bahrein'),
('BI','Burundi'),
('BJ','Benin'),
('BM','Bermudas'),
('BN','Brunei Darussalam'),
('BO','Bolivia'),
('BR','Brasil'),
('BS','Bahamas'),
('BT','Butan'),
('BW','Botswana'),
('BY','Belorus'),
('BZ','Belice'),
('CA','Canada'),
('CC','Cocos (Keeling) Islas'),
('CD','Republica Democratica Del Congo'),
('CF','Republica Centroafri'),
('CG','Congo'),
('CH','Suiza'),
('CI','Costa De Marfil'),
('CK','Cook Islas'),
('CL','Chile'),
('CM','Camerun Republica U'),
('CN','China'),
('CO','Colombia'),
('CR','Costa Rica'),
('CU','Cuba'),
('CV','Cabo Verde'),
('CX','Navidad (Christmas)'),
('CY','Chipre'),
('CZ','Republica Checa'),
('DE','Alemania'),
('DJ','Djibouti'),
('DK','Dinamarca'),
('DM','Dominica'),
('DO','Republica Dominicana'),
('DZ','Argelia'),
('EC','Ecuador'),
('EE','Estonia'),
('EG','Egipto'),
('EH','Sahara Occidental'),
('ER','Eritrea'),
('ES','España'),
('ET','Etiopia'),
('EU','Comunidad Europea'),
('FI','Finlandia'),
('FJ','Fiji'),
('FM','Micronesia Estados F'),
('FO','Feroe Islas'),
('FR','Francia'),
('GA','Gabon'),
('GB','Reino Unido'),
('GD','Granada'),
('GE','Georgia'),
('GF','Guayana Francesa'),
('GH','Ghana'),
('GI','Gibraltar'),
('GL','Groenlandia'),
('GM','Gambia'),
('GN','Guinea'),
('GP','Guadalupe'),
('GQ','Guinea Ecuatorial'),
('GR','Grecia'),
('GT','Guatemala'),
('GU','Guam'),
('GW','Guinea - Bissau'),
('GY','Guyana'),
('HK','Hong Kong'),
('HN','Honduras'),
('HR','Croacia'),
('HT','Haiti'),
('HU','Hungria'),
('ID','Indonesia'),
('IE','Irlanda (Eire)'),
('IL','Israel'),
('IM','Isla De Man'),
('IN','India'),
('IO','Territori Britanico'),
('IQ','Irak'),
('IR','Iran Republica Islamica'),
('IS','Islandia'),
('IT','Italia'),
('JM','Jamaica'),
('JO','Jordania'),
('JP','Japon'),
('KE','Kenya'),
('KG','Kirguizistan'),
('KH','Kampuchea (Camboya)'),
('KI','Kiribati'),
('KM','Comoras'),
('KN','San Cristobal Y Nieves'),
('KP','Corea Del Norte Republica'),
('KR','Corea Del Sur Republica'),
('KW','Kuwait'),
('KY','Caiman Islas'),
('KZ','Kazajstan'),
('LA','Laos Republica Popular'),
('LB','Libano'),
('LC','Santa Lucia'),
('LI','Liechtenstein'),
('LK','Sri Lanka'),
('LR','Liberia'),
('LS','Lesotho'),
('LT','Lituania'),
('LU','Luxemburgo'),
('LV','Letonia'),
('LY','Libia(Incluye Fezzan'),
('MA','Marruecos'),
('MC','Monaco'),
('MD','Moldavia'),
('MG','Madagascar'),
('MH','Marshall Islas'),
('MK','Macedonia'),
('ML','Mali'),
('MM','Birmania (Myanmar)'),
('MN','Mongolia'),
('MO','Macao'),
('MP','Marianas Del Norte Islas'),
('MQ','Martinica'),
('MR','Mauritania'),
('MS','Monserrat Islas'),
('MT','Malta'),
('MU','Mauricio'),
('MV','Maldivas'),
('MW','Malawi'),
('MX','Mexico'),
('MY','Malasia'),
('MZ','Mozambique'),
('NA','Namibia'),
('NC','Nueva Caledonia'),
('NE','Niger'),
('NF','Norfolk Isla'),
('NG','Nigeria'),
('NI','Nicaragua'),
('NL','Paises Bajos(Holanda'),
('NO','Noruega'),
('NP','Nepal'),
('NR','Nauru'),
('NU','Nive Isla'),
('NZ','Nueva Zelandia'),
('OM','Oman'),
('PA','Panama'),
('PE','Peru'),
('PF','Polinesia Francesa'),
('PG','Papuasia Nuev Guinea'),
('PH','Filipinas'),
('PK','Pakistan'),
('PL','Polonia'),
('PM','San Pedro Y Miguelon'),
('PN','Pitcairn Isla'),
('PR','Puerto Rico'),
('PS','Palestina'),
('PT','Portugal'),
('PW','Palau Islas'),
('PY','Paraguay'),
('QA','Qatar'),
('RE','Reunion'),
('RO','Rumania'),
('RS','Serbia'),
('RU','Rusia'),
('RW','Rwanda'),
('SA','Arabia Saudita'),
('SB','Salomsn Islas'),
('SC','Seychelles'),
('SD','Sudan'),
('SE','Suecia'),
('SG','Singapur'),
('SH','Santa Elena'),
('SI','Eslovenia'),
('SK','Eslovaquia'),
('SL','Sierra Leona'),
('SM','San Marino'),
('SN','Senegal'),
('SO','Somalia'),
('SR','Surinam'),
('ST','Santo Tome Y Princip'),
('SV','El Salvador'),
('SY','Siria Republica Arabe'),
('SZ','Swazilandia'),
('TC','Turcas Y Caicos Isla'),
('TD','Chad'),
('TG','Togo'),
('TH','Tailandia'),
('TJ','Tadjikistan'),
('TK','Tokelau'),
('TL','Timor Del Este'),
('TM','Turkmenistan'),
('TN','Tunicia'),
('TO','Tonga'),
('TR','Turquia'),
('TT','Trinidad Y Tobago'),
('TV','Tuvalu'),
('TW','Taiwan (Formosa)'),
('TZ','Tanzania Republica'),
('UA','Ucrania'),
('UG','Uganda'),
('UM','Islas Menores De Estados Unidos'),
('UN','Niue Isla'),
('US','Estados Unidos'),
('UY','Uruguay'),
('UZ','Uzbekistan'),
('VA','Ciudad Del Vaticano'),
('VC','San Vicente Y Las Gr'),
('VE','Venezuela'),
('VG','Virgenes Islas Britanicas'),
('VI','Virgenes Islas'),
('VN','Vietnam'),
('VU','Vanuatu'),
('WF','Wallis Y Fortuna Islas'),
('WS','Samoa'),
('YE','Yemen'),
('YU','Yugoslavia'),
('ZA','Sudafrica Republica'),
('ZM','Zambia'),
('ZW','Zimbabwe')
], validate_choice=True)
idDepartamento = SelectField('Departamento Residencia', choices=[
(5,'Antioquia'),
(8,'Atlántico'),
(11,'Bogotá DC'),
(13,'Bolívar'),
(15,'Boyacá'),
(17,'Caldas'),
(18,'Caquetá'),
(19,'Cauca'),
(20,'Cesar'),
(23,'Córdoba'),
(25,'Cundinamarca'),
(27,'Chocó'),
(41,'Huila'),
(44,'La Guajira'),
(47,'Magdalena'),
(50,'Meta'),
(52,'Nariño'),
(54,'Norte de Santander'),
(63,'Quindío'),
(66,'Risaralda'),
(68,'Santander'),
(70,'Sucre'),
(73,'Tolima'),
(76,'Valle del Cauca'),
(81,'Arauca'),
(85,'Casanare'),
(86,'Putumayo'),
(88,'San Andres'),
(91,'Amazonas'),
(94,'Guainía'),
(95,'Guaviare'),
(97,'Vaupés'),
(99,'Vichada'),
], validate_choice=True)
idMunicipio = SelectField('Municipio Residencia', choices=[
(5001,'Medellín'),
(5002,'Abejorral'),
(5004,'Abriaquí'),
(5021,'Alejandría'),
(5030,'Amagá'),
(5031,'Amalfi'),
(5034,'Andes'),
(5036,'Angelópolis'),
(5038,'Angostura'),
(5040,'Anorí'),
(5042,'Santafé De Antioquia'),
(5044,'Anza'),
(5045,'Apartadó'),
(5051,'Arboletes'),
(5055,'Argelia'),
(5059,'Armenia'),
(5079,'Barbosa'),
(5086,'Belmira'),
(5088,'Bello'),
(5091,'Betania'),
(5093,'Betulia'),
(5101,'Ciudad Bolívar'),
(5107,'Briceño'),
(5113,'Buriticá'),
(5120,'Cáceres'),
(5125,'Caicedo'),
(5129,'Caldas'),
(5134,'Campamento'),
(5138,'Cañasgordas'),
(5142,'Caracolí'),
(5145,'Caramanta'),
(5147,'Carepa'),
(5148,'El Carmen De Viboral'),
(5150,'Carolina'),
(5154,'Caucasia'),
(5172,'Chigorodó'),
(5190,'Cisneros'),
(5197,'Cocorná'),
(5206,'Concepción'),
(5209,'Concordia'),
(5212,'Copacabana'),
(5234,'Dabeiba'),
(5237,'Don Matías'),
(5240,'Ebéjico'),
(5250,'El Bagre'),
(5264,'Entrerrios'),
(5266,'Envigado'),
(5282,'Fredonia'),
(5284,'Frontino'),
(5306,'Giraldo'),
(5308,'Girardota'),
(5310,'Gómez Plata'),
(5313,'Granada'),
(5315,'Guadalupe'),
(5318,'Guarne'),
(5321,'Guatape'),
(5347,'Heliconia'),
(5353,'Hispania'),
(5360,'Itagui'),
(5361,'Ituango'),
(5364,'Jardín'),
(5368,'Jericó'),
(5376,'La Ceja'),
(5380,'La Estrella'),
(5390,'La Pintada'),
(5400,'La Unión'),
(5411,'Liborina'),
(5425,'Maceo'),
(5440,'Marinilla'),
(5467,'Montebello'),
(5475,'Murindó'),
(5480,'Mutatá'),
(5483,'Nariño'),
(5490,'Necoclí'),
(5495,'Nechí'),
(5501,'Olaya'),
(5541,'Peñol'),
(5543,'Peque'),
(5576,'Pueblorrico'),
(5579,'Puerto Berrío'),
(5585,'Puerto Nare'),
(5591,'Puerto Triunfo'),
(5604,'Remedios'),
(5607,'Retiro'),
(5615,'Rionegro'),
(5628,'Sabanalarga'),
(5631,'Sabaneta'),
(5642,'Salgar'),
(5647,'San Andrés De Cuerquía'),
(5649,'San Carlos'),
(5652,'San Francisco'),
(5656,'San Jerónimo'),
(5658,'San José De La Montaña'),
(5659,'San Juan De Urabá'),
(5660,'San Luis'),
(5664,'San Pedro'),
(5665,'San Pedro De Uraba'),
(5667,'San Rafael'),
(5670,'San Roque'),
(5674,'San Vicente'),
(5679,'Santa Bárbara'),
(5686,'Santa Rosa De Osos'),
(5690,'Santo Domingo'),
(5697,'El Santuario'),
(5736,'Segovia'),
(5756,'Sonson'),
(5761,'Sopetrán'),
(5789,'Támesis'),
(5790,'Tarazá'),
(5792,'Tarso'),
(5809,'Titiribí'),
(5819,'Toledo'),
(5837,'Turbo'),
(5842,'Uramita'),
(5847,'Urrao'),
(5854,'Valdivia'),
(5856,'Valparaíso'),
(5858,'Vegachí'),
(5861,'Venecia'),
(5873,'Vigía Del Fuerte'),
(5885,'Yalí'),
(5887,'Yarumal'),
(5890,'Yolombó'),
(5893,'Yondó'),
(5895,'Zaragoza'),
(8001,'Barranquilla'),
(8078,'Baranoa'),
(8137,'Campo De La Cruz'),
(8141,'Candelaria'),
(8296,'Galapa'),
(8372,'Juan De Acosta'),
(8421,'Luruaco'),
(8433,'Malambo'),
(8436,'Manatí'),
(8520,'Palmar De Varela'),
(8549,'Piojó'),
(8558,'Polonuevo'),
(8560,'Ponedera'),
(8573,'Puerto Colombia'),
(8606,'Repelón'),
(8634,'Sabanagrande'),
(8638,'Sabanalarga'),
(8675,'Santa Lucía'),
(8685,'Santo Tomás'),
(8758,'Soledad'),
(8770,'Suan'),
(8832,'Tubará'),
(8849,'Usiacurí'),
(11001,'Bogota DC'),
(13001,'Cartagena'),
(13006,'Choachí'),
(13030,'Altos Del Rosario'),
(13042,'Arenal'),
(13052,'Arjona'),
(13062,'Arroyohondo'),
(13074,'Barranco De Loba'),
(13140,'Calamar'),
(13160,'Cantagallo'),
(13188,'Cicuco'),
(13212,'Córdoba'),
(13222,'Clemencia'),
(13244,'El Carmen De Bolívar'),
(13248,'El Guamo'),
(13268,'El Peñón'),
(13300,'Hatillo De Loba'),
(13430,'Magangué'),
(13433,'Mahates'),
(13440,'Margarita'),
(13442,'María La Baja'),
(13458,'Montecristo'),
(13468,'Mompós'),
(13473,'Morales'),
(13549,'Pinillos'),
(13580,'Regidor'),
(13600,'Río Viejo'),
(13620,'San Cristóbal'),
(13647,'San Estanislao'),
(13650,'San Fernando'),
(13654,'San Jacinto'),
(13655,'San Jacinto Del Cauca'),
(13657,'San Juan Nepomuceno'),
(13667,'San Martín De Loba'),
(13670,'San Pablo'),
(13673,'Santa Catalina'),
(13683,'Santa Rosa'),
(13688,'Santa Rosa Del Sur'),
(13744,'Simití'),
(13760,'Soplaviento'),
(13780,'Talaigua Nuevo'),
(13810,'Tiquisio'),
(13836,'Turbaco'),
(13838,'Turbaná'),
(13873,'Villanueva'),
(13894,'Zambrano'),
(15001,'Tunja'),
(15022,'Almeida'),
(15047,'Aquitania'),
(15051,'Arcabuco'),
(15087,'Belén'),
(15090,'Berbeo'),
(15092,'Betéitiva'),
(15097,'Boavita'),
(15104,'Boyacá'),
(15106,'Briceño'),
(15109,'Buenavista'),
(15114,'Busbanzá'),
(15131,'Caldas'),
(15135,'Campohermoso'),
(15162,'Cerinza'),
(15172,'Chinavita'),
(15176,'Chiquinquirá'),
(15180,'Chiscas'),
(15183,'Chita'),
(15185,'Chitaraque'),
(15187,'Chivatá'),
(15189,'Ciénega'),
(15204,'Cómbita'),
(15212,'Coper'),
(15215,'Corrales'),
(15218,'Covarachía'),
(15223,'Cubará'),
(15224,'Cucaita'),
(15226,'Cuítiva'),
(15232,'Chíquiza'),
(15236,'Chivor'),
(15238,'Duitama'),
(15244,'El Cocuy'),
(15248,'El6Aspino'),
(15272,'Firavitoba'),
(15276,'Floresta'),
(15293,'Gachantivá'),
(15296,'Gameza'),
(15299,'Garagoa'),
(15317,'Guacamayas'),
(15322,'Guateque'),
(15325,'Guayatá'),
(15332,'Guican'),
(15362,'Iza'),
(15367,'Jenesano'),
(15368,'Jericó'),
(15377,'Labranzagrande'),
(15380,'La Capilla'),
(15401,'La Victoria'),
(15403,'La Uvita'),
(15407,'Villa De Leyva'),
(15425,'Macanal'),
(15442,'Maripí'),
(15455,'Miraflores'),
(15464,'Mongua'),
(15466,'Monguí'),
(15469,'Moniquirá'),
(15476,'Motavita'),
(15480,'Muzo'),
(15491,'Nobsa'),
(15494,'Nuevo Colón'),
(15500,'Oicatá'),
(15507,'Otanche'),
(15511,'Pachavita'),
(15514,'Páez'),
(15516,'Paipa'),
(15518,'Pajarito'),
(15522,'Panqueba'),
(15531,'Pauna'),
(15533,'Paya'),
(15537,'Paz De Río'),
(15542,'Pesca'),
(15550,'Pisba'),
(15572,'Puerto Boyacá'),
(15580,'Quípama'),
(15599,'Ramiriquí'),
(15600,'Ráquira'),
(15621,'Rondón'),
(15632,'Saboyá'),
(15638,'Sáchica'),
(15646,'Samacá'),
(15660,'San Eduardo'),
(15664,'San José De Pare'),
(15667,'San Luis De Gaceno'),
(15673,'San Mateo'),
(15676,'San Miguel De Sema'),
(15681,'San Pablo De Borbur'),
(15686,'Santana'),
(15690,'Santa María'),
(15693,'Santa Rosa De Viterbo'),
(15696,'Santa Sofía'),
(15720,'Sativanorte'),
(15723,'Sativasur'),
(15740,'Siachoque'),
(15753,'Soatá'),
(15755,'Socotá'),
(15757,'Socha'),
(15759,'Sogamoso'),
(15761,'Somondoco'),
(15762,'Sora'),
(15763,'Sotaquirá'),
(15764,'Soracá'),
(15774,'Susacón'),
(15776,'Sutamarchán'),
(15778,'Sutatenza'),
(15790,'Tasco'),
(15798,'Tenza'),
(15804,'Tibaná'),
(15806,'Tibasosa'),
(15808,'Tinjacá'),
(15810,'Tipacoque'),
(15814,'Toca'),
(15816,'Togüí'),
(15820,'Tópaga'),
(15822,'Tota'),
(15832,'Tununguá'),
(15835,'Turmequé'),
(15837,'Tuta'),
(15839,'Tutazá'),
(15842,'Umbita'),
(15861,'Ventaquemada'),
(15879,'Viracachá'),
(15897,'Zetaquira'),
(17001,'Manizales'),
(17013,'Aguadas'),
(17042,'Anserma'),
(17050,'Aranzazu'),
(17088,'Belalcázar'),
(17174,'Chinchiná'),
(17272,'Filadelfia'),
(17380,'La Dorada'),
(17388,'La Merced'),
(17433,'Manzanares'),
(17442,'Marmato'),
(17444,'Marquetalia'),
(17446,'Marulanda'),
(17486,'Neira'),
(17495,'Norcasia'),
(17513,'Pácora'),
(17524,'Palestina'),
(17541,'Pensilvania'),
(17614,'Riosucio'),
(17616,'Risaralda'),
(17653,'Salamina'),
(17662,'Samaná'),
(17665,'San José'),
(17777,'Supía'),
(17867,'Victoria'),
(17873,'Villamaría'),
(17877,'Viterbo'),
(18001,'Florencia'),
(18029,'Albania'),
(18094,'Belén De Los Andaquies'),
(18150,'Cartagena Del Chairá'),
(18205,'Curillo'),
(18247,'El Doncello'),
(18256,'El Paujil'),
(18410,'La Montañita'),
(18460,'Milán'),
(18479,'Morelia'),
(18592,'Puerto Rico'),
(18610,'San José Del Fragua'),
(18753,'San Vicente Del Caguán'),
(18756,'Solano'),
(18785,'Solita'),
(18860,'Valparaíso'),
(19001,'Popayán'),
(19022,'Almaguer'),
(19050,'Argelia'),
(19075,'Balboa'),
(19100,'Bolívar'),
(19110,'Buenos Aires'),
(19130,'Cajibío'),
(19137,'Caldono'),
(19142,'Caloto'),
(19212,'Corinto'),
(19256,'El Tambo'),
(19290,'Florencia'),
(19300,'Guachené'),
(19318,'Guapi'),
(19355,'Inzá'),
(19364,'Jambaló'),
(19392,'La Sierra'),
(19397,'La Vega'),
(19418,'López'),
(19450,'Mercaderes'),
(19455,'Miranda'),
(19473,'Morales'),
(19513,'Padilla'),
(19517,'Paez'),
(19532,'Patía'),
(19533,'Piamonte'),
(19548,'Piendamó'),
(19573,'Puerto Tejada'),
(19585,'Puracé'),
(19622,'Rosas'),
(19693,'San Sebastián'),
(19698,'Santander De Quilichao'),
(19701,'Santa Rosa'),
(19743,'Silvia'),
(19760,'Sotara'),
(19780,'Suárez'),
(19785,'Sucre'),
(19807,'Timbío'),
(19809,'Timbiquí'),
(19821,'Toribio'),
(19824,'Totoró'),
(19845,'Villa Rica'),
(20001,'Valledupar'),
(20011,'Aguachica'),
(20013,'Agustín Codazzi'),
(20032,'Astrea'),
(20045,'Becerril'),
(20060,'Bosconia'),
(20175,'Chimichagua'),
(20178,'Chiriguaná'),
(20228,'Curumaní'),
(20238,'El Copey'),
(20250,'El Paso'),
(20295,'Gamarra'),
(20310,'González'),
(20383,'La Gloria'),
(20400,'La Jagua De Ibirico'),
(20443,'Manaure'),
(20517,'Pailitas'),
(20550,'Pelaya'),
(20570,'Pueblo Bello'),
(20614,'Río De Oro'),
(20621,'La Paz'),
(20710,'San Alberto'),
(20750,'San Diego'),
(20770,'San Martín'),
(20787,'Tamalameque'),
(23001,'Montería'),
(23068,'Ayapel'),
(23079,'Buenavista'),
(23090,'Canalete'),
(23162,'Cereté'),
(23168,'Chimá'),
(23182,'Chinú'),
(23189,'Ciénaga De Oro'),
(23300,'Cotorra'),
(23350,'La Apartada'),
(23417,'Lorica'),
(23419,'Los Córdobas'),
(23464,'Momil'),
(23466,'Montelíbano'),
(23500,'Moñitos'),
(23555,'Planeta Rica'),
(23570,'Pueblo Nuevo'),
(23574,'Puerto Escondido'),
(23580,'Puerto Libertador'),
(23586,'Purísima'),
(23660,'Sahagún'),
(23670,'San Andrés Sotavento'),
(23672,'San Antero'),
(23675,'San Bernardo Del Viento'),
(23678,'San Carlos'),
(23686,'San Pelayo'),
(23807,'Tierralta'),
(23855,'Valencia'),
(25001,'Agua De Dios'),
(25019,'Albán'),
(25035,'Anapoima'),
(25040,'Anolaima'),
(25053,'Arbeláez'),
(25086,'Beltrán'),
(25095,'Bituima'),
(25099,'Bojacá'),
(25120,'Cabrera'),
(25123,'Cachipay'),
(25126,'Cajicá'),
(25148,'Caparrapí'),
(25151,'Caqueza'),
(25154,'Carmen De Carupa'),
(25168,'Chaguaní'),
(25175,'Chía'),
(25178,'Chipaque'),
(25181,'Choachí'),
(25183,'Chocontá'),
(25200,'Cogua'),
(25214,'Cota'),
(25224,'Cucunuba'),
(25245,'El Colegio'),
(25258,'El Peñón'),
(25260,'El Rosal'),
(25269,'Facatativá'),
(25279,'Fomeque'),
(25281,'Fosca'),
(25286,'Funza'),
(25288,'Fúquene'),
(25290,'Fusagasugá'),
(25293,'Gachala'),
(25295,'Gachancipá'),
(25297,'Gachetá'),
(25299,'Gama'),
(25307,'Girardot'),
(25312,'Granada'),
(25317,'Guachetá'),
(25320,'Guaduas'),
(25322,'Guasca'),
(25324,'Guataquí'),
(25326,'Guatavita'),
(25328,'Guayabal De Siquima'),
(25335,'Guayabetal'),
(25339,'Gutiérrez'),
(25368,'Jerusalén'),
(25372,'Junín'),
(25377,'La Calera'),
(25386,'La Mesa'),
(25394,'La Palma'),
(25398,'La Peña'),
(25402,'La Vega'),
(25407,'Lenguazaque'),
(25426,'Macheta'),
(25430,'Madrid'),
(25436,'Manta'),
(25438,'Medina'),
(25473,'Mosquera'),
(25483,'Nariño'),
(25486,'Nemocón'),
(25488,'Nilo'),
(25489,'Nimaima'),
(25491,'Nocaima'),
(25506,'Venecia'),
(25513,'Pacho'),
(25518,'Paime'),
(25524,'Pandi'),
(25530,'Paratebueno'),
(25535,'Pasca'),
(25572,'Puerto Salgar'),
(25580,'Pulí'),
(25592,'Quebradanegra'),
(25594,'Quetame'),
(25596,'Quipile'),
(25599,'Apulo'),
(25612,'Ricaurte'),
(25645,'San Antonio Del Tequendama'),
(25649,'San Bernardo'),
(25653,'San Cayetano'),
(25658,'San Francisco'),
(25662,'San Juan De Río Seco'),
(25718,'Sasaima'),
(25736,'Sesquilé'),
(25740,'Sibaté'),
(25743,'Silvania'),
(25745,'Simijaca'),
(25754,'Soacha'),
(25758,'Sopó'),
(25769,'Subachoque'),
(25772,'Suesca'),
(25777,'Supatá'),
(25779,'Susa'),
(25781,'Sutatausa'),
(25785,'Tabio'),
(25793,'Tausa'),
(25797,'Tena'),
(25799,'Tenjo'),
(25805,'Tibacuy'),
(25807,'Tibirita'),
(25815,'Tocaima'),
(25817,'Tocancipá'),
(25823,'Topaipi'),
(25839,'Ubalá'),
(25841,'Ubaque'),
(25843,'Villa De San Diego De Ubate'),
(25845,'Une'),
(25851,'Útica'),
(25862,'Vergara'),
(25867,'Vianí'),
(25871,'Villagómez'),
(25873,'Villapinzón'),
(25875,'Villeta'),
(25878,'Viotá'),
(25885,'Yacopí'),
(25898,'Zipacón'),
(25899,'Zipaquirá'),
(27001,'Quibdó'),
(27006,'Acandí'),
(27025,'Alto Baudo'),
(27050,'Atrato'),
(27073,'Bagadó'),
(27075,'Bahía Solano'),
(27077,'Bajo Baudó'),
(27086,'Belén De Bajirá'),
(27099,'Bojaya'),
(27135,'El Cantón Del San Pablo'),
(27150,'Carmen Del Darien'),
(27160,'Cértegui'),
(27205,'Condoto'),
(27245,'El Carmen De Atrato'),
(27250,'El Litoral Del San Juan'),
(27361,'Istmina'),
(27372,'Juradó'),
(27413,'Lloró'),
(27425,'Medio Atrato'),
(27430,'Medio Baudó'),
(27450,'Medio San Juan'),
(27491,'Nóvita'),
(27495,'Nuquí'),
(27580,'Río Iro'),
(27600,'Río Quito'),
(27615,'Riosucio'),
(27660,'San José Del Palmar'),
(27745,'Sipí'),
(27787,'Tadó'),
(27800,'Unguía'),
(27810,'Unión Panamericana'),
(41001,'Neiva'),
(41006,'Acevedo'),
(41013,'Agrado'),
(41016,'Aipe'),
(41020,'Algeciras'),
(41026,'Altamira'),
(41078,'Baraya'),
(41132,'Campoalegre'),
(41206,'Colombia'),
(41244,'Elías'),
(41298,'Garzón'),
(41306,'Gigante'),
(41319,'Guadalupe'),
(41349,'Hobo'),
(41357,'Iquira'),
(41359,'Isnos'),
(41378,'La Argentina'),
(41396,'La Plata'),
(41483,'Nátaga'),
(41503,'Oporapa'),
(41518,'Paicol'),
(41524,'Palermo'),
(41530,'Palestina'),
(41548,'Pital'),
(41551,'Pitalito'),
(41615,'Rivera'),
(41660,'Saladoblanco'),
(41668,'San Agustín'),
(41676,'Santa María'),
(41770,'Suaza'),
(41791,'Tarqui'),
(41797,'Tesalia'),
(41799,'Tello'),
(41801,'Teruel'),
(41807,'Timana'),
(41872,'Villavieja'),
(41885,'Yaguará'),
(44001,'Riohacha'),
(44035,'Albania'),
(44078,'Barrancas'),
(44090,'Dibulla'),
(44098,'Distracción'),
(44110,'El Molino'),
(44279,'Fonseca'),
(44378,'Hatonuevo'),
(44420,'La Jagua Del Pilar'),
(44430,'Maicao'),
(44560,'Manaure'),
(44650,'San Juan Del Cesar'),
(44847,'Uribia'),
(44855,'Urumita'),
(44874,'Villanueva'),
(47001,'Santa Marta'),
(47030,'Algarrobo'),
(47053,'Aracataca'),
(47058,'Ariguaní'),
(47161,'Cerro San Antonio'),
(47170,'Chibolo'),
(47189,'Ciénaga'),
(47205,'Concordia'),
(47245,'El Banco'),
(47258,'El Piñon'),
(47268,'El Retén'),
(47288,'Fundación'),
(47318,'Guamal'),
(47460,'Nueva Granada'),
(47541,'Pedraza'),
(47545,'Pijiño Del Carmen'),
(47551,'Pivijay'),
(47555,'Plato'),
(47570,'Puebloviejo'),
(47605,'Remolino'),
(47660,'Sabanas De San Angel'),
(47675,'Salamina'),
(47692,'San Sebastián De Buenavista'),
(47703,'San Zenón'),
(47707,'Santa Ana'),
(47720,'Santa Bárbara De Pinto'),
(47745,'Sitionuevo'),
(47798,'Tenerife'),
(47960,'Zapayán'),
(47980,'Zona Bananera'),
(50001,'Villavicencio'),
(50006,'Acacías'),
(50110,'Barranca De Upía'),
(50124,'Cabuyaro'),
(50150,'Castilla La Nueva'),
(50223,'Cubarral'),
(50226,'Cumaral'),
(50245,'El Calvario'),
(50251,'El Castillo'),
(50270,'El Dorado'),
(50287,'Fuente De Oro'),
(50313,'Granada'),
(50318,'Guamal'),
(50325,'Mapiripán'),
(50330,'Mesetas'),
(50350,'La Macarena'),
(50370,'Uribe'),
(50400,'Lejanías'),
(50450,'Puerto Concordia'),
(50568,'Puerto Gaitán'),
(50573,'Puerto López'),
(50577,'Puerto Lleras'),
(50590,'Puerto Rico'),
(50606,'Restrepo'),
(50680,'San Carlos De Guaroa'),
(50683,'San Juan De Arama'),
(50686,'San Juanito'),
(50689,'San Martín'),
(50711,'Vistahermosa'),
(52001,'Pasto'),
(52019,'Albán'),
(52022,'Aldana'),
(52036,'Ancuya'),
(52051,'Arboleda'),
(52079,'Barbacoas'),
(52083,'Belén'),
(52110,'Buesaco'),
(52203,'Colón'),
(52207,'Consaca'),
(52210,'Contadero'),
(52215,'Córdoba'),
(52224,'Cuaspud'),
(52227,'Cumbal'),
(52233,'Cumbitara'),
(52240,'Chachagüí'),
(52250,'El Charco'),
(52254,'El Peñol'),
(52256,'El Rosario'),
(52258,'El Tablón De Gómez'),
(52260,'El Tambo'),
(52287,'Funes'),
(52317,'Guachucal'),
(52320,'Guaitarilla'),
(52323,'Gualmatán'),
(52352,'Iles'),
(52354,'Imués'),
(52356,'Ipiales'),
(52378,'La Cruz'),
(52381,'La Florida'),
(52385,'La Llanada'),
(52390,'La Tola'),
(52399,'La Unión'),
(52405,'Leiva'),
(52411,'Linares'),
(52418,'Los Andes'),
(52427,'Magüi'),
(52435,'Mallama'),
(52473,'Mosquera'),
(52480,'Nariño'),
(52490,'Olaya Herrera'),
(52506,'Ospina'),
(52520,'Francisco Pizarro'),
(52540,'Policarpa'),
(52560,'Potosí'),
(52565,'Providencia'),
(52573,'Puerres'),
(52585,'Pupiales'),
(52612,'Ricaurte'),
(52621,'Roberto Payán'),
(52678,'Samaniego'),
(52683,'Sandoná'),
(52685,'San Bernardo'),
(52687,'San Lorenzo'),
(52693,'San Pablo'),
(52694,'San Pedro De Cartago'),
(52696,'Santa Bárbara'),
(52699,'Santacruz'),
(52720,'Sapuyes'),
(52786,'Taminango'),
(52788,'Tangua'),
(52835,'San Andres De Tumaco'),
(52838,'Túquerres'),
(52885,'Yacuanquer'),
(54001,'Cúcuta'),
(54003,'Abrego'),
(54051,'Arboledas'),
(54099,'Bochalema'),
(54109,'Bucarasica'),
(54125,'Cácota'),
(54128,'Cachirá'),
(54172,'Chinácota'),
(54174,'Chitagá'),
(54206,'Convención'),
(54223,'Cucutilla'),
(54239,'Durania'),
(54245,'El Carmen'),
(54250,'El Tarra'),
(54261,'El Zulia'),
(54313,'Gramalote'),
(54344,'Hacarí'),
(54347,'Herrán'),
(54377,'Labateca'),
(54385,'La Esperanza'),
(54398,'La Playa'),
(54405,'Los Patios'),
(54418,'Lourdes'),
(54480,'Mutiscua'),
(54498,'Ocaña'),
(54518,'Pamplona'),
(54520,'Pamplonita'),
(54553,'Puerto Santander'),
(54599,'Ragonvalia'),
(54660,'Salazar'),
(54670,'San Calixto'),
(54673,'San Cayetano'),
(54680,'Santiago'),
(54720,'Sardinata'),
(54743,'Silos'),
(54800,'Teorama'),
(54810,'Tibú'),
(54820,'Toledo'),
(54871,'Villa Caro'),
(54874,'Villa Del Rosario'),
(63001,'Armenia'),
(63111,'Buenavista'),
(63130,'Calarca'),
(63190,'Circasia'),
(63212,'Córdoba'),
(63272,'Filandia'),
(63302,'Génova'),
(63401,'La Tebaida'),
(63470,'Montenegro'),
(63548,'Pijao'),
(63594,'Quimbaya'),
(63690,'Salento'),
(66001,'Pereira'),
(66045,'Apía'),
(66075,'Balboa'),
(66088,'Belén De Umbría'),
(66170,'Dosquebradas'),
(66318,'Guática'),
(66383,'La Celia'),
(66400,'La Virginia'),
(66440,'Marsella'),
(66456,'Mistrató'),
(66572,'Pueblo Rico'),
(66594,'Quinchía'),
(66682,'Santa Rosa De Cabal'),
(66687,'Santuario'),
(68001,'Bucaramanga'),
(68013,'Aguada'),
(68020,'Albania'),
(68051,'Aratoca'),
(68077,'Barbosa'),
(68079,'Barichara'),
(68081,'Barrancabermeja'),
(68092,'Betulia'),
(68101,'Bolívar'),
(68121,'Cabrera'),
(68132,'California'),
(68147,'Capitanejo'),
(68152,'Carcasí'),
(68160,'Cepitá'),
(68162,'Cerrito'),
(68167,'Charalá'),
(68169,'Charta'),
(68176,'Chima'),
(68179,'Chipatá'),
(68190,'Cimitarra'),
(68207,'Concepción'),
(68209,'Confines'),
(68211,'Contratación'),
(68217,'Coromoro'),
(68229,'Curití'),
(68235,'El Carmen De Chucurí'),
(68245,'El Guacamayo'),
(68250,'El Peñón'),
(68255,'El Playón'),
(68264,'Encino'),
(68266,'Enciso'),
(68271,'Florián'),
(68276,'Floridablanca'),
(68296,'Galan'),
(68298,'Gambita'),
(68307,'Girón'),
(68318,'Guaca'),
(68320,'Guadalupe'),
(68322,'Guapotá'),
(68324,'Guavatá'),
(68327,'Güepsa'),
(68344,'Hato'),
(68368,'Jesús María'),
(68370,'Jordán'),
(68377,'La Belleza'),
(68385,'Landázuri'),
(68397,'La Paz'),
(68406,'Lebríja'),
(68418,'Los Santos'),
(68425,'Macaravita'),
(68432,'Málaga'),
(68444,'Matanza'),
(68464,'Mogotes'),
(68468,'Molagavita'),
(68498,'Ocamonte'),
(68500,'Oiba'),
(68502,'Onzaga'),
(68522,'Palmar'),
(68524,'Palmas Del Socorro'),
(68533,'Páramo'),
(68547,'Piedecuesta'),
(68549,'Pinchote'),
(68572,'Puente Nacional'),
(68573,'Puerto Parra'),
(68575,'Puerto Wilches'),
(68615,'Rionegro'),
(68655,'Sabana De Torres'),
(68669,'San Andrés'),
(68673,'San Benito'),
(68679,'San Gil'),
(68682,'San Joaquín'),
(68684,'San José De Miranda'),
(68686,'San Miguel'),
(68689,'San Vicente De Chucurí'),
(68705,'Santa Bárbara'),
(68720,'Santa Helena Del Opón'),
(68745,'Simacota'),
(68755,'Socorro'),
(68770,'Suaita'),
(68773,'Sucre'),
(68780,'Suratá'),
(68820,'Tona'),
(68855,'Valle De San José'),
(68861,'Vélez'),
(68867,'Vetas'),
(68872,'Villanueva'),
(68895,'Zapatoca'),
(70001,'Sincelejo'),
(70110,'Buenavista'),
(70124,'Caimito'),
(70204,'Coloso'),
(70215,'Corozal'),
(70221,'Coveñas'),
(70230,'Chalán'),
(70233,'El Roble'),
(70235,'Galeras'),
(70265,'Guaranda'),
(70400,'La Unión'),
(70418,'Los Palmitos'),
(70429,'Majagual'),
(70473,'Morroa'),
(70508,'Ovejas'),
(70523,'Palmito'),
(70670,'Sampués'),
(70678,'San Benito Abad'),
(70702,'San Juan De Betulia'),
(70708,'San Marcos'),
(70713,'San Onofre'),
(70717,'San Pedro'),
(70742,'San Luis De Sincé'),
(70771,'Sucre'),
(70820,'Santiago De Tolú'),
(70823,'Tolú Viejo'),
(73001,'Ibague'),
(73024,'Alpujarra'),
(73026,'Alvarado'),
(73030,'Ambalema'),
(73043,'Anzoátegui'),
(73055,'Armero'),
(73067,'Ataco'),
(73124,'Cajamarca'),
(73148,'Carmen De Apicalá'),
(73152,'Casabianca'),
(73168,'Chaparral'),
(73200,'Coello'),
(73217,'Coyaima'),
(73226,'Cunday'),
(73236,'Dolores'),
(73268,'Espinal'),
(73270,'Falan'),
(73275,'Flandes'),
(73283,'Fresno'),
(73319,'Guamo'),
(73347,'Herveo'),
(73349,'Honda'),
(73352,'Icononzo'),
(73408,'Lérida'),
(73411,'Líbano'),
(73443,'Mariquita'),
(73449,'Melgar'),
(73461,'Murillo'),
(73483,'Natagaima'),
(73504,'Ortega'),
(73520,'Palocabildo'),
(73547,'Piedras'),
(73555,'Planadas'),
(73563,'Prado'),
(73585,'Purificación'),
(73616,'Rioblanco'),
(73622,'Roncesvalles'),
(73624,'Rovira'),
(73671,'Saldaña'),
(73675,'San Antonio'),
(73678,'San Luis'),
(73686,'Santa Isabel'),
(73770,'Suárez'),
(73854,'Valle De San Juan'),
(73861,'Venadillo'),
(73870,'Villahermosa'),
(73873,'Villarrica'),
(76001,'Cali'),
(76020,'Alcalá'),
(76036,'Andalucía'),
(76041,'Ansermanuevo'),
(76054,'Argelia'),
(76100,'Bolívar'),
(76109,'Buenaventura'),
(76111,'Guadalajara De Buga'),
(76113,'Bugalagrande'),
(76122,'Caicedonia'),
(76126,'Calima'),
(76130,'Candelaria'),
(76147,'Cartago'),
(76233,'Dagua'),
(76243,'El Águila'),
(76246,'El Cairo'),
(76248,'El Cerrito'),
(76250,'El Dovio'),
(76275,'Florida'),
(76306,'Ginebra'),
(76318,'Guacarí'),
(76364,'Jamundí'),
(76377,'La Cumbre'),
(76400,'La Unión'),
(76403,'La Victoria'),
(76497,'Obando'),
(76520,'Palmira'),
(76563,'Pradera'),
(76606,'Restrepo'),
(76616,'Riofrío'),
(76622,'Roldanillo'),
(76670,'San Pedro'),
(76736,'Sevilla'),
(76823,'Toro'),
(76828,'Trujillo'),
(76834,'Tuluá'),
(76845,'Ulloa'),
(76863,'Versalles'),
(76869,'Vijes'),
(76890,'Yotoco'),
(76892,'Yumbo'),
(76895,'Zarzal'),
(81001,'Arauca'),
(81065,'Arauquita'),
(81220,'Cravo Norte'),
(81300,'Fortul'),
(81591,'Puerto Rondón'),
(81736,'Saravena'),
(81794,'Tame'),
(85001,'Yopal'),
(85010,'Aguazul'),
(85015,'Chameza'),
(85125,'Hato Corozal'),
(85136,'La Salina'),
(85139,'Maní'),
(85162,'Monterrey'),
(85225,'Nunchía'),
(85230,'Orocué'),
(85250,'Paz De Ariporo'),
(85263,'Pore'),
(85279,'Recetor'),
(85300,'Sabanalarga'),
(85315,'Sácama'),
(85325,'San Luis De Palenque'),
(85400,'Támara'),
(85410,'Tauramena'),
(85430,'Trinidad'),
(85440,'Villanueva'),
(86001,'Mocoa'),
(86219,'Colón'),
(86320,'Orito'),
(86568,'Puerto Asís'),
(86569,'Puerto Caicedo'),
(86571,'Puerto Guzmán'),
(86573,'Leguízamo'),
(86749,'Sibundoy'),
(86755,'San Francisco'),
(86757,'San Miguel'),
(86760,'Santiago'),
(86865,'Valle Del Guamuez'),
(86885,'Villagarzón'),
(88001,'San Andrés'),
(88564,'Providencia'),
(91001,'Leticia'),
(91263,'El Encanto'),
(91405,'La Chorrera'),
(91407,'La Pedrera'),
(91430,'La Victoria'),
(91460,'Miriti - Paraná'),
(91530,'Puerto Alegría'),
(91536,'Puerto Arica'),
(91540,'Puerto Nariño'),
(91669,'Puerto Santander'),
(91798,'Tarapacá'),
(94001,'Inírida'),
(94343,'Barranco Minas'),
(94663,'Mapiripana'),
(94883,'San Felipe'),
(94884,'Puerto Colombia'),
(94885,'La Guadalupe'),
(94886,'Cacahual'),
(94887,'Pana Pana'),
(94888,'Morichal'),
(95001,'San José Del Guaviare'),
(95015,'Calamar'),
(95025,'El Retorno'),
(95200,'Miraflores'),
(97001,'Mitú'),
(97161,'Caruru'),
(97511,'Pacoa'),
(97666,'Taraira'),
(97777,'Papunaua'),
(97889,'Yavaraté'),
(99001,'Puerto Carreño'),
(99524,'La Primavera'),
(99624,'Santa Rosalía'),
(99773,'Cumaribo')
], validate_choice=True)
celularEmpleado = IntegerField('Numero Telefono Movil', validators=[
Required(message='El campo es obligatorio'),
Length(max=10, min=10, message='El campo debe tener 10 caracteres')
])
correoElectronicoEmpleado = StringField('Correo Electronico Principal', validators=[
Required(message='El campo es obligatorio'),
Email()
])
enviar = SubmitField("Enviar")
class inscribirDepositos(FlaskForm):
tipoDeposito = SelectField('Tipo Deposito Electronico', choices=[
('DETS','Deposito Electronico De Tramite Simplificado'),
('DECSE','Deposito Electronico Para Canalizar Subsidios Estatales'),
('DETO','Deposito Electronico De Tramite Ordinario'),
('DETTS','Deposito Electronico Transaccional De Tramite Simplificado'),
('DETTO','Deposito Electronico Transaccional De Tramite Ordinario')], validators=[
Required(message='El campo es obligatorio'),
])
depositoElectronico = IntegerField('Deposito Electronico Numero', validators=[
Required(message='El campo es obligatorio')
])
nombrePersonalizado = StringField('Nombre Personalizado', validators=[
Required(message='El campo es obligatorio')
])
tipoId = SelectField('Tipo Identificacion', choices=[
('CC','Cedula de Ciudadania'),
('CE','Cedula de Extrangeria'),
('PA','Pasaporte'),
('RC','Registro Civil'),
('TI','Tarjeta de Identidad')], validators=[
Required(message='El campo es obligatorio'),
])
numeroIdCliente = IntegerField('Numero Identificacion', validators=[
Required(message='El campo es obligatorio'),
Length(max=10, min=6, message='El campo debe tener entre 6 y 10 caracteres')
])
inscribirDeposito = SubmitField("Inscribir Deposito")
class transferir(FlaskForm):
productoDestino = IntegerField('Deposito de Destino', validators=[
Required(message='El campo es obligatorio')
])
valorATransferir = IntegerField('Valor a Transferir', validators=[
Required(message='El campos es obligatorio')
])
transferir = SubmitField("Realizar Transferencia")
| nilq/baby-python | python |
from .serializers import User | nilq/baby-python | python |
"""
Other plotting routines outside of matplotlib
"""
import matplotlib.transforms as transforms
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.lines import Line2D
import matplotlib.dates as mdates
from matplotlib import collections
from matplotlib.ticker import Formatter
from datetime import datetime, timedelta
import numpy as np
from sfoda.utils import othertime
class StreakPlot(object):
"""
Class for generating a streak plot
"""
# Width of the start and end of the tail
widthmin = 0.1
widthmax = 1.5
# Plotting parameters
colors = '0.9'
alpha = 0.9
xlim=None
ylim=None
def __init__(self,xp,yp,**kwargs):
"""
StreakPlot:
xp, yp - spatial location matrices with dimension Nt x Nxy
Streaks are along the first dimension Nt
"""
self.__dict__.update(**kwargs)
self.xp = xp
self.yp = yp
self.nx,self.nt = np.shape(self.xp)
self.create_xy()
def create_xy(self):
# Create the start and end points
self.points = np.concatenate([self.xp[...,np.newaxis],\
self.yp[...,np.newaxis]],axis=-1)
# Create the linewidths
lwidths = np.linspace(self.widthmin,self.widthmax,self.nt-1)
lwidths = lwidths**2 # this thins out the tail a bit
self.lwidths = lwidths/lwidths[-1] * self.widthmax
# Create a list of segment arrays
self.segments=[ np.concatenate([self.points[ii,:-1,np.newaxis,:],\
self.points[ii,1:,np.newaxis,:]],axis=1)\
for ii in range(self.nx) ]
# Create a list of line collections
self.lcs = [ LineCollection(segment, linewidths=self.lwidths,\
colors=self.colors,alpha=self.alpha)\
for segment in self.segments ]
def update(self,xp,yp):
"""
Update the line collections with new x,y points
"""
self.xp=xp
self.yp=yp
# Create the start and end points
self.points = np.concatenate([xp[...,np.newaxis],yp[...,np.newaxis]],axis=-1)
# Create a list of segment arrays
self.segments=[ np.concatenate([self.points[ii,:-1,np.newaxis,:],\
self.points[ii,1:,np.newaxis,:]],axis=1)\
for ii in range(self.nx) ]
for lc, seg in zip(self.lcs,self.segments):
lc.set_segments(seg)
def plot(self, ax):
"""Inserts each line collection into current plot"""
if self.xlim == None:
self.xlim = [self.xp.min(),self.xp.max()]
if self.ylim == None:
self.ylim = [self.yp.min(),self.yp.max()]
ax.set_xlim(self.xlim)
ax.set_ylim(self.ylim)
ax.set_aspect('equal')
list(map(ax.add_collection,self.lcs))
#for lc in self.lcs:
# ax.add_collection(lc)
return ax
def streakplot(xp,yp,ax=None,**kwargs):
"""
Functional call to StreakPlot class
"""
if ax==None:
ax=plt.gca()
S = StreakPlot(xp,yp,**kwargs)
S.plot(ax)
return S
def stackplot(t,y,scale=None,gap=0.2,ax=None,fig=None,units='',labels=None,**kwargs):
"""
Vertically stacked time series plot.
Puts all of the time-series into one axes by working out a suitable spacing.
Inputs:
y - 2d array [nt,ny] where ny is the number of time series
t - datetime vector
Returns:
fig, ax : figure and axes handles
ll : plot handles to each line plot [list]
"""
# Determine the scale factors and the heights of all of the axes
ny = y.shape[0]
# Make sure that the time is datetime
if isinstance(t[0], np.datetime64):
t = othertime.datetime64todatetime(t)
if scale==None:
scale = np.abs(y).max()
if not labels == None:
assert len(labels)==ny, ' number of labels (%d) must equal number of layers (%d)'%(len(labels),ny)
# Height of each axes in normalized coordinates
yheight = 1.0 / (ny + (ny+1.0)*gap)
# Create a new figure
if fig==None:
fig=plt.figure()
else:
fig = plt.gcf()
if ax == None:
ax = fig.add_subplot(111,frame_on=False,ylim=[0,1.0],yticks=[])
# Now add each line to the figure
ll = [] # List of line objects
def fakeaxes(yval,dy):
cc=[0.5,0.5,0.5]
ax.add_line(Line2D([0,1],[yval,yval],linewidth=0.5,color=cc,transform=ax.transAxes,linestyle='--'))
yp = yval + dy/2.
ym = yval - dy/2.
ax.add_line(Line2D([0,0],[yp,ym],linewidth=0.5,color=cc,transform=ax.transAxes))
ax.add_line(Line2D([1,1],[yp,ym],linewidth=0.5,color=cc,transform=ax.transAxes))
#Little caps
ax.add_line(Line2D([0,0.01],[yp,yp],linewidth=0.5,color=cc,transform=ax.transAxes))
ax.add_line(Line2D([0,0.01],[ym,ym],linewidth=0.5,color=cc,transform=ax.transAxes))
ax.add_line(Line2D([0.99,1],[yp,yp],linewidth=0.5,color=cc,transform=ax.transAxes))
ax.add_line(Line2D([0.99,1],[ym,ym],linewidth=0.5,color=cc,transform=ax.transAxes))
for N in range(1,ny+1):
yoffset = N*(gap*yheight) + 0.5*yheight + (N-1)*yheight
# scaling factor
#vscale = yheight / (scale+yoffset)
vscale = yheight / (2*scale)
l = ax.plot(t,vscale*y[N-1,:]+yoffset,**kwargs)
ll.append(l)
#Adds an axes
fakeaxes(yoffset,yheight)
if not labels==None:
plt.text(0.2,yoffset+0.5*yheight-0.02,labels[N-1],transform=ax.transAxes,fontstyle='italic')
# Add a few extra features
ax.add_line(Line2D([0,1],[0.01,0.01],linewidth=0.5,color='k',transform=ax.transAxes))
ax.add_line(Line2D([0,1],[1,1],linewidth=0.5,color='k',transform=ax.transAxes))
plt.xticks(rotation=17)
plt.ylabel('Scale = $\pm$%2.1f [%s]'%(scale,units))
return fig,ax,ll
def polar_pdf( u, v,\
speedmax=1.0, ndirbins=90, nspeedbins=25, cmap='RdYlBu_r',\
ax=None):
"""
Polar plot of speed-direction joint frequency distribution
"""
# Convert cartesian polar coordinates
u_hat_mod = u + 1j*v
speed_mod = np.abs(u_hat_mod)
theta_mod = np.angle(u_hat_mod)
# Create a 2d histogram of speed direction
abins = np.linspace(-np.pi, np.pi, ndirbins) # 0 to 360 in steps of 360/N.
sbins = np.linspace(0.0, speedmax, nspeedbins)
Hmod, xedges, yedges = np.histogram2d(theta_mod, speed_mod,\
bins=(abins,sbins), normed=True)
#Grid to plot your data on using pcolormesh
theta = 0.5*abins[1:]+0.5*abins[0:-1]
r = 0.5*sbins[1:]+0.5*sbins[0:-1]
# Make sure plot covers the whole circle
theta[0] = -np.pi
theta[-1] = np.pi
#theta, r = np.mgrid[0:2*np.pi:360j, 1:100:50j]
# Contour levels precentages
clevs = [0.001, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]
xlabels = ['E','ENE','N','WNW','W','WSW','S','ESE']
#fig = plt.figure( figsize = (14,6))
if ax is None:
ax = plt.subplot(111, projection='polar')
ax.set_xticklabels(xlabels)
C = ax.contourf(theta, r, Hmod.T, clevs, cmap = cmap)
return C, ax
def SpeedDirPlot(t,u,v,convention='current',units='m s^{-1}',color1='b',color2='r'):
"""
Plots speed and direction on the same axes
Inputs:
t - time vector
u,v - velocity cartesian components
Returns:
ax - list of axes handles
h - list of plot handles
convention = 'current' or 'wind'
See this example:
http://matplotlib.org/examples/api/two_scales.html
"""
import airsea
Dir, Spd = airsea.convertUV2SpeedDirn(u,v,convention=convention)
ax = list(range(2))
h = list(range(2))
fig = plt.gcf()
ax[0] = fig.gca()
# Left axes
h[0] = ax[0].fill_between(t, Spd, color=color1,alpha=0.7)
# Make the y-axis label and tick labels match the line color.
ax[0].set_ylabel('Speed [$%s$]'%units, color=color1)
for tl in ax[0].get_yticklabels():
tl.set_color(color1)
#Right axes
ax[1] = ax[0].twinx() # This sets up the second axes
ax[1].plot(t, Dir, '.',color=color2)
ax[1].set_ylabel("Dir'n [$\circ$]", color=color2)
ax[1].set_ylim([0,360])
ax[1].set_yticks([0,90,180,270])
ax[1].set_yticklabels(['N','E','S','W'])
for tl in ax[1].get_yticklabels():
tl.set_color(color2)
plt.setp( ax[0].xaxis.get_majorticklabels(), rotation=17 )
return ax, h
def ProfilePlot(t,y,z,scale=86400,\
axis=0,color=[0.5,0.5,0.5],xlim=None,units='m/s',scalebar=1.0):
"""
Plot a series of vertical profiles as a time series
scale - Sets 1 unit = scale (seconds)
See this page on formatting:
http://matplotlib.org/examples/pylab_examples/date_index_formatter.html
"""
class MyFormatter(Formatter):
def __init__(self, dates, fmt='%b %d %Y'):
self.fmt = fmt
self.dates = dates
def __call__(self, x, pos=0):
'Return the label for time x s'
return datetime.strftime(datetime(1990,1,1)+timedelta(seconds=x),self.fmt)
tsec = othertime.SecondsSince(t)
formatter = MyFormatter(tsec)
y = np.swapaxes(y,0,axis)
lines=[]
line2 =[]
for ii, tt in enumerate(tsec):
#xplot = set_scale(y[:,ii],tt)
xplot = tt + y[:,ii]*scale
lines.append(np.array((xplot,z)).T)
line2.append(np.array([[tt,tt],[z[0],z[-1]]]).T)
LC1 = collections.LineCollection(lines,colors=color,linewidths=1.5)
LC2 = collections.LineCollection(line2,colors='k',linestyles='dashed') # Zero axis
ax=plt.gca()
ax.add_collection(LC1)
ax.add_collection(LC2)
ax.set_ylim((z.min(),z.max()))
ax.xaxis.set_major_formatter(formatter)
if xlim==None:
xlim=(tsec[0]-scale/2,tsec[-1]+scale/2)
else:
xlim=othertime.SecondsSince(xlim)
ax.set_xlim(xlim)
plt.xticks(rotation=17)
###
# Add a scale bar
###
# Compute the scale bar size in dimensionless units
if not scalebar==None:
xscale = scalebar*scale/(xlim[-1]-xlim[0])
x0 = 0.1
y0 = 0.8
dy = 0.02
ax.add_line(Line2D([x0,x0+xscale],[y0,y0],linewidth=0.5,color='k',transform=ax.transAxes))
#Little caps
ax.add_line(Line2D([x0,x0],[y0-dy,y0+dy],linewidth=0.5,color='k',transform=ax.transAxes))
ax.add_line(Line2D([x0+xscale,x0+xscale],[y0-dy,y0+dy],linewidth=0.5,color='k',transform=ax.transAxes))
plt.text(x0,y0+0.05,'Scale %3.1f %s'%(scalebar,units),\
transform=ax.transAxes)
return ax
def monthlyhist(t,y,ylim=0.1,xlabel='',ylabel='',title='',**kwargs):
"""
Plots 12 histograms on a 6x2 matrix of variable, y, grouped by calendar month
Inputs:
y - vector of data
t - vector of datetime objects
kwargs - keyword arguments for numpy.hist
"""
month = othertime.getMonth(t)
fig=plt.gcf()
for m in range(1,13):
# Find the values
ind = np.argwhere(month==m)
data=y[ind]
ax=plt.subplot(6,2,m)
if len(data)>0:
plt.hist(data,**kwargs)
mon=datetime.strftime(datetime(1900,m,1),'%B')
plt.title(mon)
plt.ylim([0,ylim])
if m not in (11,12):
ax.set_xticklabels([])
else:
plt.xlabel(xlabel)
if m not in (1,3,5,7,9,11):
ax.set_yticklabels([])
else:
plt.ylabel(ylabel)
#Calc some stats
textstr = 'Mean: %6.1f\nStd. Dev.: %6.1f\n'%(np.mean(data),np.std(data))
plt.text(0.5,0.5,textstr,transform=ax.transAxes)
# plot a title
plt.figtext(0.5,0.95,title,fontsize=14,horizontalalignment='center')
return fig
def window_index(serieslength,windowsize,overlap):
"""
Determines the indices for start and end points of a time series window
Inputs:
serieslength - length of the vector [int]
windowsize - length of the window [int]
overlap - number of overlap points [int]
Returns: pt1,pt2 the start and end indices of each window
"""
p1=0
p2=p1 + windowsize
pt1=[p1]
pt2=[p2]
while p2 < serieslength:
p1 = p2 - overlap
p2 = min((p1 + windowsize, serieslength))
pt1.append(p1)
pt2.append(p2)
return pt1, pt2
def axcolorbar(cbobj,pos=[0.7, 0.8, 0.2, 0.04],ax=None,fig=None,orientation='horizontal',**kwargs):
"""
Inserts a colorbar with a position relative to an axes and not a figure
Inputs:
cbobj - plot object for colorbar
pos - position vector [x0, y0, width, height] in dimensionless coordinates
ax - axes to insert colobar
figure - figure
**kwargs - arguments for plt.colorbar
Returns a colorbar object
Derived from this post:
http://stackoverflow.com/questions/22413211/cant-fix-position-of-colorbar-in-image-with-multiple-subplots
"""
if fig is None:
fig=plt.gcf()
if ax is None:
ax=plt.gca()
fig.tight_layout() # You call fig.tight_layout BEFORE creating the colorbar
# You input the POSITION AND DIMENSIONS RELATIVE TO THE AXES
x0, y0, width, height = pos
# and transform them after to get the ABSOLUTE POSITION AND DIMENSIONS
Bbox = transforms.Bbox.from_bounds(x0, y0, width, height)
trans = ax.transAxes + fig.transFigure.inverted()
l, b, w, h = transforms.TransformedBbox(Bbox, trans).bounds
# Now just create the axes and the colorbar
cbaxes = fig.add_axes([l, b, w, h])
cbar = plt.colorbar(cbobj, cax=cbaxes,orientation=orientation, **kwargs)
cbar.ax.tick_params(labelsize=9)
return cbar
| nilq/baby-python | python |
import win32gui
from src.services.window_managers.base_window_manager import WindowTitleManager
class WindowsWindowManager(WindowTitleManager):
def fetch_window_title(self) -> str:
window_in_focus = win32gui.GetForegroundWindow()
return win32gui.GetWindowText(window_in_focus)
| nilq/baby-python | python |
import requests
from bs4 import BeautifulSoup
LIMIT = 50
URL = f"https://www.indeed.com/jobs?q=python&limit={LIMIT}"
def _check_has_first_page_end() -> bool:
"""Check if the first page has a link to the last page"""
first_response = requests.get(URL)
soup = BeautifulSoup(first_response.text, "html.parser")
pagination = soup.find("div", class_="pagination")
nav_items = pagination.find_all("li")
item_labels = [item.findChild()["aria-label"] for item in nav_items]
# If 'Next' is not in nav, the first page has the last page link.
return "Next" not in item_labels
def _extract_last_page_num() -> int:
"""Get the last page number"""
is_last_page = _check_has_first_page_end()
item_labels = []
page_index = 0
while not is_last_page:
response = requests.get(URL + f"&start={page_index * LIMIT}")
soup = BeautifulSoup(response.text, "html.parser")
pagination = soup.find("div", class_="pagination")
nav_items = pagination.find_all("li")
item_labels = [item.findChild()["aria-label"] for item in nav_items]
is_last_page = False if "Next" in item_labels else True
page_index += 1
return int(item_labels[-1])
def _format_location(location: str) -> str:
"""Get a location with spaces around plus and template"""
return location.replace("+", " + ").replace("•", " • ")
def _extract_job(html):
"""
Get a dictionary of a job's information
:param html: Tag
:return: dict[str, str]
"""
title = html.find("span", title=True).string
company = html.find("span", class_="companyName").string
location = _format_location(html.find("div", class_="companyLocation").text)
job_id = html.parent["data-jk"]
return {
"title": title,
"company": company,
"location": location,
"link": f"https://www.indeed.com/viewjob?jk={job_id}&tk=1fg49gh9apiab801&from=serp&vjs=3",
}
def _extract_jobs(last_page_num: int):
"""
Get a list of job info's dictionaries
:return: list[dict[str, str]]
"""
jobs = []
for i in range(last_page_num):
print(f"Scraping Indeed's page {i}...")
response = requests.get(f"{URL}&start={i * LIMIT}")
soup = BeautifulSoup(response.text, "html.parser")
job_containers = soup.find_all("div", class_="slider_container")
for job_container in job_containers:
jobs.append(_extract_job(job_container))
return jobs
def get_jobs():
"""
Extract jobs until the last page
:return: list[dict[str, str]]
"""
last_page_num = _extract_last_page_num()
jobs = _extract_jobs(last_page_num)
return jobs
| nilq/baby-python | python |
from django.contrib import admin
from django.urls import include, path
from accounts.author.api import (
ForgetPasswordView,
LoginAuthorAPIView,
RegisterAuthorView,
)
from accounts.editor.api import (
ForgetEditorPasswordView,
LoginEditorAPIView,
RegisterEditorView,
)
from accounts.reviewer.api import (
ForgetReviewerPasswordView,
LoginReviewerAPIView,
RegisterReviewerView,
)
from accounts.views import UpdateProfileApiView, UserDetailApiView
urlpatterns = [
path("register_author/", RegisterAuthorView.as_view(), name="register_author"),
path("login_author/", LoginAuthorAPIView.as_view(), name="login_author"),
path("forget-password/", ForgetPasswordView.as_view(), name="forget-password"),
# ------------------------------------------------------------------------------
path("register_editor/", RegisterEditorView.as_view(), name="register_editor"),
path("login_editor/", LoginEditorAPIView.as_view(), name="login_editor"),
path(
"forget-editor-password/",
ForgetEditorPasswordView.as_view(),
name="forget-editor-password",
),
# ------------------------------------------------------------------------------
path(
"register_reviewer/", RegisterReviewerView.as_view(), name="register_reviewer"
),
path("login_reviewer/", LoginReviewerAPIView.as_view(), name="login_reviewer"),
path(
"forget-reviewer-password/",
ForgetReviewerPasswordView.as_view(),
name="forget-reviewer-password",
),
path("update-profile/", UpdateProfileApiView.as_view(), name="update_profile"),
path("user-detail/", UserDetailApiView.as_view(), name="user_detail"),
]
| nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Useful functions for Counter manipulation.
"""
from collections import Counter
def scale(cntr, factor):
cntr_ = Counter()
for key, value in cntr.items():
cntr_[key] = value * factor
return cntr_
def normalize(cntr):
return scale(cntr, 1./sum(cntr.values()))
def equals(cntr, cntr_):
keys = set(cntr.keys()).union(set(cntr_.keys()))
for key in keys:
if key not in cntr or key not in cntr_:
return False
elif cntr[key] != cntr_[key]:
return False
return True
def fequals(cntr, cntr_, eps=1e-5):
keys = set(cntr.keys()).union(set(cntr_.keys()))
for key in keys:
if key not in cntr or key not in cntr_:
return False
elif abs(cntr[key] - cntr_[key]) > eps:
return False
return True
def test_equals():
assert equals(Counter([1,1,3,4]),Counter([1,3,1,4]))
assert not equals(Counter([1,1,3,4]),Counter([1,3,3,4]))
| nilq/baby-python | python |
# Copyright 2017-2018 The Open SoC Debug Project
#
# 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.
from setuptools import setup
from setuptools.extension import Extension
import os
import sys
import subprocess
if '--use-cython' in sys.argv:
USE_CYTHON = True
sys.argv.remove('--use-cython')
else:
USE_CYTHON = False
ext = '.pyx' if USE_CYTHON else '.c'
def pkgconfig(*packages, **kw):
config = kw.setdefault('config', {})
optional_args = kw.setdefault('optional', '')
flag_map = {'include_dirs': ['--cflags-only-I', 2],
'library_dirs': ['--libs-only-L', 2],
'libraries': ['--libs-only-l', 2],
'extra_compile_args': ['--cflags-only-other', 0],
'extra_link_args': ['--libs-only-other', 0],
}
for package in packages:
for distutils_key, (pkg_option, n) in flag_map.items():
try:
cmd = ['pkg-config', optional_args, pkg_option, package]
items = subprocess.check_output(cmd).decode('utf8').split()
config.setdefault(distutils_key, []).extend([i[n:] for i in items])
except subprocess.CalledProcessError:
return config
return config
extensions = [
Extension('osd',
['src/osd'+ext],
**pkgconfig('osd', 'libglip'))
]
if USE_CYTHON:
from Cython.Build import cythonize
extensions = cythonize(extensions,
compiler_directives={'language_level': 3,
'embedsignature': True})
with open("README.md", "r", encoding='utf-8') as readme:
long_description = readme.read()
version_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
"src/version.py")
setup(
name = "opensocdebug",
ext_modules = extensions,
use_scm_version = {
"root": "../..",
"relative_to": __file__,
"write_to": version_file,
},
author = "Philipp Wagner",
author_email = "mail@philipp-wagner.com",
description = ("Open SoC Debug is a way to interact with and obtain "
"information from a System-on-Chip (SoC)."),
long_description = long_description,
url = "http://www.opensocdebug.org",
license = 'Apache License, Version 2.0',
classifiers = [
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"Topic :: Software Development :: Debuggers",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
"License :: OSI Approved :: Apache Software License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Cython",
],
setup_requires = [
'setuptools_scm',
'pytest-runner',
],
tests_require = [
'pytest',
],
)
| nilq/baby-python | python |
from __future__ import absolute_import
import os.path
import sys
import threading
import typing
import attr
from ddtrace.internal import compat
from ddtrace.internal import nogevent
from ddtrace.internal.utils import attr as attr_utils
from ddtrace.internal.utils import formats
from ddtrace.profiling import collector
from ddtrace.profiling import event
from ddtrace.profiling.collector import _task
from ddtrace.profiling.collector import _threading
from ddtrace.profiling.collector import _traceback
from ddtrace.vendor import wrapt
@event.event_class
class LockEventBase(event.StackBasedEvent):
"""Base Lock event."""
lock_name = attr.ib(default="<unknown lock name>", type=str)
sampling_pct = attr.ib(default=0, type=int)
@event.event_class
class LockAcquireEvent(LockEventBase):
"""A lock has been acquired."""
wait_time_ns = attr.ib(default=0, type=int)
@event.event_class
class LockReleaseEvent(LockEventBase):
"""A lock has been released."""
locked_for_ns = attr.ib(default=0, type=int)
def _current_thread():
# type: (...) -> typing.Tuple[int, str]
thread_id = nogevent.thread_get_ident()
return thread_id, _threading.get_thread_name(thread_id)
# We need to know if wrapt is compiled in C or not. If it's not using the C module, then the wrappers function will
# appear in the stack trace and we need to hide it.
if os.environ.get("WRAPT_DISABLE_EXTENSIONS"):
WRAPT_C_EXT = False
else:
try:
import ddtrace.vendor.wrapt._wrappers as _w # noqa: F401
except ImportError:
WRAPT_C_EXT = False
else:
WRAPT_C_EXT = True
del _w
class _ProfiledLock(wrapt.ObjectProxy):
def __init__(self, wrapped, recorder, tracer, max_nframes, capture_sampler, endpoint_collection_enabled):
wrapt.ObjectProxy.__init__(self, wrapped)
self._self_recorder = recorder
self._self_tracer = tracer
self._self_max_nframes = max_nframes
self._self_capture_sampler = capture_sampler
self._self_endpoint_collection_enabled = endpoint_collection_enabled
frame = sys._getframe(2 if WRAPT_C_EXT else 3)
code = frame.f_code
self._self_name = "%s:%d" % (os.path.basename(code.co_filename), frame.f_lineno)
def acquire(self, *args, **kwargs):
if not self._self_capture_sampler.capture():
return self.__wrapped__.acquire(*args, **kwargs)
start = compat.monotonic_ns()
try:
return self.__wrapped__.acquire(*args, **kwargs)
finally:
try:
end = self._self_acquired_at = compat.monotonic_ns()
thread_id, thread_name = _current_thread()
task_id, task_name, task_frame = _task.get_task(thread_id)
if task_frame is None:
frame = sys._getframe(1)
else:
frame = task_frame
frames, nframes = _traceback.pyframe_to_frames(frame, self._self_max_nframes)
event = LockAcquireEvent(
lock_name=self._self_name,
frames=frames,
nframes=nframes,
thread_id=thread_id,
thread_name=thread_name,
task_id=task_id,
task_name=task_name,
wait_time_ns=end - start,
sampling_pct=self._self_capture_sampler.capture_pct,
)
if self._self_tracer is not None:
event.set_trace_info(self._self_tracer.current_span(), self._self_endpoint_collection_enabled)
self._self_recorder.push_event(event)
except Exception:
pass
def release(
self,
*args, # type: typing.Any
**kwargs # type: typing.Any
):
# type: (...) -> None
try:
return self.__wrapped__.release(*args, **kwargs)
finally:
try:
if hasattr(self, "_self_acquired_at"):
try:
end = compat.monotonic_ns()
thread_id, thread_name = _current_thread()
task_id, task_name, task_frame = _task.get_task(thread_id)
if task_frame is None:
frame = sys._getframe(1)
else:
frame = task_frame
frames, nframes = _traceback.pyframe_to_frames(frame, self._self_max_nframes)
event = LockReleaseEvent( # type: ignore[call-arg]
lock_name=self._self_name,
frames=frames,
nframes=nframes,
thread_id=thread_id,
thread_name=thread_name,
task_id=task_id,
task_name=task_name,
locked_for_ns=end - self._self_acquired_at,
sampling_pct=self._self_capture_sampler.capture_pct,
)
if self._self_tracer is not None:
event.set_trace_info(
self._self_tracer.current_span(), self._self_endpoint_collection_enabled
)
self._self_recorder.push_event(event)
finally:
del self._self_acquired_at
except Exception:
pass
acquire_lock = acquire
class FunctionWrapper(wrapt.FunctionWrapper):
# Override the __get__ method: whatever happens, _allocate_lock is always considered by Python like a "static"
# method, even when used as a class attribute. Python never tried to "bind" it to a method, because it sees it is a
# builtin function. Override default wrapt behavior here that tries to detect bound method.
def __get__(self, instance, owner=None):
return self
@attr.s
class LockCollector(collector.CaptureSamplerCollector):
"""Record lock usage."""
nframes = attr.ib(factory=attr_utils.from_env("DD_PROFILING_MAX_FRAMES", 64, int))
endpoint_collection_enabled = attr.ib(
factory=attr_utils.from_env("DD_PROFILING_ENDPOINT_COLLECTION_ENABLED", True, formats.asbool)
)
tracer = attr.ib(default=None)
def _start_service(self): # type: ignore[override]
# type: (...) -> None
"""Start collecting `threading.Lock` usage."""
self.patch()
super(LockCollector, self)._start_service()
def _stop_service(self): # type: ignore[override]
# type: (...) -> None
"""Stop collecting `threading.Lock` usage."""
super(LockCollector, self)._stop_service()
self.unpatch()
def patch(self):
# type: (...) -> None
"""Patch the threading module for tracking lock allocation."""
# We only patch the lock from the `threading` module.
# Nobody should use locks from `_thread`; if they do so, then it's deliberate and we don't profile.
self.original = threading.Lock
def _allocate_lock(wrapped, instance, args, kwargs):
lock = wrapped(*args, **kwargs)
return _ProfiledLock(
lock, self.recorder, self.tracer, self.nframes, self._capture_sampler, self.endpoint_collection_enabled
)
threading.Lock = FunctionWrapper(self.original, _allocate_lock) # type: ignore[misc]
def unpatch(self):
# type: (...) -> None
"""Unpatch the threading module for tracking lock allocation."""
threading.Lock = self.original # type: ignore[misc]
| nilq/baby-python | python |
"""
Added dag name column to executions
Revision ID: e937a5234ce4
Revises: a472b5ad50b7
Create Date: 2021-02-25 12:14:38.197522
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "e937a5234ce4"
down_revision = "a472b5ad50b7"
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"executions", sa.Column("dag_name", sa.String(length=256), nullable=True)
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("executions", "dag_name")
# ### end Alembic commands ###
| nilq/baby-python | python |
# Generated by Django 3.1 on 2020-08-05 10:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('website', '0010_auto_20200804_1433'),
]
operations = [
migrations.AlterModelOptions(
name='userplugin',
options={'ordering': ('plugin__name',)},
),
]
| nilq/baby-python | python |
from pathlib import Path
def findFullFilename(path, pattern):
filenameGenerator = Path(path).glob(pattern)
firstPath = next(filenameGenerator, None)
if firstPath is None:
return None
return firstPath.name
def findPywFilenameHere(pattern):
return findFullFilename(".", f"{pattern}*.pyw") | nilq/baby-python | python |
from heuristicSearch.planners.astar import Astar
from heuristicSearch.envs.env import GridEnvironment
from heuristicSearch.graph.node import Node
from heuristicSearch.envs.occupancy_grid import OccupancyGrid
from heuristicSearch.utils.visualizer import ImageVisualizer
from heuristicSearch.utils.utils import *
import matplotlib.pyplot as plt
import cv2 as cv
import sys
import pickle
"""
Note: Numpy array is accessed as (r, c) while a point is (x, y). The
code follows (r, c) convention everywhere. Hence, be careful whenever
using a point with opencv.
"""
def main():
"""
The main function that sets up the environment and calls the planner.
Each planning run has three components:
* Environment
* Graph
* Planner
The Environment class contains details about the specific planning problem,
eg: a 2D map for 2D planning. Its primary role is to implement a
`getChildren` method that returns the successors of each node. This helps
in building the graph implicitly.
Each vertex in the graph is an instance of `Node` class. It stores details
specific to the node.
An Astar instance runs on the graph so created.
"""
folder = sys.argv[1]
image = folder + "/image.png"
start_goal = folder + "/start_goal.pkl"
startPoint, goalPoint = pickle.load( open(start_goal, "rb") )
# Build the planning environment.
occGrid = OccupancyGrid()
occMap = occGrid.getMapFromImage(image)
print(occMap.shape)
gridEnv = GridEnvironment(occMap, occMap.shape[0], occMap.shape[1])
gridEnv.setHeuristicType(0)
# For visualization.
viz = ImageVisualizer(occMap, True)
## To take input by clicking.
#startPoint = (100, 20)
#goalPoint = (201, 200)
#print("Click start point")
#startPoint = inputClickedPoint(occMap)
#print("Click end point")
#goalPoint = inputClickedPoint(occMap)
print(startPoint, goalPoint)
assert(gridEnv.isValidPoint(startPoint))
assert(gridEnv.isValidPoint(goalPoint))
startNode = Node(gridEnv.getIdFromPoint(startPoint))
startNode.setParent(None)
goalNode = Node(gridEnv.getIdFromPoint(goalPoint))
gridEnv.addNode(goalNode)
# Choose your planner.
planner = Astar(gridEnv, inflation=1)
# Plan!
planFound = planner.plan(startNode, goalNode, viz=viz)
path = []
if planFound:
print("Planning successful")
# Retrieve the path.
currNode = gridEnv.graph[goalNode.getNodeId()]
while(currNode.getNodeId() != startNode.getNodeId()):
path.append(currNode)
currNode = currNode.getParent()
# Reverse the list.
path = path[::-1]
print("Cost of solution is %f"%path[-1].g)
pathPoints = []
for node in path:
pathPoints.append(gridEnv.getPointFromId(node.getNodeId()))
viz.joinPointsInOrder(pathPoints, thickness=2)
viz.displayImage()
main()
| nilq/baby-python | python |
#! /usr/bin/env python
from pathlib import Path
import re
import uxn
import sys
token_prog = re.compile(r"\s*(\)|\S+)")
line_comment_prog = re.compile(r".*")
string_prog = re.compile(r".*?(?<!\\)\"")
fixed_prog = re.compile(r"(-|\+)?\d+\.\d+")
prefix_chars = '%:.;,@&|$#~\'"'
def eprint(s):
sys.stderr.write(f"{s}\n")
class CompilationUnit():
def __init__(self):
self.macros = {}
self.variables = []
self.body = None
self.rst = []
self.current_word = None
self.include_stdlib = True
self.stdlib_included = False
self.pending_token = None
self.prev_word = None
self.sep = ""
self.depth = 0
def compile_file(self, filename):
old_body = self.body
old_rst = self.rst
self.body = read_file(filename)
self.sep = ""
self.depth = 0
while True:
w = self.next_word(keep_newline=True)
if not w:
break
self.compile(w)
self.body = old_body
self.rst = old_rst
print()
def next_word(self, keep_newline=False):
if self.pending_token:
w = self.pending_token
self.pending_token = None
return w
m = token_prog.match(self.body)
if not m:
return None
self.body = self.body[m.end():]
w = m.group(1)
if keep_newline and '\n' in m.group():
self.pending_token = w
return '\n'
return w
def print(self, w):
if self.prev_word == '\n' and w == '\n':
pass
elif w == '\n':
indent = " " * self.depth
print()
self.sep = indent
else:
print(self.sep + w, end="")
self.sep = " "
self.prev_word = w
def compile_stdlib(self):
self.stdlib_included = True
print()
self.compile_file(self.forth_path)
def compile(self, w):
if w == '\n':
self.print(w)
return
if w == ':':
self.depth += 1
self.sep = ""
name = self.next_word()
if name == 'init':
self.print('|0100')
assert self.current_word == None
if self.current_word == 'init' and self.include_stdlib and self.stdlib_included == False:
self.current_word = name
self.compile_stdlib()
else:
self.current_word = name
self.print(f"@{name}")
elif w == ';':
self.depth -= 1
self.print('JMP2r\n')
if self.current_word == 'init':
raise ValueError('init must be closed with brk;')
elif w == 'brk;':
self.depth -= 1
self.print('BRK\n')
elif w == 'do':
self.depth += 1
loop_lbl = gensym('loop')
pred_lbl = gensym('pred')
self.rst.append(['do', loop_lbl, pred_lbl])
self.print('( do )')
self.print('SWP2 STH2 STH2')
self.print(f';&{pred_lbl} JMP2')
self.print(f'&{loop_lbl}')
elif w == 'loop' or w == '+loop':
header, loop_lbl, pred_lbl = self.rst[-1]
assert header == 'do'
if w == 'loop':
self.print('( loop )')
self.print('INC2r')
else:
self.print('( loop )')
self.print('STH2 ADD2r')
self.print(f'&{pred_lbl}')
self.print(f'GTH2kr STHr ;&{loop_lbl} JCN2')
self.print('POP2r POP2r')
self.rst.pop()
self.depth -= 1
elif w == 'if':
false_lbl = gensym('false')
end_lbl = gensym('end')
self.rst.append(['if', false_lbl, end_lbl])
self.print(f'( if ) #0000 EQU2 ,&{false_lbl} JCN')
self.depth += 1
elif w == 'else':
self.print('( else )')
header, false_lbl, end_lbl = self.rst[-1]
assert header == 'if'
self.rst[-1][0] = 'else'
self.print(f',&{end_lbl} JMP')
self.print(f'&{false_lbl}')
elif w == 'endif':
self.print('( endif )')
header, false_lbl, end_lbl = self.rst[-1]
if header == 'if':
self.print(f'&{false_lbl}')
elif header == 'else':
self.print(f'&{end_lbl}')
else:
assert False
self.rst.pop()
self.depth -= 1
elif w == 'begin':
self.depth += 1
begin_lbl = gensym('begin')
end_lbl = gensym('end-begin')
self.rst.append(['begin', begin_lbl, end_lbl])
self.print('( begin )')
self.print(f'&{begin_lbl}')
elif w == 'while':
header, begin_lbl, end_lbl = self.rst[-1]
assert header == 'begin'
self.print(f'( while ) #0000 EQU2 ;&{end_lbl} JCN2')
elif w == 'repeat':
header, begin_lbl, end_lbl = self.rst[-1]
assert header == 'begin'
self.print('( repeat )')
self.print(f';&{begin_lbl} JMP2')
self.print(f'&{end_lbl}')
self.rst.pop()
elif w == 'until':
header, begin_lbl, end_lbl = self.rst[-1]
assert header == 'begin'
self.print(f'( until ) #0000 EQU2 ;&{begin_lbl} JCN2')
self.print(f'&{end_lbl}')
self.rst.pop()
self.depth -= 1
elif w == 'again':
header, begin_lbl, end_lbl = self.rst[-1]
assert header == 'begin'
self.print('( again )')
self.print(f';&{begin_lbl} JMP2')
self.print(f'&{end_lbl}')
self.rst.pop()
self.depth -= 1
elif w == 'leave':
header, begin_lbl, pred_lbl, end_lbl = self.rst[-1]
assert header == 'begin'
self.print(f'( leave ) ;&{end_lbl} JMP2')
elif w == 'tal':
self.read_tal()
elif w == 'incbin':
self.read_binary_file()
elif w == 'variable':
self.create_variable()
elif w == 'sprite-1bpp':
self.compile_sprite_1bpp()
elif w == '(':
self.read_comment()
elif w == '\\':
self.read_line_comment()
elif w[0] == '"':
self.read_string(w[1:])
elif w[0] == '%':
self.read_macro(w[1:])
elif w[0] == '~':
self.compile_file(w[1:])
elif w in self.macros:
body = self.macros[w]
for child in body:
self.compile(child)
elif is_uxntal(w):
self.print(f"{w}")
elif w in self.variables:
self.print(f';{w}')
else:
try:
if w[:2] == '0x':
n = int(w[2:], 16)
elif w[:2] == '0b':
n = int(w[2:], 2)
elif fixed_prog.match(w):
n = parse_fixed_point(w)
else:
n = int(w, 10)
if n < 0:
n += 0x10000
n &= 0xffff
self.print(f"#{n:04x}")
except ValueError:
self.print(f';{w} JSR2')
def read_tal(self):
#todo count depth for nested comments
w = self.next_word()
while w != 'endtal':
if w == '(':
self.read_comment()
else:
self.print(w)
w = self.next_word()
def read_binary_file(self):
filename = self.next_word()
with open(filename, 'rb', buffering=4) as f:
while True:
line = f.read(16)
if len(line) == 0:
break
tal = ' '.join(f"{c:02x}" for c in line)
self.print(tal)
def read_line_comment(self):
m = line_comment_prog.match(self.body)
if not m:
return None
self.body = self.body[m.end():]
comment = m.group().strip()
def read_comment(self):
depth = 1
body = ['(']
while True:
w = self.next_word()
body.append(w)
if w == '(':
depth += 1
elif w == ')':
depth -= 1
elif w == None:
break
if depth == 0:
break
s = ' '.join(body)
self.print(s)
def read_macro(self, name):
nw = self.next_word()
assert nw == '{'
nw = self.next_word()
body = []
while nw != '}':
body.append(nw)
nw = self.next_word()
if name in self.macros:
raise ValueError(f"Duplicate macro: {name}")
self.macros[name] = body
def create_variable(self):
name = self.next_word()
if name in self.variables:
raise ValueError(f"Duplicate variable: {name}")
if is_uxntal(name):
raise ValueError(f"Invalid varialbe name: {name}, it looks like uxntal.")
self.variables.append(name)
def compile_variables(self):
for name in self.variables:
self.print(f"@{name} $2")
def compile_sprite_1bpp(self):
for i in range(8):
w = self.next_word()
s = w
s = re.sub('\.', '0', s)
s = re.sub('[^0]', '1', s)
n = int(s, 2)
self.print(f"{n:02x}")
def read_string(self, w):
if w[-1] == '"':
s = w[:-1]
else:
m = string_prog.match(self.body)
if not m:
raise ValueError("failed to find end of string")
s = w + m.group()[:-1]
self.body = self.body[m.end():]
s = s.replace(r'\"', '"')
ss = ' 20 '.join('"' + elem for elem in s.split())
self.print(f"{ss} 00")
def read_file(filename):
with open(filename) as f:
return f.read()
counter = 0
def gensym(s):
global counter
name = f"gs-{s}-{counter}"
counter += 1
return name
def is_uxntal(w):
if uxn.is_op(w):
return True
elif w[0] in prefix_chars:
return len(w) != 1
elif w in ['{', '}', '[', ']']:
return True
else:
return False
def parse_fixed_point(s):
"""
Q11.4
binary:
0 000 0000 0000 0000
^ ^ ^ fractional part
| | integer part
|
| sign bit
"""
lhs, rhs = s.split('.')
i = int(lhs)
if i < 0:
i += 0b1_0000_0000_0000
i &= 0b1111_1111_1111
i <<= 4
eprint(f"{i}")
eprint(f"{i:x}")
eprint(f"{i:b}")
# -1.25
# 0100
a = 0b1111
b = a / 16
c = int(b * 255)
eprint(f"{a} {b} {c} {c:b}")
f = float('0.' + rhs) * 16
f = int(f) & 0b1111
n = i + f
return n
def main(filename):
script_dir = Path(__file__).resolve().parent
header_path = script_dir.joinpath('header.tal')
footer_path = script_dir.joinpath('footer.tal')
#print(script_dir)
#print(header_path)
#print(forth_path)
cu = CompilationUnit()
cu.forth_path = script_dir.joinpath('forth.fth')
cu.compile_file(header_path)
cu.compile_file(filename)
if cu.include_stdlib and cu.stdlib_included == False:
cu.compile_stdlib()
cu.compile_variables()
cu.compile_file(footer_path)
print()
if __name__ == '__main__':
main(sys.argv[1])
| nilq/baby-python | python |
# Python3 program for Painting Fence Algorithm
# optimised version
# Returns count of ways to color k posts
def countWays(n, k):
dp = [0] * (n + 1)
total = k
mod = 1000000007
dp[1] = k
dp[2] = k * k
for i in range(3,n+1):
dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])) % mod
return dp[n]
# Driver code
n = 3
k = 2
print(countWays(n, k)) | nilq/baby-python | python |
"""
Manipulate Excel workbooks.
"""
from datetime import datetime
import os
from openpyxl import Workbook
from openpyxl.styles import NamedStyle, Font, Border, Side, PatternFill
from trellominer.api import trello
from trellominer.config import yaml
class Excel(object):
def __init__(self):
self.config = yaml.read(os.getenv("TRELLO_CONFIG", default=os.path.join(os.path.expanduser('~'), ".trellominer.yaml")))
self.output_file = os.getenv("TRELLO_OUTPUT_FILE", default=self.config['api']['output_file_name'])
self.filename = os.path.join(os.path.expanduser('~'), "{0} {1}.xlsx".format(self.output_file, datetime.now().strftime("%Y-%m-%d")))
def filename(self):
return self.filename
def process_boards(self, boards):
"""Creates a series of worksheets in a workbook based on Trello board names."""
highlight = NamedStyle(name='highlight')
highlight.font = Font(bold=True, size=20)
tabletop = NamedStyle(name='tabletop')
tabletop.font = Font(bold=True, color='FFFFFF')
bd = Side(style='thin', color="000000", border_style='thin')
tabletop.border = Border(left=bd, right=bd, top=bd, bottom=bd)
tabletop.fill = PatternFill("solid", bgColor="333333")
wb = Workbook()
wb.add_named_style(highlight)
lookup = trello.Trello()
current_row = 6
# Dump the default worksheet from the document.
# TODO: (PS) Is there a better way to handle this?
for sheet in wb:
if "Sheet" in sheet.title:
wb.remove_sheet(sheet)
for board in boards:
if "Projects" in board['name']:
ws = wb.create_sheet(title="{0}".format(board['name']), index=0)
ws.sheet_properties.tabColor = "0000FF"
elif "Break Fix" in board['name']:
ws = wb.create_sheet(title="{0}".format(board['name']), index=1)
ws.sheet_properties.tabColor = "FF0000"
elif "Change Control" in board['name']:
ws = wb.create_sheet(title="{0}".format(board['name']), index=2)
ws.sheet_properties.tabColor = "228B22"
else:
ws = wb.create_sheet(title="{0}".format(board['name'][0:30]), index=None)
ws['A1'].style = 'highlight'
ws['A1'] = "{0}".format(board['name'])
ws['A2'] = "" # was going to contain board descriptions. Trello have deprecated these, just not from the API
ws['A3'] = "{0}".format(board['url'])
ws['A3'].style = 'Hyperlink'
ws['A4'] = ""
headings = ["Name", "Description", "Status", "Due Date", "Complete", "Perc", "Members"]
ws.append(headings)
header_row = ws[5]
for cell in header_row:
cell.style = tabletop
cards = lookup.cards(board['shortLink'])
# Apply some default column widths to each worksheet
ws.column_dimensions["A"].width = 40
ws.column_dimensions["B"].width = 100
ws.column_dimensions["C"].width = 10
ws.column_dimensions["D"].width = 22
ws.column_dimensions["G"].width = 45
for card in cards:
# TODO: Pretty slow to iterate like this. Improve.
listname = lookup.lists(card['idList'])
member_list = ""
for member in card['members']:
member_list += "{0},".format(member['fullName'])
member_list.replace(',', ', ')
ws["A{0}".format(current_row)] = card['name']
ws["A{0}".format(current_row)].style = 'Output'
ws["B{0}".format(current_row)] = card['desc']
ws["C{0}".format(current_row)] = listname['name']
if 'Conceptual' in listname['name']:
ws["C{0}".format(current_row)].style = 'Accent5'
elif 'Backlog' in listname['name']:
ws["C{0}".format(current_row)].style = 'Accent4'
elif 'In Progress' in listname['name']:
ws["C{0}".format(current_row)].style = 'Accent1'
elif 'Impeded' in listname['name']:
ws["C{0}".format(current_row)].style = 'Bad'
elif 'Completed' in listname['name']:
ws["C{0}".format(current_row)].style = 'Good'
elif 'Stopped' in listname['name']:
ws["C{0}".format(current_row)].style = 'Accent2'
elif 'Planned' in listname['name']:
ws["C{0}".format(current_row)].style = 'Accent4'
elif 'Successful' in listname['name']:
ws["C{0}".format(current_row)].style = 'Good'
elif 'Failed' in listname['name']:
ws["C{0}".format(current_row)].style = 'Bad'
elif 'Cancelled' in listname['name']:
ws["C{0}".format(current_row)].style = 'Neutral'
elif 'Course Development' in listname['name']:
ws["C{0}".format(current_row)].style = 'Neutral'
elif 'On Training' in listname['name']:
ws["C{0}".format(current_row)].style = 'Accent5'
elif 'Once Off Scheduled' in listname['name']:
ws["C{0}".format(current_row)].style = 'Accent5'
else:
ws["C{0}".format(current_row)] = listname['name']
ws["D{0}".format(current_row)] = card['due']
ws["E{0}".format(current_row)] = card['dueComplete']
# ws["F{0}".format(current_row)] = card['closed']
tasks = 0
complete = 0
checklists = lookup.checklists(card['shortLink'])
for checklist in checklists:
for cl in checklist['checkItems']:
tasks += 1
if cl['state'] == 'complete':
complete += 1
if tasks > 0:
perc = 100 * complete / tasks
else:
perc = 0
ws["F{0}".format(current_row)] = "{0}%".format(int(perc))
if perc < 25:
ws["F{0}".format(current_row)].style = 'Bad'
elif perc < 100:
ws["F{0}".format(current_row)].style = 'Neutral'
else:
ws["F{0}".format(current_row)].style = 'Good'
ws["G{0}".format(current_row)] = member_list[:-1]
current_row += 1
current_row = 6
wb.save(self.filename)
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
This is the Keras implementation for the GermEval-2014 dataset on NER
This model uses the idea from Collobert et al., Natural Language Processing almost from Scratch.
It implements the window approach with an isolated tag criterion.
For more details on the task see:
https://www.ukp.tu-darmstadt.de/fileadmin/user_upload/Group_UKP/publikationen/2014/2014_GermEval_Nested_Named_Entity_Recognition_with_Neural_Networks.pdf
@author: Nils Reimers
Code was written & tested with:
- Python 2.7
- Theano 0.8.x
- Keras 1.0.x
"""
import numpy as np
import theano
import theano.tensor as T
import time
import gzip
import GermEvalReader
import BIOF1Validation
import keras
from keras.models import Sequential
from keras.layers.core import Dense, Flatten, Merge
from keras.optimizers import SGD
from keras.utils import np_utils
from keras.layers.embeddings import Embedding
windowSize = 2 # 2 to the left, 2 to the right
numHiddenUnits = 100
trainFile = 'data/NER-de-train.tsv'
devFile = 'data/NER-de-dev.tsv'
testFile = 'data/NER-de-test.tsv'
print "NER with Keras, only token, window size %d, float: %s" % (windowSize, theano.config.floatX)
#####################
#
# Read in the vocab
#
#####################
print "Read in the vocab"
vocabPath = 'embeddings/GermEval.vocab.gz'
word2Idx = {} #Maps a word to the index in the embeddings matrix
embeddings = [] #Embeddings matrix
with gzip.open(vocabPath, 'r') as fIn:
idx = 0
for line in fIn:
split = line.strip().split(' ')
embeddings.append(np.array([float(num) for num in split[1:]]))
word2Idx[split[0]] = idx
idx += 1
embeddings = np.asarray(embeddings, dtype='float32')
embedding_size = embeddings.shape[1]
# Create a mapping for our labels
label2Idx = {'O':0}
idx = 1
for bioTag in ['B-', 'I-']:
for nerClass in ['PER', 'LOC', 'ORG', 'OTH']:
for subtype in ['', 'deriv', 'part']:
label2Idx[bioTag+nerClass+subtype] = idx
idx += 1
#Inverse label mapping
idx2Label = {v: k for k, v in label2Idx.items()}
#Casing matrix
caseLookup = {'numeric': 0, 'allLower':1, 'allUpper':2, 'initialUpper':3, 'other':4, 'mainly_numeric':5, 'contains_digit': 6, 'PADDING':7}
caseMatrix = np.identity(len(caseLookup), dtype=theano.config.floatX)
# Read in data
print "Read in data and create matrices"
train_sentences = GermEvalReader.readFile(trainFile)
dev_sentences = GermEvalReader.readFile(devFile)
test_sentences = GermEvalReader.readFile(testFile)
# Create numpy arrays
train_x, train_case_x, train_y = GermEvalReader.createNumpyArrayWithCasing(train_sentences, windowSize, word2Idx, label2Idx, caseLookup)
dev_x, dev_case_x, dev_y = GermEvalReader.createNumpyArrayWithCasing(dev_sentences, windowSize, word2Idx, label2Idx, caseLookup)
test_x, test_case_x, test_y = GermEvalReader.createNumpyArrayWithCasing(test_sentences, windowSize, word2Idx, label2Idx, caseLookup)
#####################################
#
# Create the Network
#
#####################################
# Create the train and predict_labels function
n_in = 2*windowSize+1
n_hidden = numHiddenUnits
n_out = len(label2Idx)
number_of_epochs = 10
minibatch_size = 35
embedding_size = embeddings.shape[1]
dim_case = 6
x = T.imatrix('x') # the data, one word+context per row
y = T.ivector('y') # the labels are presented as 1D vector of [int] labels
print "Embeddings shape",embeddings.shape
words = Sequential()
words.add(Embedding(output_dim=embeddings.shape[1], input_dim=embeddings.shape[0], input_length=n_in, weights=[embeddings]))
words.layers[0].trainable_weights = [] #Fixed Embedding layer
words.add(Flatten())
casing = Sequential()
casing.add(Embedding(output_dim=caseMatrix.shape[1], input_dim=caseMatrix.shape[0], input_length=n_in, weights=[caseMatrix]))
casing.layers[0].trainable_weights = [] #Fixed Embedding layer
casing.add(Flatten())
model = Sequential()
model.add(Merge([words, casing], mode='concat'))
model.add(Dense(output_dim=n_hidden, input_dim=n_in*embedding_size, init='uniform', activation='tanh'))
model.add(Dense(output_dim=n_out, init='uniform', activation='softmax'))
# Use Adam optimizer
model.compile(loss='categorical_crossentropy', optimizer='adam')
print train_x.shape[0], ' train samples'
print train_x.shape[1], ' train dimension'
print test_x.shape[0], ' test samples'
# Train_y is a 1-dimensional vector containing the index of the label
# With np_utils.to_categorical we map it to a 1 hot matrix
train_y_cat = np_utils.to_categorical(train_y, n_out)
##################################
#
# Training of the Network
#
##################################
number_of_epochs = 10
minibatch_size = 64
print "%d epochs" % number_of_epochs
print "%d mini batches" % (len(train_x)/minibatch_size)
for epoch in xrange(number_of_epochs):
start_time = time.time()
#Train for 1 epoch
model.fit([train_x, train_case_x], train_y_cat, nb_epoch=1, batch_size=minibatch_size, verbose=False, shuffle=True)
print "%.2f sec for training" % (time.time() - start_time)
# Compute precision, recall, F1 on dev & test data
pre_dev, rec_dev, f1_dev = BIOF1Validation.compute_f1(model.predict_classes([dev_x, dev_case_x], verbose=0), dev_y, idx2Label)
pre_test, rec_test, f1_test = BIOF1Validation.compute_f1(model.predict_classes([test_x, test_case_x], verbose=0), test_y, idx2Label)
print "%d epoch: F1 on dev: %f, F1 on test: %f" % (epoch+1, f1_dev, f1_test)
| nilq/baby-python | python |
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
application = Cling(get_wsgi_application())
| nilq/baby-python | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: fabric_next.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='fabric_next.proto',
package='protos',
syntax='proto3',
serialized_pb=_b('\n\x11\x66\x61\x62ric_next.proto\x12\x06protos\x1a\x1fgoogle/protobuf/timestamp.proto\"@\n\x08\x45nvelope\x12\x11\n\tsignature\x18\x01 \x01(\x0c\x12!\n\x07message\x18\x02 \x01(\x0b\x32\x10.protos.Message2\"\x90\x02\n\x08Message2\x12#\n\x04type\x18\x01 \x01(\x0e\x32\x15.protos.Message2.Type\x12\x0f\n\x07version\x18\x02 \x01(\x05\x12-\n\ttimestamp\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07payload\x18\x04 \x01(\x0c\"\x8d\x01\n\x04Type\x12\r\n\tUNDEFINED\x10\x00\x12\r\n\tDISCOVERY\x10\x01\x12\x08\n\x04SYNC\x10\x02\x12\x0c\n\x08PROPOSAL\x10\x03\x12\x10\n\x0cPROPOSAL_SET\x10\x04\x12\x13\n\x0fPROPOSAL_RESULT\x10\x05\x12\x17\n\x13PROPOSAL_SET_RESULT\x10\x06\x12\x0f\n\x0bTRANSACTION\x10\x07\"r\n\x08Proposal\x12#\n\x04type\x18\x01 \x01(\x0e\x32\x15.protos.Proposal.Type\x12\n\n\x02id\x18\x02 \x01(\t\x12\x0f\n\x07payload\x18\x03 \x01(\x0c\"$\n\x04Type\x12\r\n\tUNDEFINED\x10\x00\x12\r\n\tCHAINCODE\x10\x01\"=\n\tResponse2\x12\x0e\n\x06status\x18\x01 \x01(\x05\x12\x0f\n\x07message\x18\x02 \x01(\t\x12\x0f\n\x07payload\x18\x03 \x01(\x0c\"\x1d\n\x0fSystemChaincode\x12\n\n\x02id\x18\x01 \x01(\t\"\x96\x01\n\x06\x41\x63tion\x12\x14\n\x0cproposalHash\x18\x01 \x01(\x0c\x12\x18\n\x10simulationResult\x18\x02 \x01(\x0c\x12\x0e\n\x06\x65vents\x18\x03 \x03(\x0c\x12%\n\x04\x65scc\x18\x04 \x01(\x0b\x32\x17.protos.SystemChaincode\x12%\n\x04vscc\x18\x05 \x01(\x0b\x32\x17.protos.SystemChaincode\" \n\x0b\x45ndorsement\x12\x11\n\tsignature\x18\x01 \x01(\x0c\"v\n\x10ProposalResponse\x12#\n\x08response\x18\x01 \x01(\x0b\x32\x11.protos.Response2\x12\x13\n\x0b\x61\x63tionBytes\x18\x02 \x01(\x0c\x12(\n\x0b\x65ndorsement\x18\x03 \x01(\x0b\x32\x13.protos.Endorsement\"g\n\x0e\x45ndorsedAction\x12\x13\n\x0b\x61\x63tionBytes\x18\x01 \x01(\x0c\x12)\n\x0c\x65ndorsements\x18\x02 \x03(\x0b\x32\x13.protos.Endorsement\x12\x15\n\rproposalBytes\x18\x03 \x01(\x0c\"?\n\x0cTransaction2\x12/\n\x0f\x65ndorsedActions\x18\x01 \x03(\x0b\x32\x16.protos.EndorsedAction2K\n\x08\x45ndorser\x12?\n\x0fProcessProposal\x12\x10.protos.Proposal\x1a\x18.protos.ProposalResponse\"\x00\x62\x06proto3')
,
dependencies=[google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,])
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_MESSAGE2_TYPE = _descriptor.EnumDescriptor(
name='Type',
full_name='protos.Message2.Type',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='UNDEFINED', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='DISCOVERY', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SYNC', index=2, number=2,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='PROPOSAL', index=3, number=3,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='PROPOSAL_SET', index=4, number=4,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='PROPOSAL_RESULT', index=5, number=5,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='PROPOSAL_SET_RESULT', index=6, number=6,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TRANSACTION', index=7, number=7,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=260,
serialized_end=401,
)
_sym_db.RegisterEnumDescriptor(_MESSAGE2_TYPE)
_PROPOSAL_TYPE = _descriptor.EnumDescriptor(
name='Type',
full_name='protos.Proposal.Type',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='UNDEFINED', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CHAINCODE', index=1, number=1,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=481,
serialized_end=517,
)
_sym_db.RegisterEnumDescriptor(_PROPOSAL_TYPE)
_ENVELOPE = _descriptor.Descriptor(
name='Envelope',
full_name='protos.Envelope',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='signature', full_name='protos.Envelope.signature', index=0,
number=1, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='message', full_name='protos.Envelope.message', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=62,
serialized_end=126,
)
_MESSAGE2 = _descriptor.Descriptor(
name='Message2',
full_name='protos.Message2',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='type', full_name='protos.Message2.type', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='version', full_name='protos.Message2.version', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='timestamp', full_name='protos.Message2.timestamp', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='payload', full_name='protos.Message2.payload', index=3,
number=4, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_MESSAGE2_TYPE,
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=129,
serialized_end=401,
)
_PROPOSAL = _descriptor.Descriptor(
name='Proposal',
full_name='protos.Proposal',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='type', full_name='protos.Proposal.type', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='id', full_name='protos.Proposal.id', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='payload', full_name='protos.Proposal.payload', index=2,
number=3, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_PROPOSAL_TYPE,
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=403,
serialized_end=517,
)
_RESPONSE2 = _descriptor.Descriptor(
name='Response2',
full_name='protos.Response2',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='protos.Response2.status', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='message', full_name='protos.Response2.message', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='payload', full_name='protos.Response2.payload', index=2,
number=3, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=519,
serialized_end=580,
)
_SYSTEMCHAINCODE = _descriptor.Descriptor(
name='SystemChaincode',
full_name='protos.SystemChaincode',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='id', full_name='protos.SystemChaincode.id', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=582,
serialized_end=611,
)
_ACTION = _descriptor.Descriptor(
name='Action',
full_name='protos.Action',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='proposalHash', full_name='protos.Action.proposalHash', index=0,
number=1, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='simulationResult', full_name='protos.Action.simulationResult', index=1,
number=2, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='events', full_name='protos.Action.events', index=2,
number=3, type=12, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='escc', full_name='protos.Action.escc', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='vscc', full_name='protos.Action.vscc', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=614,
serialized_end=764,
)
_ENDORSEMENT = _descriptor.Descriptor(
name='Endorsement',
full_name='protos.Endorsement',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='signature', full_name='protos.Endorsement.signature', index=0,
number=1, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=766,
serialized_end=798,
)
_PROPOSALRESPONSE = _descriptor.Descriptor(
name='ProposalResponse',
full_name='protos.ProposalResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='response', full_name='protos.ProposalResponse.response', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='actionBytes', full_name='protos.ProposalResponse.actionBytes', index=1,
number=2, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='endorsement', full_name='protos.ProposalResponse.endorsement', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=800,
serialized_end=918,
)
_ENDORSEDACTION = _descriptor.Descriptor(
name='EndorsedAction',
full_name='protos.EndorsedAction',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='actionBytes', full_name='protos.EndorsedAction.actionBytes', index=0,
number=1, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='endorsements', full_name='protos.EndorsedAction.endorsements', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='proposalBytes', full_name='protos.EndorsedAction.proposalBytes', index=2,
number=3, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=920,
serialized_end=1023,
)
_TRANSACTION2 = _descriptor.Descriptor(
name='Transaction2',
full_name='protos.Transaction2',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='endorsedActions', full_name='protos.Transaction2.endorsedActions', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1025,
serialized_end=1088,
)
_ENVELOPE.fields_by_name['message'].message_type = _MESSAGE2
_MESSAGE2.fields_by_name['type'].enum_type = _MESSAGE2_TYPE
_MESSAGE2.fields_by_name['timestamp'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_MESSAGE2_TYPE.containing_type = _MESSAGE2
_PROPOSAL.fields_by_name['type'].enum_type = _PROPOSAL_TYPE
_PROPOSAL_TYPE.containing_type = _PROPOSAL
_ACTION.fields_by_name['escc'].message_type = _SYSTEMCHAINCODE
_ACTION.fields_by_name['vscc'].message_type = _SYSTEMCHAINCODE
_PROPOSALRESPONSE.fields_by_name['response'].message_type = _RESPONSE2
_PROPOSALRESPONSE.fields_by_name['endorsement'].message_type = _ENDORSEMENT
_ENDORSEDACTION.fields_by_name['endorsements'].message_type = _ENDORSEMENT
_TRANSACTION2.fields_by_name['endorsedActions'].message_type = _ENDORSEDACTION
DESCRIPTOR.message_types_by_name['Envelope'] = _ENVELOPE
DESCRIPTOR.message_types_by_name['Message2'] = _MESSAGE2
DESCRIPTOR.message_types_by_name['Proposal'] = _PROPOSAL
DESCRIPTOR.message_types_by_name['Response2'] = _RESPONSE2
DESCRIPTOR.message_types_by_name['SystemChaincode'] = _SYSTEMCHAINCODE
DESCRIPTOR.message_types_by_name['Action'] = _ACTION
DESCRIPTOR.message_types_by_name['Endorsement'] = _ENDORSEMENT
DESCRIPTOR.message_types_by_name['ProposalResponse'] = _PROPOSALRESPONSE
DESCRIPTOR.message_types_by_name['EndorsedAction'] = _ENDORSEDACTION
DESCRIPTOR.message_types_by_name['Transaction2'] = _TRANSACTION2
Envelope = _reflection.GeneratedProtocolMessageType('Envelope', (_message.Message,), dict(
DESCRIPTOR = _ENVELOPE,
__module__ = 'fabric_next_pb2'
# @@protoc_insertion_point(class_scope:protos.Envelope)
))
_sym_db.RegisterMessage(Envelope)
Message2 = _reflection.GeneratedProtocolMessageType('Message2', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE2,
__module__ = 'fabric_next_pb2'
# @@protoc_insertion_point(class_scope:protos.Message2)
))
_sym_db.RegisterMessage(Message2)
Proposal = _reflection.GeneratedProtocolMessageType('Proposal', (_message.Message,), dict(
DESCRIPTOR = _PROPOSAL,
__module__ = 'fabric_next_pb2'
# @@protoc_insertion_point(class_scope:protos.Proposal)
))
_sym_db.RegisterMessage(Proposal)
Response2 = _reflection.GeneratedProtocolMessageType('Response2', (_message.Message,), dict(
DESCRIPTOR = _RESPONSE2,
__module__ = 'fabric_next_pb2'
# @@protoc_insertion_point(class_scope:protos.Response2)
))
_sym_db.RegisterMessage(Response2)
SystemChaincode = _reflection.GeneratedProtocolMessageType('SystemChaincode', (_message.Message,), dict(
DESCRIPTOR = _SYSTEMCHAINCODE,
__module__ = 'fabric_next_pb2'
# @@protoc_insertion_point(class_scope:protos.SystemChaincode)
))
_sym_db.RegisterMessage(SystemChaincode)
Action = _reflection.GeneratedProtocolMessageType('Action', (_message.Message,), dict(
DESCRIPTOR = _ACTION,
__module__ = 'fabric_next_pb2'
# @@protoc_insertion_point(class_scope:protos.Action)
))
_sym_db.RegisterMessage(Action)
Endorsement = _reflection.GeneratedProtocolMessageType('Endorsement', (_message.Message,), dict(
DESCRIPTOR = _ENDORSEMENT,
__module__ = 'fabric_next_pb2'
# @@protoc_insertion_point(class_scope:protos.Endorsement)
))
_sym_db.RegisterMessage(Endorsement)
ProposalResponse = _reflection.GeneratedProtocolMessageType('ProposalResponse', (_message.Message,), dict(
DESCRIPTOR = _PROPOSALRESPONSE,
__module__ = 'fabric_next_pb2'
# @@protoc_insertion_point(class_scope:protos.ProposalResponse)
))
_sym_db.RegisterMessage(ProposalResponse)
EndorsedAction = _reflection.GeneratedProtocolMessageType('EndorsedAction', (_message.Message,), dict(
DESCRIPTOR = _ENDORSEDACTION,
__module__ = 'fabric_next_pb2'
# @@protoc_insertion_point(class_scope:protos.EndorsedAction)
))
_sym_db.RegisterMessage(EndorsedAction)
Transaction2 = _reflection.GeneratedProtocolMessageType('Transaction2', (_message.Message,), dict(
DESCRIPTOR = _TRANSACTION2,
__module__ = 'fabric_next_pb2'
# @@protoc_insertion_point(class_scope:protos.Transaction2)
))
_sym_db.RegisterMessage(Transaction2)
import grpc
from grpc.beta import implementations as beta_implementations
from grpc.beta import interfaces as beta_interfaces
from grpc.framework.common import cardinality
from grpc.framework.interfaces.face import utilities as face_utilities
class EndorserStub(object):
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.ProcessProposal = channel.unary_unary(
'/protos.Endorser/ProcessProposal',
request_serializer=Proposal.SerializeToString,
response_deserializer=ProposalResponse.FromString,
)
class EndorserServicer(object):
def ProcessProposal(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_EndorserServicer_to_server(servicer, server):
rpc_method_handlers = {
'ProcessProposal': grpc.unary_unary_rpc_method_handler(
servicer.ProcessProposal,
request_deserializer=Proposal.FromString,
response_serializer=ProposalResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'protos.Endorser', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
class BetaEndorserServicer(object):
def ProcessProposal(self, request, context):
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
class BetaEndorserStub(object):
def ProcessProposal(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
raise NotImplementedError()
ProcessProposal.future = None
def beta_create_Endorser_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None):
request_deserializers = {
('protos.Endorser', 'ProcessProposal'): Proposal.FromString,
}
response_serializers = {
('protos.Endorser', 'ProcessProposal'): ProposalResponse.SerializeToString,
}
method_implementations = {
('protos.Endorser', 'ProcessProposal'): face_utilities.unary_unary_inline(servicer.ProcessProposal),
}
server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout)
return beta_implementations.server(method_implementations, options=server_options)
def beta_create_Endorser_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None):
request_serializers = {
('protos.Endorser', 'ProcessProposal'): Proposal.SerializeToString,
}
response_deserializers = {
('protos.Endorser', 'ProcessProposal'): ProposalResponse.FromString,
}
cardinalities = {
'ProcessProposal': cardinality.Cardinality.UNARY_UNARY,
}
stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size)
return beta_implementations.dynamic_stub(channel, 'protos.Endorser', cardinalities, options=stub_options)
# @@protoc_insertion_point(module_scope)
| nilq/baby-python | python |
import torch as th
import numpy as np
from gym import Env
from gym.spaces import Discrete, MultiDiscrete
__all__ = [
"MatrixGameEnv"
]
class MatrixGameEnv(Env):
def __init__(self, matrices, reward_perturbation=0, rand: th.Generator = th.default_generator):
super().__init__()
matrices = th.as_tensor(matrices)
reward_perturbation = th.as_tensor(reward_perturbation)
# Check shape of transition matrix
n_agents = matrices.dim()-1
if matrices.shape[0]!=n_agents:
raise ValueError("Number of matrices does not match dimensions of each matrix")
# Check shape of reward perturbation
if reward_perturbation.shape!=() and reward_perturbation.shape!=(n_agents,):
raise ValueError("Reward perturbation must be either same or specified for each agent")
# Check values of reward perturbation
if (reward_perturbation<0).any():
raise ValueError("Values of reward perturbation must be non-negative")
## State space
self.observation_space = Discrete(1)
## Action space
self.action_space = MultiDiscrete(matrices.shape[1:])
## Matrices of the matrix game
self.matrices = matrices
## Standard deviation of reward perturbation
self.reward_perturbation = reward_perturbation
## Random number generator
self.rand = rand
def reset(self):
return th.tensor(0)
def step(self, actions):
# Check validity of joint actions
if not self.action_space.contains(np.array(actions)):
raise ValueError("Joint actions {} is invalid".format(actions))
# Rewards for each agent
rewards = self.matrices[(slice(None), *actions)].clone()
# Add random perturbation to rewards
reward_perturbation = self.reward_perturbation
if (reward_perturbation!=0).all():
rewards += th.normal(0., reward_perturbation, generator=self.rand)
# Step result
return th.tensor(0), rewards, True, {}
| nilq/baby-python | python |
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
else:
unicode = str
import os
from matplotlib import rc
from matplotlib import rcParams
font_size=14
rcParams["backend"] = "PDF"
rcParams["figure.figsize"] = (4, 3)
rcParams["font.family"] = "Serif"
rcParams["font.serif"] = ["Palatino"]
rcParams["font.size"] = font_size
rcParams["axes.labelsize"] = font_size
rcParams["xtick.labelsize"] = font_size - 2
rcParams["ytick.labelsize"] = font_size - 2
rcParams["legend.numpoints"] = 1
rcParams["legend.fontsize"] = "small"
rcParams["lines.markersize"] = 4
rcParams["figure.subplot.right"] = 0.95
rcParams["figure.subplot.top"] = 0.95
rcParams["figure.subplot.right"] = 0.95
rcParams["figure.subplot.top"] = 0.95
rcParams["figure.subplot.left"] = 0.2
rcParams["figure.subplot.bottom"] = 0.2
rcParams["image.cmap"] = "hot"
rcParams["text.usetex"] = True
rcParams["ps.usedistiller"] = "xpdf"
rcParams["pdf.compression"] = 9
rcParams["ps.useafm"] = True
rcParams["path.simplify"] = True
rcParams["text.latex.preamble"] = [#"\usepackage{times}",
#"\usepackage{euler}",
r"\usepackage{amssymb}",
r"\usepackage{amsmath}"]
import scipy
import scipy.stats
import numpy as np
from pylab import *
from numpy import *
import graph_tool.all as gt
import random as prandom
figure()
try:
gt.openmp_set_num_threads(1)
except RuntimeError:
pass
prandom.seed(42)
np.random.seed(42)
gt.seed_rng(42)
| nilq/baby-python | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
try:
from ._models_py3 import AzureEntityResource
from ._models_py3 import ComplianceStatus
from ._models_py3 import ErrorDefinition
from ._models_py3 import ErrorResponse, ErrorResponseException
from ._models_py3 import HelmOperatorProperties
from ._models_py3 import ProxyResource
from ._models_py3 import Resource
from ._models_py3 import ResourceProviderOperation
from ._models_py3 import ResourceProviderOperationDisplay
from ._models_py3 import Result
from ._models_py3 import SourceControlConfiguration
from ._models_py3 import SystemData
from ._models_py3 import TrackedResource
except (SyntaxError, ImportError):
from ._models import AzureEntityResource
from ._models import ComplianceStatus
from ._models import ErrorDefinition
from ._models import ErrorResponse, ErrorResponseException
from ._models import HelmOperatorProperties
from ._models import ProxyResource
from ._models import Resource
from ._models import ResourceProviderOperation
from ._models import ResourceProviderOperationDisplay
from ._models import Result
from ._models import SourceControlConfiguration
from ._models import SystemData
from ._models import TrackedResource
from ._paged_models import ResourceProviderOperationPaged
from ._paged_models import SourceControlConfigurationPaged
from ._source_control_configuration_client_enums import (
ComplianceStateType,
MessageLevelType,
OperatorType,
OperatorScopeType,
ProvisioningStateType,
CreatedByType,
)
__all__ = [
'AzureEntityResource',
'ComplianceStatus',
'ErrorDefinition',
'ErrorResponse', 'ErrorResponseException',
'HelmOperatorProperties',
'ProxyResource',
'Resource',
'ResourceProviderOperation',
'ResourceProviderOperationDisplay',
'Result',
'SourceControlConfiguration',
'SystemData',
'TrackedResource',
'SourceControlConfigurationPaged',
'ResourceProviderOperationPaged',
'ComplianceStateType',
'MessageLevelType',
'OperatorType',
'OperatorScopeType',
'ProvisioningStateType',
'CreatedByType',
]
| nilq/baby-python | python |
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import io
import json
import typing
# TODO(slinkydeveloper) is this really needed?
class EventGetterSetter(object):
def CloudEventVersion(self) -> str:
raise Exception("not implemented")
# CloudEvent attribute getters
def EventType(self) -> str:
raise Exception("not implemented")
def Source(self) -> str:
raise Exception("not implemented")
def EventID(self) -> str:
raise Exception("not implemented")
def EventTime(self) -> str:
raise Exception("not implemented")
def SchemaURL(self) -> str:
raise Exception("not implemented")
def Data(self) -> object:
raise Exception("not implemented")
def Extensions(self) -> dict:
raise Exception("not implemented")
def ContentType(self) -> str:
raise Exception("not implemented")
# CloudEvent attribute constructors
# Each setter return an instance of its class
# in order to build a pipeline of setter
def SetEventType(self, eventType: str) -> object:
raise Exception("not implemented")
def SetSource(self, source: str) -> object:
raise Exception("not implemented")
def SetEventID(self, eventID: str) -> object:
raise Exception("not implemented")
def SetEventTime(self, eventTime: str) -> object:
raise Exception("not implemented")
def SetSchemaURL(self, schemaURL: str) -> object:
raise Exception("not implemented")
def SetData(self, data: object) -> object:
raise Exception("not implemented")
def SetExtensions(self, extensions: dict) -> object:
raise Exception("not implemented")
def SetContentType(self, contentType: str) -> object:
raise Exception("not implemented")
def SetSubject(self, subject: str) -> object:
raise Exception("not implemented")
class BaseEvent(EventGetterSetter):
def Properties(self, with_nullable=False) -> dict:
props = dict()
for name, value in self.__dict__.items():
if str(name).startswith("ce__"):
v = value.get()
if v is not None or with_nullable:
props.update({str(name).replace("ce__", ""): value.get()})
return props
def Get(self, key: str) -> (object, bool):
formatted_key = "ce__{0}".format(key.lower())
ok = hasattr(self, formatted_key)
value = getattr(self, formatted_key, None)
if not ok:
exts = self.Extensions()
return exts.get(key), key in exts
return value.get(), ok
def Set(self, key: str, value: object):
formatted_key = "ce__{0}".format(key)
key_exists = hasattr(self, formatted_key)
if key_exists:
attr = getattr(self, formatted_key)
attr.set(value)
setattr(self, formatted_key, attr)
return
exts = self.Extensions()
exts.update({key: value})
self.Set("extensions", exts)
def MarshalJSON(self, data_marshaller: typing.Callable) -> typing.IO:
props = self.Properties()
props["data"] = data_marshaller(props.get("data"))
if not props["extensions"]:
del props["extensions"]
if props["data"] == 'null' or props["data"] is None:
del props["data"]
return io.BytesIO(json.dumps(props).encode("utf-8"))
def UnmarshalJSON(self, b: typing.IO, data_unmarshaller: typing.Callable):
raw_ce = json.load(b)
for name, value in raw_ce.items():
if name == "data":
value = data_unmarshaller(value)
self.Set(name, value)
def UnmarshalBinary(
self,
headers: dict,
body: typing.IO,
data_unmarshaller: typing.Callable
):
for header, value in headers.items():
header = header.lower()
if header == "content-type":
self.SetContentType(value)
elif header.startswith("ce-"):
self.Set(header[3:], value)
self.Set("data", data_unmarshaller(body))
def MarshalBinary(
self,
data_marshaller: typing.Callable
) -> (dict, object):
headers = {}
if self.ContentType():
headers["content-type"] = self.ContentType()
props = self.Properties()
for key, value in props.items():
if key not in ["data", "extensions", "contenttype"]:
if value is not None:
headers["ce-{0}".format(key)] = value
for key, value in props.get("extensions").items():
headers["ce-{0}".format(key)] = value
data, _ = self.Get("data")
return headers, data_marshaller(data)
| nilq/baby-python | python |
#!/usr/bin/env python3
import argparse
import sys
import logging
from pathlib import Path
from capanno_utils.validate import *
from capanno_utils.validate_inputs import validate_inputs_for_instance
from capanno_utils.helpers.validate_cwl import validate_cwl_tool
from capanno_utils.helpers.get_paths import get_types_from_path
def get_parser():
parser = argparse.ArgumentParser(description="Validate metadata and cwl files.")
parser.add_argument('path', type=Path,
help='Provide the path to validate. If a directory is specified, all content in the directory will be validated. If a file is specified, only that file will be validated.')
parser.add_argument('-p', '--root-repo-path', dest='root_path', type=Path, default=Path.cwd(),
help="Specify the root path of your cwl content repo if it is not the current working directory.")
parser.add_argument('-q', '--quiet', dest='quiet', action='store_true', help="Silence messages to stdout")
return parser
def main(argsl=None):
if not argsl:
argsl = sys.argv[1:]
parser = get_parser()
args = parser.parse_args(argsl)
# from pdb import set_trace; set_trace()
if args.path.is_absolute():
full_path = args.path
else:
full_path = args.root_path / args.path
base_type, specific_type = get_types_from_path(full_path, cwl_root_repo_name=args.root_path.name,
base_path=args.root_path)
if not args.quiet:
print(f"Validating {str(full_path)} \n")
if base_type == 'tool':
# Check for file types.
if specific_type == 'common_metadata':
validate_parent_tool_metadata(full_path)
elif specific_type == 'cwl':
validate_cwl_tool(full_path)
elif specific_type == 'metadata':
validate_subtool_metadata(full_path)
elif specific_type == 'instance':
validate_inputs_for_instance(full_path)
elif specific_type == 'instance_metadata':
raise NotImplementedError
# Check for directory types.
elif specific_type == 'base_dir':
validate_tools_dir(base_dir=args.root_path)
elif specific_type == 'tool_dir':
tool_name = full_path.parts[-1]
validate_main_tool_directory(tool_name, base_dir=args.root_path)
elif specific_type == 'version_dir':
tool_name, version_name = full_path.parts[-2:]
validate_tool_version_dir(tool_name, version_name, base_dir=args.root_path)
elif specific_type == 'common_dir':
tool_name, version_name = full_path.parts[-3:-1]
validate_tool_comomon_dir(tool_name, version_name, base_dir=args.root_path)
elif specific_type == 'subtool_dir':
path_parts = full_path.parts
tool_name, version_name = path_parts[-3:-1]
subtool_name = path_parts[-1][len(tool_name) + 1:]
if subtool_name == '':
subtool_name = None
validate_subtool_dir(tool_name, version_name, subtool_name, base_dir=args.root_path)
elif specific_type == 'instance_dir': # Must do the same as validating a subtool directory. Could skip validating subtool metadata, but won't. Don't see use for that.
path_parts = full_path.parts
tool_name, version_name = path_parts[-4:-2]
subtool_name = path_parts[-2][len(tool_name) + 1:]
if subtool_name == '':
subtool_name = None
validate_subtool_dir(tool_name, version_name, subtool_name=subtool_name, base_dir=args.root_path)
else:
raise ValueError(f"")
elif base_type == 'script':
if specific_type == 'cwl':
validate_cwl_tool(full_path)
elif specific_type == 'metadata':
validate_script_metadata(full_path)
elif specific_type == 'instance':
validate_inputs_for_instance(full_path)
elif specific_type == 'instance_metadata':
raise NotImplementedError
# Check for directory types.
elif specific_type == 'base_dir':
validate_scripts_dir(base_dir=args.root_path)
elif specific_type == 'group_dir':
group_name = full_path.parts[-1]
validate_group_scripts_dir(group_name, base_dir=args.root_path)
elif specific_type == 'project_dir':
group_name, project_name = full_path.parts[-2:]
validate_project_scripts_dir(group_name, project_name, base_dir=args.root_path)
elif specific_type == 'version_dir':
group_name, project_name, version_name = full_path.parts[-3:]
validate_version_script_dir(group_name, project_name, version_name, base_dir=args.root_path)
elif specific_type == 'script_dir':
group_name, project_name, version_name, script_name = full_path.parts[-4:]
validate_script_dir(group_name, project_name, version_name, script_name, base_dir=args.root_path)
elif specific_type == 'instance_dir':
group_name, project_name, version_name, script_name = full_path.parts[-5:-1]
validate_script_dir(group_name, project_name, version_name, script_name, base_dir=args.root_path)
else:
raise ValueError(f"")
elif base_type == 'workflow':
if specific_type == 'cwl':
raise NotImplementedError
elif specific_type == 'metadata':
validate_workflow_metadata(full_path)
elif specific_type == 'instance':
raise NotImplementedError
elif specific_type == 'instance_metadata':
raise NotImplementedError
else:
raise ValueError(f"")
elif base_type == 'repo_root':
validate_repo(full_path)
else:
parser.print_help()
if not args.quiet:
print(f"{full_path} is valid.")
return
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
| nilq/baby-python | python |
_base_ = [
'../../_base_/models/vision_transformer/vit_large_p16_sz224.py',
'../../_base_/datasets/imagenet/swin_sz384_8xbs64.py',
'../../_base_/default_runtime.py',
]
# model
model = dict(backbone=dict(img_size=384))
# data
data = dict(imgs_per_gpu=64, workers_per_gpu=6)
# additional hooks
update_interval = 8 # 64 x 8gpus x 8 accumulates = bs4096
# optimizer
optimizer = dict(
type='AdamW',
lr=0.003, # bs4096
weight_decay=0.3,
paramwise_options={
'(bn|ln|gn)(\d+)?.(weight|bias)': dict(weight_decay=0.),
'bias': dict(weight_decay=0.),
'cls_token': dict(weight_decay=0.),
'pos_embed': dict(weight_decay=0.),
})
# apex
use_fp16 = False
fp16 = dict(type='apex', loss_scale=dict(init_scale=512., mode='dynamic'))
optimizer_config = dict(
grad_clip=dict(max_norm=1.0),
update_interval=update_interval, use_fp16=use_fp16)
# lr scheduler
lr_config = dict(
policy='CosineAnnealing',
by_epoch=False, min_lr=0,
warmup='linear',
warmup_iters=10000,
warmup_ratio=1e-4,
)
# runtime settings
runner = dict(type='EpochBasedRunner', max_epochs=300)
| nilq/baby-python | python |
from rest_framework import serializers
from core.models import Link, Comment
class LinkSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Link
class CommentSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Comment
| nilq/baby-python | python |
# Generated by Django 3.2.4 on 2021-06-23 21:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timewebapp', '0044_alter_settingsmodel_first_login'),
]
operations = [
migrations.AlterField(
model_name='settingsmodel',
name='first_login',
field=models.BooleanField(default=True, verbose_name='Enable Tutorial'),
),
]
| nilq/baby-python | python |
import pytest
import os
@pytest.mark.processor("gpu")
@pytest.mark.model("placeholder")
@pytest.mark.skip_cpu
@pytest.mark.skip_py2_containers
def test_placeholder():
pass
| nilq/baby-python | python |
#!/usr/bin/env python
'''
Experimental viewer for DAVIS + OpenXC data
Author: J. Binas <jbinas@gmail.com>, 2017
This software is released under the
GNU LESSER GENERAL PUBLIC LICENSE Version 3.
Usage:
Play a file from the beginning:
$ ./view.py <recorded_file.hdf5>
Play a file, starting at X percent:
$ ./view.py <recorded_file.hdf5> -s X%
Play a file starting at second X
$ ./view.py <recorded_file.hdf5> -s Xs
'''
from __future__ import print_function
import argparse
import ctypes
from argparse import RawTextHelpFormatter
import numpy as np
import h5py
import cv2
import time
import multiprocessing as mp
import queue
from queue import Empty
from interfaces.caer import DVS_SHAPE, unpack_header, unpack_data
from datasets import CHUNK_SIZE
VIEW_DATA = {
'dvs',
'steering_wheel_angle',
'engine_speed',
'accelerator_pedal_position',
'brake_pedal_status',
'vehicle_speed',
}
# this changed in version 3
CV_AA = cv2.LINE_AA if int(cv2.__version__[0]) > 2 else cv2.CV_AA
def _flush_q(q):
''' flush queue '''
while True:
try:
q.get(timeout=1e-3)
except queue.Empty:
if q.empty():
break
class HDF5Stream(mp.Process):
def __init__(self, filename, tables, bufsize=64):
super(HDF5Stream, self).__init__()
self.f = h5py.File(filename, 'r')
self.tables = tables
self.q = {k: mp.Queue(bufsize) for k in self.tables}
self.run_search = mp.Event()
self.exit = mp.Event()
self.done = mp.Event()
self.skip_to = mp.Value('L', 0)
self._init_count()
self._init_time()
self.daemon = True
self.start()
def run(self):
while self.blocks_rem and not self.exit.is_set():
blocks_read = 0
for k in list(self.blocks_rem):
if self.q[k].full():
time.sleep(1e-6)
continue
i = self.block_offset[k]
self.q[k].put(self.f[k]['data'][int(i*CHUNK_SIZE):int((i+1)*CHUNK_SIZE)])
self.block_offset[k] += 1
if self.blocks_rem[k].value:
self.blocks_rem[k].value -= 1
else:
self.blocks_rem.pop(k)
blocks_read += 1
if not blocks_read:
time.sleep(1e-6)
if self.run_search.is_set():
self._search()
self.f.close()
print('closed input file')
while not self.exit.is_set():
time.sleep(1e-3)
# print('[DEBUG] flushing stream queues')
for k in self.q:
# print('[DEBUG] flushing', k)
_flush_q(self.q[k])
self.q[k].close()
self.q[k].join_thread()
# print('[DEBUG] flushed all stream queues')
self.done.set()
print('stream done')
def get(self, k, block=True, timeout=None):
return self.q[k].get(block, timeout)
def _init_count(self, offset={}):
self.block_offset = {k: offset.get(k, 0) / CHUNK_SIZE
for k in self.tables}
self.size = {k: len(self.f[k]['data']) - v * CHUNK_SIZE
for k, v in self.block_offset.items()}
self.blocks = {k: v / CHUNK_SIZE for k, v in self.size.items()}
self.blocks_rem = {
k: mp.Value(ctypes.c_double, v) for k, v in self.blocks.items() if v}
def _init_time(self):
self.ts_start = {}
self.ts_stop = {}
self.ind_stop = {}
for k in self.tables:
ts_start = self.f[k]['timestamp'][self.block_offset[k]*CHUNK_SIZE]
self.ts_start[k] = mp.Value('L', ts_start)
b = self.block_offset[k] + self.blocks_rem[k].value - 1
while b > self.block_offset[k] and \
self.f[k]['timestamp'][b*CHUNK_SIZE] == 0:
b -= 1
print(k, 'final block:', b)
self.ts_stop[k] = mp.Value(
'L', self.f[k]['timestamp'][(b + 1) * CHUNK_SIZE - 1])
self.ind_stop[k] = b
def init_search(self, t):
''' start streaming from given time point '''
if self.run_search.is_set():
return
self.skip_to.value = np.uint64(t)
self.run_search.set()
def _search(self):
t = self.skip_to.value
offset = {k: self._bsearch_by_timestamp(k, t) for k in self.tables}
for k in self.tables:
_flush_q(self.q[k])
self._init_count(offset)
# self._init_time()
self.run_search.clear()
def _bsearch_by_timestamp(self, k, t):
'''performs binary search on timestamp, returns closest block index'''
l, r = 0, self.ind_stop[k]
print('searching', k, t)
while True:
if r - l < 2:
print('selecting block', l)
return l * CHUNK_SIZE
if self.f[k]['timestamp'][(l + (r - l) / 2) * CHUNK_SIZE] > t:
r = l + (r - l) / 2
else:
l += (r - l) / 2
class MergedStream(mp.Process):
''' Unpacks and merges data from HDF5 stream '''
def __init__(self, fbuf, bufsize=256):
super(MergedStream, self).__init__()
self.fbuf = fbuf
self.ts_start = self.fbuf.ts_start
self.ts_stop = self.fbuf.ts_stop
self.q = mp.Queue(bufsize)
self.run_search = mp.Event()
self.skip_to = mp.Value('L', 0)
self._init_state()
self.done = mp.Event()
self.fetched_all = mp.Event()
self.exit = mp.Event()
self.daemon = True
self.start()
def run(self):
while self.blocks_rem and not self.exit.is_set():
# find next event
if self.q.full():
time.sleep(1e-4)
continue
next_k = min(self.current_ts, key=self.current_ts.get)
self.q.put((self.current_ts[next_k], self.current_dat[next_k]))
self._inc_current(next_k)
# get new blocks if necessary
for k in {k for k in self.blocks_rem if self.i[k] == CHUNK_SIZE}:
self.current_blk[k] = self.fbuf.get(k)
self.i[k] = 0
if self.blocks_rem[k]:
self.blocks_rem[k] -= 1
else:
self.blocks_rem.pop(k)
self.current_ts.pop(k)
if self.run_search.is_set():
self._search()
self.fetched_all.set()
self.fbuf.exit.set()
while not self.fbuf.done.is_set():
time.sleep(1)
# print('[DEBUG] waiting for stream process')
while not self.exit.is_set():
time.sleep(1)
# print('[DEBUG] waiting for merger process')
_flush_q(self.q)
# print('[DEBUG] flushed merger q ->', self.q.qsize())
self.q.close()
self.q.join_thread()
# print('[DEBUG] joined merger q')
self.done.set()
def close(self):
self.exit.set()
def _init_state(self):
keys = self.fbuf.blocks_rem.keys()
self.blocks_rem = {k: self.fbuf.blocks_rem[k].value for k in keys}
self.current_blk = {k: self.fbuf.get(k) for k in keys}
self.i = {k: 0 for k in keys}
self.current_dat = {}
self.current_ts = {}
for k in keys:
self._inc_current(k)
def _inc_current(self, k):
''' get next event of given type and increment row pointer '''
row = self.current_blk[k][self.i[k]]
if k == 'dvs':
ts, d = caer_event_from_row(row)
else: # vi event
ts = row[0] * 1e-6
d = {'etype': k, 'timestamp': row[0], 'data': row[1]}
if not ts and k in self.current_ts:
self.current_ts.pop(k)
self.blocks_rem.pop(k)
return False
self.current_ts[k], self.current_dat[k] = ts, d
self.i[k] += 1
def get(self, block=False):
return self.q.get(block)
@property
def has_data(self):
return not (self.fetched_all.is_set() and self.q.empty())
@property
def tmin(self):
return self.ts_start['dvs'].value
@property
def tmax(self):
return self.ts_stop['dvs'].value
def search(self, t, block=True):
if self.run_search.is_set():
return
self.skip_to.value = np.uint64(t)
self.run_search.set()
def _search(self):
self.fbuf.init_search(self.skip_to.value)
while self.fbuf.run_search.is_set():
time.sleep(1e-6)
_flush_q(self.q)
self._init_state()
self.q.put((0, {'etype': 'timestamp_reset'}))
self.run_search.clear()
class Interface(object):
def __init__(self,
tmin=0, tmax=0,
search_callback=None,
update_callback=None,
create_callback=None,
destroy_callback=None):
self.tmin, self.tmax = tmin, tmax
self.search_callback = search_callback
self.update_callback = update_callback
self.create_callback = create_callback
self.destroy_callback = destroy_callback
def _set_t(self, t):
self.t_now = int(t - self.tmin)
if self.update_callback is not None:
self.update_callback(t)
def close(self):
if self.close_callback is not None:
self.close_callback
class Viewer(Interface):
''' Simple visualizer for events '''
def __init__(self, max_fps=40, zoom=1, rotate180=False, **kwargs):
super(Viewer, self).__init__(**kwargs)
self.zoom = zoom
cv2.namedWindow('frame')
# tobi added from https://stackoverflow.com/questions/21810452/
# cv2-imshow-command-doesnt-work-properly-in-opencv-python/
# 24172409#24172409
cv2.startWindowThread()
cv2.namedWindow('polarity')
ox = 0
oy = 0
cv2.moveWindow('frame', ox, oy)
cv2.moveWindow('polarity', ox + int(448*self.zoom), oy)
self.set_fps(max_fps)
self.pol_img = 0.5 * np.ones(DVS_SHAPE)
self.t_now = 0
self.t_pre = {}
self.count = {}
self.cache = {}
self.font = cv2.FONT_HERSHEY_SIMPLEX
self.display_info = True
self.display_color = 0
self.playback_speed = 1. # seems to do nothing
self.rotate180 = rotate180
# sets contrast for full scale event count for white/black
self.dvs_contrast = 2
self.paused = False
def set_fps(self, max_fps):
self.min_dt = 1. / max_fps
def show(self, d, t=None):
# handle keyboad input
key_pressed = cv2.waitKey(1) & 0xFF # http://www.asciitable.com/
if key_pressed != -1:
if key_pressed == ord('i'): # 'i' pressed
if self.display_color == 0:
self.display_color = 255
elif self.display_color == 255:
self.display_color = 0
self.display_info = not self.display_info
print('rotated car info display')
elif key_pressed == ord('x'): # exit
print('exiting from x key')
raise SystemExit
elif key_pressed == ord('f'): # f (faster) key pressed
self.min_dt = self.min_dt*1.2
print('increased min_dt to ', self.min_dt, ' s')
# self.playback_speed = min(self.playback_speed + 0.2, 5.0)
# print('increased playback speed to ',self.playback_speed)
elif key_pressed == ord('s'): # s (slower) key pressed
self.min_dt = self.min_dt/1.2
print('decreased min_dt to ', self.min_dt, ' s')
# self.playback_speed = max(self.playback_speed - 0.2, 0.2)
# print('decreased playback speed to ',self.playback_speed)
elif key_pressed == ord('b'): # brighter
self.dvs_contrast = max(1, self.dvs_contrast-1)
print('increased DVS contrast to ', self.dvs_contrast,
' full scale event count')
elif key_pressed == ord('d'): # brighter
self.dvs_contrast = self.dvs_contrast+1
print('decreased DVS contrast to ', self.dvs_contrast,
' full scale event count')
elif key_pressed == ord(' '): # toggle paused
self.paused = not self.paused
print('decreased DVS contrast to ', self.dvs_contrast,
' full scale event count')
if self.paused:
while True:
key_paused = cv2.waitKey(1) or 0xff
if key_paused == ord(' '):
self.paused = False
break
''' receive and handle single event '''
if 'etype' not in d:
d['etype'] = d['name']
etype = d['etype']
if not self.t_pre.get(etype):
self.t_pre[etype] = -1
self.count[etype] = self.count.get(etype, 0) + 1
if etype == 'frame_event' and \
time.time() - self.t_pre[etype] > self.min_dt:
if 'data' not in d:
unpack_data(d)
img = (d['data'] / 256).astype(np.uint8)
if self.rotate180 is True:
# grab the dimensions of the image and calculate the center
# of the image
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
# rotate the image by 180 degrees
M = cv2.getRotationMatrix2D(center, 180, 1.0)
img = cv2.warpAffine(img, M, (w, h))
if self.display_info:
self._plot_steering_wheel(img)
self._print(img, (50, 220), 'accelerator_pedal_position', '%')
self._print(img, (100, 220), 'brake_pedal_status',
'brake', True)
self._print(img, (200, 220), 'vehicle_speed', 'km/h')
self._print(img, (300, 220), 'engine_speed', 'rpm')
if t is not None:
self._plot_timeline(img)
if self.zoom != 1:
img = cv2.resize(
img, None, fx=self.zoom, fy=self.zoom,
interpolation=cv2.INTER_CUBIC)
cv2.imshow('frame', img)
# cv2.waitKey(1)
self.t_pre[etype] = time.time()
elif etype == 'polarity_event':
if 'data' not in d:
unpack_data(d)
# makes DVS image, but only from latest message
self.pol_img[d['data'][:, 2], d['data'][:, 1]] += \
(d['data'][:, 3]-.5)/self.dvs_contrast
if time.time() - self.t_pre[etype] > self.min_dt:
if self.zoom != 1:
self.pol_img = cv2.resize(
self.pol_img, None,
fx=self.zoom, fy=self.zoom,
interpolation=cv2.INTER_CUBIC)
if self.rotate180 is True:
# grab the dimensions of the image and
# calculate the center
# of the image
(h, w) = self.pol_img.shape[:2]
center = (w // 2, h // 2)
# rotate the image by 180 degrees
M = cv2.getRotationMatrix2D(center, 180, 1.0)
self.pol_img = cv2.warpAffine(self.pol_img, M, (w, h))
if self.display_info:
self._print_string(self.pol_img, (25, 25), "%.2fms"%(self.min_dt*1000))
cv2.imshow('polarity', self.pol_img)
# cv2.waitKey(1)
self.pol_img = 0.5 * np.ones(DVS_SHAPE)
self.t_pre[etype] = time.time()
elif etype in VIEW_DATA:
if 'data' not in d:
d['data'] = d['value']
self.cache[etype] = d['data']
self.t_pre[etype] = time.time()
if t is not None:
self._set_t(t)
def _plot_steering_wheel(self, img):
if 'steering_wheel_angle' not in self.cache:
return
c, r = (173, 130), 65 # center, radius
a = self.cache['steering_wheel_angle']
a_rad = + a / 180. * np.pi + np.pi / 2
if self.rotate180:
a_rad = np.pi-a_rad
t = (c[0] + int(np.cos(a_rad) * r), c[1] - int(np.sin(a_rad) * r))
cv2.line(img, c, t, self.display_color, 2, CV_AA)
cv2.circle(img, c, r, self.display_color, 1, CV_AA)
cv2.line(img, (c[0]-r+5, c[1]), (c[0]-r, c[1]),
self.display_color, 1, CV_AA)
cv2.line(img, (c[0]+r-5, c[1]), (c[0]+r, c[1]),
self.display_color, 1, CV_AA)
cv2.line(img, (c[0], c[1]-r+5), (c[0], c[1]-r),
self.display_color, 1, CV_AA)
cv2.line(img, (c[0], c[1]+r-5), (c[0], c[1]+r),
self.display_color, 1, CV_AA)
cv2.putText(
img, '%0.1f deg' % a,
(c[0]-35, c[1]+30), self.font, 0.4, self.display_color, 1, CV_AA)
def _print(self, img, pos, name, unit, autohide=False):
if name not in self.cache:
return
v = self.cache[name]
if autohide and v == 0:
return
cv2.putText(
img, '%d %s' % (v, unit),
(pos[0]-40, pos[1]+20), self.font, 0.4,
self.display_color, 1, CV_AA)
def _print_string(self, img, pos, string):
cv2.putText(
img, '%s' % string,
(pos[0], pos[1]), self.font, 0.4, self.display_color, 1, CV_AA)
def _plot_timeline(self, img):
pos = (50, 10)
p = int(346 * self.t_now / (self.tmax - self.tmin))
cv2.line(img, (0, 2), (p, 2), 255, 1, CV_AA)
cv2.putText(
img, '%d s' % self.t_now,
(pos[0]-40, pos[1]+20), self.font, 0.4, self.display_color, 1, CV_AA)
def close(self):
cv2.destroyAllWindows()
class Controller(Interface):
def __init__(self, filename, **kwargs):
super(Controller, self).__init__(**kwargs)
cv2.namedWindow('control')
cv2.moveWindow('control', 400, 698)
self.f = h5py.File(filename, 'r')
self.tmin, self.tmax = self._get_ts()
self.len = int(self.tmax - self.tmin) + 1
img = np.zeros((100, self.len))
self.plot_pixels(img, 'headlamp_status', 0, 10)
self.plot_line(img, 'steering_wheel_angle', 20, 30)
self.plot_line(img, 'vehicle_speed', 69, 30)
self.width = 978
self.img = cv2.resize(
img, (self.width, 100), interpolation=cv2.INTER_NEAREST)
cv2.setMouseCallback('control', self._set_search)
self.t_pre = 0
self.update(0)
self.f.close()
def update(self, t):
self._set_t(t)
t = int(float(self.width) / self.len * (t - self.tmin))
if t == self.t_pre:
return
self.t_pre = t
img = self.img.copy()
img[:, :t+1] = img[:, :t+1] * 0.5 + 0.5
cv2.imshow('control', img)
cv2.waitKey(1)
def plot_line(self, img, name, offset, height):
x, y = self.get_xy(name)
if x is None:
return
y -= y.min()
y = y / y.max() * height
x = x.clip(0, self.len - 1)
img[offset+height-y.astype(int), x] = 1
def plot_pixels(self, img, name, offset=0, height=1):
x, y = self.get_xy(name)
if x is None:
return
img[offset:offset+height, x] = y
def _set_search(self, event, x, y, flags, param):
if event != cv2.EVENT_LBUTTONDOWN:
return
t = self.len * 1e6 * x / float(self.width) + self.tmin * 1e6
self._search_callback(t)
def _get_ts(self):
ts = self.f['dvs']['timestamp']
tmin = ts[0]
i = -1
while ts[i] == 0:
i -= 1
tmax = ts[i]
print('tmin/tmax', tmin, tmax)
return int(tmin * 1e-6), int(tmax * 1e-6)
def get_xy(self, name):
d = self.f[name]['data']
print('name', name)
gtz_ids = d[:, 0] > 0
if not gtz_ids.any():
return None, 0
gtz = d[gtz_ids, :]
return (gtz[:, 0] * 1e-6 - self.tmin).astype(int), gtz[:, 1]
def caer_event_from_row(row):
'''
Takes binary dvs data as input,
returns unpacked event data or False if event type does not exist.
'''
sys_ts, head, body = (v.tobytes() for v in row)
if not sys_ts:
# rows with 0 timestamp do not contain any data
return 0, False
d = unpack_header(head)
d['dvs_data'] = body
return int(sys_ts) * 1e-6, unpack_data(d)
if __name__ == '__main__':
parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter)
parser.add_argument('filename')
parser.add_argument('--start', '-s', type=str, default=0.,
help="Examples:\n"
"-s 50%% - play file starting at 50%%\n"
"-s 66s - play file starting at 66s")
parser.add_argument('--rotate', '-r', type=bool, default=True,
help="Rotate the scene 180 degrees if True, "
"Otherwise False")
args = parser.parse_args()
fname = args.filename
c = Controller(fname,)
m = MergedStream(HDF5Stream(fname, VIEW_DATA))
c._search_callback = m.search
t = time.time()
t_pre = 0
t_offset = 0
r180 = args.rotate
# r180arg = "-r180"
print('recording duration', (m.tmax - m.tmin) * 1e-6, 's')
# direct skip by command line
# parse second argument
try:
second_opt = args.start
n_, type_ = second_opt[:-1], second_opt[-1]
if type_ == '%':
m.search((m.tmax - m.tmin) * 1e-2 * float(n_) + m.tmin)
elif type_ == 's':
m.search(float(n_) * 1e6 + m.tmin)
except:
pass
v = Viewer(tmin=m.tmin * 1e-6, tmax=m.tmax * 1e-6,
zoom=1.41, rotate180=r180, update_callback=c.update)
# run main loop
ts_reset = False
while m.has_data:
try:
sys_ts, d = m.get()
# except Queue.Empty:
except Empty:
continue
if not d:
continue
if d['etype'] == 'timestamp_reset':
ts_reset = True
continue
if not d['etype'] in {'frame_event', 'polarity_event'}:
v.show(d)
continue
if d['timestamp'] < t_pre:
print('[WARN] negative dt detected!')
t_pre = d['timestamp']
if ts_reset:
print('resetting timestamp')
t_offset = 0
ts_reset = False
if not t_offset:
t_offset = time.time() - d['timestamp']
print('setting offset', t_offset)
t_sleep = max(d['timestamp'] - time.time() + t_offset, 0)
time.sleep(t_sleep)
v.show(d, sys_ts)
if time.time() - t > 1:
print(chr(27) + "[2J")
t = time.time()
print('fps:\n', '\n'.join(
[' %s %s' % (
k.ljust(20), v_) for k, v_ in v.count.items()]))
v.count = {k: 0 for k in v.count}
| nilq/baby-python | python |
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from pages.top_bars.top_navigate_bar import TopNavigateBar
class TemplatesPage(TopNavigateBar):
""" Templates page - contains variety of templates to select """
_TEMPLATES_BLOCK = (By.CSS_SELECTOR, "#template-gallery tbody tr")
_CHOOSE_BUTTON = (By.CSS_SELECTOR, "a .btn.btn-primary")
def __init__(self, driver):
super().__init__(driver)
def choose_template(self, template_name):
self._wait.until(
expected_conditions.visibility_of_all_elements_located(self._TEMPLATES_BLOCK))
templates = self._wait.until(expected_conditions.visibility_of_all_elements_located(self._TEMPLATES_BLOCK))
for template in templates:
if template_name in template.text:
button = template.find_element(*self._CHOOSE_BUTTON)
self.move_to_element(button)
button.click()
break
| nilq/baby-python | python |
#Hall bar geometry device. Measurements have r_xx and/or r_xy
import numpy as np
import matplotlib.pyplot as plt
import warnings
from scipy.signal import savgol_filter
from pylectric.analysis import mobility
from scipy import optimize as opt
class Meas_GatedResistance():
"""Class to handle a single sweep of raw data. Measures resistance against gate voltage to infer properties."""
def __init__(self, data, Cg, L, W, D = None):
""" Takes numpy array of the form array[rows, columns]
Requires columns to be of the form: [V_gate (Volts), Resistance (Ohms)]
Also takes Length L, Width W, and Thickness D to infer scaled material properties.
If 2D materials, thickness can be left as None, and units don't matter.
If 3D, thickness should in cm units (assuming L & W cancel out).
"""
#1. Cols = [V_gate, Resistance]
self.raw_data = np.array(data, np.longfloat).copy()
self.conductivity_data = self.raw_data.copy()[:,0:2]
#Note, Resistance = Resistivity * L / (W * D) -> Conductivity = 1/Resistance * L / (W * D)
self.conductivity_data[:,1] = np.reciprocal(self.conductivity_data[:,1] * W / L) if D is None else np.reciprocal(self.conductivity_data[:,1] * W * D / L)
self.L = L
self.W = W
self.D = D
self.Cg = Cg
self.is2D = (D is None)
def mobility_dtm_2D(self, graph = True, ax=None, graph_kwargs = None, vg_offset = 0):
""" Calculates the direct transconductance method mobility.
Requires the gate capacitance (Farads).
Returns Mobility and a graph if parameter is True.
Mobility units are cm$^2$V$^{-1}$s${-1}$"""
#Return Analysis gate voltage
mu_dtm_2D = mobility.mobility_gated_dtm(self.conductivity_data.copy(), self.Cg)
#Graphing
if graph:
#Check if graph to paste onto:
if ax: #exists
fig = ax.get_figure()
else: #create new graph
fig, (ax) = plt.subplots(1,1)
#Plot
ax.scatter(mu_dtm_2D[:,0] - vg_offset, mu_dtm_2D[:,1], **graph_kwargs)
ax.set_xlabel("Gate voltage (V)")
ax.set_ylabel("Mobility (cm$^2$V$^{-1}$s${-1}$)")
return (mu_dtm_2D, fig)
else:
return mu_dtm_2D
def conductivity_min(self):
""" Finds the minimum value of conductivity and returns the index.
"""
min = np.min(self.conductivity_data[:,1])
index = np.where(self.conductivity_data[:,1] == min)[0][0]
return index
def discrete_sample_voltages(self, gate_voltages=None, center_voltage = 0, tollerance = 0.01):
""" Acquires a subset of resitivities, corresponding to gate voltages.
Useful for tracking temperature behaviour over multiple samples.
Matches requested voltage to within tollerance, from a central voltage.
"""
#Default sampling if no list provided.
if gate_voltages is None:
gate_voltages = [-50,-40,-30,-20,-15,-10,-7.5,-5,-3,-2,-1,0,1,2,3,5,7.5,10,15,20,30,40,50]
#Resistsances and gate voltages
rvg_sampled = []
#Find
for gv in gate_voltages:
vdelta = np.abs(self.conductivity_data[:,0] - center_voltage - gv)
v_i = np.where(vdelta == np.min(vdelta))[0][0]
if vdelta[v_i] < tollerance:
#Offset center voltage, and take reciporical of conductivity for resistivity.
rvg_sampled.append([self.conductivity_data[v_i,0]-center_voltage, 1.0/self.conductivity_data[v_i,1]])
else:
rvg_sampled.append([gv, np.nan]) #Add a NAN value to the array because value out of range.
rvg_sampled = np.array(rvg_sampled)
return rvg_sampled
def discrete_interpolated_voltages(self, gate_voltages=None, center_voltage = 0):
""" Acquires a subset of resitivities, corresponding to gate voltages.
Useful for tracking temperature behaviour over multiple samples.
Matches requested voltage to within tollerance, from a central voltage.
"""
cv = center_voltage
#Default sampling if no list provided.
if gate_voltages is None:
gate_voltages = [-50,-40,-30,-20,-15,-10,-7.5,-5,-3,-2,-1,0,1,2,3,5,7.5,10,15,20,30,40,50]
#Resistsances and gate voltages
rvg_sampled = []
#Find
for gv in gate_voltages:
vraw = self.conductivity_data[:,0] - center_voltage - gv
vdelta = np.abs(vraw)
v_i = np.where(vdelta == np.min(vdelta))[0][0]
if vdelta[v_i] == 0:
#Offset center voltage, and take reciporical of conductivity for resistivity.
rvg_sampled.append([self.conductivity_data[v_i,0]-center_voltage, 1.0/self.conductivity_data[v_i,1]])
else:
if not (v_i < 1 or v_i > len(self.conductivity_data)-2): #check endpoint condition
# Interpolate data if not endpoints:
B1 = self.conductivity_data[v_i,:]
if vdelta[v_i + 1] < vdelta[v_i - 1]: #smaller is better for interpolation, closer to dirac point.
B2 = self.conductivity_data[v_i + 1,:]
else:
B2 = self.conductivity_data[v_i - 1,:]
#re-arranged gv = (alpha * (B1-cv) + (1-alpha) * (B2-cv)), finding linear interpolation.
alpha = (gv - (B2[0] - cv)) / (B1[0] - B2[0])
# Saftey check for result consistency.
if alpha < 0 or alpha > 1:
raise(ValueError("Calculation of linear interpolation factor (alpha = " + str(alpha) + ") is outside (0,1)."))
#Interolate
inter_v = (alpha * (B1[0] - cv)) + ((1-alpha) * (B2[0] - cv))
inter_resistivity = 1.0/(alpha * (B1[1]) + (1-alpha) * (B2[1]))
#append
rvg_sampled.append([inter_v, inter_resistivity]) #Add a NAN value to the array because value out of range.
else:
rvg_sampled.append([gv, np.nan]) #Add a NAN value to the array because value out of range.
rvg_sampled = np.array(rvg_sampled)
return rvg_sampled
def global_RVg_fit(self, fit_function, params, boundsU=None, boundsL=None):
""" Public function for globally fitting to the R Vg data.
Fits to initial provided temperature and gate voltage dependent resistivity.
"""
return Meas_GatedResistance.__fit(vg=self.conductivity_data[:,0], sigma=self.conductivity_data[:,1], fit_function=fit_function, x0=params, boundsU=boundsU, boundsL=boundsL)
def __fit(fit_function, vg, sigma, x0, boundsU=None, boundsL=None):
""" Private method to generate a fit to Sigma Vg data, not object specific.
Requires 1D arrays of gate voltage and conductivity (sigma).
"""
#Check that shapes match:
vg = np.array(vg, dtype=np.longfloat)
sigma = np.array(sigma, dtype=np.longfloat)
#conditions
if not (vg.shape == sigma.shape and len(vg.shape) == 1):
raise ValueError("Either Vg or Sigma arrays do not match in shape, or are not one-dimensional.")
params, covar = opt.curve_fit(fit_function, xdata=vg, ydata=sigma, p0=x0 ,bounds=(boundsL, boundsU))
return params, covar
################### PLOTTING PARAMETERS ########################
def __scatterVG(data, ax = None, s=1, c=None, label=None, style=None, vg_offset = 0, scatter=True):
if ax is None:
fig, (ax1) = plt.subplots(1,1)
else:
ax1 = ax
ax1.set_title("Electronic transport")
ax1.set_xlabel("Gate Voltage (V)")
ax1.tick_params(direction="in")
if c is None:
c = plt.rcParams['axes.prop_cycle'].by_key()['color'][0]
if style != None:
if scatter:
ax1.scatter(data[:,0] - vg_offset, data[:,1], style, label=label, s=s, c=c)
else:
ax1.plot(data[:,0] - vg_offset, data[:,1], style, label=label, linewidth=s, c=c)
else:
if scatter:
ax1.scatter(data[:,0] - vg_offset, data[:,1], label=label, s=s, c=c)
else:
ax1.plot(data[:,0] - vg_offset, data[:,1], label=label, linewidth=s, c=c)
return ax1
def plot_R_vG(self, ax = None, c = None, s=1, label="", vg_offset = 0, scatter=True):
"""Plots the raw resistance data versus gate voltage"""
# Plot Resistance
ax1 = Meas_GatedResistance.__scatterVG(self.raw_data[:,0:2], ax=ax, s=s, c=c, label=label, vg_offset=vg_offset, scatter=scatter)
# Generate Label
ax1.set_ylabel("Resistance ($\Omega$)")
return ax1
def plot_Rho_vG(self, ax = None, c = None, s=1, label="", style=None, vg_offset = 0, scatter=True):
"""Plots the scaled resitivity data versus gate voltage"""
# Calculate resistivity
Rho = np.reciprocal(self.conductivity_data[:,1])
# Plot restivitiy
ax1 = Meas_GatedResistance.__scatterVG(np.c_[self.conductivity_data[:,0], Rho], ax=ax, s=s, c=c, label=label, style=style, vg_offset=vg_offset, scatter=scatter)
# Generate 2D/3D Label
ax1.set_ylabel("Resisitivity ($\Omega$)") if self.is2D else ax1.set_ylabel("Resisitivity ($\Omega$ cm)")
return ax1
def plot_C_vG(self, ax = None, c = None, s=1, label="", vg_offset = 0, scatter=True):
"""Plots the raw conductance data versus gate voltage"""
# Calculate conductance
conductance = np.reciprocal(self.raw_data[:,1])
# Plot conductance
ax1 = Meas_GatedResistance.__scatterVG(np.c_[self.raw_data[:,0], conductance], ax=ax, s=s, c=c, label=label, vg_offset=vg_offset, scatter=scatter)
# Generate Label
ax1.set_ylabel("Conductivity (S)")
return ax1
def plot_Sigma_vG(self, ax = None, c = None, s=1, label="", vg_offset = 0, scatter=True):
"""Plots the scaled conductivity data versus gate voltage"""
ax1 = Meas_GatedResistance.__scatterVG(self.conductivity_data[:,0:2], ax=ax, s=s, c=c, label=label, vg_offset=vg_offset, scatter=scatter)
ax1.set_ylabel("Conductivity (S)") if self.is2D else ax1.set_ylabel("Conductivity (S cm$^{1}$)")
return ax1
class Meas_Temp_GatedResistance():
""" Class to handle temperature indexed multiple sweeps of gated data.
Measures resistance against gate voltage and temperature to infer properties."""
def __init__(self, temps, vg, resistivity, is2D = True):
""" Takes 1D arrays of temperature and gate voltage,
and a 2D array (temp, voltage) of corresponding resitivities.
"""
self.temps = np.array(temps)
self.vg = np.array(vg)
self.resistivity = np.array(resistivity)
self.ylabel = "Resistivity ($\Omega$)" if is2D else "Resistivity ($\Omega$m)"
### Check for null columns or rows in resistivity data.
# Clone original resistances
new_res = np.copy(self.resistivity)
new_vg = np.copy(self.vg)
new_temps = np.copy(self.temps)
# Find temperatures which are all Vg are null
slices = []
for k in range(self.resistivity.shape[0]):
if np.all(np.isnan(self.resistivity[k,:])==True):
slices.append(k)
if len(slices) > 0:
warnings.warn("Warning: Rows corresponding to T = " + str(self.temps[slices]) + " only contain NaN values, and are being removed.")
new_res = np.delete(new_res, slices, axis=0)
new_temps = np.delete(new_temps, slices)
# Find voltages which all temperatures are null
slices2 = []
for l in range(self.resistivity.shape[1]):
if np.all(np.isnan(self.resistivity[:,l])==True):
slices2.append(l)
if len(slices2) > 0:
warnings.warn("Warning: Columns corresponding to Vg = " + str(self.vg[slices2]) + " only contain NaN values, and are being removed.")
new_res = np.delete(new_res, slices2, axis=1)
new_vg = np.delete(new_vg, slices2)
# Set arrays to new object.
if len(slices) > 0 or len(slices2) > 0:
self.vg = new_vg
self.temps = new_temps
self.resistivity = new_res
#Check dimensions matchup.
if not (self.temps.shape[0] == self.resistivity.shape[0] and self.vg.shape[0] == self.resistivity.shape[1]):
raise ValueError("Dimension mismatch: Temperature and gate voltage arrays didn't match dimensions of resisitivty array.")
return
def plot_Rho_vT(self, ax=None, c=None, labels=None, singleLabel=None, offsets=None, hollow=False, **kwargs):
""" Generic scatter plot for resistance vs gate voltage.
Colours length has to match length of voltages.
"""
if c is not None and (len(self.vg) > len(c) or (labels is not None and len(self.vg) != len(labels))):
raise(AttributeError("There is a mismatch betweeen the number of colours (" + str(len(c)) +"), voltages (" + str(len(self.vg)) + "), and labels (" + str(len(labels)) + ")."))
if offsets is not None:
if len(offsets) != len(self.vg):
raise(AttributeError("There is a mismatch betweeen the number of offsets (" + str(len(offsets)) + ") and the number of voltages (" + str(len(self.vg)) + ")"))
else:
offsets = [0 for vg in self.vg]
if ax is None:
fig, (ax1) = plt.subplots(1,1)
else:
ax1 = ax
# kwargs
if c is None:
c = plt.rcParams['axes.prop_cycle'].by_key()['color']
for i in range(len(self.vg)):
#Colour:
c_i = c[i % len(c)]
kwargs["edgecolors"]=c_i
kwargs["c"]=c_i
if hollow and "c" in kwargs:
kwargs.pop("c")
elif not hollow and "edgecolors" in kwargs:
kwargs.pop("edgecolors")
#Labels:
if singleLabel is not None:
if i == 0:
label=singleLabel
else:
label=None
else:
if labels is None:
vg = self.vg[i]
label="%0.02f" % vg
else:
label=labels[i]
kwargs["label"]=label
# Boom.
ax1.scatter(self.temps, self.resistivity[:,i] - offsets[i], **kwargs)
ax1.set_xlabel("Temperature (K)")
ax1.set_ylabel(self.ylabel)
return ax1
def global_RTVg_fit(self, fit_function, params, boundsU=None, boundsL=None):
""" Public function for globally fitting to the RTVg data.
Fits to initial provided temperature and gate voltage dependent resistivity.
"""
return Meas_Temp_GatedResistance.__fit(temps=self.temps, vg=self.vg, data=self.resistivity, fit_function=fit_function, x0=params, boundsU=boundsU, boundsL=boundsL)
def global_RTVg_plot(self, function, params, ax=None, c=None, linewidth=1, labels=None, points=100, style='', singleLabel=None, offsets=None, T_max=None):
""" Generic plotting function for parameter set of function.
Similar to __fit, requires
"""
if ax is None:
fig, (ax1) = plt.subplots(1,1)
else:
ax1 = ax
#Check if `offset`s exist for each gate voltage. If not generate 0 values.
if offsets is not None:
if len(offsets) != len(self.vg):
raise(AttributeError("There is a mismatch betweeen the number of offsets (" + str(len(offsets)) + ") and the number of voltages (" + str(len(self.vg)) + ")"))
else:
offsets = [0 for vg in self.vg]
# ax1.set_title("Electronic transport")
ax1.set_xlabel("Temperature (K)")
ax1.set_ylabel(self.ylabel)
ax1.tick_params(direction="in")
if T_max is None:
max_t = np.max(self.temps)
else:
max_t = T_max
min_t = np.min(self.temps)
fit_temps = np.linspace(min_t, max_t, points) #Arbitrary 100 plot points to look smooth.
#Reshape inputs: First index is temp, second index is vg
T = np.array([np.array(fit_temps) for i in range(len(self.vg))], dtype=np.longfloat) #Resize temp list for each vg.
VG = np.array([np.array(self.vg) for i in range(len(fit_temps))], dtype=np.longfloat).T #Resize VG list for each temp.
#Reshape inputs into 1D arrays:
T_1D = np.reshape(T, (-1))
VG_1D = np.reshape(VG, (-1))
X = (T_1D, VG_1D)
#Calculate function output
param_resistivity = function(X, *params)
self.last_vg = VG_1D
self.last_T = T_1D
self.last_res = param_resistivity
#Plot result
if c is None:
c = plt.rcParams['axes.prop_cycle'].by_key()['color']
for i in range(len(self.vg)):
c_i = c[i % len(c)]
param_resistivity_subset = param_resistivity[i*len(fit_temps):(i+1)*len(fit_temps)]
if singleLabel is not None:
if i==0:
ax1.plot(fit_temps, param_resistivity_subset - offsets[i], style, linewidth=linewidth, label=str(singleLabel), c=c_i)
else:
ax1.plot(fit_temps, param_resistivity_subset - offsets[i], style, linewidth=linewidth, c=c_i)
else:
if labels is None:
ax1.plot(fit_temps, param_resistivity_subset - offsets[i], style, linewidth=linewidth, label=str(self.vg[i]), c=c_i)
else:
ax1.plot(fit_temps, param_resistivity_subset - offsets[i], style, linewidth=linewidth, label=labels[i], c=c_i)
return
def __fit(temps, vg, data, fit_function, x0, boundsU=None, boundsL=None):
""" Private method to generate a fit to RVT data, not object specific.
Requires 1D arrays of temperature, gate voltage, and a 2D matching array of data.
This function reshapes into a 1D array for T, VG and Data, for the curve fit method to run.
"""
#Reshape inputs: First index is temp, second index is vg
T = np.array([np.array(temps) for i in range(len(vg))], dtype=np.longfloat) #Resize temp list for each vg.
VG = np.array([np.array(vg) for i in range(len(temps))], dtype=np.longfloat).T #Resize VG list for each temp.
#Reshape inputs into 1D arrays:
T_1D = np.reshape(T, (-1))
VG_1D = np.reshape(VG, (-1))
data_1D = np.reshape(data.T, (-1))
#Define warning strings.
tmsg = "Warning: Some temperatures were 'NaN' value; %0.0d datalines have been removed (of total %0.0d)."
vmsg = "Warning: Some voltages were 'NaN' value; %0.0d datalines have been removed (of total %0.0d)."
rmsg = "Warning: Some resistances were 'NaN' value; %0.0d datalines have been removed (of total %0.0d)."
xmsg = "Warning: Some initial params were 'NaN' value; %0.0d param values have been set to initialize at 0 (of total %0.0d params)."
#Find any NaN data in the reshaped input.
nans = np.where(np.isnan(T_1D))[0]
# Remove NaN data
if len(nans) > 0:
T_1D = np.delete(T_1D, nans)
VG_1D = np.delete(VG_1D, nans)
data_1D = np.delete(data_1D, nans)
warnings.warn(tmsg % (len(nans), len(T_1D)))
#Repeat
nans = np.where(np.isnan(VG_1D))[0]
if len(nans) > 0:
T_1D = np.delete(T_1D, nans)
VG_1D = np.delete(VG_1D, nans)
data_1D = np.delete(data_1D, nans)
warnings.warn(vmsg % (len(nans), len(VG_1D)))
#Repeat
nans = np.where(np.isnan(data_1D))[0]
if len(nans) > 0:
T_1D = np.delete(T_1D, nans)
VG_1D = np.delete(VG_1D, nans)
data_1D = np.delete(data_1D, nans)
warnings.warn(rmsg % (len(nans), len(data_1D)))
# Check if nans in x0 as a reuslt too:
nans = np.where(np.isnan(x0))[0]
if len(nans) > 0:
warnings.warn(xmsg % (len(nans), len(x0)))
x0 = np.nan_to_num(x0)
#Now fit data!
params, covar = opt.curve_fit(fit_function, xdata=(T_1D, VG_1D), ydata=np.array(data_1D,dtype=np.longfloat), p0=x0 ,bounds=(boundsL, boundsU))
return params, covar
| nilq/baby-python | python |
import pyautogui
import time
while True:
initial_mouse = pyautogui.position()
time.sleep(0.5)
final_mouse = pyautogui.position()
print(initial_mouse)
print(final_mouse)
if initial_mouse != final_mouse:
pyautogui.hotkey("alt","tab")
else:
exit
| nilq/baby-python | python |
'''
Crie um programa:
Leia o nome de um aluno
leia duas notas do aluno
guarde em uma lista composta
no final mostre:
Um boletim contendo:
A média de cada um
permita que o usuário possa mostrar as notas de cada aluno individualmente
'''
alunos = list()
while True:
nome = str ( input ( 'Qual seu Nome: ' ) )
nota1 = float ( input ( 'Nota 1: ' ) )
nota2 = float ( input ( 'Nota 2: ' ) )
media = (nota1 + nota1) / 2
alunos.append( [ nome, [ nota1, nota2 ], media] )
resp = str ( input ( 'Quer Continuar? [S/N] ' ) )
if resp in 'Nn':
break
print('-=' * 30)
print(f'{"No.":<4} {"NOME":<10} {"Média":>8}')
print('-' * 26)
for indice, aluno in enumerate(alunos):
print(f'{indice:<4} {aluno[0]:<10} {aluno[2]:>8.1f} \n')
print(alunos)
while True:
print('_' * 35)
opcao = int ( input ( 'Mostrar Notas de Qual Aluno? [999 Para Sair]: ' ) )
if opcao == 999:
print('Finalizando...')
break
if opcao <= len(alunos) - 1:
print(f'Notas de {alunos[opcao][0]} são {alunos[opcao][1]}')
| nilq/baby-python | python |
"""
pyTRIS
------
pyTRIS - a simple API wrapper for Highways England's WebTRIS Traffic Flow API.
"""
from .api import API
from . import models
__all__ = ['API']
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
created by huash06 at 2015-04-15 08:45
Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
如果是求不连续的字串
方法1:
令f(i,j)表示s[i:j+1]的最长回文的长度
if s[i]==s[j]:
f(i,j) = f(i+1, j-1)
else:
f(i,j) = max(f(i+1,j), f(i,j-1))
方法2:
反转s得到rs,然后求s和rs的最长公共子串
"""
__author__ = 'huash06'
import sys
import os
import datetime
import functools
import itertools
import collections
class Solution:
# @param s, a string
# @return a string
def longestPalindrome(self, s):
if not s:
return ''
starttime = datetime.datetime.now()
result = s[0]
rlen = 2
for i in range(len(s)):
for j in range(i+rlen+1, len(s)):
if self.isPalindrome(s[i:j]):
if j-i > rlen:
rlen = j-i
result = s[i:j]
print('Time Cost: {}'.format(datetime.datetime.now()-starttime))
return result
def longestPalindrome_byval(self, s):
if not s:
return ''
diff = [0] * len(s)
for i in range(1, len(s)):
diff[i] = s[i]-s[i-1]
count = [0]*len(s)
start = 0
for i in range(len(s)):
count[i] = diff[i]+diff[i-1]
def span(self, s):
"""
比manacher稍微慢点的方法
:param s:
:return:
"""
if not s:
return ''
span = [0] * (len(s) * 2)
for i in range(len(s)):
a, b = i, i
span[a + b] = self.calSpan(s, a, b)
if i < len(s) - 1:
a, b = i, i+1
span[a + b] = self.calSpan(s, a, b)
for plen in range(len(s), 0, -1):
for i in range(len(s)-plen+1):
j = i + plen-1
if self.isPalindrome2(span, i, j):
return s[i: j+1]
return s[0]
def isPalindrome2(self, span, a, b):
return span[a+b] >= b - a
def calSpan(self, s, a, b):
while a >= 0 and b < len(s) and s[a] == s[b]:
a -= 1
b += 1
return b - 1 - (a + 1)
def manacher(self, s):
if not s:
return ''
starttime = datetime.datetime.now()
hs = '$#'
for char in s:
hs += char + '#'
# print(hs)
p = [0] * len(hs)
mx = 0
mid = 0
for i in range(1, len(hs)-1):
if mx > i:
# ---mx'------j------mid------i------mx---
# 以mid为中心的最长回文串的右边部分延伸到mx
# 1. 如果以j为中心的回文的右边延伸到位置jr==j+p[j]+,
# 并且i+p[j]<mx, 可以确定以i为中心的回文字符串至少可以延伸到ir=i+p[j],
# 这是因为[jl:jr] 与 [il:ir]关于mid对称
# ---mx'----jl--j--jr----mid----il--i--ir----mx---
# 2. 通过#1能够确定的i的最长右边界是mx,所以取 min(p[2*mid-i], mx-i)
# 3. 通过#1,#2可以确定以i为中心的回文串至少可以延伸到的位置,然后继续向右
# 查找看是否能够继续延伸
p[i] = min(p[2*mid-i], mx-i)
else:
p[i] = 1
# print(p[i])
# corresponding to #3
while i+p[i] < len(hs) and \
i-p[i] > 0 and \
hs[i+p[i]] == hs[i-p[i]]:
p[i] += 1
# print(p[i])
if p[i] > mx-mid:
mx = p[i]+i
mid = i
# print(' '.join(list(map(str, p))))
# print('mid {} mx {}'.format(mid, mx))
result = ''
for i in range(2*mid-mx+1, mx):
if hs[i] != '#':
result += hs[i]
# print('Time Cost: {}'.format(datetime.datetime.now() - starttime))
return result
def longestPalindrome_dp(self, s):
"""
动态规划求不连续的子序列
:param s:
:return:
"""
if not s:
return ''
starttime = datetime.datetime.now()
dpa = [[1 for c in range(len(s))] for r in range(len(s))]
# dpa = collections.defaultdict(int)
for i in range(len(s)-1):
# dpa[(i, i)] = 1
if s[i] == s[i+1]:
dpa[i][i+1] = 2
# dpa[(i, i+1)] = 2
for gap in range(2, len(s)):
for i in range(len(s)-gap):
j = i+gap
if s[i] == s[j]:
dpa[i][j] = dpa[i+1][j-1]+2
# dpa[(i, j)] = dpa[(i+1, j-1)]+2
else:
dpa[i][j] = max(dpa[i+1][j], dpa[i][j-1])
# dpa[(i, j)] = max(dpa[(i+1, j)], dpa[(i, j-1)])
print('Build String')
result = ''
strlen = dpa[0][len(s)-1]
# strlen = dpa[(0, len(s)-1)]
if strlen <= 1:
return s[0]
l, r = 0, len(s)-1
while l < r:
if dpa[l][r] == strlen and s[l] == s[r]:
# if dpa[(l, r)] == strlen and s[l] == s[r]:
result += s[l]
strlen -= 2
l += 1
r -= 1
elif dpa[l+1][r] == strlen:
# elif dpa[(l+1, r)] == strlen or dpa:
l += 1
elif dpa[l][r-1] == strlen:
# elif dpa.get[(l, r-1)] == strlen:
r -= 1
if l == r:
result += s[l] + ''.join(reversed(result))
else:
result += ''.join(reversed(result))
print('Time Cost: {}'.format(datetime.datetime.now()-starttime))
return result
def isPalindrome(self, s):
if not s:
return True
for i in range(len(s) // 2):
if s[i] != s[len(s)-i-1]:
return False
return True
# sys.stdin = open('input/A-large-practice.in', 'r')
# sys.stdout = open('output/longestPalindrome.txt', 'w')
s = Solution()
# print('===============BRUTAL============')
# print(s.longestPalindrome('zaaaabbbbbaaaacc'))
# print(s.longestPalindrome('ab'))
# print(s.longestPalindrome(''))
# print(s.longestPalindrome("zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir"))
# print(s.longestPalindrome("cyyoacmjwjubfkzrrbvquqkwhsxvmytmjvbborrtoiyotobzjmohpadfrvmxuagbdczsjuekjrmcwyaovpiogspbslcppxojgbfxhtsxmecgqjfuvahzpgprscjwwutwoiksegfreortttdotgxbfkisyakejihfjnrdngkwjxeituomuhmeiesctywhryqtjimwjadhhymydlsmcpycfdzrjhstxddvoqprrjufvihjcsoseltpyuaywgiocfodtylluuikkqkbrdxgjhrqiselmwnpdzdmpsvbfimnoulayqgdiavdgeiilayrafxlgxxtoqskmtixhbyjikfmsmxwribfzeffccczwdwukubopsoxliagenzwkbiveiajfirzvngverrbcwqmryvckvhpiioccmaqoxgmbwenyeyhzhliusupmrgmrcvwmdnniipvztmtklihobbekkgeopgwipihadswbqhzyxqsdgekazdtnamwzbitwfwezhhqznipalmomanbyezapgpxtjhudlcsfqondoiojkqadacnhcgwkhaxmttfebqelkjfigglxjfqegxpcawhpihrxydprdgavxjygfhgpcylpvsfcizkfbqzdnmxdgsjcekvrhesykldgptbeasktkasyuevtxrcrxmiylrlclocldmiwhuizhuaiophykxskufgjbmcmzpogpmyerzovzhqusxzrjcwgsdpcienkizutedcwrmowwolekockvyukyvmeidhjvbkoortjbemevrsquwnjoaikhbkycvvcscyamffbjyvkqkyeavtlkxyrrnsmqohyyqxzgtjdavgwpsgpjhqzttukynonbnnkuqfxgaatpilrrxhcqhfyyextrvqzktcrtrsbimuokxqtsbfkrgoiznhiysfhzspkpvrhtewthpbafmzgchqpgfsuiddjkhnwchpleibavgmuivfiorpteflholmnxdwewj"))
# print(s.longestPalindrome("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg"))
# print(s.longestPalindrome("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"))
print('===============MANACHER============')
print(s.manacher('zaaaabbbbbaaaacc'))
print(s.manacher('ab'))
print(s.manacher(''))
print(s.manacher("zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir"))
print(s.manacher("cyyoacmjwjubfkzrrbvquqkwhsxvmytmjvbborrtoiyotobzjmohpadfrvmxuagbdczsjuekjrmcwyaovpiogspbslcppxojgbfxhtsxmecgqjfuvahzpgprscjwwutwoiksegfreortttdotgxbfkisyakejihfjnrdngkwjxeituomuhmeiesctywhryqtjimwjadhhymydlsmcpycfdzrjhstxddvoqprrjufvihjcsoseltpyuaywgiocfodtylluuikkqkbrdxgjhrqiselmwnpdzdmpsvbfimnoulayqgdiavdgeiilayrafxlgxxtoqskmtixhbyjikfmsmxwribfzeffccczwdwukubopsoxliagenzwkbiveiajfirzvngverrbcwqmryvckvhpiioccmaqoxgmbwenyeyhzhliusupmrgmrcvwmdnniipvztmtklihobbekkgeopgwipihadswbqhzyxqsdgekazdtnamwzbitwfwezhhqznipalmomanbyezapgpxtjhudlcsfqondoiojkqadacnhcgwkhaxmttfebqelkjfigglxjfqegxpcawhpihrxydprdgavxjygfhgpcylpvsfcizkfbqzdnmxdgsjcekvrhesykldgptbeasktkasyuevtxrcrxmiylrlclocldmiwhuizhuaiophykxskufgjbmcmzpogpmyerzovzhqusxzrjcwgsdpcienkizutedcwrmowwolekockvyukyvmeidhjvbkoortjbemevrsquwnjoaikhbkycvvcscyamffbjyvkqkyeavtlkxyrrnsmqohyyqxzgtjdavgwpsgpjhqzttukynonbnnkuqfxgaatpilrrxhcqhfyyextrvqzktcrtrsbimuokxqtsbfkrgoiznhiysfhzspkpvrhtewthpbafmzgchqpgfsuiddjkhnwchpleibavgmuivfiorpteflholmnxdwewj"))
print(s.manacher("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg"))
print(s.manacher("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"))
print(s.manacher("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"))
print('===============SPAN============')
print(s.span('zaaaabbbbbaaaacc'))
print(s.span('ab'))
print(s.span(''))
print(s.span("zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir"))
print(s.span("cyyoacmjwjubfkzrrbvquqkwhsxvmytmjvbborrtoiyotobzjmohpadfrvmxuagbdczsjuekjrmcwyaovpiogspbslcppxojgbfxhtsxmecgqjfuvahzpgprscjwwutwoiksegfreortttdotgxbfkisyakejihfjnrdngkwjxeituomuhmeiesctywhryqtjimwjadhhymydlsmcpycfdzrjhstxddvoqprrjufvihjcsoseltpyuaywgiocfodtylluuikkqkbrdxgjhrqiselmwnpdzdmpsvbfimnoulayqgdiavdgeiilayrafxlgxxtoqskmtixhbyjikfmsmxwribfzeffccczwdwukubopsoxliagenzwkbiveiajfirzvngverrbcwqmryvckvhpiioccmaqoxgmbwenyeyhzhliusupmrgmrcvwmdnniipvztmtklihobbekkgeopgwipihadswbqhzyxqsdgekazdtnamwzbitwfwezhhqznipalmomanbyezapgpxtjhudlcsfqondoiojkqadacnhcgwkhaxmttfebqelkjfigglxjfqegxpcawhpihrxydprdgavxjygfhgpcylpvsfcizkfbqzdnmxdgsjcekvrhesykldgptbeasktkasyuevtxrcrxmiylrlclocldmiwhuizhuaiophykxskufgjbmcmzpogpmyerzovzhqusxzrjcwgsdpcienkizutedcwrmowwolekockvyukyvmeidhjvbkoortjbemevrsquwnjoaikhbkycvvcscyamffbjyvkqkyeavtlkxyrrnsmqohyyqxzgtjdavgwpsgpjhqzttukynonbnnkuqfxgaatpilrrxhcqhfyyextrvqzktcrtrsbimuokxqtsbfkrgoiznhiysfhzspkpvrhtewthpbafmzgchqpgfsuiddjkhnwchpleibavgmuivfiorpteflholmnxdwewj"))
print(s.span("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg"))
print(s.span("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"))
print(s.span("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"))
# print('===============DP============')
# print(s.longestPalindrome_dp('zaaaabbbbbaaaacc'))
# print(s.longestPalindrome_dp('ab'))
# print(s.longestPalindrome_dp(''))
# print(s.longestPalindrome_dp("zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir"))
# print(s.longestPalindrome_dp("cyyoacmjwjubfkzrrbvquqkwhsxvmytmjvbborrtoiyotobzjmohpadfrvmxuagbdczsjuekjrmcwyaovpiogspbslcppxojgbfxhtsxmecgqjfuvahzpgprscjwwutwoiksegfreortttdotgxbfkisyakejihfjnrdngkwjxeituomuhmeiesctywhryqtjimwjadhhymydlsmcpycfdzrjhstxddvoqprrjufvihjcsoseltpyuaywgiocfodtylluuikkqkbrdxgjhrqiselmwnpdzdmpsvbfimnoulayqgdiavdgeiilayrafxlgxxtoqskmtixhbyjikfmsmxwribfzeffccczwdwukubopsoxliagenzwkbiveiajfirzvngverrbcwqmryvckvhpiioccmaqoxgmbwenyeyhzhliusupmrgmrcvwmdnniipvztmtklihobbekkgeopgwipihadswbqhzyxqsdgekazdtnamwzbitwfwezhhqznipalmomanbyezapgpxtjhudlcsfqondoiojkqadacnhcgwkhaxmttfebqelkjfigglxjfqegxpcawhpihrxydprdgavxjygfhgpcylpvsfcizkfbqzdnmxdgsjcekvrhesykldgptbeasktkasyuevtxrcrxmiylrlclocldmiwhuizhuaiophykxskufgjbmcmzpogpmyerzovzhqusxzrjcwgsdpcienkizutedcwrmowwolekockvyukyvmeidhjvbkoortjbemevrsquwnjoaikhbkycvvcscyamffbjyvkqkyeavtlkxyrrnsmqohyyqxzgtjdavgwpsgpjhqzttukynonbnnkuqfxgaatpilrrxhcqhfyyextrvqzktcrtrsbimuokxqtsbfkrgoiznhiysfhzspkpvrhtewthpbafmzgchqpgfsuiddjkhnwchpleibavgmuivfiorpteflholmnxdwewj"))
# print('===============DP MEMO============')
# print(s.longestPalindrome_dpmemo('zaaaabbbbbaaaacc'))
# print(s.longestPalindrome_dpmemo('ab'))
# print(s.longestPalindrome_dpmemo(''))
# print(s.longestPalindrome_dpmemo("zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir"))
# print(s.longestPalindrome_dpmemo("cyyoacmjwjubfkzrrbvquqkwhsxvmytmjvbborrtoiyotobzjmohpadfrvmxuagbdczsjuekjrmcwyaovpiogspbslcppxojgbfxhtsxmecgqjfuvahzpgprscjwwutwoiksegfreortttdotgxbfkisyakejihfjnrdngkwjxeituomuhmeiesctywhryqtjimwjadhhymydlsmcpycfdzrjhstxddvoqprrjufvihjcsoseltpyuaywgiocfodtylluuikkqkbrdxgjhrqiselmwnpdzdmpsvbfimnoulayqgdiavdgeiilayrafxlgxxtoqskmtixhbyjikfmsmxwribfzeffccczwdwukubopsoxliagenzwkbiveiajfirzvngverrbcwqmryvckvhpiioccmaqoxgmbwenyeyhzhliusupmrgmrcvwmdnniipvztmtklihobbekkgeopgwipihadswbqhzyxqsdgekazdtnamwzbitwfwezhhqznipalmomanbyezapgpxtjhudlcsfqondoiojkqadacnhcgwkhaxmttfebqelkjfigglxjfqegxpcawhpihrxydprdgavxjygfhgpcylpvsfcizkfbqzdnmxdgsjcekvrhesykldgptbeasktkasyuevtxrcrxmiylrlclocldmiwhuizhuaiophykxskufgjbmcmzpogpmyerzovzhqusxzrjcwgsdpcienkizutedcwrmowwolekockvyukyvmeidhjvbkoortjbemevrsquwnjoaikhbkycvvcscyamffbjyvkqkyeavtlkxyrrnsmqohyyqxzgtjdavgwpsgpjhqzttukynonbnnkuqfxgaatpilrrxhcqhfyyextrvqzktcrtrsbimuokxqtsbfkrgoiznhiysfhzspkpvrhtewthpbafmzgchqpgfsuiddjkhnwchpleibavgmuivfiorpteflholmnxdwewj"))
| nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 31 13:10:45 2018
@author: aloswain
"""
from datetime import datetime
import backtrader as bt
class SmaCross(bt.SignalStrategy):
def __init__(self):
sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
crossover = bt.ind.CrossOver(sma1, sma2)
self.signal_add(bt.SIGNAL_LONG, crossover)
cerebro = bt.Cerebro()
cerebro.addstrategy(SmaCross)
# **NOTE**: Read the note about the Yahoo API above. This sample is kept for
# historical reasons. Use any other data feed.
data0 = bt.feeds.YahooFinanceData(dataname='BAC', fromdate=datetime(2011, 1, 1),
todate=datetime(2012, 12, 31))
cerebro.adddata(data0)
cerebro.run()
cerebro.plot() | nilq/baby-python | python |
'''
Algoritmo de Prim
1. T ← vazio;
2. V' ← {u};
3. para-todo v E V – V' faça
4. L(v) ← peso ({u,v});
5. fim-para-todo
6. enquanto V' != V faça
7. ache um vértice w tal que L(w) = min {L(v) | v E V-V'};
8. u = o vértice de V', ligado a w, representando a aresta com o menor custo;
9. e = {u,w};
10. T ← T U {e};
11. V'← V' U {w};
12. para-todo v E V – V' faça
13. se peso({v,w}) < L(v) então
14. L(v) ← p({v,w});
15. fim-se
16. fim-para-todo
17. fim-enquanto
'''
import sys
def read_graph():
nodes, edges = map(int, input().split())
# Cria grafo vazio
graph = [[0 for i in range(nodes)] for _ in range(nodes)]
for _ in range(edges):
origin, destiny, weight = map(int, input().split())
# preenche o grafo com os nós -1 para facilitar com indices
graph[origin - 1][destiny - 1] = weight
graph[destiny - 1][origin - 1] = weight
return graph, nodes
# Procura o vertice de menor peso na arvore
def find_min(weights, tree):
aux_min = sys.maxsize
node = -1
# Busca no vetor
for i in range(len(weights)):
# Procura vertice que ainda não esteja na arvore e tenha menor peso
if weights[i] < aux_min and i not in tree:
aux_min = weights[i]
node = i
return node
def prim(graph, nodes):
# Inicializa o vetor de pesos com um valor muito grande
weights = [sys.maxsize for i in range(nodes)]
# Escolhe o ponto inicial e modifica o peso
tree = set()
tree_size = 0
weights[0] = 0
# while len(tree) + 1 < nodes:
while tree_size < nodes:
# acha o vertice de menor peso e adiciona ele a mst
u = find_min(weights, tree)
tree.add(u)
tree_size += 1
# relaxa os vertices
for w in range(nodes):
# o peso será modificado se o nó n estiver na mst
# e se for menor do que o peso já achado
if graph[u][w] != 0 and w not in tree and graph[u][w] < weights[w]:
weights[w] = graph[u][w]
# retorna a soma dos pesos (equivalente ao custo total)
return sum(weights)
#-------------------------------------------------------------------------------
graph, nodes = read_graph()
print(prim(graph, nodes)) | nilq/baby-python | python |
#! /usr/bin/python
from pylab import *
from sys import argv,exit,stdout
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
from scipy import interpolate
import numpy as np
from finite_differences_x import *
from interp import *
def read_EFIT(EFIT_file_name):
EFITdict = {}
f = open(EFIT_file_name,'r')
eqdsk=f.readlines()
line1=eqdsk[0].split()
if len(line1) == 2:
nwnh = eqdsk[0].split()[1]
nw = int(nwnh[0:3])
nh = int(nwnh[3:7])
else:
nw = int(line1[-2])
nh = int(line1[-1])
EFITdict['nw'] = nw #number of grid for Rgrid
EFITdict['nh'] = nh #number of grid for Zgrid
entrylength=16
#note: here rmin is rleft from EFIT
#print(len(eqdsk[1])/entrylength) is not integer
try:
rdim,zdim,rcentr,rleft,zmid = \
[float(eqdsk[1][j*entrylength:(j+1)*entrylength]) \
for j in range(len(eqdsk[1])//entrylength)]
except:
entrylength=15
try:
rdim,zdim,rcentr,rleft,zmid = \
[float(eqdsk[1][j*entrylength:(j+1)*entrylength]) \
for j in range(len(eqdsk[1])//entrylength)]
except:
exit('Error reading EQDSK file, please check format!')
rmaxis,zmaxis,simag,sibry,bcentr = \
[float(eqdsk[2][j*entrylength:(j+1)*entrylength]) \
for j in range(len(eqdsk[2])//entrylength)]
current,simag2,xdum,rmaxis2,xdum = \
[float(eqdsk[3][j*entrylength:(j+1)*entrylength]) \
for j in range(len(eqdsk[3])//entrylength)]
zmaxis2,xdum,sibry2,xdum,xdum = \
[float(eqdsk[4][j*entrylength:(j+1)*entrylength]) \
for j in range(len(eqdsk[4])//entrylength)]
EFITdict['rdim'] = rdim
EFITdict['zdim'] = zdim
EFITdict['rcentr'] = rcentr
EFITdict['rleft'] = rleft
EFITdict['zmid'] = zmid
EFITdict['rmaxis'] = rmaxis # R of magnetic axis (m)
EFITdict['zmaxis'] = zmaxis # Z of magnetic axis (m)
EFITdict['simag'] = simag # poloidal flux at magnetic axis
EFITdict['sibry'] = sibry # poloidal flux at plasma boundary
EFITdict['bcentr'] = bcentr # vacuum toroidal magnetic field in Telsa
EFITdict['current'] = current # plasma current in Ampere
print('EFIT file Resolution: %d x %d' %(EFITdict['nw'],EFITdict['nh']))
print('Horizontal dimension(m): %10.4f' %EFITdict['rdim'])
print('Vertical dimension(m): %10.4f' %EFITdict['zdim'])
print('Minimum R of rectangular grid: %10.4f' %EFITdict['rleft'])
print('(R, Z) of magnetic axis: (%10.4f, %10.4f)' %(EFITdict['rmaxis'],EFITdict['zmaxis']))
print('poloidal flux at magnetic axis in Weber/rad: %10.4f' %EFITdict['simag'])
print('poloidal flux at the plasma boundary in Weber/rad: %10.4f' %EFITdict['sibry'])
print('Vacuum toroidal magnetic field at R = %10.4f: %10.4f Tesla' %(EFITdict['rcentr'],EFITdict['bcentr']))
print('Z of center of rectangular grid: %10.4f' %EFITdict['zmid'])
print('Plasma current: %10.4f Ampere' %EFITdict['current'])
Rgrid = np.linspace(0, 1, nw, endpoint = True) * rdim + rleft
Zgrid = np.linspace(0, 1, nh, endpoint = True) * zdim + (zmid - zdim/2.)
EFITdict['Rgrid'] = Rgrid # Rgrid of psi(Z, R)
EFITdict['Zgrid'] = Zgrid # Zgrid of psi(Z, R)
Fpol = empty(nw, dtype = float)
Pres = empty(nw, dtype = float)
FFprime = empty(nw, dtype = float)
Pprime = empty(nw, dtype = float)
qpsi = empty(nw, dtype = float)
jtor = empty(nw, dtype = float)
# psi_pol is written on uniform (R,Z) grid (res=nw(R)*nh(Z))
psirz_1d = empty(nw * nh, dtype = float)
start_line = 5
wordsInLine = 5
lines=range(nw//wordsInLine)
if nw%wordsInLine!=0: lines=range(nw//wordsInLine+1)
for i in lines:
n_entries=len(eqdsk[i+start_line])//entrylength
Fpol[i*wordsInLine:i*wordsInLine+n_entries] = \
[float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \
for j in range(n_entries)]
start_line=i+start_line+1
EFITdict['Fpol'] = Fpol # poloidal current function F = R * Btor on psipn grid
for i in lines:
n_entries=len(eqdsk[i+start_line])//entrylength
Pres[i*wordsInLine:i*wordsInLine+n_entries] = \
[float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \
for j in range(n_entries)]
start_line=i+start_line+1
EFITdict['Pres'] = Pres # plasma pressure in N / m^2 on psipn grid
for i in lines:
n_entries=len(eqdsk[i+start_line])//entrylength
FFprime[i*wordsInLine:i*wordsInLine+n_entries] = \
[float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \
for j in range(n_entries)]
start_line=i+start_line+1
EFITdict['FFprime'] = FFprime # FFprime on psipn grid
for i in lines:
n_entries=len(eqdsk[i+start_line])//entrylength
Pprime[i*wordsInLine:i*wordsInLine+n_entries] = \
[float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \
for j in range(n_entries)]
start_line=i+start_line+1
EFITdict['Pprime'] = Pprime # Pprime on psipn grid
lines_twod=range(nw*nh//wordsInLine)
if nw*nh%wordsInLine!=0: lines_twod=range(nw*nh//wordsInLine+1)
for i in lines_twod:
n_entries=len(eqdsk[i+start_line])//entrylength
psirz_1d[i*wordsInLine:i*wordsInLine+n_entries] = \
[float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \
for j in range(n_entries)]
start_line=i+start_line+1
psirz=psirz_1d.reshape(nh,nw)
EFITdict['psirz'] = psirz # poloidal flux on the rectangular grid (Rgrid, Zgrid)
for i in lines:
n_entries=len(eqdsk[i+start_line])//entrylength
qpsi[i*wordsInLine:i*wordsInLine+n_entries] = \
[float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \
for j in range(n_entries)]
start_line=i+start_line+1
EFITdict['qpsi'] = qpsi # safety factor on psipn grid
# even grid of psi_pol, on which all 1D fields are defined
psipn = np.linspace(0., 1., nw)
EFITdict['psipn'] = psipn # uniform psipn grid
interpol_order = 3
psip = psipn * (sibry - simag) + simag
q_spl_psi = UnivariateSpline(psip, qpsi, k=interpol_order, s=1e-5)
psi_pol_fine = linspace(psip[0], psip[-1], nw*10)
psi_tor_fine = empty((nw*10),dtype=float)
psi_tor_fine[0] = 0.
for i in range(1, nw * 10):
x = psi_pol_fine[:i+1]
y = q_spl_psi(x)
psi_tor_fine[i] = np.trapz(y,x)
rhot_n_fine = np.sqrt(psi_tor_fine/(psi_tor_fine[-1]-psi_tor_fine[0]))
rho_tor_spl = UnivariateSpline(psi_pol_fine, rhot_n_fine, k=interpol_order, s=1e-5)
rhotn = rho_tor_spl(psip)
EFITdict['rhotn'] = rhotn # square root of toroidal flux on psipn grid
Z0_ind = np.argmin(abs(Zgrid - zmaxis))
R0_ind = np.argmin(abs(Rgrid - rmaxis - 0.02))
R_obmp = Rgrid[R0_ind:]
psirz_obmp = psirz[Z0_ind, R0_ind:]
psipn_obmp = (psirz_obmp - simag) / (sibry - simag)
sepInd = np.argmin(abs(psipn_obmp - 1.))
psipn_obmp = psipn_obmp[:sepInd + 1]
R_obmp = list(R_obmp[:sepInd + 1])
R = interp(psipn_obmp, R_obmp, psipn)
if 1 == 0:
plt.plot(psipn_obmp, R_obmp, label = 'before')
plt.plot(psipn, R, label = 'after')
plt.xlabel('psipn')
plt.ylabel('R')
plt.legend(loc = 2)
plt.show()
EFITdict['R'] = R # major radius (m) on psipn grid
#jtor = rmaxis * Pprime + FFprime / rmaxis
jtor = R * Pprime + FFprime / R
EFITdict['jtor'] = jtor # toroidal current density on psipn grid
#psirz_spl = interpolate.RectBivariateSpline(Zgrid, Rgrid, psirz)
Bp_Z_grid = np.empty(np.shape(psirz))
for i in range(nh):
Bp_Z_grid_this = first_derivative(psirz[i,:].flatten(), Rgrid) / Rgrid
Bp_Z_grid[i,:] = Bp_Z_grid_this.copy()
Bp_R_grid = np.empty(np.shape(psirz))
for i in range(nw):
Bp_R_grid_this = - first_derivative(psirz[:,i].flatten(), Zgrid) / Rgrid[i]
Bp_R_grid[:,i] = Bp_R_grid_this.copy()
#Bp_R_spl = interpolate.RectBivariateSpline(Zgrid, Rgrid, Bp_R_grid)
#Bp_Z_spl = interpolate.RectBivariateSpline(Zgrid, Rgrid, Bp_Z_grid)
Bp_tot_grid = np.sqrt(Bp_R_grid ** 2 + Bp_Z_grid ** 2)
Bp_obmp = Bp_tot_grid[Z0_ind, R0_ind : R0_ind + sepInd + 1]
Bpol = interp(psipn_obmp, Bp_obmp, psipn)
EFITdict['Bpol'] = Bpol # B_pol on psipn grid
F_spl = interpolate.UnivariateSpline(psipn, Fpol)
Btor = F_spl(psipn) / R
EFITdict['Btor'] = abs(Btor) #B_tor on psipn grid
return EFITdict
def magneticShear(EFITdict, show_plots = False):
rhotn = EFITdict['rhotn']
q = EFITdict['qpsi']
#uni_rhot = np.linspace(rhotn[0], rhotn[-1], len(rhotn) * 10)
uni_rhot = np.linspace(rhotn[0], rhotn[-1], len(rhotn))
q_unirhot = interp(rhotn, q, uni_rhot)
shat_unirhot = uni_rhot / q_unirhot * first_derivative(q_unirhot, uni_rhot)
shat = interp(uni_rhot, shat_unirhot, rhotn)
R_unirhot = interp(rhotn, EFITdict['R'], uni_rhot)
Ls_unirhot = q_unirhot * R_unirhot / shat_unirhot
Ls = interp(uni_rhot, Ls_unirhot, rhotn)
if show_plots:
plt.plot(uni_rhot, shat_unirhot)
plt.ylabel('shat')
plt.xlabel('rhot')
plt.axis([0.8, 1., 0., 10.])
plt.show()
plt.plot(uni_rhot, Ls_unirhot)
plt.ylabel('Ls')
plt.xlabel('rhot')
plt.axis([0.8, 1., 0., 2.])
plt.show()
return uni_rhot, shat_unirhot, Ls_unirhot
| nilq/baby-python | python |
# from __future__ import absolute_import
from abstractions.recognition import DistanceEstimator
import numpy
from typing import List
class NumpyDistanceEstimator(DistanceEstimator):
def distance(self,
face_features_we_have : [bytes],
face_feature_to_compare
) -> List[float]:
if len(face_features_we_have) == 0:
return numpy.empty((0))
#todo: there might be a mistake, sometimes for the same picture we get different distances although they should be 0.0
array_we_have = [numpy.frombuffer(face_feature_we_have, dtype=numpy.dtype(float)) for face_feature_we_have in face_features_we_have]
if isinstance(face_feature_to_compare, bytes):
face_feature_to_compare = numpy.frombuffer(face_feature_to_compare, dtype=numpy.dtype(float))
diff_result = numpy.asfarray(array_we_have) - face_feature_to_compare
return numpy.linalg.norm(diff_result, axis=1)
| nilq/baby-python | python |
import json
import os
import random
import sqlite3
import urllib
import requests
from flask import Flask
app = Flask(__name__)
def get_cursor():
connection = sqlite3.connect("database.db")
c = connection.cursor()
return c
USER_ID = 1
def init_db():
c = get_cursor()
c.execute("""
CREATE TABLE IF NOT EXISTS meals (
id integer PRIMARY KEY AUTOINCREMENT NOT NULL,
title text,
available integer,
picture text,
price real,
category integer
)
""")
c.execute("""
CREATE TABLE IF NOT EXISTS promocodes (
id integer PRIMARY KEY,
code text,
discount real
)
""")
c.execute("""
CREATE TABLE IF NOT EXISTS users (
id integer PRIMARY KEY,
promocode text
)
""")
c.execute("""
INSERT INTO meals VALUES (1, "Chicken", 1, "", 20.0, 1)
""")
c.execute("""
INSERT INTO meals VALUES (2, "Milk", 1, "", 10.0, 1)
""")
c.execute("""
INSERT INTO promocodes VALUES (1, "stepik", 30.0)
""")
c.execute("""
INSERT INTO promocodes VALUES (2, "delivery", 20.0)
""")
c.execute("""
INSERT INTO users VALUES (1, null)
""")
c.connection.commit()
c.connection.close()
def fill_database():
"""
See https://www.food2fork.com/
:return:
"""
api_key = "f96f947346e0439bf62117e1c291e685"
key_words = "cake"
c = get_cursor()
for page in range(1, 2):
params = urllib.parse.urlencode({'key': api_key, 'q': key_words, 'page': page})
url_string = "https://www.food2fork.com/api/search?" + params
r = requests.get(url_string)
data = r.json()
for recipe in data['recipes']:
c.execute("""
INSERT INTO meals (title, available, picture, price, category) VALUES (?, ?, ?, ?, ?)
""", [
recipe['title'],
1,
recipe['image_url'],
recipe['social_rank'] + random.randint(0, 100),
1
])
c.connection.commit()
c.connection.close()
@app.route("/promo/<code>")
def promo(code):
c = get_cursor()
c.execute("""
SELECT * FROM promocodes WHERE code = ?
""", (code, ))
result = c.fetchone()
if result is None:
return json.dumps({'valid': False})
promo_id, promo_code, promo_discount = result
c.execute("""
UPDATE users
SET promocode=?
WHERE id = ?
""", (code, USER_ID))
c.connection.commit()
c.connection.close()
return json.dumps({'valid': True, 'discount': promo_discount})
@app.route("/meals")
def meals():
c = get_cursor()
c.execute("""
SELECT discount
FROM promocodes
WHERE code = (
SELECT promocode
FROM users
WHERE id = ?
)
""", (USER_ID,))
result = c.fetchone()
discount = 0
if result is not None:
discount = result[0]
meals = []
for meal_info in c.execute("SELECT * FROM meals"):
meal_id, title, available, picture, price, category = meal_info
meals.append({
'id': meal_id,
'title': title,
'available': bool(available),
'picture': picture,
'price': price * (1.0-discount/100),
'category': category
})
return json.dumps(meals)
if not os.path.exists("database.db"):
init_db()
fill_database()
app.run('0.0.0.0', 8000) | nilq/baby-python | python |
#######################################################################
### Script for Calling Plotting Scripts and Merging the Plots ###
#######################################################################
import sys
current_path = sys.path[0]
ex_op_str = current_path[current_path.index('progs')+6: current_path.index('w2w_ensembleplots')-1]
sys.path.append('/progs/{}'.format(ex_op_str))
from w2w_ensembleplots.core.ensemble_spread_maps import ens_spread_contourplot
from w2w_ensembleplots.core.download_forecast import calc_latest_run_time
from w2w_ensembleplots.core.domain_definitions import get_domain
def main():
model = 'icon-eu-eps'
run = calc_latest_run_time(model)
if run['hour'] == 6 or run['hour'] == 18:
run['hour'] -= 6
#run = dict(year = 2020, month = 10, day = 15, hour = 0)
domains =[]
domains.append(get_domain('EU-Nest'))
variable1 = dict(name='gph_500hPa', unit='gpdm', grid='icosahedral')
variable2 = dict(name='gph_500hPa', unit='gpdm', grid='latlon_0.2')
ens_spread_contourplot(domains, variable1, variable2, model, run)
return
########################################################################
########################################################################
########################################################################
if __name__ == '__main__':
import time
t1 = time.time()
main()
t2 = time.time()
delta_t = t2-t1
if delta_t < 60:
print('total script time: {:.1f}s'.format(delta_t))
elif 60 <= delta_t <= 3600:
print('total script time: {:.0f}min{:.0f}s'.format(delta_t//60, delta_t-delta_t//60*60))
else:
print('total script time: {:.0f}h{:.1f}min'.format(delta_t//3600, (delta_t-delta_t//3600*3600)/60))
| nilq/baby-python | python |
from heapq import heappush, heappop, heapify
import itertools
class Queue:
def __init__(self):
self.q = []
def enqueue(self, element):
self.q.append(element)
def dequeue(self):
return self.q.pop(0)
def is_empty(self):
return len(self.q) == 0
def front(self):
return self.q[0]
class DisjointSets:
def __init__(self, size):
self.parent = [int] * size
self.rank = [int] * size
def make_set(self, x):
self.parent[x] = x
self.rank[x] = 0
def find_set(self, x):
if self.parent[x] != x:
self.parent[x] = self.find_set(self.parent[x])
return self.parent[x]
def union(self, x, y):
xRoot = self.find_set(x)
yRoot = self.find_set(y)
if xRoot != yRoot:
if self.rank[xRoot] < self.rank[yRoot]:
self.parent[xRoot] = yRoot
elif self.rank[xRoot] > self.rank[yRoot]:
self.parent[yRoot] = xRoot
else:
self.parent[yRoot] = xRoot
self.rank[xRoot] += 1
class Heap:
REMOVED = -1
def __init__(self, size):
self.heap = []
self.finder = {}
self.counter = itertools.count()
def add_or_update_item(self, elementIndex, priority=0):
if elementIndex in self.finder:
self.__remove_item(elementIndex)
count = next(self.counter)
entry = [priority, count, elementIndex]
self.finder[elementIndex] = entry
heappush(self.heap, entry)
def extract_min(self):
while self.heap:
(priority, count, elementIndex) = heappop(self.heap)
if elementIndex is not self.REMOVED:
del self.finder[elementIndex]
return elementIndex
raise KeyError("pop from an empty priority queue")
def __remove_item(self, elementIndex):
entry = self.finder.pop(elementIndex)
entry[-1] = self.REMOVED
def key(self, elementIndex):
entry = self.finder[elementIndex]
return self.heap[entry[-1]]
def contains(self, elementIndex):
return elementIndex in self.finder
def is_empty(self):
return len(self.finder) == 0
| nilq/baby-python | python |
# import pytest
# from ..accessor import session
# @pytest.mark.skip(reason="initial run on gh actions (please remove)")
# def test_session():
# """
# tests that a session can be created without error
# """
# with session() as db:
# assert db
| nilq/baby-python | python |
"""
This file builds Tiled Squeeze-and-Excitation(TSE) from paper:
<STiled Squeeze-and-Excite: Channel Attention With Local Spatial Context> --> https://arxiv.org/abs/2107.02145
Created by Kunhong Yu
Date: 2021/07/06
"""
import torch as t
def weights_init(layer):
"""
weights initialization
Args :
--layer: one layer instance
"""
if isinstance(layer, t.nn.Linear) or isinstance(layer, t.nn.BatchNorm1d):
t.nn.init.normal_(layer.weight, 0.0, 0.02) # we use 0.02 as initial value
t.nn.init.constant_(layer.bias, 0.0)
class TSE(t.nn.Module):
"""Define TSE operation"""
"""According to the paper, simple TSE can be implemented by
several 1x1 conv followed by a average pooling with kernel size and stride,
which is simple and effective to verify and to do parameter sharing
In this implementation, column and row pooling kernel sizes are shared!
"""
def __init__(self, num_channels : int, attn_ratio : float, pool_kernel = 7):
"""
Args :
--num_channels: # of input channels
--attn_ratio: hidden size ratio
--pool_kernel: pooling kernel size, default best is 7 according to paper
"""
super().__init__()
self.num_channels = num_channels
self.sigmoid = t.nn.Sigmoid()
self.avg_pool = t.nn.AvgPool2d(kernel_size = pool_kernel, stride = pool_kernel, ceil_mode = True)
self.tse = t.nn.Sequential(
t.nn.Conv2d(self.num_channels, int(self.num_channels * attn_ratio), kernel_size = 1, stride = 1),
t.nn.BatchNorm2d(int(self.num_channels * attn_ratio)),
t.nn.ReLU(inplace = True),
t.nn.Conv2d(int(self.num_channels * attn_ratio), self.num_channels, kernel_size = 1, stride = 1),
t.nn.Sigmoid()
)
self.kernel_size = pool_kernel
def forward(self, x):
"""x has shape [m, C, H, W]"""
_, C, H, W = x.size()
# 1. TSE
y = self.tse(self.avg_pool(x))
# 2. Re-calibrated
y = t.repeat_interleave(y, self.kernel_size, dim = -2)[:, :, :H, :]
y = t.repeat_interleave(y, self.kernel_size, dim = -1)[:, :, :, :W]
return x * y
# unit test
if __name__ == '__main__':
tse = TSE(1024, 0.5, 7)
print(tse)
| nilq/baby-python | python |
from typing import Iterable
from eth2spec.test.context import PHASE0
from eth2spec.test.phase0.genesis import test_initialization, test_validity
from gen_base import gen_runner, gen_typing
from gen_from_tests.gen import generate_from_tests
from eth2spec.phase0 import spec as spec
from importlib import reload
from eth2spec.config import config_util
from eth2spec.utils import bls
def create_provider(handler_name: str, tests_src, config_name: str) -> gen_typing.TestProvider:
def prepare_fn(configs_path: str) -> str:
config_util.prepare_config(configs_path, config_name)
reload(spec)
bls.use_milagro()
return config_name
def cases_fn() -> Iterable[gen_typing.TestCase]:
return generate_from_tests(
runner_name='genesis',
handler_name=handler_name,
src=tests_src,
fork_name=PHASE0,
)
return gen_typing.TestProvider(prepare=prepare_fn, make_cases=cases_fn)
if __name__ == "__main__":
gen_runner.run_generator("genesis", [
create_provider('initialization', test_initialization, 'minimal'),
create_provider('validity', test_validity, 'minimal'),
])
| nilq/baby-python | python |
#!/usr/bin/env python
import os
import sys
import shutil
download_fail_times = 0
pvmp3_path = sys.path[0]
download_path = os.path.join(pvmp3_path, "source")
final_src_path = os.path.join(pvmp3_path, "src")
print('download pvmp3 source file')
if not os.path.exists(final_src_path):
while True:
if not os.path.exists(download_path):
#os.system("git clone https://github.com/aosp-mirror/platform_external_opencore.git -b android-2.2.3_r2.1 " + str(download_path))
os.system("git clone https://gitee.com/mirrors_aosp-mirror/platform_external_opencore.git -b android-2.2.3_r2.1 " + str(download_path))
if os.path.exists(download_path):
print("Download pvmp3 source success!\n")
break
else:
download_fail_times = download_fail_times + 1
if download_fail_times >= 3:
print("Download pvmp3 fail!\n")
break
break
shutil.copytree('source/codecs_v2/audio/mp3/dec/src', 'src')
shutil.copytree('source/codecs_v2/audio/mp3/dec/include', 'include')
n = 0
filelist = os.listdir(final_src_path)
for i in filelist:
oldname = os.path.join(final_src_path, filelist[n])
suffix = oldname.split('.')[-1]
if suffix == 'h' or suffix == 'cpp':
code =''
with open(oldname, 'r') as f:
code = f.read()
code = code.replace('double(', '(double)(')
code = code.replace('int32(', '(int32)(')
code = code.replace('huffcodetab ht[HUFF_TBL];', 'struct huffcodetab ht[HUFF_TBL];')
code = code.replace('huffcodetab *pHuff;', 'struct huffcodetab *pHuff;')
code = code.replace('__inline', 'static inline')
code = code.replace('inline int16 saturate16', 'static int16 saturate16')
code = code.replace('new_slen[4];', 'new_slen[4] = {0,0,0,0};')
with open(oldname, 'w') as f:
f.write(code)
if suffix == 'cpp':
newname = oldname[:-4] + '.c'
os.rename(oldname, newname)
print(oldname,'->', newname)
n = n + 1
shutil.copyfile('oscl_base.h', 'include/oscl_base.h')
shutil.copyfile('oscl_mem.h', 'include/oscl_mem.h')
shutil.rmtree(download_path)
print('Download pvmp3 source file success!')
| nilq/baby-python | python |
import csv
from environs import Env
env = Env()
env.read_env()
fieldnames = ['id', 'nome_da_receita', 'descricao_da_receita']
def listar_receitas():
with open(env('RECEITAS_CSV')) as f:
reader = csv.DictReader(f)
return [receita for receita in reader]
def buscar_receitas(nome):
with open(env('RECEITAS_CSV')) as f:
reader = csv.DictReader(f)
return [receita
for receita in reader
if receita['nome_da_receita'].lower().startswith(nome.lower())
]
def pega_ultimo_id():
receita = {'id': 1}
with open(env('RECEITAS_CSV')) as f:
for receita in csv.DictReader(f):
pass
return int(receita.get('id'))
def verifica_se_receita_existe(nome):
with open(env('RECEITAS_CSV')) as f:
receitas = [receita
for receita in csv.DictReader(f)
if receita.get('nome_da_receita') == nome]
return len(receitas) > 0
def gravar_receita(nome, descricao):
if verifica_se_receita_existe(nome):
return {'status': 409, 'data': "Receita já existe"}
novo_id = pega_ultimo_id() + 1
receita = {
'id': novo_id,
'nome_da_receita': nome,
'descricao_da_receita': descricao
}
with open(env('RECEITAS_CSV'), 'a+') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writerow(receita)
return {'status': 201, 'data': receita}
| nilq/baby-python | python |
from datetime import datetime, timedelta
from pynput.keyboard import Listener as KeyboardListener
from pynput.mouse import Listener as MouseListener
from apis.mongo.mongo_client import log_event, log_processes
from apis.monitoring_details.win32_window_details import active_window_process, all_open_windows
# logging.basicConfig(filename="../window_log.txt", level=logging.DEBUG, format='%(message)s')
MOUSE_MOVE = "MOUSE_MOVE"
MOUSE_CLICK = "MOUSE_CLICK"
MOUSE_SCROLL = "MOUSE_SCROLL"
KEYBOARD_RELEASE = "KEYBOARD_RELEASE"
KEYBOARD_PRESS = "KEYBOARD_PRESS"
event_types = {
KEYBOARD_PRESS: 0,
KEYBOARD_RELEASE: 1,
MOUSE_MOVE: 2,
MOUSE_CLICK: 3,
MOUSE_SCROLL: 4,
}
current_event_type = None
prev_event_type = None
active_window_details = None
active_windows = []
last_time = datetime.utcnow()
min_log_frequency = timedelta(seconds=2)
def set_event_type(event_type_input):
global current_event_type
global last_time
# Determine cause of this event
current_event_type = event_types[event_type_input]
# Do not log if not enough time since last log has elapsed
if last_time + min_log_frequency <= datetime.utcnow():
# Active window details - what is in the foreground
payload = active_window_process()
if payload is not None: # This fails sometimes...
payload['event_type'] = event_type_input
log_event(payload)
# All window details - what is open on the system
log_processes(all_open_windows())
# Update last time a log was made
last_time = datetime.utcnow()
def on_press(key):
# t = Thread(target=set_event_type, args=(KEYBOARD_PRESS,))
# t.start()
set_event_type(KEYBOARD_PRESS)
# print("ON PRESS:", datetime.utcnow())
# log_event(active_window_process())
# logging.info("Key Press: " + str(key))
# print("Key Press: " + str(key))
def on_release(key):
# t = Thread(target=set_event_type, args=(KEYBOARD_RELEASE,))
# t.start()
set_event_type(KEYBOARD_RELEASE)
# print("ON RELEASE:", datetime.utcnow())
# logging.info("Key Press: " + str(key))
# print("Key Press: " + str(key))
def on_move(x, y):
pass
# t = Thread(target=set_event_type, args=(MOUSE_MOVE,))
# t.start()
set_event_type(MOUSE_MOVE)
# print("ON MOVE:", datetime.utcnow())
# log_event(active_window_process())
# time.sleep(5)
# logging.info("Mouse moved to ({0}, {1})".format(x, y))
# print("Mouse moved to ({0}, {1})".format(x, y))
def on_click(x, y, button, pressed):
if pressed:
# t = Thread(target=set_event_type, args=(MOUSE_CLICK,))
# t.start()
set_event_type(MOUSE_CLICK)
# print("ON CLICK:", datetime.utcnow())
# log_event(active_window_process())
# logging.info('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
# print('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
def on_scroll(x, y, dx, dy):
# t = Thread(target=set_event_type, args=(MOUSE_SCROLL,))
# t.start()
set_event_type(MOUSE_SCROLL)
# print("ON SCROLL:", datetime.utcnow())
# log_event(active_window_process())
# logging.info('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))
# print('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))
def start_listeners():
with MouseListener(on_click=on_click, on_scroll=on_scroll, on_move=on_move) as m_listener:
with KeyboardListener(on_press=on_press, on_release=on_release) as k_listener:
m_listener.join()
k_listener.join()
if __name__ == '__main__':
start_listeners()
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# noc.core.snmp.ber tests
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Third-party modules
import pytest
# NOC modules
from noc.core.snmp.ber import BEREncoder, BERDecoder
@pytest.mark.parametrize(
"raw, value",
[
("", 0),
("\x00", 0),
("\x01", 1),
("\x7f", 127),
("\x00\x80", 128),
("\x01\x00", 256),
("\x80", -128),
("\xff\x7f", -129),
],
)
def test_decode_int(raw, value):
decoder = BERDecoder()
assert decoder.parse_int(raw) == value
@pytest.mark.parametrize(
"raw, value",
[
("@", float("+inf")),
("A", float("-inf")),
("\x031E+0", float("1")),
("\x0315E-1", float("1.5")),
],
)
def test_decode_real(raw, value):
decoder = BERDecoder()
assert decoder.parse_real(raw) == value
@pytest.mark.parametrize("raw, value", [("B", float("nan")), ("C", float("-0"))])
def test_decode_real_error(raw, value):
decoder = BERDecoder()
with pytest.raises(Exception):
assert decoder.parse_real(raw) == value
@pytest.mark.xfail()
def test_decode_p_bitstring():
raise NotImplementedError()
@pytest.mark.parametrize("raw, value", [("test", "test"), ("public", "public"), ("", "")])
def test_decode_p_octetstring(raw, value):
decoder = BERDecoder()
assert decoder.parse_p_octetstring(raw) == value
@pytest.mark.xfail()
def test_decode_p_t61_string():
raise NotImplementedError()
@pytest.mark.xfail()
def test_decode_c_octetstring():
raise NotImplementedError()
@pytest.mark.xfail()
def test_decode_c_t61_string():
raise NotImplementedError()
@pytest.mark.parametrize("raw", ["\x00"])
def test_decode_null(raw):
decoder = BERDecoder()
assert decoder.parse_null(raw) is None
@pytest.mark.xfail()
def test_decode_a_ipaddress():
raise NotImplementedError()
@pytest.mark.parametrize("raw, value", [("+\x06\x01\x02\x01\x01\x05\x00", "1.3.6.1.2.1.1.5.0")])
def test_decode_p_oid(raw, value):
decoder = BERDecoder()
assert decoder.parse_p_oid(raw) == value
@pytest.mark.xfail()
def test_decode_compressed_oid():
raise NotImplementedError()
@pytest.mark.xfail()
def test_decode_sequence():
raise NotImplementedError()
@pytest.mark.xfail()
def test_decode_implicit():
raise NotImplementedError()
@pytest.mark.xfail()
def test_decode_set():
raise NotImplementedError()
@pytest.mark.xfail()
def test_decode_utctime():
raise NotImplementedError()
@pytest.mark.parametrize(
"raw,value",
[
("\x9f\x78\x04\x42\xf6\x00\x00", 123.0),
# Opaque
("\x44\x07\x9f\x78\x04\x42\xf6\x00\x00", 123.0),
],
)
def test_decode_float(raw, value):
decoder = BERDecoder()
assert decoder.parse_tlv(raw)[0] == value
@pytest.mark.parametrize(
"raw,value",
[
("\x9f\x79\x08\x40\x5e\xc0\x00\x00\x00\x00\x00", 123.0),
# Opaque
("\x44\x0b\x9f\x79\x08\x40\x5e\xc0\x00\x00\x00\x00\x00", 123.0),
],
)
def test_decode_double(raw, value):
decoder = BERDecoder()
assert decoder.parse_tlv(raw)[0] == value
@pytest.mark.parametrize("raw,value", [("\x44\x81\x06\x04\x04test", "test")])
def test_decode_opaque(raw, value):
decoder = BERDecoder()
assert decoder.parse_tlv(raw)[0] == value
@pytest.mark.xfail()
def test_encode_tlv():
raise NotImplementedError()
@pytest.mark.parametrize(
"raw, value", [("test", "\x04\x04test"), ("public", "\x04\x06public"), ("", "\x04\x00")]
)
def test_encode_octet_string(raw, value):
encoder = BEREncoder()
assert encoder.encode_octet_string(raw) == value
@pytest.mark.xfail()
def test_encode_sequence():
raise NotImplementedError()
@pytest.mark.xfail()
def test_encode_choice():
raise NotImplementedError()
@pytest.mark.parametrize(
"value,raw",
[
(0, "\x02\x01\x00"),
(1, "\x02\x01\x01"),
(127, "\x02\x01\x7f"),
(128, "\x02\x02\x00\x80"),
(256, "\x02\x02\x01\x00"),
(0x2085, "\x02\x02\x20\x85"),
(0x208511, "\x02\x03\x20\x85\x11"),
(-128, "\x02\x01\x80"),
(-129, "\x02\x02\xff\x7f"),
],
)
def test_encode_int(value, raw):
encoder = BEREncoder()
assert encoder.encode_int(value) == raw
@pytest.mark.parametrize(
"raw, value",
[
(float("+inf"), "\t\x01@"),
(float("-inf"), "\t\x01A"),
(float("nan"), "\t\x01B"),
(float("-0"), "\t\x01C"),
(float("1"), "\t\x080x031E+0"),
(float("1.5"), "\t\t0x0315E-1"),
],
)
def test_encode_real(raw, value):
encoder = BEREncoder()
assert encoder.encode_real(raw) == value
@pytest.mark.parametrize("value", ["\x05\x00"])
def test_encode_null(value):
encoder = BEREncoder()
assert encoder.encode_null() == value
@pytest.mark.parametrize(
"oid,raw",
[
("1.3.6.1.2.1.1.5.0", "\x06\x08+\x06\x01\x02\x01\x01\x05\x00"),
("1.3.6.0", "\x06\x03+\x06\x00"),
("1.3.6.127", "\x06\x03+\x06\x7f"),
("1.3.6.128", "\x06\x04+\x06\x81\x00"),
("1.3.6.255", "\x06\x04+\x06\x81\x7f"),
("1.3.6.256", "\x06\x04+\x06\x82\x00"),
("1.3.6.16383", "\x06\x04+\x06\xff\x7f"),
("1.3.6.16384", "\x06\x05+\x06\x81\x80\x00"),
("1.3.6.65535", "\x06\x05+\x06\x83\xff\x7f"),
("1.3.6.65535", "\x06\x05+\x06\x83\xff\x7f"),
("1.3.6.2097151", "\x06\x05+\x06\xff\xff\x7f"),
("1.3.6.2097152", "\x06\x06+\x06\x81\x80\x80\x00"),
("1.3.6.16777215", "\x06\x06+\x06\x87\xff\xff\x7f"),
("1.3.6.268435455", "\x06\x06+\x06\xff\xff\xff\x7f"),
("1.3.6.268435456", "\x06\x07+\x06\x81\x80\x80\x80\x00"),
("1.3.6.2147483647", "\x06\x07+\x06\x87\xff\xff\xff\x7f"),
],
)
def test_encode_oid(oid, raw):
encoder = BEREncoder()
assert encoder.encode_oid(oid) == raw
| nilq/baby-python | python |
import logging
from itertools import cycle, islice
from typing import Callable, List, Optional
import torch
from hypergraph_nets.hypergraphs import (
EDGES,
GLOBALS,
N_EDGE,
N_NODE,
NODES,
RECEIVERS,
SENDERS,
ZERO_PADDING,
HypergraphsTuple,
)
from strips_hgn.hypergraph.hypergraph_view import HypergraphView
_log = logging.getLogger(__name__)
def _validate_features(features, expected_size, label):
"""
Check features conform to expected size. Only support lists for now,
no np.ndarray or torch.Tensor
"""
if features is None:
return
if isinstance(features, torch.Tensor):
assert features.shape[0] == expected_size
else:
raise NotImplementedError(
f"Unexpected features type of {type(features)} for {label}"
)
def repeat_up_to_k(lst, k):
"""
Repeats a list so that it is of length k:
https://stackoverflow.com/a/39863275
e.g. _repeat_up_to_k([1,2,3], 10)
=> [1,2,3,1,2,3,1,2,3,1]
"""
assert k >= len(lst)
return list(islice(cycle(lst), k))
def pad_with_obj_up_to_k(lst, k, pad_with=-1):
"""
Pads a list with an object so resulting length is k
e.g. _pad_with_zeros_up_to_k([1,2,3], 5, 0)
=> [1,2,3,0,0]
"""
assert k >= len(lst)
return lst + (k - len(lst)) * [pad_with]
# noinspection PyArgumentList
def hypergraph_view_to_hypergraphs_tuple(
hypergraph: HypergraphView,
receiver_k: int,
sender_k: int,
node_features: Optional[torch.Tensor] = None,
edge_features: Optional[torch.Tensor] = None,
global_features: Optional[torch.Tensor] = None,
pad_func: Callable[[list, int], list] = pad_with_obj_up_to_k,
) -> HypergraphsTuple:
"""
Convert a Delete-Relaxation Task to a Hypergraphs Tuple (with
node/edge/global features)
:param hypergraph: HypergraphView
:param receiver_k: maximum number of receivers for a hyperedge, receivers will be repeated to fit k
:param sender_k: maximum number of senders for a hyperedge, senders will be repeated to fit k
:param node_features: node features as a torch.Tensor
:param edge_features: edge features as a torch.Tensor
:param global_features: global features as a torch.Tensor
:param pad_func: function for handling different number of sender/receiver nodes
:return: parsed HypergraphsTuple
"""
# Receivers are the additive effects for each action
receivers = torch.LongTensor(
[
pad_func(
[
# FIXME
hypergraph.node_to_idx(atom)
for atom in sorted(hyperedge.receivers)
],
receiver_k,
)
for hyperedge in hypergraph.hyperedges
]
)
# Senders are preconditions for each action
senders = torch.LongTensor(
[
pad_func(
[
# FIXME
hypergraph.node_to_idx(atom)
for atom in sorted(hyperedge.senders)
],
sender_k,
)
for hyperedge in hypergraph.hyperedges
]
)
# Validate features
_validate_features(node_features, len(hypergraph.nodes), "Nodes")
_validate_features(edge_features, len(hypergraph.hyperedges), "Edges")
if global_features is not None:
_validate_features(global_features, len(global_features), "Global")
params = {
N_NODE: torch.LongTensor([len(hypergraph.nodes)]),
N_EDGE: torch.LongTensor([len(hypergraph.hyperedges)]),
# Hyperedge connection information
RECEIVERS: receivers,
SENDERS: senders,
# Features, set to None
NODES: node_features,
EDGES: edge_features,
GLOBALS: global_features,
ZERO_PADDING: pad_func == pad_with_obj_up_to_k,
}
return HypergraphsTuple(**params)
def merge_hypergraphs_tuple(
graphs_tuple_list: List[HypergraphsTuple]
) -> HypergraphsTuple:
"""
Merge multiple HypergraphsTuple (each representing one hypergraph)
together into one - i.e. batch them up
"""
assert len(graphs_tuple_list) > 0
def _stack_features(attr_name, force_matrix=True):
""" Stack matrices on top of each other """
features = [
getattr(h_tup, attr_name)
for h_tup in graphs_tuple_list
if getattr(h_tup, attr_name) is not None
]
if len(features) == 0:
return None
else:
stacked = torch.cat(features)
if force_matrix and len(stacked.shape) == 1:
stacked = stacked.reshape(-1, 1)
return stacked
# New tuple attributes
n_node, n_edge, receivers, senders, nodes, edges, globals_ = (
_stack_features(attr_name, force_matrix)
for attr_name, force_matrix in [
(N_NODE, False),
(N_EDGE, False),
(RECEIVERS, True),
(SENDERS, True),
(NODES, True),
(EDGES, True),
(GLOBALS, True),
]
)
# Check padding consistent across hypergraphs
assert len(set(h.zero_padding for h in graphs_tuple_list)) == 1
zero_padding = graphs_tuple_list[0].zero_padding
# Check general sizes have been maintained
assert len(n_node) == len(n_edge) == len(graphs_tuple_list)
assert receivers.shape[0] == senders.shape[0] == torch.sum(n_edge)
if edges is not None:
assert edges.shape[0] == torch.sum(n_edge)
if nodes is not None:
assert nodes.shape[0] == torch.sum(n_node)
if globals_ is not None:
assert globals_.shape[0] == len(graphs_tuple_list)
return HypergraphsTuple(
**{
N_NODE: n_node,
N_EDGE: n_edge,
# Hyperedge connection information
RECEIVERS: receivers,
SENDERS: senders,
# Features, turn them to tensors
NODES: nodes,
EDGES: edges,
GLOBALS: globals_,
ZERO_PADDING: zero_padding,
}
)
| nilq/baby-python | python |
# Generated by Django 2.2.7 on 2019-12-18 14:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('catalog', '0003_favourite'),
]
operations = [
migrations.AlterField(
model_name='recipe',
name='edit_date',
field=models.DateTimeField(auto_now=True),
),
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('pub_date', models.DateTimeField(auto_now_add=True)),
('text', models.CharField(max_length=250)),
('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='catalog.Recipe')),
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Comment',
'verbose_name_plural': 'Comments',
'ordering': ['-pub_date'],
},
),
]
| nilq/baby-python | python |
# always write to disk
FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.TemporaryFileUploadHandler'
]
STATIC_URL = '/static/'
STATIC_ROOT = '/app/public'
MEDIA_ROOT = '/data'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# compressor
'compressor.finders.CompressorFinder',
)
COMPRESS_PRECOMPILERS = (
('text/less', 'lessc {infile} {outfile}'),
)
COMPRESS_CSS_FILTERS = (
'compressor.filters.css_default.CssAbsoluteFilter',
'compressor.filters.yuglify.YUglifyCSSFilter',
)
| nilq/baby-python | python |
import os
import keras
import random as rn
import numpy as np
import tensorflow as tf
from keras.layers import Dense, Activation, Embedding
from keras.layers import Input, Flatten, dot, concatenate, Dropout
from keras import backend as K
from keras.models import Model
from keras.engine.topology import Layer
from keras import initializers
from TemporalPositionEncoding import PositionalEncoding
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config = config)
K.tensorflow_backend.set_session(sess)
class SurroundingSlots(Layer):
def __init__(self, window_length, max_range, trainable=True, name=None, **kwargs):
super(SurroundingSlots, self).__init__(name=name, trainable=trainable, **kwargs)
self.window_length = window_length
self.max_range = max_range
def build(self, inshape):
1
def call(self, x):
surr = K.cast(x, dtype=tf.int32) + K.arange(start=-self.window_length, stop=self.window_length + 1, step=1)
surrUnderflow = K.cast(surr < 0, dtype=tf.int32)
surrOverflow = K.cast(surr > self.max_range - 1, dtype=tf.int32)
return surr * (-(surrUnderflow + surrOverflow) + 1) + surrUnderflow * (surr + self.max_range) + surrOverflow * (surr - self.max_range)
def compute_output_shape(self, inshape):
return (inshape[0], self.window_length * 2 + 1)
class MATE(Layer):
def __init__(self, dimension, trainable=True, name=None, **kwargs):
super(MATE, self).__init__(name=name, trainable=trainable, **kwargs)
self.dimension = dimension
def build(self, inshape):
# for multiplicative attention
self.W = self.add_weight(name="W", shape=(self.dimension, self.dimension), initializer=initializers.get("random_normal"))
# for personalization
self.Wmonth = self.add_weight(name="Wmonth", shape=(self.dimension, self.dimension), initializer=initializers.get("random_normal"))
self.Wday = self.add_weight(name="Wday", shape=(self.dimension, self.dimension), initializer=initializers.get("random_normal"))
self.Wdate = self.add_weight(name="Wdate", shape=(self.dimension, self.dimension), initializer=initializers.get("random_normal"))
self.Whour = self.add_weight(name="Whour", shape=(self.dimension, self.dimension), initializer=initializers.get("random_normal"))
def call(self, x):
userEmbedding = x[0]
curMonthEmbedding = K.reshape(x[1], shape=(-1, 1, self.dimension))
curDayEmbedding = K.reshape(x[2], shape=(-1, 1, self.dimension))
curDateEmbedding = K.reshape(x[3], shape=(-1, 1, self.dimension))
curHourEmbedding = K.reshape(x[4], shape=(-1, 1, self.dimension))
monthEmbeddings = x[5]
dayEmbeddings = x[6]
dateEmbeddings = x[7]
hourEmbeddings = x[8]
# personalization
curMonthEmbedding = curMonthEmbedding * (K.dot(userEmbedding, self.Wmonth))
curDayEmbedding = curDayEmbedding * (K.dot(userEmbedding, self.Wday))
curDateEmbedding = curDateEmbedding * (K.dot(userEmbedding, self.Wdate))
curHourEmbedding = curHourEmbedding * (K.dot(userEmbedding, self.Whour))
monthEmbeddings = monthEmbeddings * (K.dot(userEmbedding, self.Wmonth))
dayEmbeddings = dayEmbeddings * (K.dot(userEmbedding, self.Wday))
dateEmbeddings = dateEmbeddings * (K.dot(userEmbedding, self.Wdate))
hourEmbeddings = hourEmbeddings * (K.dot(userEmbedding, self.Whour))
# query for gradated attention
monthQ = curMonthEmbedding
dayQ = curDayEmbedding
dateQ = curDateEmbedding
hourQ = curHourEmbedding
# key, value
monthKV = concatenate([monthEmbeddings, curMonthEmbedding], axis=1)
dayKV = concatenate([dayEmbeddings, curDayEmbedding], axis=1)
dateKV = concatenate([dateEmbeddings, curDateEmbedding], axis=1)
hourKV = concatenate([hourEmbeddings, curHourEmbedding], axis=1)
# attention score
monthQKV = K.softmax(K.batch_dot(monthQ, K.permute_dimensions(monthKV, pattern=(0, 2, 1))) / K.sqrt(K.cast(self.dimension, dtype=tf.float32)), axis=-1)
dayQKV = K.softmax(K.batch_dot(dayQ, K.permute_dimensions(dayKV, pattern=(0, 2, 1))) / K.sqrt(K.cast(self.dimension, dtype=tf.float32)), axis=-1)
dateQKV = K.softmax(K.batch_dot(dateQ, K.permute_dimensions(dateKV, pattern=(0, 2, 1))) / K.sqrt(K.cast(self.dimension, dtype=tf.float32)), axis=-1)
hourQKV = K.softmax(K.batch_dot(hourQ, K.permute_dimensions(hourKV, pattern=(0, 2, 1))) / K.sqrt(K.cast(self.dimension, dtype=tf.float32)), axis=-1)
# embedding for each granularity of period information
monthEmbedding = K.batch_dot(monthQKV, monthKV)
dayEmbedding = K.batch_dot(dayQKV, dayKV)
dateEmbedding = K.batch_dot(dateQKV, dateKV)
hourEmbedding = K.batch_dot(hourQKV, hourKV)
# multiplicative attention
q = userEmbedding
kv = K.concatenate([monthEmbedding, dayEmbedding, dateEmbedding, hourEmbedding], axis=1)
qW = K.dot(q, self.W)
a = K.sigmoid(K.batch_dot(qW, K.permute_dimensions(kv, pattern=(0, 2, 1))))
timeRepresentation = K.batch_dot(a, kv)
return timeRepresentation
def compute_output_shape(self, inshape):
return (None, 1, self.dimension)
class TAHE(Layer):
def __init__(self, dimension, trainable=True, name=None, **kwargs):
super(TAHE, self).__init__(name=name, trainable=trainable, **kwargs)
self.dimension = dimension
def build(self, inshape):
1
def call(self, x):
recentTimeRepresentations = x[0]
curTimeRepresentation = x[1]
recentTimestamps = x[2]
recentItemEmbeddings = x[3]
# previous timestamp == 0 ==> no history
mask = K.cast(recentTimestamps > 0, dtype=tf.float32)
# time-based attention
similarity = K.batch_dot(K.l2_normalize(curTimeRepresentation, axis=-1), K.permute_dimensions(K.l2_normalize(recentTimeRepresentations, axis=-1), pattern=(0, 2, 1)))
masked_similarity = mask * ((similarity + 1.0) / 2.0)
weightedPrevItemEmbeddings = K.batch_dot(masked_similarity, recentItemEmbeddings)
userHistoryRepresentation = weightedPrevItemEmbeddings
return userHistoryRepresentation
def compute_output_shape(self, inshape):
return (None, self.dimension)
class meanLayer(Layer):
def __init__(self, trainable=True, name=None, **kwargs):
super(meanLayer, self).__init__(name=name, trainable=trainable, **kwargs)
def build(self, inshape):
1
def call(self, x):
return K.mean(x, axis=1, keepdims=True)
def compute_output_shape(self, inshape):
return (inshape[0], 1, inshape[2])
class Slice(Layer):
def __init__(self, index, trainable=True, name=None, **kwargs):
super(Slice, self).__init__(name=name, trainable=trainable, **kwargs)
self.index = index
def build(self, inshape):
1
def call(self, x):
return x[:, self.index, :]
def compute_output_shape(self, inshape):
return (inshape[0], inshape[2])
class TemporalPositionEncoding(Layer):
def __init__(self, trainable=True, name=None, **kwargs):
super(TemporalPositionEncoding, self).__init__(name=name, trainable=trainable, **kwargs)
def build(self, inshape):
self.a = self.add_weight(name="a", shape=(1, ), initializer=initializers.get("ones"))
def call(self, x):
item = x[0]
time = x[1]
return item + time * self.a
def compute_output_shape(self, inshape):
return inshape[0]
def TimelyRec(input_shape, num_users, num_items, embedding_size, sequence_length, width, depth, dropout=None):
userInput = Input(shape=[1], dtype=tf.int32)
itemInput = Input(shape=[1], dtype=tf.int32)
monthInput = Input(shape=[1], dtype=tf.int32)
dayInput = Input(shape=[1], dtype=tf.int32)
dateInput = Input(shape=[1], dtype=tf.int32)
hourInput = Input(shape=[1], dtype=tf.int32)
curTimestampInput = Input(shape=[1], dtype=tf.int32)
recentMonthInput = []
recentDayInput = []
recentDateInput = []
recentHourInput = []
recentTimestampInput = []
recentItemidInput = []
for i in range(sequence_length):
recentMonthInput.append(Input(shape=[1], dtype=tf.int32))
for i in range(sequence_length):
recentDayInput.append(Input(shape=[1], dtype=tf.int32))
for i in range(sequence_length):
recentDateInput.append(Input(shape=[1], dtype=tf.int32))
for i in range(sequence_length):
recentHourInput.append(Input(shape=[1], dtype=tf.int32))
for i in range(sequence_length):
recentTimestampInput.append(Input(shape=[1], dtype=tf.int32))
for i in range(sequence_length):
recentItemidInput.append(Input(shape=[1], dtype=tf.int32))
userEmbedding = Embedding(num_users+1, embedding_size)(userInput)
itemEmbeddingSet = Embedding(num_items+1, embedding_size)
itemEmbedding = itemEmbeddingSet(itemInput)
recentItemEmbeddings = itemEmbeddingSet(concatenate(recentItemidInput, axis=-1))
recentTimestamps = concatenate(recentTimestampInput, axis=-1)
monthEmbedding = Embedding(12, embedding_size)
dayEmbedding = Embedding(7, embedding_size)
dateEmbedding = Embedding(31, embedding_size)
hourEmbedding = Embedding(24, embedding_size)
curMonthEmbedding = monthEmbedding(monthInput)
curDayEmbedding = dayEmbedding(dayInput)
curDateEmbedding = dateEmbedding(dateInput)
curHourEmbedding = hourEmbedding(hourInput)
recentMonthEmbeddings = monthEmbedding(concatenate(recentMonthInput, axis=-1))
recentDayEmbeddings = dayEmbedding(concatenate(recentDayInput, axis=-1))
recentDateEmbeddings = dateEmbedding(concatenate(recentDateInput, axis=-1))
recentHourEmbeddings = hourEmbedding(concatenate(recentHourInput, axis=-1))
monthEmbeddings = []
dayEmbeddings = []
dateEmbeddings = []
hourEmbeddings = []
prevMonthEmbeddings = []
prevDayEmbeddings = []
prevDateEmbeddings = []
prevHourEmbeddings = []
ratio = 0.2
for i in range(sequence_length):
prevMonthEmbeddings.append([])
for j in range(1, max(int(12 * ratio + 0.5), 1) + 1):
monthSurr = monthEmbedding(SurroundingSlots(window_length=j, max_range=12)(recentMonthInput[i]))
prevMonthEmbeddings[i].append(meanLayer()(monthSurr))
prevDayEmbeddings.append([])
for j in range(1, max(int(7 * ratio + 0.5), 1) + 1):
daySurr = dayEmbedding(SurroundingSlots(window_length=j, max_range=7)(recentDayInput[i]))
prevDayEmbeddings[i].append(meanLayer()(daySurr))
prevDateEmbeddings.append([])
for j in range(1, max(int(31 * ratio + 0.5), 1) + 1):
dateSurr = dateEmbedding(SurroundingSlots(window_length=j, max_range=31)(recentDateInput[i]))
prevDateEmbeddings[i].append(meanLayer()(dateSurr))
prevHourEmbeddings.append([])
for j in range(1, max(int(24 * ratio + 0.5), 1) + 1):
hourSurr = hourEmbedding(SurroundingSlots(window_length=j, max_range=24)(recentHourInput[i]))
prevHourEmbeddings[i].append(meanLayer()(hourSurr))
for i in range(1, max(int(12 * ratio + 0.5), 1) + 1):
monthSurr = monthEmbedding(SurroundingSlots(window_length=i, max_range=12)(monthInput))
monthEmbeddings.append(meanLayer()(monthSurr))
for i in range(1, max(int(7 * ratio + 0.5), 1) + 1):
daySurr = dayEmbedding(SurroundingSlots(window_length=i, max_range=7)(dayInput))
dayEmbeddings.append(meanLayer()(daySurr))
for i in range(1, max(int(31 * ratio + 0.5), 1) + 1):
dateSurr = dateEmbedding(SurroundingSlots(window_length=i, max_range=31)(dateInput))
dateEmbeddings.append(meanLayer()(dateSurr))
for i in range(1, max(int(24 * ratio + 0.5), 1) + 1):
hourSurr = hourEmbedding(SurroundingSlots(window_length=i, max_range=24)(hourInput))
hourEmbeddings.append(meanLayer()(hourSurr))
if int(12 * ratio + 0.5) <= 1:
monthEmbeddings = monthEmbeddings[0]
for i in range(sequence_length):
prevMonthEmbeddings[i] = prevMonthEmbeddings[i][0]
else:
monthEmbeddings = concatenate(monthEmbeddings, axis=1)
for i in range(sequence_length):
prevMonthEmbeddings[i] = concatenate(prevMonthEmbeddings[i], axis=1)
if int(7 * ratio + 0.5) <= 1:
dayEmbeddings = dayEmbeddings[0]
for i in range(sequence_length):
prevDayEmbeddings[i] = prevDayEmbeddings[i][0]
else:
dayEmbeddings = concatenate(dayEmbeddings, axis=1)
for i in range(sequence_length):
prevDayEmbeddings[i] = concatenate(prevDayEmbeddings[i], axis=1)
if int(31 * ratio + 0.5) <= 1:
dateEmbeddings = dateEmbeddings[0]
for i in range(sequence_length):
prevDateEmbeddings[i] = prevDateEmbeddings[i][0]
else:
dateEmbeddings = concatenate(dateEmbeddings, axis=1)
for i in range(sequence_length):
prevDateEmbeddings[i] = concatenate(prevDateEmbeddings[i], axis=1)
if int(24 * ratio + 0.5) <= 1:
hourEmbeddings = hourEmbeddings[0]
for i in range(sequence_length):
prevHourEmbeddings[i] = prevHourEmbeddings[i][0]
else:
hourEmbeddings = concatenate(hourEmbeddings, axis=1)
for i in range(sequence_length):
prevHourEmbeddings[i] = concatenate(prevHourEmbeddings[i], axis=1)
recentTimestampTEs = PositionalEncoding(output_dim=embedding_size)(recentTimestamps)
curTimestampTE = PositionalEncoding(output_dim=embedding_size)(curTimestampInput)
# temporal position encoding
te = TemporalPositionEncoding()
itemEmbedding = te([itemEmbedding, curTimestampTE])
recentItemEmbeddings = te([recentItemEmbeddings, recentTimestampTEs])
userVector = Flatten()(userEmbedding)
itemVector = Flatten()(itemEmbedding)
curTimestampTE = Flatten()(curTimestampTE)
# MATE
curTimeRepresentation = Flatten()(MATE(embedding_size)([userEmbedding, curMonthEmbedding, curDayEmbedding, curDateEmbedding, curHourEmbedding, monthEmbeddings, dayEmbeddings, dateEmbeddings, hourEmbeddings])) # None * embedding_size
prevTimeRepresentations = []
for i in range(sequence_length):
prevTimeRepresentations.append(MATE(embedding_size)([userEmbedding, Slice(i)(recentMonthEmbeddings), Slice(i)(recentDayEmbeddings), Slice(i)(recentDateEmbeddings), Slice(i)(recentHourEmbeddings), prevMonthEmbeddings[i], prevDayEmbeddings[i], prevDateEmbeddings[i], prevHourEmbeddings[i]])) # None * embedding_size)
prevTimeRepresentations = concatenate(prevTimeRepresentations, axis=1)
# TAHE
userHistoryRepresentation = TAHE(embedding_size)([prevTimeRepresentations, curTimeRepresentation, recentTimestamps, recentItemEmbeddings])
# combination
x = concatenate([userVector, itemVector, curTimeRepresentation, userHistoryRepresentation])
in_shape = embedding_size * 4
for i in range(depth):
if i == depth - 1:
x = Dense(1, input_shape=(in_shape,))(x)
else:
x = Dense(width, input_shape=(in_shape,))(x)
x = Activation('relu')(x)
if dropout is not None:
x = Dropout(dropout)(x)
in_shape = width
outputs = Activation('sigmoid')(x)
model = Model(inputs=[userInput, itemInput, monthInput, dayInput, dateInput, hourInput, curTimestampInput] + [recentMonthInput[i] for i in range(sequence_length)] + [recentDayInput[i] for i in range(sequence_length)] + [recentDateInput[i] for i in range(sequence_length)] + [recentHourInput[i] for i in range(sequence_length)] + [recentTimestampInput[i] for i in range(sequence_length)] + [recentItemidInput[i] for i in range(sequence_length)], outputs=outputs)
return model | nilq/baby-python | python |
from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd
import unidecode as udc
import scipy
class CustomOneHotEncoder(BaseEstimator, TransformerMixin):
"""
Clase que convierte a dummies las variables categóricas de un dataFrame. Permite eliminar
las dummies creadas según su representación.
:param X: DataFrame sobre el que se van a realizar los cambios.
:param categorical_columns: Lista de las variables categóricas para transformar.
:param features_not_drop: Lista de las variables categóricas que se transforman pero de las que no
queremos eliminar las columnas resultantes según su representación.
:param threshold: Valor númerico entre 0 y 1 que indica el punto de corte para eliminar las dummies
según representación. Se corta según el % de 0 que contiene la columna. Todas las
columnas con un % de 0s mayor que el threshold indicado son eliminadas.
:param sparse_matrix: Bool. Si es True el transformador devuelve una SparseMatrix. Por defecto
False y devuelve un DataFrame
:return: Devuelve el DataFrame o SparseMatrix modificado con las nuevas dummies.
"""
def __init__(self, categorical_columns, features_not_drop, threshold, sparse_matrix = False):
super().__init__()
self.categorical_columns = categorical_columns
self.threshold = threshold
self.features_not_drop = features_not_drop
self.sparse_matrix = sparse_matrix
self.columns_to_drop_ = list()
def fit(self, X, y=None):
X_ = X.copy()
# Dummies para las categóricas
X__ = pd.get_dummies(X_, drop_first = False)
# Se marcan las columnas que se van a borrar
for feat in self.categorical_columns:
X__.rename(columns=lambda x:
udc.unidecode(x.replace(feat, 'oneHotEncoder_' + feat)),
inplace = True)
for feat in self.features_not_drop:
X__.rename(columns=lambda x:
udc.unidecode(x.replace('oneHotEncoder_' + feat, 'oneHotEncoderX_' + feat)),
inplace = True)
# Se seleccionan las columnas del OneHot con representación 'threshold'
for feat in X__.columns:
try:
if ((X__[feat].value_counts(normalize = True)[0] > self.threshold) & ('oneHotEncoder_' in feat)):
self.columns_to_drop_.append(feat)
except:
pass
return self
def transform(self, X, y=None):
X_ = X.copy()
X__ = pd.get_dummies(X_, drop_first = False)
for feat in self.categorical_columns:
X__.rename(columns=lambda x:
udc.unidecode(x.replace(feat, 'oneHotEncoder_' + feat)),
inplace = True)
# Se eliminan las columnas seleccionadas del dataframe
for col in self.columns_to_drop_:
try:
X__.drop(columns= col, inplace = True)
except:
pass
# Se eliminan caracteres de los column_names no admitidos por el modelo
X__.rename(columns=lambda x: udc.unidecode(x.replace("]", ")")), inplace = True)
if self.sparse_matrix:
X__ = scipy.sparse.csr_matrix(X__.values)
return X__ | nilq/baby-python | python |
# -*- coding: utf-8 -*-
###########################################################
# #
# Copyright (c) 2018 Radek Augustýn, licensed under MIT. #
# #
###########################################################
__author__ = "radek.augustyn@email.cz"
# @PRODUCTION MODULE [Full]
from base import fileRead
templates = { }
def registerTemplate(templateName, fileName, content = None):
templates[templateName] = (fileName, content)
templates["sample"] = (None, 'ahoj<div id="mojeTestId"><p class="caption">Moje Caption</p><p class="shortDescription">Moje shortDescription</p><p class="description">Moje dDescription</p></div>')
def getTemplate(name):
"""Returns HTML template content. For the first time in a given template it reads data from the file.
:param String name: Name of the template.
:return String: Template HTML content.
>>> print getTemplate("sample")
ahoj<div id="mojeTestId"><p class="caption">Moje Caption</p><p class="shortDescription">Moje shortDescription</p><p class="description">Moje dDescription</p></div>
"""
if name in templates:
fileName, content = templates[name]
if not content:
content = fileRead(fileName)
registerTemplate(name, fileName, content)
return content
else:
return ""
def getHtmlDiv(templateName, identifier):
"""Extracts content of the html DIV element with given id. There must not be another div inside.
:param String templateName: Name of the template in the templates list.
:param String identifier: Id of the selected DIV element.
:return String: Content of DIV element with given id.
>>> getHtmlDiv("sample", "mojeTestId")
'<p id="caption">Moje Caption</p><p id="shortDescription">Moje shortDescription</p><p id="description">Moje dDescription</p>'
"""
html = getTemplate(templateName)
startPos = html.find('<div id="%s"' % identifier)
startPos = html.find(">", startPos)
endPos = html.find('</div>', startPos)
if startPos >= 0 and endPos >= 0:
return html[startPos+1:endPos]
else:
return ""
def getHtmlItems(templateName, identifier):
"""
:param templateName:
:param identifier:
:return:
>>> getHtmlItems("sample", "mojeTestId")
{'caption': 'Moje Caption', 'shortDescription': 'Moje shortDescription', 'description': 'Moje dDescription'}
"""
result = {}
divContent = getHtmlDiv(templateName, identifier)
for paragraph in divContent.split("</p>"):
paragraph = paragraph.strip()
if paragraph and paragraph.startswith("<p"):
classNameStart = paragraph.find('class="') + 7
classNameEnd = paragraph.find('"', classNameStart)
className = paragraph[classNameStart:classNameEnd]
content = paragraph[paragraph.find(">") + 1:]
result[className] = content
return result
def setAttrsFromHTML(obj, templateName, identifier):
"""
:param obj:
:param templateName:
:param identifier:
:return:
>>> class A:pass
>>> a = A
>>> setAttrsFromHTML(a, "sample", "mojeTestId")
>>> a.caption
"""
for key, value in getHtmlItems(templateName, identifier).iteritems():
setattr(obj, key, value)
class HTMLFormatter:
def __init__(self):
self.html = ""
self._indent = 0
self.indentStr = ""
def add(self, str):
self.html += str
def addLine(self, str):
for i in range(self._indent):
str = "\t" + str
self.add(str + "\n")
def addLineAndIndent(self, str):
self.addLine(str)
self.indent()
def unIndentAndAddLine(self, str):
self.unIndent()
self.addLine(str)
def indent(self, count = 1):
self._indent = self._indent + count
def unIndent(self, count = 1):
self._indent = self._indent - count
if self._indent < 0 :
self._indent = 0 | nilq/baby-python | python |
"""
Check if 2 strings are anagrams of each other
"""
from collections import Counter
def check_anagrams(str1, str2):
ctr1 = Counter(str1)
ctr2 = Counter(str2)
return ctr1 == ctr2
def check_anagrams_version2(str1, str2):
hmap1 = [0] * 26
hmap2 = [0] * 26
for char in str1:
pos = ord(char) - ord("a")
hmap1[pos] += 1
for char in str2:
pos = ord(char) - ord("a")
hmap2[pos] += 1
return hmap1 == hmap2
if __name__ == "__main__":
str1 = "apple"
str2 = "pleap"
op = check_anagrams(str1, str2)
print(op)
| nilq/baby-python | python |
import sys
import os
#reference = sys.argv[1]
#os.system("cp "+reference+" "+sys.argv[4])
firstfile = sys.argv[1] #sys.argv[1]
secondfile = sys.argv[2]
thirdfile = sys.argv[3]
seq1 = set()
seq2 = set()
file3 = open(thirdfile, 'r')
for line in file3:
myline = line.strip()
seqnames = myline.split('\t')
seq1.add(seqnames[0])
seq2.add(seqnames[1])
lines1 = []
file1 = open(firstfile, 'r')
for line in file1:
myline = line.strip()
if (myline[0] == '>'):
#contents = myline.split('\w')
#myseq = contents[0][1:]
myseq = myline[1:myline.find(' ')]
if (myseq in seq1):
lines1.append(myline)
lines1.append(file1.readline().strip())
lines2 = []
file2 = open(secondfile, 'r')
for line in file2:
myline = line.strip()
if (myline[0] == '>'):
myseq = myline[1:myline.find(' ')]
if (myseq in seq2):
lines2.append(myline)
lines2.append(file2.readline().strip())
fourthfile = open(firstfile, 'w')
#fifthfile = open(sys.argv[2], 'w')
for line in lines1:
fourthfile.write(line+"\n")
#for line in lines2:
# fifthfile.write(line+"\n")
| nilq/baby-python | python |
class TicTacToe():
'''
Game of Tic-Tac-Toe
rules reference: https://en.wikipedia.org/wiki/Tic-tac-toe
'''
# coordinates of the cells for each possible line
lines = [ [(0,0), (0,1), (0,2)],
[(1,0), (1,1), (1,2)],
[(2,0), (2,1), (2,2)],
[(0,0), (1,0), (2,0)],
[(0,1), (1,1), (2,1)],
[(0,2), (1,2), (2,2)],
[(0,0), (1,1), (2,2)],
[(0,2), (1,1), (2,0)]
]
def __init__(self):
# 3x3 board, 0 = empty, 1 = occupied by player 1, 2 = occupied by player 2
self.board = [[0 for y in range(self.rows())] for x in range(self.cols())]
self.current_player = 1
def rows(self):
return 3
def cols(self):
return 3
# for display : width and height of a cell when displaying the game
def cell_size(self):
return 80, 80
# for display: label for cell at coordinates (x, y)
def get_label(self, x, y):
s = self.board[x][y]
if s == 0:
return ""
elif s == 1:
return "O"
elif s == 2:
return "X"
# a move by a player is valid if the cell is empty
def is_valid_play(self, move, player):
x, y = move
return self.board[x][y] == 0
# update the board with the move from a player
def play(self, move, player):
x, y = move
self.board[x][y] = player
# update the current_player
self.current_player = 2 if self.current_player == 1 else 1
def get_current_player(self):
return self.current_player
# return -1 if the game is not finished, 0 if draw, 1 or 2 if one of the player wins
def winner(self):
for line in TicTacToe.lines:
a, b, c = line
if self.board[a[0]][a[1]] != 0 and \
self.board[a[0]][a[1]] == self.board[b[0]][b[1]] == self.board[c[0]][c[1]]:
# one of the player won, return the player id (1 or 2)
return self.board[a[0]][a[1]]
# no player has won yet, check for a draw
for x in range(3):
for y in range(3):
if self.board[x][y] == 0:
# play still possible, game not finished
return -1
# no play is possible anymore, this is a draw
return 0
| nilq/baby-python | python |
import cv2
import numpy as np
# Read image
img = cv2.imread("imori.jpg")
# Dicrease color
out = img.copy()
out = out // 64 * 64 + 32
cv2.imwrite("out.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
| nilq/baby-python | python |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import collections.abc
import json
import typing
from azure.functions import _sql as sql
from . import meta
class SqlConverter(meta.InConverter, meta.OutConverter,
binding='sql'):
@classmethod
def check_input_type_annotation(cls, pytype: type) -> bool:
return issubclass(pytype, sql.SqlRowList)
@classmethod
def check_output_type_annotation(cls, pytype: type) -> bool:
return issubclass(pytype, (sql.SqlRowList, sql.SqlRow))
@classmethod
def decode(cls,
data: meta.Datum,
*,
trigger_metadata) -> typing.Optional[sql.SqlRowList]:
if data is None or data.type is None:
return None
data_type = data.type
if data_type in ['string', 'json']:
body = data.value
elif data_type == 'bytes':
body = data.value.decode('utf-8')
else:
raise NotImplementedError(
f'Unsupported payload type: {data_type}')
rows = json.loads(body)
if not isinstance(rows, list):
rows = [rows]
return sql.SqlRowList(
(None if row is None else sql.SqlRow.from_dict(row))
for row in rows)
@classmethod
def encode(cls, obj: typing.Any, *,
expected_type: typing.Optional[type]) -> meta.Datum:
if isinstance(obj, sql.SqlRow):
data = sql.SqlRowList([obj])
elif isinstance(obj, sql.SqlRowList):
data = obj
elif isinstance(obj, collections.abc.Iterable):
data = sql.SqlRowList()
for row in obj:
if not isinstance(row, sql.SqlRow):
raise NotImplementedError(
f'Unsupported list type: {type(obj)}, \
lists must contain SqlRow objects')
else:
data.append(row)
else:
raise NotImplementedError(f'Unsupported type: {type(obj)}')
return meta.Datum(
type='json',
value=json.dumps([dict(d) for d in data])
)
| nilq/baby-python | python |
'''
This program parses a txt file containing proteins to analyse with IUPRED/BLAST/JALVIEW
'''
import warnings # allows program to be able to ignore benign warnings
#####
# IGNORE WARNINGS
#####
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
import requests
import csv # allows for csv r/w
import pandas as pd # allows for csv r/w
import json
import mechanize
import webbrowser
import time
import collections # allows orderedDict
from selenium import webdriver # for web browser interation/headless browser
from bs4 import BeautifulSoup
import glob
import os.path
import datetime
import urllib2
# Also Using PhantomJS installed via npm (included with NodeJS)
#########################################
############WORKING FUNCTIONS############
#########################################
def parseDataSet(fileName='FruitiData.txt'):
'''
Parses original dataSet containing the amino acid sequences of the maternal transcription factors we're interested in.
Takes in file name as string
Outputs:
1. orderdDict
2. list of dict keys
3. list of dict vals
Can call function and set global variable equal to one or all of
the dataTypes/Sets that this outputs.
Example:
variable = parseDataSet()[1]
This would result in variable being equal to list of all keys in dict
created.
'''
# open dataset text file > create var == to each line as list
fList = open(fileName).readlines()
# convert list to dictionary
fDict = collections.OrderedDict() # creates empty orderedDict
##fDict = {}
dictVal = '' # empty string to hold dictVals
dictKey = '' # empty string to hold dictKeys
length = len(fList)
for line in xrange(0, length):
#print('inside for')
#print('line: ' + str(line))
if(line % 2 == 0): # if zero or even > use as key
#print('inside if1')
dictKey = str(fList[line]).replace('\n', '')
if(line % 2 != 0): # if odd > use as value
#print('inside if2')
dictVal = str(fList[line]).replace('\n', '')
if(dictKey != '' and dictVal != ''):
#print('inside if3')
fDict.update({dictKey: dictVal})
dictKey = dictVal = ''
listFDictKeys = fDict.keys() # saves dict keys as list
listFDictVals = fDict.values() # saves dict vals as list
# testing prints
# print(fDict)
# print(listFDictVals)
return fDict, listFDictKeys, listFDictVals
# creates timestamp
def timeStamp():
'''
returns list = ['mmddyy','hh:mm:ss','Weekday']
'''
# ts = time.gmtime()
ts = time.localtime()
ts2 = time.strftime('%m%d%y,%H:%M:%S,%d%m%y-%H%M%S,%A', ts)
ts2 = ts2.split(',')
return ts2
###############################################
############TESTING BELOW THIS LINE############
###############################################
# creates a csv to write to, add headers row
def csvCreate(listX, listY, csvName='preIupred.csv'):
'''
Takes in listFDictKeys, listFDictVals
'''
f = csv.writer(open(csvName, 'w'), delimiter=',', lineterminator='\n')
# f.writerow(['iupred2', 'meta', 'seqence', 'anchor2'])
f.writerow(['mmddyy', 'hh:mm:ss', 'Key', 'Value', 'example1', 'example2', 'example3'])
for i in xrange(len(listX)):
f.writerow((timeStamp()[0], timeStamp()[1], listX[i], listY[i]))
# using 'csv' library open csv > updates specific cell
def csvUpdate():
'''
1. Opens preIupred.csv (r)
2. Opens preIupred.csv (w)
3. Writes over header names
4.
'''
# read csv file into 'fooReader'
fooReader = csv.reader(open('preIupred.csv', 'rb'), delimiter=',', lineterminator='\n')
f = csv.writer(open('preIupred.csv', 'w'), delimiter=',', lineterminator='\n')
f.writerow(['mmddyy', 'hh:mm:ss', 'Key', 'Value', 'example1', 'example2', 'example3'])
input = '>Mnt 64.001883 0.822785'
# read each row in 'fooReader'
for row in fooReader:
# define first row column as 'value' for testing
key = row[2]
# test if value (1st column) is the same as input (user input)
if key == input:
#... if it is then print the 5th column in a certain way
f.writerow(('FUCKOFF-ITWORKED', '', '', '', '', '', 'hello'))
#print('this is where the beat drops!')
'''
# f.writerow(['iupred2', 'meta', 'seqence', 'anchor2']) #OLD HEADER NAMES, MIGHT USE THEM AGAIN, JUST HERE TO SAVE EM
# f.writerow(['mmddyy', 'hh:mm:ss', 'Key', 'Value', 'example1', 'example2', 'example3'])
for i in xrange(5):
f.writerow(('FUCKOFF-ITWORKED', '', '', '', '', '', 'hello'))
'''
# using pandas - update csv file at cell level
def csvUpdate2():
'''
Pandas Cheatsheet:
import pandas as pd
#Open csv and set to var:
df = pd.read_csv('preIupred.csv')
#Select single cell by row/column:
df.iloc([0], [0])
OR
df.iat([0], [0])
#Select single cell by row and column label
df.loc([0], ['COLUMN-HEADER-NAME'])
OR
df.at([0], ['COLUMN-HEADER-NAME'])
#Select single cell by row and column label
df.ix[0, 'COLUMN-HEADER-NAME']
'''
pd.options.display.max_colwidth = 1000 # sets max string length to display
df = pd.read_csv('preIupred.csv') # load csv to var 'df'
df['example1'] # focuses on column with header 'example1'
match = df['example1'].str.contains('>Mnt 64.001883 0.822785')
#print('match: ' + str(match))
shell = df['Value'][match]
# print(df)
# print(df['Key'][match].value_counts())
# df.set_value(5, 'example1', 'USEFUL-DATA') #updates value of cell at row 5 + header 'Value' to 'CHANGED'
#df.to_csv('preIupred.csv', index=False)
# creates list holding URLs to visit
def urlCreate():
pages = [] # empty list to hold URLs to visit
# create list of urls to visit
for i in xrange(1, 2):
url = 'https://iupred2a.elte.hu/'
# is missing other types of scenarios
pages.append(url)
'''
# opens each URL > sets var to html > sets var to cleaned up html
for item in pages:
page = requests.get(item)
soup = BeautifulSoup(page.text, 'html.parser')
# print(soup)
'''
# Demo function
def demo(txtName='FruitiData.txt', csvName='preIupred.csv', dateApndOpt=1):
if(csvName[-4:] == '.csv'):
if(dateApndOpt == 1):
csvNameTime = csvName[:-4] + '_' + timeStamp()[2] + '.csv'
else:
csvNameTime = csvName[:-4] + '.csv'
else:
if(dateApndOpt == 1):
csvNameTime = csvName + '_' + timeStamp()[2] + '.csv'
else:
csvNameTime = csvName + '.csv'
listD, listX, listY = parseDataSet(txtName) # this parses data from file txtName, can insert different file name within same directory
'''
1. Calls function to parse data set from FruitiData.txt then saves/outputs as ordered dict
2. Calls function that takes parsed data from step one and then saves it to a csv 'collectData1.csv'
'''
csvCreate(listX, listY, csvNameTime) # this takes in vars from 'parseDataSet()' > creates/writes to csv
# csvUpdate()
# csvUpdate2()
# csvUpdate() # uncomment to continue testing this
# csvUpdate2() # updates csv at cell level using pandas (seems best method)
# demo() # uncomment to run main program
def blastParse(fileName='PFK3E0EY015-Alignment.json', jalName='jalViewFile.fa'):
with open(fileName) as json_file:
data = json.load(json_file)
# print(type(data))
# print(json.dumps(data, indent=2)) #pretty printed
# for i in xrange(10):
# print(data['BlastOutput2'][0]['report']['results']['search']['hits'][2]['hsps'][i])
# print('')
# print('')
dictHolder = {}
iterMain = data['BlastOutput2'][0]['report']['results']['search']['hits']
f = open(jalName, 'w')
f.write('')
fl = open(jalName, 'a')
for i in xrange(4):
print '#########################'
for item in xrange(len(iterMain)):
subject = data['BlastOutput2'][0]['report']['results']['search']['hits'][item]['hsps']
title = data['BlastOutput2'][0]['report']['results']['search']['hits'][item]['description'][0]['title']
sciName = str(data['BlastOutput2'][0]['report']['results']['search']['hits'][item]['description'][0]['sciname'])
dictHolder[sciName] = dictHolder.get(sciName, 0) + 1
if(dictHolder[sciName] == 1):
fl.write('\n' + '> ' + sciName)
print("title: " + str(title))
print("sciname: " + str(sciName))
subHolder = ''
for i in xrange(len(subject)):
subHolder += str(subject[i]['hseq'])
print("index: " + str(i) + " subject: " + str(subject[i]['hseq']))
print("subjectFull: " + str(subHolder))
fl.write('\n' + str(subHolder))
print('\n\n')
print(dictHolder)
fl.close()
# print data['BlastOutput2'][0]['report']['results']['search']['hits'][0]['description'][0]['title']
# fList = open(fileName).readlines()
# print fList
'''
# open dataset text file > create var == to each line as list
fList = open(fileName).readlines()
# convert list to dictionary
fDict = collections.OrderedDict() # creates empty orderedDict
##fDict = {}
dictVal = '' # empty string to hold dictVals
dictKey = '' # empty string to hold dictKeys
length = len(fList)
for line in xrange(0, length):
#print('inside for')
#print('line: ' + str(line))
if(line % 2 == 0): # if zero or even > use as key
#print('inside if1')
dictKey = str(fList[line]).replace('\n', '')
if(line % 2 != 0): # if odd > use as value
#print('inside if2')
dictVal = str(fList[line]).replace('\n', '')
if(dictKey != '' and dictVal != ''):
#print('inside if3')
fDict.update({dictKey: dictVal})
dictKey = dictVal = ''
listFDictKeys = fDict.keys() # saves dict keys as list
listFDictVals = fDict.values() # saves dict vals as list
# testing prints
# print(fDict)
# print(listFDictVals)
return fDict, listFDictKeys, listFDictVals
'''
def openDownloads():
list_of_files = glob.glob("C:/Users/SJCCRAC/Documents/Python Code") # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print list_of_files
print latest_file
# blastParse() #runs blastParse function
def downloadUrl():
print('Beginning file download with urllib2...')
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi?RESULTS_FILE=on&RID=P09YHPX0014&FORMAT_TYPE=JSON2_S&FORMAT_OBJECT=Alignment&CMD=Get'
filedata = urllib2.urlopen(url)
datatowrite = filedata.read()
with open('/Users/SJCCRAC/Documents/Python Code/testDownload.json', 'wb') as f:
f.write(datatowrite)
print(datatowrite)
# openDownloads() # tests openDownloads() functions
# downloadUrl()
demo('7_proteins.txt', 'preIupred.csv', 1) # (txtName='FruitiData.txt', csvName='preIupred.csv', apndDate[1=yes, 0=no])
'''
Parses original formatted amino acid sequence data
Outputs is to csv file that you specify, default = 'preIupred.csv'
'''
| nilq/baby-python | python |
from typing import TYPE_CHECKING
from UE4Parse.BinaryReader import BinaryStream
from UE4Parse.Provider.Common import GameFile
if TYPE_CHECKING:
from UE4Parse.IO import FFileIoStoreReader
from UE4Parse.IO.IoObjects.FIoChunkId import FIoChunkId
from UE4Parse.IO.IoObjects.FIoOffsetAndLength import FIoOffsetAndLength
class FIoStoreEntry(GameFile):
__slots__ = ("UserData",)
UserData: int
def CompressionMethodString(self) -> str:
return "COMPRESS_" + self.Container.TocResource.CompressionMethods[
self.CompressionMethodIndex - 1] if self.CompressionMethodIndex > 0 else "COMPRESS_None"
@property
def Offset(self) -> int:
return self.OffsetLength.GetOffset
@property
def Length(self) -> int:
return self.OffsetLength.GetLength
@property
def ContainerName(self) -> str:
return self.Container.FileName[:-5] + ".utoc"
@property
def Encrypted(self) -> bool:
return self.Container.TocResource.Header.is_encrypted()
@property
def OffsetLength(self) -> 'FIoOffsetAndLength':
return self.Container.Toc[self.ChunkId]
@property
def ChunkId(self) -> 'FIoChunkId':
return self.Container.TocResource.ChunkIds[self.UserData]
def __init__(self, io_store, userdata: int, name: str):
super().__init__()
self.Container = io_store
self.UserData = userdata
self.Name = name.lower() if io_store.caseinSensitive else name
# compressionBlockSize = ioStore.TocResource.Header.CompressionBlockSize
# firstBlockIndex = int(self.Offset / compressionBlockSize) - 1
# lastBlockIndex = int((Align(self.Offset + self.Length, compressionBlockSize) - 1) / compressionBlockSize)
# for i in range(firstBlockIndex, lastBlockIndex):
# compressionBlock = ioStore.TocResource.CompressionBlocks[i]
# self.UncompressedSize += compressionBlock.UncompressedSize
# self.CompressionMethodIndex = compressionBlock.CompressionMethodIndex
#
# rawSize = Align(compressionBlock.CompressedSize, 16)
# self.Size += rawSize
#
# if ioStore.TocResource.Header.is_encrypted():
# self.Encrypted = True
def get_data(self) -> BinaryStream:
return self.Container.Read(self.ChunkId)
| nilq/baby-python | python |
# Copyright 2014 The Crashpad Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
{
'includes': [
'../build/crashpad.gypi',
],
'targets': [
{
'target_name': 'crashpad_snapshot_test_lib',
'type': 'static_library',
'dependencies': [
'snapshot.gyp:crashpad_snapshot',
'../compat/compat.gyp:crashpad_compat',
'../third_party/mini_chromium/mini_chromium.gyp:base',
'../util/util.gyp:crashpad_util',
],
'include_dirs': [
'..',
],
'sources': [
'test/test_cpu_context.cc',
'test/test_cpu_context.h',
'test/test_exception_snapshot.cc',
'test/test_exception_snapshot.h',
'test/test_memory_snapshot.cc',
'test/test_memory_snapshot.h',
'test/test_module_snapshot.cc',
'test/test_module_snapshot.h',
'test/test_process_snapshot.cc',
'test/test_process_snapshot.h',
'test/test_system_snapshot.cc',
'test/test_system_snapshot.h',
'test/test_thread_snapshot.cc',
'test/test_thread_snapshot.h',
],
},
{
'target_name': 'crashpad_snapshot_test',
'type': 'executable',
'dependencies': [
'crashpad_snapshot_test_module',
'snapshot.gyp:crashpad_snapshot',
'../client/client.gyp:crashpad_client',
'../compat/compat.gyp:crashpad_compat',
'../test/test.gyp:crashpad_test',
'../third_party/gtest/gtest.gyp:gtest',
'../third_party/gtest/gtest.gyp:gtest_main',
'../third_party/mini_chromium/mini_chromium.gyp:base',
'../util/util.gyp:crashpad_util',
],
'include_dirs': [
'..',
],
'sources': [
'cpu_context_test.cc',
'crashpad_info_client_options_test.cc',
'mac/cpu_context_mac_test.cc',
'mac/mach_o_image_annotations_reader_test.cc',
'mac/mach_o_image_reader_test.cc',
'mac/mach_o_image_segment_reader_test.cc',
'mac/process_reader_test.cc',
'mac/process_types_test.cc',
'mac/system_snapshot_mac_test.cc',
'minidump/process_snapshot_minidump_test.cc',
'win/pe_image_annotations_reader_test.cc',
'win/process_reader_win_test.cc',
'win/system_snapshot_win_test.cc',
],
'conditions': [
['OS=="mac"', {
'link_settings': {
'libraries': [
'$(SDKROOT)/System/Library/Frameworks/OpenCL.framework',
],
},
}],
],
},
{
'target_name': 'crashpad_snapshot_test_module',
'type': 'loadable_module',
'dependencies': [
'../client/client.gyp:crashpad_client',
'../third_party/mini_chromium/mini_chromium.gyp:base',
],
'include_dirs': [
'..',
],
'sources': [
'crashpad_info_client_options_test_module.cc',
],
},
],
}
| nilq/baby-python | python |
import unittest
import numpy as np
import tensorflow as tf
from pplp.core import box_4c_encoder
class Box4cEncoderTest(unittest.TestCase):
def test_np_box_3d_to_box_4c(self):
# Test non-vectorized numpy version on ortho boxes
# Sideways box
box_3d_1 = np.asarray([0, 0, 0, 2, 1, 5, 0])
# Straight box
box_3d_2 = np.asarray([0, 0, 0, 2, 1, 5, -np.pi / 2])
# Ground plane facing upwards, at 2m along y axis
ground_plane = [0, -1, 0, 2]
exp_box_4c_1 = np.asarray(
[1.0, 1.0, -1.0, -1.0,
0.5, -0.5, -0.5, 0.5,
2.0, 7.0])
exp_box_4c_2 = np.asarray(
[0.5, 0.5, -0.5, -0.5,
1.0, -1.0, -1.0, 1.0,
2.0, 7.0])
# Convert box_3d to box_4c
box_4c_1 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_1, ground_plane)
box_4c_2 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_2, ground_plane)
np.testing.assert_almost_equal(box_4c_1, exp_box_4c_1, decimal=3)
np.testing.assert_almost_equal(box_4c_2, exp_box_4c_2, decimal=3)
def test_np_box_3d_to_box_4c_rotated_translated(self):
# Test non-vectorized numpy version on rotated boxes
box_3d_1 = np.asarray([0.0, 0.0, 0.0, 2.0, 1.0, 5.0, -1 * np.pi / 8])
box_3d_2 = np.asarray([0.0, 0.0, 0.0, 2.0, 1.0, 5.0, -3 * np.pi / 8])
box_3d_3 = np.asarray([0.0, 0.0, 0.0, 2.0, 1.0, 5.0, -5 * np.pi / 8])
box_3d_4 = np.asarray([0.0, 0.0, 0.0, 2.0, 1.0, 5.0, -7 * np.pi / 8])
box_3d_5 = np.asarray([0.0, 0.0, 0.0, 2.0, 1.0, 5.0, 1 * np.pi / 8])
box_3d_6 = np.asarray([0.0, 0.0, 0.0, 2.0, 1.0, 5.0, 3 * np.pi / 8])
box_3d_7 = np.asarray([0.0, 0.0, 0.0, 2.0, 1.0, 5.0, 5 * np.pi / 8])
box_3d_8 = np.asarray([0.0, 0.0, 0.0, 2.0, 1.0, 5.0, 7 * np.pi / 8])
# Also test a box translated along xz
box_3d_translated = box_3d_1 + [10, 0, 10, 0, 0, 0, 0]
# Ground plane facing upwards, at 2m along y axis
ground_plane = [0, -1, 0, 2]
# Convert box_3d to box_4c
box_4c_1 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_1, ground_plane)
box_4c_2 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_2, ground_plane)
box_4c_3 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_3, ground_plane)
box_4c_4 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_4, ground_plane)
box_4c_5 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_5, ground_plane)
box_4c_6 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_6, ground_plane)
box_4c_7 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_7, ground_plane)
box_4c_8 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_8, ground_plane)
box_4c_translated = box_4c_encoder.np_box_3d_to_box_4c(
box_3d_translated, ground_plane)
# Expected boxes_4c
exp_box_4c_1 = [0.733, 1.115, -0.733, -1.115,
0.845, -0.079, -0.845, 0.079,
2.000, 7.000]
exp_box_4c_2 = [0.845, 0.079, -0.845, -0.079,
0.733, -1.115, -0.733, 1.115,
2.000, 7.000]
exp_box_4c_3 = [0.079, 0.845, -0.079, -0.845,
1.115, -0.733, -1.115, 0.733,
2.000, 7.000]
exp_box_4c_4 = [1.115, 0.733, -1.115, -0.733,
0.079, -0.845, -0.079, 0.845,
2.000, 7.000]
exp_box_4c_5 = [1.115, 0.733, -1.115, -0.733,
0.079, -0.845, -0.079, 0.845,
2.000, 7.000]
exp_box_4c_6 = [0.079, 0.845, -0.079, -0.845,
1.115, -0.733, -1.115, 0.733,
2.000, 7.000]
exp_box_4c_7 = [0.845, 0.079, -0.845, -0.079,
0.733, -1.115, -0.733, 1.115,
2.000, 7.000]
exp_box_4c_8 = [0.733, 1.115, -0.733, -1.115,
0.845, -0.079, -0.845, 0.079,
2.000, 7.000]
exp_box_4c_translated = [10.733, 11.115, 9.267, 8.885,
10.845, 9.921, 9.155, 10.079,
2.000, 7.000]
np.testing.assert_almost_equal(box_4c_1, exp_box_4c_1, decimal=3)
np.testing.assert_almost_equal(box_4c_2, exp_box_4c_2, decimal=3)
np.testing.assert_almost_equal(box_4c_3, exp_box_4c_3, decimal=3)
np.testing.assert_almost_equal(box_4c_4, exp_box_4c_4, decimal=3)
np.testing.assert_almost_equal(box_4c_5, exp_box_4c_5, decimal=3)
np.testing.assert_almost_equal(box_4c_6, exp_box_4c_6, decimal=3)
np.testing.assert_almost_equal(box_4c_7, exp_box_4c_7, decimal=3)
np.testing.assert_almost_equal(box_4c_8, exp_box_4c_8, decimal=3)
np.testing.assert_almost_equal(box_4c_translated,
exp_box_4c_translated, decimal=3)
def test_np_box_3d_to_box_4c_heights(self):
# Boxes above, on, or below ground plane
box_3d_1 = np.asarray([0.0, 3.0, 0.0, 2.0, 1.0, 5.0, 0.0]) # below
box_3d_2 = np.asarray([0.0, 2.0, 0.0, 2.0, 1.0, 5.0, 0.0]) # on
box_3d_3 = np.asarray([0.0, 1.0, 0.0, 2.0, 1.0, 5.0, 0.0]) # above
# Ground plane facing upwards, at 2m along y axis
ground_plane = [0, -1, 0, 2]
# Convert box_3d to box_4c
box_4c_1 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_1, ground_plane)
box_4c_2 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_2, ground_plane)
box_4c_3 = box_4c_encoder.np_box_3d_to_box_4c(box_3d_3, ground_plane)
# Expected boxes_4c
exp_box_4c_1 = np.asarray([1.0, 1.0, -1.0, -1.0,
0.5, -0.5, -0.5, 0.5,
-1.0, 4.0])
exp_box_4c_2 = np.asarray([1.0, 1.0, -1.0, -1.0,
0.5, -0.5, -0.5, 0.5,
0.0, 5.0])
exp_box_4c_3 = np.asarray([1.0, 1.0, -1.0, -1.0,
0.5, -0.5, -0.5, 0.5,
1.0, 6.0])
np.testing.assert_almost_equal(box_4c_1, exp_box_4c_1)
np.testing.assert_almost_equal(box_4c_2, exp_box_4c_2)
np.testing.assert_almost_equal(box_4c_3, exp_box_4c_3)
def test_tf_box_3d_to_box_4c(self):
# Test that tf version matches np version
# (rotations, xz translation, heights)
boxes_3d = np.asarray([
# Rotated
[0.0, 0.0, 0.0, 2.0, 1.0, 5.0, -1 * np.pi / 8],
[0.0, 0.0, 0.0, 2.0, 1.0, 5.0, -3 * np.pi / 8],
[0.0, 0.0, 0.0, 2.0, 1.0, 5.0, -5 * np.pi / 8],
[0.0, 0.0, 0.0, 2.0, 1.0, 5.0, -7 * np.pi / 8],
[0.0, 0.0, 0.0, 2.0, 1.0, 5.0, 1 * np.pi / 8],
[0.0, 0.0, 0.0, 2.0, 1.0, 5.0, 3 * np.pi / 8],
[0.0, 0.0, 0.0, 2.0, 1.0, 5.0, 5 * np.pi / 8],
[0.0, 0.0, 0.0, 2.0, 1.0, 5.0, 7 * np.pi / 8],
# Translated along xz
[10, 0, 5, 2, 1, 5, - 1 * np.pi / 8],
# Below, on, or above ground plane
[0.0, 3.0, 0.0, 2.0, 1.0, 5.0, 0.0],
[0.0, 2.0, 0.0, 2.0, 1.0, 5.0, 0.0],
[0.0, 1.0, 0.0, 2.0, 1.0, 5.0, 0.0],
])
# Ground plane facing upwards, at 2m along y axis
ground_plane = [0, -1, 0, 2]
# Numpy conversion box_3d to box_4c
np_boxes_4c = np.asarray(
[box_4c_encoder.np_box_3d_to_box_4c(box_3d, ground_plane)
for box_3d in boxes_3d])
# Convert to tensors
tf_boxes_3d = tf.convert_to_tensor(boxes_3d, dtype=tf.float32)
tf_ground_plane = tf.convert_to_tensor(ground_plane, dtype=tf.float32)
# Tensorflow conversion box_3d to box_4c
tf_boxes_4c = box_4c_encoder.tf_box_3d_to_box_4c(tf_boxes_3d,
tf_ground_plane)
sess = tf.Session()
with sess.as_default():
tf_boxes_4c_out = tf_boxes_4c.eval()
# Loop through to show a separate error when box doesn't match
for box_idx in range(len(np_boxes_4c)):
np.testing.assert_almost_equal(np_boxes_4c[box_idx],
tf_boxes_4c_out[box_idx],
decimal=5)
def test_np_box_4c_to_box_3d(self):
box_4c_1 = np.asarray([1.0, 0.0, -1.0, 0.5,
0.5, -1.0, 0.0, 1.0,
1.0, 3.0])
box_4c_2 = np.asarray([1.0, 0.0, -1.0, -0.5,
0.0, -1.0, 0.5, 1.0,
1.0, 3.0])
ground_plane = np.asarray([0, -1, 0, 2])
box_3d_1 = box_4c_encoder.np_box_4c_to_box_3d(box_4c_1, ground_plane)
box_3d_2 = box_4c_encoder.np_box_4c_to_box_3d(box_4c_2, ground_plane)
# Expected boxes_3d
exp_box_3d_1 = [0.125, 1.000, 0.125, 1.768, 1.414, 2.000, -0.785]
exp_box_3d_2 = [-0.125, 1.000, 0.125, 1.768, 1.414, 2.000, 0.785]
np.testing.assert_almost_equal(box_3d_1, exp_box_3d_1, decimal=3)
np.testing.assert_almost_equal(box_3d_2, exp_box_3d_2, decimal=3)
def test_tf_box_4c_to_box_3d(self):
np_boxes_4c = np.asarray(
[
[1.0, 0.0, -1.0, 0.5, 0.5, -1.0, 0.0, 1.0, 1.0, 3.0],
[1.0, 0.0, -1.0, -0.5, 0.0, -1.0, 0.5, 1.0, 1.0, 3.0],
[1.0, 0.0, -1.0, -0.5, 0.0, -1.0, 0.5, 1.0, 1.0, 3.0],
[1.0, 0.0, -1.0, -0.5, 0.0, -1.0, 0.5, 1.0, 1.0, 3.0],
[1.0, 0.0, -1.0, -0.5, 0.0, -1.0, 0.5, 1.0, 1.0, 3.0],
])
np_ground_plane = np.asarray([0, -1, 0, -1])
np_boxes_3d = [box_4c_encoder.np_box_4c_to_box_3d(box_4c,
np_ground_plane)
for box_4c in np_boxes_4c]
tf_boxes_4c = tf.convert_to_tensor(np_boxes_4c,
dtype=tf.float32)
tf_ground_plane = tf.convert_to_tensor(np_ground_plane,
dtype=tf.float32)
tf_boxes_3d = box_4c_encoder.tf_box_4c_to_box_3d(tf_boxes_4c,
tf_ground_plane)
sess = tf.Session()
with sess.as_default():
tf_boxes_3d_out = tf_boxes_3d.eval()
for box_idx in range(len(np_boxes_3d)):
np.testing.assert_almost_equal(np_boxes_3d[box_idx],
tf_boxes_3d_out[box_idx],
decimal=3)
| nilq/baby-python | python |
from .xml_style import XMLDataset
class VOCDataset(XMLDataset):
CLASSES = ['spike']
def __init__(self, **kwargs):
super(VOCDataset, self).__init__(**kwargs)
| nilq/baby-python | python |
#!/usr/bin/env python
from .web_api_2 import SwaggerGiant | nilq/baby-python | python |
import os, paramiko, time, schedule, smtplib, ssl
from datetime import datetime
from email.message import EmailMessage
host='localhost'
port='5432'
user='postgres'
password='admin'
database='testdb'
#chemin de sauvegarde locale
local_dir = 'C:\\Users\\Kamla\\projets\\auto-backup-sqldb\\backup\\'
#local_dir = 'Chemin vers le dossier de la base de donnees a sauvegarder\\'
#chemin de sauvegarde distant
remote_dir = '/C:/Users/vmwin10/Documents/ftpfile/'
def job():
print("Backup working...")
filestamp = time.strftime('%Y-%m-%dT%H-%M-%S.%z')
#nom pour le fichier sql qui serra genere par pg_dump
database_remote = database+"_"+filestamp+".bak.sql"
PASS="set PGPASSWORD=%s" % (password)
#lancement de la commande mysqldump qui va faire une sauvegarde en local
#les fichiers sont sauvegarder dans le respertoire 'backup'
os.system("(cd backup) && ("+PASS+") && (pg_dump -h %s -p %s -U %s -f %s -C -d %s)" % (host, port, user, database_remote, database))
print("Database dumped to "+database_remote)
# debut du SFTP
ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#on se connecte a la machine dans laquelle serra sauvegarde le le fichier backup
ssh_client.connect(hostname='192.168.126.2',username='vmwin10',password='vmwin10')
ftp_client=ssh_client.open_sftp()
#envoie du fichier local vers le remote
ftp_client.put(local_dir+database_remote,remote_dir+database_remote)
ftp_client.close()
print("Successfull Backup")
# A chaque backup un email est envoye
msg = EmailMessage()
msg.set_content("Un backup vient d'etre effectue")
msg["Subject"] = "Email de Backup"
msg["From"] = "ksb.cmr@gmail.com"
msg["To"] = "test@mail.com"
context=ssl.create_default_context()
with smtplib.SMTP("smtp.gmail.com", port=587) as smtp:
smtp.starttls(context=context)
smtp.login(msg["From"], "password")
smtp.send_message(msg)
# le backup se fait chaque 1h
schedule.every(3).seconds.do(job)
#schedule.every(15).minutes.do(job)
#schedule.every().hour.do(job)
#schedule.every().day.at("10:30").do(job)
#schedule.every(10).to(10).minutes.do(job)
#schedule.every().monday.do(job)
#schedule.every().wednesday.at("15:00").do(job)
#schedule.every().minute.at(":15").do(job)
while True:
schedule.run_pending()
time.sleep(1)
| nilq/baby-python | python |
from pathlib import Path
import pandas as pd
from collections import defaultdict
from typing import List, Union
from .types import Child
def create_csv(children: List[Child], output_dir: Union[Path,str]):
header_df = create_header(children)
episodes_df = create_episodes(children)
uasc_df = create_uasc(children)
reviews_df = create_reviews(children)
oc2_df = create_oc2(children)
oc3_df = create_oc3(children)
ad1_df = create_ad1(children)
sbpfa_df = create_should_be_placed_for_adoption(children)
prev_perm_df = create_previous_permanence(children)
missing_df = create_missing(children)
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
header_df.to_csv(output_dir / 'header.csv', index=False)
episodes_df.to_csv(output_dir / 'episodes.csv', index=False)
uasc_df.to_csv(output_dir / 'uasc.csv', index=False)
reviews_df.to_csv(output_dir / 'reviews.csv', index=False)
oc2_df.to_csv(output_dir / 'oc2.csv', index=False)
oc3_df.to_csv(output_dir / 'oc3.csv', index=False)
ad1_df.to_csv(output_dir / 'ad1.csv', index=False)
sbpfa_df.to_csv(output_dir / 'placed_for_adoption.csv', index=False)
prev_perm_df.to_csv(output_dir / 'previous_permanence.csv', index=False)
missing_df.to_csv(output_dir / 'missing.csv', index=False)
def create_header(children: List[Child]) -> pd.DataFrame:
return pd.DataFrame({
'CHILD': [c.child_id for c in children],
'SEX': [c.sex for c in children],
'DOB': [c.dob.strftime('%d/%m/%Y') for c in children],
'ETHNIC': [c.ethnicity for c in children],
'UPN': [c.upn for c in children],
'MOTHER': [1 if c.mother_child_dob is not None else None for c in children],
'MC_DOB': [c.mother_child_dob.strftime('%d/%m/%Y') if c.mother_child_dob is not None else None for c in children],
})
def create_episodes(children: List[Child]) -> pd.DataFrame:
data = defaultdict(list)
for child in children:
for episode in child.episodes:
data['CHILD'].append(child.child_id)
data['DECOM'].append(episode.start_date.strftime('%d/%m/%Y'))
data['RNE'].append(episode.reason_for_new_episode)
data['LS'].append(episode.legal_status)
data['CIN'].append(episode.cin)
data['PLACE'].append(episode.place)
data['PLACE_PROVIDER'].append(episode.place_provider)
data['DEC'].append(episode.end_date.strftime('%d/%m/%y') if episode.end_date is not None else None)
data['REC'].append(episode.reason_end)
data['REASON_PLACE_CHANGE'].append(episode.reason_place_change)
data['HOME_POST'].append(episode.home_postcode)
data['PL_POST'].append(episode.place_postcode)
data['URN'].append(episode.urn)
return pd.DataFrame(data)
def create_uasc(children: List[Child]) -> pd.DataFrame:
data = defaultdict(list)
for child in children:
if child.date_uasc_ceased is not None:
data['CHILD'].append(child.child_id)
data['SEX'].append(child.sex)
data['DOB'].append(child.dob.strftime('%d/%m/%Y'))
data['DUC'].append(child.date_uasc_ceased.strftime('%d/%m/%Y'))
return pd.DataFrame(data)
def create_reviews(children: List[Child]) -> pd.DataFrame:
data = defaultdict(list)
for child in children:
for review in child.reviews:
data['CHILD'].append(child.child_id)
data['DOB'].append(child.dob.strftime('%d/%m/%Y'))
data['REVIEW'].append(review.review_date.strftime('%d/%m/%Y'))
data['REVIEW_CODE'].append(review.review_code)
return pd.DataFrame(data)
def create_oc3(children: List[Child]) -> pd.DataFrame:
data = defaultdict(list)
for child in children:
if child.leaving_care_data is not None:
data['CHILD'].append(child.child_id)
data['DOB'].append(child.dob.strftime('%d/%m/%Y'))
data['IN_TOUCH'].append(child.leaving_care_data.in_touch)
data['ACTIV'].append(child.leaving_care_data.activ)
data['ACCOM'].append(child.leaving_care_data.accom)
return pd.DataFrame(data)
def create_ad1(children: List[Child]) -> pd.DataFrame:
data = defaultdict(list)
for child in children:
if child.adoption_data is not None:
ad = child.adoption_data
data['CHILD'].append(child.child_id)
data['DOB'].append(child.dob.strftime('%d/%m/%Y'))
data['DATE_INT'].append(ad.start_date.strftime('%d/%m/%Y'))
data['DATE_MATCH'].append(ad.start_date.strftime('%d/%m/%Y'))
data['FOSTER_CARE'].append(ad.foster_care)
data['NB_ADOPTR'].append(ad.number_adopters)
data['SEX_ADOPTR'].append(ad.sex_adopter)
data['LS_ADOPTR'].append(ad.ls_adopter)
return pd.DataFrame(data)
def create_should_be_placed_for_adoption(children: List[Child]) -> pd.DataFrame:
data = defaultdict(list)
for child in children:
if child.adoption_data is not None:
ad = child.adoption_data
data['CHILD'].append(child.child_id)
data['DOB'].append(child.dob.strftime('%d/%m/%Y'))
data['DATE_PLACED'].append(ad.start_date.strftime('%d/%m/%Y'))
data['DATE_PLACED_CEASED'].append(ad.end_date.strftime('%d/%m/%Y') if ad.end_date is not None else None)
data['REASON_PLACED_CEASED'].append(ad.reason_ceased if ad.reason_ceased is not None else None)
return pd.DataFrame(data)
def create_oc2(children: List[Child]) -> pd.DataFrame:
bool_to_str = lambda x: 1 if x else 0
data = defaultdict(list)
for child in children:
if child.outcomes_data is not None:
oc = child.outcomes_data
data['CHILD'].append(child.child_id)
data['DOB'].append(child.dob.strftime('%d/%m/%Y'))
data['SDQ_SCORE'].append(oc.sdq_score)
data['SDQ_REASON'].append(oc.sdq_reason)
data['CONVICTED'].append(bool_to_str(oc.convicted))
data['HEALTH_CHECK'].append(bool_to_str(oc.health_check))
data['IMMUNISATIONS'].append(bool_to_str(oc.immunisations))
data['TEETH_CHECK'].append(bool_to_str(oc.teeth_check))
data['HEALTH_ASSESSMENT'].append(bool_to_str(oc.health_assessment))
data['SUBSTANCE_MISUSE'].append(bool_to_str(oc.substance_misuse))
data['INTERVENTION_RECEIVED'].append(bool_to_str(oc.intervention_received))
data['INTERVENTION_OFFERED'].append(bool_to_str(oc.intervention_offered))
df = pd.DataFrame(data)
# Pandas converts ints with null to float by default, so need to convert back
# to nullable integer.
df['SDQ_SCORE'] = df['SDQ_SCORE'].astype('Int64')
return df
def create_previous_permanence(children: List[Child]) -> pd.DataFrame:
data = defaultdict(list)
for child in children:
data['CHILD'].append(child.child_id)
data['DOB'].append(child.dob.strftime('%d/%m/%Y'))
data['PREV_PERM'].append(child.previous_permanent)
data['LA_PERM'].append(None) # this needs to be inferred
data['DATE_PERM'].append(child.prev_permanent_date.strftime('%d/%m/%Y') if child.prev_permanent_date is not None else None)
return pd.DataFrame(data)
def create_missing(children: List[Child]) -> pd.DataFrame:
data = defaultdict(list)
for child in children:
for mp in child.missing_periods:
data['CHILD'].append(child.child_id)
data['DOB'].append(child.dob.strftime('%d/%m/%Y'))
data['MISSING'].append(mp.missing_type)
data['MIS_START'].append(mp.start_date.strftime('%d/%m/%Y'))
data['MIS_END'].append(mp.end_date.strftime('%d/%m/%Y') if mp.end_date is not None else None)
return pd.DataFrame(data) | nilq/baby-python | python |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--latitude", type=float, required=True, help="The latitude of your bounding box center")
parser.add_argument("--longitude", type=float, required=True, help="The longitude of your bounding box center")
args = parser.parse_args()
dlat = 0.005
dlon = 0.02 # double it from 0.01
n = args.latitude + (dlat/2)
s = args.latitude - (dlat/2)
e = args.longitude + (dlon/2)
w = args.longitude - (dlon/2)
query = """<query type="way">
<bbox-query s="${south}" w="${west}" n="${north}" e="${east}"/>
<has-kv k="highway" regv="."/>
<has-kv k="access" modv="not" regv="no"/>
<has-kv k="access" modv="not" regv="private"/>
<has-kv k="area" modv="not" regv="yes"/>
</query>
<union>
<item/>
<recurse type="down"/>
</union>
<print/>"""
from string import Template
t = Template(query)
interpolated = t.substitute(north=str(n), south=str(s), east=str(e), west=str(w))
print interpolated
| nilq/baby-python | python |
from modules.data.fileRead import readMat
from numpy import arange
from modules.modelar.leastSquares import calculate
# Alternativa para caso as constantes escolhidas não forem escolhidas pelo Usuário
SP = 50
OVERSHOOT = 0.10
TS = 70
# Pegando vetores de entrada e saída
ENTRADA, SAIDA, TEMPO = readMat()
# Calculando intervalo de tempo
TEMPO_AMOSTRAGEM = TEMPO[0][1]
# Calculando intervalo de tempo
TEMPO_CALCULO = arange(0,(len(TEMPO[0])*TEMPO_AMOSTRAGEM),TEMPO_AMOSTRAGEM)
# Calculando coeficientes
COEFICIENTE_A1, COEFICIENTE_B1 = calculate()
| nilq/baby-python | python |
import argparse
import os
import pandas as pd
import re
import spacy
import sys
from datetime import datetime
from geopy.extra.rate_limiter import RateLimiter
from geopy import Nominatim
from epitator.geoname_annotator import GeonameAnnotator
from epitator.date_annotator import DateAnnotator
from epitator.count_annotator import CountAnnotator
from epitator.annotator import AnnoDoc
from typing import Iterable, Union
from transformers import BartForConditionalGeneration, BartTokenizer
from tqdm import tqdm
os.environ['SPACY_MODEL_SHORTCUT_LINK'] = 'en_core_web_trf'
spacy.prefer_gpu()
sys.path.append('../EpiTator')
locator = Nominatim(user_agent="ppcoom")
geocode = RateLimiter(locator.geocode, min_delay_seconds=1/20)
locator = Nominatim(user_agent="ppcoom")
geocode = RateLimiter(locator.geocode, min_delay_seconds=1/20)
dengue_regex = re.compile(
r'([A-Za-z ]+).*\[w\/e (.+)\] \/ (.+) \/ (.+) \/ (.+) \/ (.+) \/ (.+)', re.MULTILINE)
tqdm.pandas()
# setup our BART transformer summarization model
print('loading transformers')
tokenizer = BartTokenizer.from_pretrained('facebook/bart-large-cnn')
model = BartForConditionalGeneration.from_pretrained(
'facebook/bart-large-cnn')
COUNTRY_COL = "country"
CONTENT_COL = "content"
SUMMARY_COL = "summary"
DATA_DIR = "../data"
SUMMARIZED_DATA_DIR = f"{DATA_DIR}/summarized"
EXTRACTED_DATA_DIR = f"{DATA_DIR}/extracted"
def extract_arguments() -> Iterable[Union[str, list]]:
"""
Name: extract_arguments
Purpose: extracts the arguments specified by the user
Input: None
Output: filepath - The csv filepath specified by the user
countries - The countries specified by the user
"""
CSV_FILE_ENDING = ".csv"
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filepath", type=str, required=True, help="The filepath to the promed data to analyze")
parser.add_argument("-c", "--countries", nargs="+", required=True, help="The countries to filter for in the data")
args = parser.parse_args()
"""
Validate the following:
1. The filepath has a length > 0
2. The filepath actually points to a file
3. The file pointed to by the filepath is a csv
"""
filepath = args.filepath
if (
len(filepath) <= 0 or
os.path.isfile(filepath) is False or
filepath.endswith(CSV_FILE_ENDING) is False
):
print(f"The filepath: {filepath} is either not a valid csv or a valid file.")
sys.exit(-1)
"""
Validate the countries specified are valid strings
"""
invalid_country_specified = False
for country in args.countries:
if (len(country.strip()) <= 0 or country is None):
print(f"The country: {country} is not valid")
invalid_country_specified = True
if invalid_country_specified:
sys.exit(-1)
return filepath, args.countries
def read_data(csv_filepath: str) -> pd.DataFrame:
"""
Name: read_data
Purpose: To read the data inside the csv filepath specified
Input: csv_filepath - The filepath to the csv
Output: A DataFrame representation of the csv data
"""
return pd.read_csv(csv_filepath)
def filter_df_by_countries(promed_df: pd.DataFrame, countries_to_srch_for: list) -> pd.DataFrame:
"""
Name: filter_df_by_countries
Purpose: Filter the specified data frame by the countries specified
Input: promed_df - The promed dataframe
countries_to_srch_for - The countries we shoud filter on
Output: A new filtered dataframe
"""
filtered_pd = None
for country in countries_to_srch_for:
country_filtered_df = promed_df.loc[(promed_df[COUNTRY_COL].str.lower() == country.lower())]
if filtered_pd is None:
filtered_pd = country_filtered_df
else:
filtered_pd.append(country_filtered_df)
return filtered_pd
def clean_df_content(promed_df: pd.DataFrame, debug: bool = False) -> pd.DataFrame:
cleaned_df = {}
for index, row in promed_df.iterrows():
content = row[CONTENT_COL]
cleaned_content = clean(content)
if (debug):
print("---------------------------")
print(f"{content}")
print("---------------------------")
for col in promed_df.columns:
row_val = row[col]
if col == CONTENT_COL:
row_val = cleaned_content
if col in cleaned_df:
cleaned_df[col].append(row_val)
else:
cleaned_df[col] = [row_val]
return pd.DataFrame(cleaned_df)
def clean(content):
split = content.splitlines()
last_index = -1
lower = [x.lower().strip() for x in split]
if '--' in lower:
last_index = lower.index('--')
elif 'communicated by:' in lower:
last_index = lower.index('communicated by:')-1
cleaned = split[12:last_index]
return '\n'.join([x for x in cleaned if x])
def summarize_df_content(promed_df: pd.DataFrame) -> pd.DataFrame:
summarized_df = {}
for index, row in promed_df.iterrows():
content = row[CONTENT_COL]
summarized_content = summarizer(content)
for col in promed_df.columns:
row_val = row[col]
if col == SUMMARY_COL:
row_val = summarized_content
if col != CONTENT_COL:
if col in summarized_df:
summarized_df[col].append(row_val)
else:
summarized_df[col] = [row_val]
return pd.DataFrame(summarized_df)
def summarizer(text: str) -> str:
input_ids = tokenizer(text, return_tensors='pt', max_length=1024,
padding=True, truncation=True)['input_ids']
summary_ids = model.generate(input_ids)
summary = ''.join([tokenizer.decode(s) for s in summary_ids])
summary = summary.replace('<s>', '').replace('</s>', '')
return summary
def extract_cchf_data_from_df(promed_df: pd.DataFrame) -> pd.DataFrame:
promed_df[[
'admin1_code',
'admin2_code',
'admin3_code',
'admin4_code',
'location_name',
'location_lat',
'location_lon',
'cases',
'cases_tags',
'deaths',
'deaths_tags',
'dates_start',
'dates_end',
]] = promed_df[SUMMARY_COL].progress_apply(epitator_extract)
promed_df = promed_df.applymap(lambda x: x[0] if isinstance(
x, list) and len(x) > 0 else x)
promed_df = promed_df.applymap(lambda y: pd.NA if isinstance(
y, (list, str)) and len(y) == 0 else y)
promed_df = promed_df.reset_index(drop=True)
return promed_df
# function that extracts location names/admin codes/lat/lng, case and death counts, and date ranges from the input string
# uses epitator since it already trained rules for extracting medical/infectious disease data
def epitator_extract(txt: str, max_ents: int = 1) -> dict:
# input string and add annotators
doc = AnnoDoc(txt)
doc.add_tiers(GeonameAnnotator())
doc.add_tiers(CountAnnotator())
doc.add_tiers(DateAnnotator())
# extract geographic data
geos = doc.tiers["geonames"].spans
geo_admin1s = [x.geoname.admin1_code for x in geos]
geo_admin2s = [x.geoname.admin2_code for x in geos]
geo_admin3s = [x.geoname.admin3_code for x in geos]
geo_admin4s = [x.geoname.admin4_code for x in geos]
geo_names = [x.geoname.name for x in geos]
geo_lats = [x.geoname.latitude for x in geos]
geo_lons = [x.geoname.longitude for x in geos]
# extract case counts and death counts
counts = doc.tiers["counts"].spans
cases_counts = [x.metadata['count'] for x in counts if 'case' in x.metadata['attributes']
and 'death' not in x.metadata['attributes']]
cases_tags = [x.metadata['attributes']
for x in counts if 'case' in x.metadata['attributes'] and 'death' not in x.metadata['attributes']]
death_counts = [x.metadata['count']
for x in counts if 'death' in x.metadata['attributes']]
death_tags = [x.metadata['attributes']
for x in counts if 'death' in x.metadata['attributes']]
# extract the date range
dates = doc.tiers["dates"].spans
dates_start = [pd.to_datetime(
x.metadata["datetime_range"][0], errors='coerce') for x in dates]
dates_end = [pd.to_datetime(
x.metadata["datetime_range"][1], errors='coerce') for x in dates]
# return only max_ents entities from the extracted lists
# currently set to the first result for each list, since that is usually the most important one
# and other ones can be filler/garbage data
return pd.Series([
geo_admin1s[:max_ents],
geo_admin2s[:max_ents],
geo_admin3s[:max_ents],
geo_admin4s[:max_ents],
geo_names[:max_ents],
geo_lats[:max_ents],
geo_lons[:max_ents],
cases_counts[:max_ents],
cases_tags[:max_ents],
death_counts[:max_ents],
death_tags[:max_ents],
dates_start[:max_ents],
dates_end[:max_ents],
])
def main():
print("Extracting the specified arguments")
csv_filepath, countries = extract_arguments()
print("Reading the promed data")
orig_promed_df = read_data(
csv_filepath = csv_filepath
)
print("Filtering the promed data")
filtered_promed_df = filter_df_by_countries(
promed_df = orig_promed_df,
countries_to_srch_for = countries
)
print(filtered_promed_df)
print("Cleaning the promed data")
cleaned_promed_content_df = clean_df_content(
promed_df = filtered_promed_df
)
print("Summarizing dataframe contents")
summarized_promed_data = summarize_df_content(
promed_df = filtered_promed_df
)
if os.path.isdir(SUMMARIZED_DATA_DIR) is False:
os.mkdir(SUMMARIZED_DATA_DIR)
csv_countries_selected = ""
for country in countries:
csv_countries_selected += f"_{country.lower()}"
print("Saving summarized promed data")
csv_country_summarized_data = f"summarized_promed_cchf_data"
summarized_promed_data.to_csv(f"{SUMMARIZED_DATA_DIR}/{csv_country_summarized_data}{csv_countries_selected}.csv", index=False)
print("Extracting promed data")
extraced_promed_data_df = extract_cchf_data_from_df(
promed_df = summarized_promed_data
)
print("Saving extracted promed data")
if os.path.isdir(EXTRACTED_DATA_DIR) is False:
os.mkdir(EXTRACTED_DATA_DIR)
csv_country_extracted_data = f"extracted_promed_cchf_data"
extraced_promed_data_df.to_csv(f"{EXTRACTED_DATA_DIR}/{csv_country_extracted_data}{csv_countries_selected}.csv", index=False)
if __name__ == "__main__":
main() | nilq/baby-python | python |
from cmsisdsp.sdf.nodes.simu import *
import numpy as np
import cmsisdsp as dsp
class Processing(GenericNode):
def __init__(self,inputSize,outputSize,fifoin,fifoout):
GenericNode.__init__(self,inputSize,outputSize,fifoin,fifoout)
def run(self):
i=self.getReadBuffer()
o=self.getWriteBuffer()
b=dsp.arm_scale_q15(i,0x6000,1)
o[:]=b[:]
return(0) | nilq/baby-python | python |
def say_hi():
print("hello world function")
def cube(num):
return num*num*num
say_hi()
print(cube(3))
# Statements
is_male = False
if is_male:
say_hi()
else:
print("Goodbay")
# Statements
is_female = True
if is_female or is_male:
print("Hi")
else:
print("Goodbay")
# Dictionary
months = {
0: "hola",
1: "adiós"
}
| nilq/baby-python | python |
import os
from argh.dispatching import dispatch_command
import application
def start_app():
port = int(os.getenv('PORT'))
application.start(port=port)
if __name__ == '__main__':
dispatch_command(start_app)
| nilq/baby-python | python |
import os
from git import Repo
from django.core.exceptions import PermissionDenied
from base.handlers.extra_handlers import ExtraHandler
from base.handlers.file_handler import FileHandler
from base.handlers.form_handler import FormHandler
from base.handlers.path_handlers import PathHandler
from base.handlers.github_handler import GithubHandler
from base.handlers.yaml_handlers import YAMLHandler
from startbootstrap.dbio import PostDbIO, SiteDataDbIO, SocialProfileDbIO
from theJekyllProject.dbio import RepoDbIO
class SBSFormHandler:
def __init__(self, user, repo):
"""
:param user: logged in user
:param repo: the main repo name
"""
self.path = PathHandler(user, repo).create_repo_path()
def load_site_initials(self, request, form_class):
"""
Load the site data initials from the database
"""
site_data = SiteDataDbIO().get_obj({
'repo': RepoDbIO().get_repo(request.user)
})
return FormHandler(request, form_class).load_initials(site_data)
def post_site_data(self, user, form_field_dict):
"""
handle the post site data View method
:param user: the logged in user
:param form_field_dict: form field cleaned data
:return:
"""
repo = RepoDbIO().get_repo(user)
form_field_dict['repo'] = repo
site_data = SiteDataDbIO().get_obj({'repo': repo})
if site_data:
SiteDataDbIO().update_obj(site_data, form_field_dict)
else:
SiteDataDbIO().create_obj(**form_field_dict)
config_path = os.path.join(self.path, '_config.yml')
self.del_repo(form_field_dict)
# Complete all the yaml operations
yaml_dict = YAMLHandler().read_yaml_file(config_path, True)
new_yaml = YAMLHandler().change_yaml(yaml_dict, form_field_dict)
YAMLHandler().write_dict_yaml(config_path, new_yaml)
# Complete all the git operations
repo = Repo(self.path)
GithubHandler.commit_all_changes(repo, 'Change site data')
GithubHandler.push_code(repo, 'gh-pages')
def load_social_profile_initials(self, request, form_class):
"""
Load the site profile initials from the database
"""
social_data = SocialProfileDbIO().get_obj({
'repo': RepoDbIO().get_repo(request.user)
})
return FormHandler(request, form_class).load_initials(social_data)
def post_social_profile_data(self, user, form_field_dict):
"""
handle the post social profile View method
:param user: the logged in user
:param form_field_dict: form field cleaned data
:return:
"""
repo = RepoDbIO().get_repo(user)
# repo is the foriegn key so it needs to be in the dict.
form_field_dict['repo'] = repo
social_data = SocialProfileDbIO().get_obj({'repo': repo})
if social_data:
SocialProfileDbIO().update_obj(social_data, form_field_dict)
else:
SocialProfileDbIO().create_obj(**form_field_dict)
config_path = os.path.join(self.path, '_config.yml')
self.del_repo(form_field_dict)
# Complete all the yaml operations
yaml_dict = YAMLHandler().read_yaml_file(config_path, True)
new_yaml = YAMLHandler().change_yaml(yaml_dict, form_field_dict)
YAMLHandler().write_dict_yaml(config_path, new_yaml)
# Complete all the git operations
repo = Repo(self.path)
GithubHandler.commit_all_changes(repo, 'Change site data')
GithubHandler.push_code(repo, 'gh-pages')
def load_posts_initials(self, request, form_class, pk=None):
"""
Load the posts initials from the database
"""
repo = RepoDbIO().get_repo(request.user)
if pk:
post = PostDbIO().get_obj({
'pk': pk,
'repo__user': request.user,
'repo': repo
})
if post is None:
raise PermissionDenied
else:
post = None
return FormHandler(request, form_class).load_initials(post)
def post_posts_data(self, user, form_field_dict, pk=None):
"""
handle the post posts View method
:param user: the logged in user
:param form_field_dict: form field cleaned data
We have to delete the file if the title is changed otherwise two
different files will be created.
:return:
"""
# TODO image copying is not done and delete the old one.
# TODO take care of the layout
repo = RepoDbIO().get_repo(user)
if pk:
post = PostDbIO().get_obj({
'pk': pk,
'repo__user': user,
'repo': repo
})
if pk is None:
raise PermissionDenied
if post.title is not form_field_dict['title']:
file_name = ExtraHandler().file_name_f_title(post.title,
'html')
FileHandler('/'.join([self.path, '_posts']),
file_name).delete_file()
post = PostDbIO().update_obj(post, **form_field_dict)
else:
form_field_dict['repo'] = repo
post = PostDbIO().create_obj(**form_field_dict)
ExtraHandler().del_keys(form_field_dict, ('repo', 'content',))
yaml_content = YAMLHandler().create_yaml(form_field_dict)
w_yaml_content = ExtraHandler().wrap_content('---', yaml_content)
full_content = ExtraHandler().join_content(w_yaml_content,
post.content)
file_name = ExtraHandler().file_name_f_title(post.title,
'html')
FileHandler('/'.join([self.path, '_posts']),
file_name).rewrite_file(full_content)
# Complete all the git operations
repo = Repo(self.path)
GithubHandler.commit_all_changes(repo, 'Change site data')
GithubHandler.push_code(repo, 'gh-pages')
def load_page_initials(self, request, form_class, pk=None):
"""
Load the page initials from the database
"""
repo = RepoDbIO().get_repo(request.user)
if pk:
post = PostDbIO().get_obj({
'pk': pk,
'repo__user': request.user,
'repo': repo
})
else:
raise PermissionDenied
return FormHandler(request, form_class).load_initials(post)
def post_page_data(self, user, form_field_dict, pk=None):
"""
handle the post page View method
:param user: the logged in user
:param form_field_dict: form field cleaned data
We have to delete the file if the title is changed otherwise two
different files will be created.
:return:
"""
# TODO image copying is not done.
# TODO take care of the layout
repo = RepoDbIO().get_repo(user)
if pk:
post = PostDbIO().get_obj({
'pk': pk,
'repo__user': user,
'repo': repo
})
if pk is None:
raise PermissionDenied
if post.title is not form_field_dict['title']:
file_name = ExtraHandler().file_name_f_title(post.title,
'html')
FileHandler('/'.join([self.path, '_posts']),
file_name).delete_file()
post = PostDbIO().update_obj(post, **form_field_dict)
else:
raise PermissionDenied
ExtraHandler().del_keys(form_field_dict, ('repo', 'content',))
yaml_content = YAMLHandler().create_yaml(form_field_dict)
w_yaml_content = ExtraHandler().wrap_content('---', yaml_content)
full_content = ExtraHandler().join_content(w_yaml_content,
post.content)
file_name = ExtraHandler().file_name_f_title(post.title,
'html')
FileHandler('/'.join([self.path, '_posts']),
file_name).rewrite_file(full_content)
# Complete all the git operations
repo = Repo(self.path)
GithubHandler.commit_all_changes(repo, 'Change site data')
GithubHandler.push_code(repo, 'gh-pages')
| nilq/baby-python | python |
from radixlib.api_types.identifiers import AccountIdentifier
from radixlib.serializable import Serializable
from radixlib.api_types import TokenAmount
from typing import Dict, Any
import radixlib as radix
import json
class TransferTokens(Serializable):
""" Defines a TransferTokens action """
def __init__(
self,
from_account: str,
to_account: str,
amount: int,
token_rri: str,
) -> None:
""" Instantiates a new TransferTokens action used for the creation of new tokens.
Args:
from_account (str): The account which will be sending the tokens.
to_account (str): The account which will be getting the tokens.
amount (int): The amount of tokens to send.
token_rri (str): The RRI of the token to send.
"""
self.from_account: AccountIdentifier = AccountIdentifier(from_account)
self.to_account: AccountIdentifier = AccountIdentifier(to_account)
self.amount: int = amount
self.token_rri: str = token_rri
def to_dict(self) -> Dict[str, Any]:
"""" Converts the object to a dictionary """
return radix.utils.remove_none_values_recursively(
radix.utils.convert_to_dict_recursively({
"type": "TransferTokens",
"from_account": self.from_account,
"to_account": self.to_account,
"amount": TokenAmount(
rri = self.token_rri,
amount = self.amount
)
})
)
def to_json_string(self) -> str:
""" Converts the object to a JSON string """
return json.dumps(self.to_dict())
@classmethod
def from_dict(
cls,
dictionary: Dict[Any, Any]
) -> 'TransferTokens':
""" Loads a TransferTokens from a Gateway API response dictionary
Args:
dictionary (dict): The dictionary to load the object from
Returns:
TransferTokens: A new TransferTokens initalized from the dictionary
Raises:
TypeError: Raised when the type of the action in the dictionary does not match
the action name of the class
"""
if dictionary.get('type') != "TransferTokens":
raise TypeError(f"Expected a dictionary with a type of TransferTokens but got: {dictionary.get('type')}")
return cls(
from_account = dictionary['from_account']['address'],
to_account = dictionary['to_account']['address'],
amount = int(dictionary['amount']['value']),
token_rri = dictionary['amount']['token_identifier']['rri']
)
@classmethod
def from_json_string(
cls,
json_string: str
) -> 'TransferTokens':
""" Loads a TransferTokens from a Gateway API response JSON string. """
return cls.from_dict(json.loads(json_string)) | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.