max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111 values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
src/flytracker/io/__init__.py | nicolaseberle/flyTracker | 2 | 6617651 | <gh_stars>1-10
from .dataset import DataLoader
| from .dataset import DataLoader | none | 1 | 1.113746 | 1 | |
lizard_auth_server/tests/test_admin.py | lisannewapstra/lizard-auth-server | 1 | 6617652 | <filename>lizard_auth_server/tests/test_admin.py<gh_stars>1-10
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from django.core import mail
from django.test import Client
from django.test import TestCase
from django.test.client import RequestFactory
from django.urls import reverse
from lizard_auth_server import admin
from lizard_auth_server import models
from lizard_auth_server.tests import factories
import mock
class TestSearchFields(TestCase):
def test_for_valid_search_fields(self):
# It is easy to add a foreignkey in a search field instead of a
# stringfield on the class the foreign key points to.
for model_admin_class in [
admin.PortalAdmin,
admin.TokenAdmin,
admin.InvitationAdmin,
admin.UserProfileAdmin,
admin.RoleAdmin,
admin.OrganisationAdmin,
admin.OrganisationRoleAdmin,
]:
model_class = model_admin_class.model
for fieldname in model_admin_class.search_fields:
query = "%s__icontains" % fieldname
kwargs = {query: "reinout"}
# We have no content, so the number of results if we search on
# something should be zero. The only thing that matters is
# that we get no 'cannot search on foreignkey' error.
self.assertEqual(model_class.objects.filter(**kwargs).count(), 0)
class TestInvitationAdmin(TestCase):
def setUp(self):
self.invitation = factories.InvitationF()
self.request_factory = RequestFactory()
self.some_request = self.request_factory.get("/admin/")
site = AdminSite()
self.admin_instance = admin.InvitationAdmin(models.Invitation, site)
@mock.patch.object(models.Invitation, "send_new_activation_email")
def test_send_new_activation_email1(self, patched_method):
# Patch method actually sends the activation email.
queryset = models.Invitation.objects.filter(id=self.invitation.id)
self.admin_instance.send_new_activation_email(self.some_request, queryset)
self.assertTrue(patched_method.called)
@mock.patch("django.contrib.messages.error")
def test_send_new_activation_email2(self, patched_method):
# Patched method is the error message printing
# "We are already activated".
self.invitation.is_activated = True
self.invitation.save()
queryset = models.Invitation.objects.filter(id=self.invitation.id)
self.admin_instance.send_new_activation_email(self.some_request, queryset)
self.assertTrue(patched_method.called)
def test_invitation_email(self):
"""
Sending mail from a test doesn't actually send the mail, but puts it in
a mail.outbox list of EmailMessage instances.
"""
queryset = models.Invitation.objects.filter(id=self.invitation.id)
self.admin_instance.send_new_activation_email(self.some_request, queryset)
# check whether there is a mail in the outbox
self.assertEqual(len(mail.outbox), 1)
# check subject
self.assertEqual(
mail.outbox[0].subject,
"Er is een account voor u aangemaakt op sso.lizard.net",
)
self.assertEqual(mail.outbox[0].to, ["<EMAIL>"])
# check mail starts with '<NAME>,'
self.assertTrue(mail.outbox[0].body.startswith("<NAME>,"))
def test_shortcut_urls1(self):
# By default, show a shortcut url for manual activation.
self.assertTrue("href" in self.admin_instance.shortcut_urls(self.invitation))
def test_shortcut_urls2(self):
# If activated, no shortcut url for manual activation.
self.invitation.is_activated = True
self.assertEqual(self.admin_instance.shortcut_urls(self.invitation), "")
def test_user_profile_link1(self):
# No user profle? No handy link.
self.assertEqual(self.admin_instance.user_profile_link(self.invitation), None)
def test_user_profile_link2(self):
user_profile = factories.UserProfileF()
self.invitation.user = user_profile.user
# User profle? Link to the user profile.
self.assertTrue(
"href" in self.admin_instance.user_profile_link(self.invitation)
)
class TestSmokeAdminPages(TestCase):
"""Smoke tests with the basic test client
The test calls the list page and the edit page for all models and simply
checks if you get a '200 OK' status code back.
"""
def setUp(self):
User.objects.create_superuser("admin", "<EMAIL>", "admin")
self.client = Client()
self.client.login(username="admin", password="<PASSWORD>")
# Create a bunch of objects.
self.user_profile = factories.UserProfileF()
self.portal = factories.PortalF()
self.role = factories.RoleF()
self.token = factories.TokenF()
self.organisation = factories.OrganisationF()
self.invitation = factories.InvitationF()
# Part one: list pages.
def _check_changelist_page_200(self, model_name):
url = reverse("admin:lizard_auth_server_%s_changelist" % model_name)
self.assertEqual(self.client.get(url).status_code, 200)
def test_userprofile_list(self):
self._check_changelist_page_200("userprofile")
def test_portal_list(self):
self._check_changelist_page_200("portal")
def test_role_list(self):
self._check_changelist_page_200("role")
def test_token_list(self):
self._check_changelist_page_200("token")
def test_organisation_list(self):
self._check_changelist_page_200("organisation")
def test_invitation_list(self):
self._check_changelist_page_200("invitation")
# Part one: edit pages.
def _check_change_page_200(self, obj):
model_name = obj._meta.model_name
url = reverse("admin:lizard_auth_server_%s_change" % model_name, args=[obj.id])
self.assertEqual(self.client.get(url).status_code, 200)
def test_userprofile_change_page(self):
self._check_change_page_200(self.user_profile)
def test_portal_change_page(self):
self._check_change_page_200(self.portal)
def test_role_change_page(self):
self._check_change_page_200(self.role)
def test_token_change_page(self):
self._check_change_page_200(self.token)
def test_organisation_change_page(self):
self._check_change_page_200(self.organisation)
def test_invitation_change_page(self):
self._check_change_page_200(self.invitation)
| <filename>lizard_auth_server/tests/test_admin.py<gh_stars>1-10
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from django.core import mail
from django.test import Client
from django.test import TestCase
from django.test.client import RequestFactory
from django.urls import reverse
from lizard_auth_server import admin
from lizard_auth_server import models
from lizard_auth_server.tests import factories
import mock
class TestSearchFields(TestCase):
def test_for_valid_search_fields(self):
# It is easy to add a foreignkey in a search field instead of a
# stringfield on the class the foreign key points to.
for model_admin_class in [
admin.PortalAdmin,
admin.TokenAdmin,
admin.InvitationAdmin,
admin.UserProfileAdmin,
admin.RoleAdmin,
admin.OrganisationAdmin,
admin.OrganisationRoleAdmin,
]:
model_class = model_admin_class.model
for fieldname in model_admin_class.search_fields:
query = "%s__icontains" % fieldname
kwargs = {query: "reinout"}
# We have no content, so the number of results if we search on
# something should be zero. The only thing that matters is
# that we get no 'cannot search on foreignkey' error.
self.assertEqual(model_class.objects.filter(**kwargs).count(), 0)
class TestInvitationAdmin(TestCase):
def setUp(self):
self.invitation = factories.InvitationF()
self.request_factory = RequestFactory()
self.some_request = self.request_factory.get("/admin/")
site = AdminSite()
self.admin_instance = admin.InvitationAdmin(models.Invitation, site)
@mock.patch.object(models.Invitation, "send_new_activation_email")
def test_send_new_activation_email1(self, patched_method):
# Patch method actually sends the activation email.
queryset = models.Invitation.objects.filter(id=self.invitation.id)
self.admin_instance.send_new_activation_email(self.some_request, queryset)
self.assertTrue(patched_method.called)
@mock.patch("django.contrib.messages.error")
def test_send_new_activation_email2(self, patched_method):
# Patched method is the error message printing
# "We are already activated".
self.invitation.is_activated = True
self.invitation.save()
queryset = models.Invitation.objects.filter(id=self.invitation.id)
self.admin_instance.send_new_activation_email(self.some_request, queryset)
self.assertTrue(patched_method.called)
def test_invitation_email(self):
"""
Sending mail from a test doesn't actually send the mail, but puts it in
a mail.outbox list of EmailMessage instances.
"""
queryset = models.Invitation.objects.filter(id=self.invitation.id)
self.admin_instance.send_new_activation_email(self.some_request, queryset)
# check whether there is a mail in the outbox
self.assertEqual(len(mail.outbox), 1)
# check subject
self.assertEqual(
mail.outbox[0].subject,
"Er is een account voor u aangemaakt op sso.lizard.net",
)
self.assertEqual(mail.outbox[0].to, ["<EMAIL>"])
# check mail starts with '<NAME>,'
self.assertTrue(mail.outbox[0].body.startswith("<NAME>,"))
def test_shortcut_urls1(self):
# By default, show a shortcut url for manual activation.
self.assertTrue("href" in self.admin_instance.shortcut_urls(self.invitation))
def test_shortcut_urls2(self):
# If activated, no shortcut url for manual activation.
self.invitation.is_activated = True
self.assertEqual(self.admin_instance.shortcut_urls(self.invitation), "")
def test_user_profile_link1(self):
# No user profle? No handy link.
self.assertEqual(self.admin_instance.user_profile_link(self.invitation), None)
def test_user_profile_link2(self):
user_profile = factories.UserProfileF()
self.invitation.user = user_profile.user
# User profle? Link to the user profile.
self.assertTrue(
"href" in self.admin_instance.user_profile_link(self.invitation)
)
class TestSmokeAdminPages(TestCase):
"""Smoke tests with the basic test client
The test calls the list page and the edit page for all models and simply
checks if you get a '200 OK' status code back.
"""
def setUp(self):
User.objects.create_superuser("admin", "<EMAIL>", "admin")
self.client = Client()
self.client.login(username="admin", password="<PASSWORD>")
# Create a bunch of objects.
self.user_profile = factories.UserProfileF()
self.portal = factories.PortalF()
self.role = factories.RoleF()
self.token = factories.TokenF()
self.organisation = factories.OrganisationF()
self.invitation = factories.InvitationF()
# Part one: list pages.
def _check_changelist_page_200(self, model_name):
url = reverse("admin:lizard_auth_server_%s_changelist" % model_name)
self.assertEqual(self.client.get(url).status_code, 200)
def test_userprofile_list(self):
self._check_changelist_page_200("userprofile")
def test_portal_list(self):
self._check_changelist_page_200("portal")
def test_role_list(self):
self._check_changelist_page_200("role")
def test_token_list(self):
self._check_changelist_page_200("token")
def test_organisation_list(self):
self._check_changelist_page_200("organisation")
def test_invitation_list(self):
self._check_changelist_page_200("invitation")
# Part one: edit pages.
def _check_change_page_200(self, obj):
model_name = obj._meta.model_name
url = reverse("admin:lizard_auth_server_%s_change" % model_name, args=[obj.id])
self.assertEqual(self.client.get(url).status_code, 200)
def test_userprofile_change_page(self):
self._check_change_page_200(self.user_profile)
def test_portal_change_page(self):
self._check_change_page_200(self.portal)
def test_role_change_page(self):
self._check_change_page_200(self.role)
def test_token_change_page(self):
self._check_change_page_200(self.token)
def test_organisation_change_page(self):
self._check_change_page_200(self.organisation)
def test_invitation_change_page(self):
self._check_change_page_200(self.invitation)
| en | 0.801204 | # It is easy to add a foreignkey in a search field instead of a # stringfield on the class the foreign key points to. # We have no content, so the number of results if we search on # something should be zero. The only thing that matters is # that we get no 'cannot search on foreignkey' error. # Patch method actually sends the activation email. # Patched method is the error message printing # "We are already activated". Sending mail from a test doesn't actually send the mail, but puts it in a mail.outbox list of EmailMessage instances. # check whether there is a mail in the outbox # check subject # check mail starts with '<NAME>,' # By default, show a shortcut url for manual activation. # If activated, no shortcut url for manual activation. # No user profle? No handy link. # User profle? Link to the user profile. Smoke tests with the basic test client The test calls the list page and the edit page for all models and simply checks if you get a '200 OK' status code back. # Create a bunch of objects. # Part one: list pages. # Part one: edit pages. | 2.207225 | 2 |
examples/context.py | ssebs/pg | 151 | 6617653 | import pg
class Window(pg.Window):
def setup(self):
self.wasd = pg.WASD(self)
self.wasd.look_at((0, 0, 4), (0, 0, 0))
self.program = pg.DirectionalLightProgram()
self.context1 = pg.Context(self.program)
self.context2 = pg.Context(self.program)
self.sphere1 = pg.Sphere(4, 0.5, (2, 0, 0))
self.sphere2 = pg.Sphere(4, 0.5, (-2, 0, 0))
def update(self, t, dt):
matrix = pg.Matrix()
matrix = self.wasd.get_matrix(matrix)
matrix = matrix.perspective(65, self.aspect, 0.01, 100)
self.context1.matrix = matrix
self.context1.camera_position = self.wasd.position
self.context1.object_color = (1.0, 0.2, 0.0)
self.context2.matrix = matrix
self.context2.camera_position = self.wasd.position
def draw(self):
self.clear()
self.sphere1.draw(self.context1)
self.sphere2.draw(self.context2)
if __name__ == "__main__":
pg.run(Window)
| import pg
class Window(pg.Window):
def setup(self):
self.wasd = pg.WASD(self)
self.wasd.look_at((0, 0, 4), (0, 0, 0))
self.program = pg.DirectionalLightProgram()
self.context1 = pg.Context(self.program)
self.context2 = pg.Context(self.program)
self.sphere1 = pg.Sphere(4, 0.5, (2, 0, 0))
self.sphere2 = pg.Sphere(4, 0.5, (-2, 0, 0))
def update(self, t, dt):
matrix = pg.Matrix()
matrix = self.wasd.get_matrix(matrix)
matrix = matrix.perspective(65, self.aspect, 0.01, 100)
self.context1.matrix = matrix
self.context1.camera_position = self.wasd.position
self.context1.object_color = (1.0, 0.2, 0.0)
self.context2.matrix = matrix
self.context2.camera_position = self.wasd.position
def draw(self):
self.clear()
self.sphere1.draw(self.context1)
self.sphere2.draw(self.context2)
if __name__ == "__main__":
pg.run(Window)
| none | 1 | 2.594357 | 3 | |
nflfantaspy/__main__.py | mpanelo/nflfantaspy | 0 | 6617654 | <reponame>mpanelo/nflfantaspy
from collections import defaultdict
from nflfantaspy import constants
from nflfantaspy.fetcher import http
from nflfantaspy import parser
from nflfantaspy import spyder
from nflfantaspy.db.backends import airtable, json
from nflfantaspy import cli
def main():
args = cli.parse_args()
executeCfg = {}
filename = None
if args.data_type == constants.DATA_TYPE_GAMES:
schedule = spyder.Schedule(args.league_id, http.get, parser.Schedule)
playoffs = spyder.Playoffs(args.league_id, http.get, parser.Playoffs)
spy = spyder.Games(schedule=schedule, playoffs=playoffs)
executeCfg = {"bracket_type": constants.BRACKET_TYPE_CONSOLATION}
filename = "games.json"
elif args.data_type == constants.DATA_TYPE_TEAMS:
spy = spyder.Teams(args.league_id, http.get, parser.Teams)
filename = "teams.json"
else:
raise Exception(f"Unsupported data-type {args.data_type}")
data = defaultdict(list)
for year in args.years:
executeCfg["year"] = year
data[year] = spy.execute(**executeCfg)
if args.cmd == constants.STORAGE_JSON:
db = json.DatabaseClient({"filename": filename})
db.save(data)
elif args.cmd == constants.STORAGE_AIRTABLE:
save_to_airtable(data, {"api_key": args.api_key, "base_id": args.base_id})
else:
raise Exception(f"backend {args.cmd} is not supported")
def save_to_airtable(data: list[dict], cfg: dict):
db = airtable.DatabaseClient(cfg)
for year, records in data.items():
db.table = str(year)
db.save(records)
if __name__ == "__main__":
main()
| from collections import defaultdict
from nflfantaspy import constants
from nflfantaspy.fetcher import http
from nflfantaspy import parser
from nflfantaspy import spyder
from nflfantaspy.db.backends import airtable, json
from nflfantaspy import cli
def main():
args = cli.parse_args()
executeCfg = {}
filename = None
if args.data_type == constants.DATA_TYPE_GAMES:
schedule = spyder.Schedule(args.league_id, http.get, parser.Schedule)
playoffs = spyder.Playoffs(args.league_id, http.get, parser.Playoffs)
spy = spyder.Games(schedule=schedule, playoffs=playoffs)
executeCfg = {"bracket_type": constants.BRACKET_TYPE_CONSOLATION}
filename = "games.json"
elif args.data_type == constants.DATA_TYPE_TEAMS:
spy = spyder.Teams(args.league_id, http.get, parser.Teams)
filename = "teams.json"
else:
raise Exception(f"Unsupported data-type {args.data_type}")
data = defaultdict(list)
for year in args.years:
executeCfg["year"] = year
data[year] = spy.execute(**executeCfg)
if args.cmd == constants.STORAGE_JSON:
db = json.DatabaseClient({"filename": filename})
db.save(data)
elif args.cmd == constants.STORAGE_AIRTABLE:
save_to_airtable(data, {"api_key": args.api_key, "base_id": args.base_id})
else:
raise Exception(f"backend {args.cmd} is not supported")
def save_to_airtable(data: list[dict], cfg: dict):
db = airtable.DatabaseClient(cfg)
for year, records in data.items():
db.table = str(year)
db.save(records)
if __name__ == "__main__":
main() | none | 1 | 2.561315 | 3 | |
main.py | alexzucca90/ssint | 0 | 6617655 | <reponame>alexzucca90/ssint
from neal import SimulatedAnnealingSampler
import networkx as nx
import dimod
import numpy as np
# ------- Set up our graph -------
# Create empty graph
G = nx.Graph()
# Add edges to the graph (also adds nodes)
G.add_edges_from([(1, 2),
(1, 3),
(2, 4),
(3, 4),
(3, 5),
(4, 5)])
# ------- Set up our QUBO -------
# Initialize our Q matrix
Q = np.zeros((len(G.nodes), len(G.nodes)))
# Update Q matrix for every edge in the graph
for i, j in G.edges:
Q[i, i] += 1
Q[j, j] += 1
Q[i, j] += 2
qubo = dimod.BinaryQuadraticModel(Q)
# ------- Run our QUBO on SA -------
# Set up SA parameters
numruns = 1
# Run the QUBO on the solver from your config file
sampler = SimulatedAnnealingSampler()
response = sampler.sample_qubo(qubo, num_reads=numruns)
energies = iter(response.data())
print(response)
| from neal import SimulatedAnnealingSampler
import networkx as nx
import dimod
import numpy as np
# ------- Set up our graph -------
# Create empty graph
G = nx.Graph()
# Add edges to the graph (also adds nodes)
G.add_edges_from([(1, 2),
(1, 3),
(2, 4),
(3, 4),
(3, 5),
(4, 5)])
# ------- Set up our QUBO -------
# Initialize our Q matrix
Q = np.zeros((len(G.nodes), len(G.nodes)))
# Update Q matrix for every edge in the graph
for i, j in G.edges:
Q[i, i] += 1
Q[j, j] += 1
Q[i, j] += 2
qubo = dimod.BinaryQuadraticModel(Q)
# ------- Run our QUBO on SA -------
# Set up SA parameters
numruns = 1
# Run the QUBO on the solver from your config file
sampler = SimulatedAnnealingSampler()
response = sampler.sample_qubo(qubo, num_reads=numruns)
energies = iter(response.data())
print(response) | en | 0.593124 | # ------- Set up our graph ------- # Create empty graph # Add edges to the graph (also adds nodes) # ------- Set up our QUBO ------- # Initialize our Q matrix # Update Q matrix for every edge in the graph # ------- Run our QUBO on SA ------- # Set up SA parameters # Run the QUBO on the solver from your config file | 2.65773 | 3 |
2019/days/computer.py | Metamess/AdventOfCode | 0 | 6617656 |
""""
parameter mode 0, position mode
parameter mode 1, immediate mode
parameter mode 2, relative mode
Parameter modes are stored in the same value as the instruction's opcode.
The opcode is the rightmost two digits of the first value in an instruction.
Parameter modes are single digits, one per parameter, read right-to-left from the opcode.
Opcode 1 adds together numbers read from two positions and stores the result in a third position.
Opcode 2 multiplies together numbers read from two positions and stores the result in a third position.
Opcode 3 takes a single integer as input and saves it to the position given by its only parameter. For example, the instruction 3,50 would take an input value and store it at address 50.
Opcode 4 outputs the value of its only parameter. For example, the instruction 4,50 would output the value at address 50.
Opcode 5 is jump-if-true: if the first parameter is non-zero, it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing.
Opcode 6 is jump-if-false: if the first parameter is zero, it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing.
Opcode 7 is less than: if the first parameter is less than the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0.
Opcode 8 is equals: if the first parameter is equal to the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0.
Opcode 9 adjusts the relative base by the value of its only parameter. The relative base increases by the value of the parameter.
Opcode 99 means that the program is finished and should immediately halt.
"""
param_count = [0, 3, 3, 1, 1, 2, 2, 3, 3, 1]
class ProgramMemory(list):
def __getitem__(self, item):
if item >= len(self):
self.extend([0]*(1+item-len(self)))
return super(ProgramMemory, self).__getitem__(item)
def __setitem__(self, key, value):
if key >= len(self):
self.extend([0]*(1+key-len(self)))
return super(ProgramMemory, self).__setitem__(key, value)
def run_program(program, input_values=None, output_values=None):
if input_values is None:
input_values = [0]
if output_values is None:
output_values = []
computer_generator = get_computer(program, input_values)
while True:
value = next(computer_generator)
if type(value) == list:
return value
output_values.append(value)
def get_computer(program, input_values=None):
program = ProgramMemory(program)
if input_values is None:
input_values = [0]
i = 0
input_i = 0
relative_base = 0
while True:
instruction = str(program[i])
# print('instruction: ' + instruction, i)
if len(instruction) == 1:
opcode = program[i]
modes = '0' * param_count[opcode]
else:
opcode = int(str(instruction)[-2:])
if opcode is 99:
break
# print(opcode)
modes = str(instruction)[:-2]
modes = modes[::-1] + '0' * (param_count[opcode] - len(modes))
if opcode is 99:
break
def get_parameter(p_i, pointer=False):
p = program[i + p_i]
if modes[p_i-1] == '1':
assert not pointer
return p
if modes[p_i-1] == '2':
p = relative_base + p
if pointer:
return p
return program[p]
if opcode is 1: # Addition
program[get_parameter(3, True)] = get_parameter(1) + get_parameter(2)
elif opcode is 2: # Multiplication
program[get_parameter(3, True)] = get_parameter(1) * get_parameter(2)
elif opcode is 3: # Set / Use input
if input_i == len(input_values):
input_i = 0
value = input_values[input_i]
input_i += 1
program[get_parameter(1, True)] = value
elif opcode is 4: # Get / Give output
yield get_parameter(1)
elif opcode is 5: # Jump-if-true
if get_parameter(1) != 0:
i = get_parameter(2)
continue
elif opcode is 6: # Jump-if-false
if get_parameter(1) == 0:
i = get_parameter(2)
continue
elif opcode is 7: # Less than
program[get_parameter(3, True)] = 1 if get_parameter(1) < get_parameter(2) else 0
elif opcode is 8: # Equals
program[get_parameter(3, True)] = 1 if get_parameter(1) == get_parameter(2) else 0
elif opcode is 9: # Adjust Relative Base
relative_base += get_parameter(1)
else:
raise ValueError("Unexpected opcode: " + str(opcode))
i += param_count[opcode] + 1
yield list(program)
|
""""
parameter mode 0, position mode
parameter mode 1, immediate mode
parameter mode 2, relative mode
Parameter modes are stored in the same value as the instruction's opcode.
The opcode is the rightmost two digits of the first value in an instruction.
Parameter modes are single digits, one per parameter, read right-to-left from the opcode.
Opcode 1 adds together numbers read from two positions and stores the result in a third position.
Opcode 2 multiplies together numbers read from two positions and stores the result in a third position.
Opcode 3 takes a single integer as input and saves it to the position given by its only parameter. For example, the instruction 3,50 would take an input value and store it at address 50.
Opcode 4 outputs the value of its only parameter. For example, the instruction 4,50 would output the value at address 50.
Opcode 5 is jump-if-true: if the first parameter is non-zero, it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing.
Opcode 6 is jump-if-false: if the first parameter is zero, it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing.
Opcode 7 is less than: if the first parameter is less than the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0.
Opcode 8 is equals: if the first parameter is equal to the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0.
Opcode 9 adjusts the relative base by the value of its only parameter. The relative base increases by the value of the parameter.
Opcode 99 means that the program is finished and should immediately halt.
"""
param_count = [0, 3, 3, 1, 1, 2, 2, 3, 3, 1]
class ProgramMemory(list):
def __getitem__(self, item):
if item >= len(self):
self.extend([0]*(1+item-len(self)))
return super(ProgramMemory, self).__getitem__(item)
def __setitem__(self, key, value):
if key >= len(self):
self.extend([0]*(1+key-len(self)))
return super(ProgramMemory, self).__setitem__(key, value)
def run_program(program, input_values=None, output_values=None):
if input_values is None:
input_values = [0]
if output_values is None:
output_values = []
computer_generator = get_computer(program, input_values)
while True:
value = next(computer_generator)
if type(value) == list:
return value
output_values.append(value)
def get_computer(program, input_values=None):
program = ProgramMemory(program)
if input_values is None:
input_values = [0]
i = 0
input_i = 0
relative_base = 0
while True:
instruction = str(program[i])
# print('instruction: ' + instruction, i)
if len(instruction) == 1:
opcode = program[i]
modes = '0' * param_count[opcode]
else:
opcode = int(str(instruction)[-2:])
if opcode is 99:
break
# print(opcode)
modes = str(instruction)[:-2]
modes = modes[::-1] + '0' * (param_count[opcode] - len(modes))
if opcode is 99:
break
def get_parameter(p_i, pointer=False):
p = program[i + p_i]
if modes[p_i-1] == '1':
assert not pointer
return p
if modes[p_i-1] == '2':
p = relative_base + p
if pointer:
return p
return program[p]
if opcode is 1: # Addition
program[get_parameter(3, True)] = get_parameter(1) + get_parameter(2)
elif opcode is 2: # Multiplication
program[get_parameter(3, True)] = get_parameter(1) * get_parameter(2)
elif opcode is 3: # Set / Use input
if input_i == len(input_values):
input_i = 0
value = input_values[input_i]
input_i += 1
program[get_parameter(1, True)] = value
elif opcode is 4: # Get / Give output
yield get_parameter(1)
elif opcode is 5: # Jump-if-true
if get_parameter(1) != 0:
i = get_parameter(2)
continue
elif opcode is 6: # Jump-if-false
if get_parameter(1) == 0:
i = get_parameter(2)
continue
elif opcode is 7: # Less than
program[get_parameter(3, True)] = 1 if get_parameter(1) < get_parameter(2) else 0
elif opcode is 8: # Equals
program[get_parameter(3, True)] = 1 if get_parameter(1) == get_parameter(2) else 0
elif opcode is 9: # Adjust Relative Base
relative_base += get_parameter(1)
else:
raise ValueError("Unexpected opcode: " + str(opcode))
i += param_count[opcode] + 1
yield list(program)
| en | 0.76895 | " parameter mode 0, position mode parameter mode 1, immediate mode parameter mode 2, relative mode Parameter modes are stored in the same value as the instruction's opcode. The opcode is the rightmost two digits of the first value in an instruction. Parameter modes are single digits, one per parameter, read right-to-left from the opcode. Opcode 1 adds together numbers read from two positions and stores the result in a third position. Opcode 2 multiplies together numbers read from two positions and stores the result in a third position. Opcode 3 takes a single integer as input and saves it to the position given by its only parameter. For example, the instruction 3,50 would take an input value and store it at address 50. Opcode 4 outputs the value of its only parameter. For example, the instruction 4,50 would output the value at address 50. Opcode 5 is jump-if-true: if the first parameter is non-zero, it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing. Opcode 6 is jump-if-false: if the first parameter is zero, it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing. Opcode 7 is less than: if the first parameter is less than the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0. Opcode 8 is equals: if the first parameter is equal to the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0. Opcode 9 adjusts the relative base by the value of its only parameter. The relative base increases by the value of the parameter. Opcode 99 means that the program is finished and should immediately halt. # print('instruction: ' + instruction, i) # print(opcode) # Addition # Multiplication # Set / Use input # Get / Give output # Jump-if-true # Jump-if-false # Less than # Equals # Adjust Relative Base | 4.308863 | 4 |
ansible/docs/resources/scripts/gen_dates.py | menandmice/ansible-module | 2 | 6617657 | #!/usr/bin/env python3
import sys
import os
import calendar
import getopt
import time
import locale
def setdates(usedate=None, r_lang='english'):
docdate = {}
# If the replacement-date is defined, make sure we
# have all other date / time parts as well
if r_lang == 'dutch':
try:
locale.setlocale(locale.LC_ALL, 'nl_NL.utf8')
except locale.Error:
locale.setlocale(locale.LC_ALL, 'nl_NL')
else:
try:
locale.setlocale(locale.LC_ALL, 'en_US.utf8')
except locale.Error:
locale.setlocale(locale.LC_ALL, 'en_US')
# If no document date found, use today
if not usedate:
usedate = time.strftime('%Y-%m-%d')
curdate = time.strptime(usedate, '%Y-%m-%d')
curdate = time.localtime(calendar.timegm(curdate))
docdate['r_year'] = {}
docdate['r_year']['desc'] = 'Year in 4 digits'
docdate['r_year']['val'] = "%04d" % curdate.tm_year
docdate['r_month'] = {}
docdate['r_month']['desc'] = 'Month in 2 digits'
docdate['r_month']['val'] = "%02d" % curdate.tm_mon
docdate['r_mday'] = {}
docdate['r_mday']['desc'] = 'Day in the month in 2 digits'
docdate['r_mday']['val'] = "%02d" % curdate.tm_mday
docdate['r_dayname'] = {}
docdate['r_dayname']['desc'] = 'Full name of the day'
docdate['r_dayname']['val'] = calendar.day_name[curdate.tm_wday]
docdate['r_daynameshort'] = {}
docdate['r_daynameshort']['desc'] = 'Short name of the day'
docdate['r_daynameshort']['val'] = calendar.day_abbr[curdate.tm_wday]
docdate['r_monthname'] = {}
docdate['r_monthname']['desc'] = 'Full name of the month'
docdate['r_monthname']['val'] = calendar.month_name[curdate.tm_mon]
docdate['r_monthnameshort'] = {}
docdate['r_monthnameshort']['desc'] = 'Short name of the month'
docdate['r_monthnameshort']['val'] = calendar.month_abbr[curdate.tm_mon]
docdate['r_weekday'] = {}
docdate['r_weekday']['desc'] = 'Day number in week.'
docdate['r_weekday']['val'] = str(curdate.tm_wday + 1)
docdate['r_yearday'] = {}
docdate['r_yearday']['desc'] = 'Day number in year'
docdate['r_yearday']['val'] = str(curdate.tm_yday)
docdate['r_weekno'] = {}
docdate['r_weekno']['desc'] = 'ISO 8601 week number'
docdate['r_weekno']['val'] = str(time.strftime('%V', curdate))
docdate['r_epoch'] = {}
docdate['r_epoch']['desc'] = 'Time in epoch (from date)'
docdate['r_epoch']['val'] = str(calendar.timegm(curdate))
docdate['r_tz'] = {}
docdate['r_tz']['desc'] = 'Timezone (CET or CEST)'
docdate['r_tzlong'] = {}
docdate['r_tzlong']['desc'] = 'Timezone long format'
docdate['r_tz_offset'] = {}
docdate['r_tz_offset']['desc'] = 'Timezone offset to UTC'
if curdate.tm_isdst == 1:
docdate['r_tz']['val'] = 'CEST'
docdate['r_tzlong']['val'] = 'W. Europe Standard Time'
docdate['r_tz_offset']['val'] = '+02:00'
else:
docdate['r_tz']['val'] = 'CET'
docdate['r_tzlong']['val'] = 'W. Europe Time'
docdate['r_tz_offset']['val'] = '+01:00'
return docdate
# Start of main program
prname = os.path.basename(sys.argv[0])
# First parameter should be the file containing the docdate
if len(sys.argv) < 2:
sys.exit("Syntax: %s fname [english|dutch]" % prname)
# Check file
if not os.path.exists(sys.argv[1]):
sys.exit("%s: File %s does not exist" % (prname, sys.argv[1]))
# And read it
with open(sys.argv[1], 'rt', encoding='utf8') as f:
content = f.readlines()
# Check if a revdate is there
revdate = None
for line in content:
if line.startswith(':revdate:'):
revdate = line.split()[1]
# Check if a language is requested
if len(sys.argv) < 3:
r_lang = 'english'
else:
r_lang = sys.argv[2]
# Get all date formats
docdate = setdates(revdate, r_lang)
# Find longest key
ml = 0
for k in docdate:
ml = max(ml, len(k))
# Print comment header
print("""//
// This file is auto-generated by the '%s' script
//
// This is a list of defined variables you can use in your
// document, to ensure it doesn't get to stale (e.g. code output)
//""" % prname)
# Show all available keys
fstr = '// %-{0}s -> %s'.format(ml)
for k in sorted(docdate):
print(fstr % (k, docdate[k]['desc']))
print('//')
# Show all defined variables
for k in sorted(docdate):
print(':%s: %s' % (k, docdate[k]['val']))
sys.exit(0)
| #!/usr/bin/env python3
import sys
import os
import calendar
import getopt
import time
import locale
def setdates(usedate=None, r_lang='english'):
docdate = {}
# If the replacement-date is defined, make sure we
# have all other date / time parts as well
if r_lang == 'dutch':
try:
locale.setlocale(locale.LC_ALL, 'nl_NL.utf8')
except locale.Error:
locale.setlocale(locale.LC_ALL, 'nl_NL')
else:
try:
locale.setlocale(locale.LC_ALL, 'en_US.utf8')
except locale.Error:
locale.setlocale(locale.LC_ALL, 'en_US')
# If no document date found, use today
if not usedate:
usedate = time.strftime('%Y-%m-%d')
curdate = time.strptime(usedate, '%Y-%m-%d')
curdate = time.localtime(calendar.timegm(curdate))
docdate['r_year'] = {}
docdate['r_year']['desc'] = 'Year in 4 digits'
docdate['r_year']['val'] = "%04d" % curdate.tm_year
docdate['r_month'] = {}
docdate['r_month']['desc'] = 'Month in 2 digits'
docdate['r_month']['val'] = "%02d" % curdate.tm_mon
docdate['r_mday'] = {}
docdate['r_mday']['desc'] = 'Day in the month in 2 digits'
docdate['r_mday']['val'] = "%02d" % curdate.tm_mday
docdate['r_dayname'] = {}
docdate['r_dayname']['desc'] = 'Full name of the day'
docdate['r_dayname']['val'] = calendar.day_name[curdate.tm_wday]
docdate['r_daynameshort'] = {}
docdate['r_daynameshort']['desc'] = 'Short name of the day'
docdate['r_daynameshort']['val'] = calendar.day_abbr[curdate.tm_wday]
docdate['r_monthname'] = {}
docdate['r_monthname']['desc'] = 'Full name of the month'
docdate['r_monthname']['val'] = calendar.month_name[curdate.tm_mon]
docdate['r_monthnameshort'] = {}
docdate['r_monthnameshort']['desc'] = 'Short name of the month'
docdate['r_monthnameshort']['val'] = calendar.month_abbr[curdate.tm_mon]
docdate['r_weekday'] = {}
docdate['r_weekday']['desc'] = 'Day number in week.'
docdate['r_weekday']['val'] = str(curdate.tm_wday + 1)
docdate['r_yearday'] = {}
docdate['r_yearday']['desc'] = 'Day number in year'
docdate['r_yearday']['val'] = str(curdate.tm_yday)
docdate['r_weekno'] = {}
docdate['r_weekno']['desc'] = 'ISO 8601 week number'
docdate['r_weekno']['val'] = str(time.strftime('%V', curdate))
docdate['r_epoch'] = {}
docdate['r_epoch']['desc'] = 'Time in epoch (from date)'
docdate['r_epoch']['val'] = str(calendar.timegm(curdate))
docdate['r_tz'] = {}
docdate['r_tz']['desc'] = 'Timezone (CET or CEST)'
docdate['r_tzlong'] = {}
docdate['r_tzlong']['desc'] = 'Timezone long format'
docdate['r_tz_offset'] = {}
docdate['r_tz_offset']['desc'] = 'Timezone offset to UTC'
if curdate.tm_isdst == 1:
docdate['r_tz']['val'] = 'CEST'
docdate['r_tzlong']['val'] = 'W. Europe Standard Time'
docdate['r_tz_offset']['val'] = '+02:00'
else:
docdate['r_tz']['val'] = 'CET'
docdate['r_tzlong']['val'] = 'W. Europe Time'
docdate['r_tz_offset']['val'] = '+01:00'
return docdate
# Start of main program
prname = os.path.basename(sys.argv[0])
# First parameter should be the file containing the docdate
if len(sys.argv) < 2:
sys.exit("Syntax: %s fname [english|dutch]" % prname)
# Check file
if not os.path.exists(sys.argv[1]):
sys.exit("%s: File %s does not exist" % (prname, sys.argv[1]))
# And read it
with open(sys.argv[1], 'rt', encoding='utf8') as f:
content = f.readlines()
# Check if a revdate is there
revdate = None
for line in content:
if line.startswith(':revdate:'):
revdate = line.split()[1]
# Check if a language is requested
if len(sys.argv) < 3:
r_lang = 'english'
else:
r_lang = sys.argv[2]
# Get all date formats
docdate = setdates(revdate, r_lang)
# Find longest key
ml = 0
for k in docdate:
ml = max(ml, len(k))
# Print comment header
print("""//
// This file is auto-generated by the '%s' script
//
// This is a list of defined variables you can use in your
// document, to ensure it doesn't get to stale (e.g. code output)
//""" % prname)
# Show all available keys
fstr = '// %-{0}s -> %s'.format(ml)
for k in sorted(docdate):
print(fstr % (k, docdate[k]['desc']))
print('//')
# Show all defined variables
for k in sorted(docdate):
print(':%s: %s' % (k, docdate[k]['val']))
sys.exit(0)
| en | 0.724145 | #!/usr/bin/env python3 # If the replacement-date is defined, make sure we # have all other date / time parts as well # If no document date found, use today # Start of main program # First parameter should be the file containing the docdate # Check file # And read it # Check if a revdate is there # Check if a language is requested # Get all date formats # Find longest key # Print comment header // // This file is auto-generated by the '%s' script // // This is a list of defined variables you can use in your // document, to ensure it doesn't get to stale (e.g. code output) // # Show all available keys # Show all defined variables | 2.969172 | 3 |
boatparts/main.py | KalawelaLo/Kattis | 0 | 6617658 | import sys as s
def main():
parts_seasons = list(map(int, s.stdin.readline().split()))
used_parts = set()
for i in range(parts_seasons[1]):
part = s.stdin.readline()
used_parts.add(part)
if(len(used_parts) == parts_seasons[0]):
print(i+1)
return
print("paradox avoided")
main() | import sys as s
def main():
parts_seasons = list(map(int, s.stdin.readline().split()))
used_parts = set()
for i in range(parts_seasons[1]):
part = s.stdin.readline()
used_parts.add(part)
if(len(used_parts) == parts_seasons[0]):
print(i+1)
return
print("paradox avoided")
main() | none | 1 | 3.083848 | 3 | |
src/models/features_tokens.py | jshcs/cfe | 0 | 6617659 | <reponame>jshcs/cfe
from config import *
from utils import *
import datetime
import numpy as np
import validators
import time
import simstring
class Features():
def __init__(self,sentence,fname_list,lname_list,vocab_bioterms,sorted_journals_db,WV):
#self.token=token
#self.jnames_vocab=vocab_journals
self.bioterms_vocab=vocab_bioterms
#len_sorted_journals=len(sorted_journals)
self.db=sorted_journals_db
self.WV=WV
#self.sorted_journals_2=sorted_journals[len_sorted_journals/2:]
#self.sorted_journals_3=sorted_journals[2*len_sorted_journals/3:]
#self.features={k:False for k in config_params['feature_names']}
self.features=[]
self.sentence=sentence
for tok in self.sentence:
self.features.append([False for i in range(len(config_params['feature_names'])+EMD_SIZE)])
self.fname_list=fname_list
self.lname_list=lname_list
#self.times=[]
def is_all_caps(self,token): #0
#return token.isupper()
#s=time.time()
self.features[token][0]=self.sentence[token].isupper()
# e=time.time()
# self.times.append(e-s)
def is_capitalized(self,token): #1
# s=time.time()
self.features[token][1]=self.sentence[token][0].isupper()
# e=time.time()
# self.times.append(e-s)
#return token[0].isupper()
def is_alpha_num(self,token): #2
# s=time.time()
self.features[token][2]=self.sentence[token].isalnum()
# e=time.time()
# self.times.append(e-s)
#return token.isalnum()
def word_length(self,token): #3
# s=time.time()
self.features[token][3]=len(self.sentence[token])
# e=time.time()
# self.times.append(e-s)
#return len(token)
def is_number(self,token): #4
# s=time.time()
self.features[token][4]=self.sentence[token].isdigit()
# e=time.time()
# self.times.append(e-s)
#return token.isdigit()
def ends_with_period(self,token): #5
# s=time.time()
self.features[token][5]=self.sentence[token][-1]=='.'
# e=time.time()
# self.times.append(e-s)
#return token[-1]=="."
def enclosed_brackets(self,token): #6
# s=time.time()
if self.sentence[token][0] in BRACKETS:
if self.sentence[token][-1]==BRACKETS[self.sentence[token][0]]:
self.features[token][6]=True
else:
self.features[token][6]=False
else:
self.features[token][6]=False
# e=time.time()
# self.times.append(e-s)
# if token[0] in BRACKETS:
# if token[-1]==BRACKETS[token[0]]:
# return True
# else:
# return False
# else:
# return False
def has_hyphen(self,token): #7
# s=time.time()
self.features[token][7]=binary_search(sorted(self.sentence[token]),'-',0,len(self.sentence[token])-1)
# e=time.time()
# self.times.append(e-s)
#return binary_search(sorted(token),"-",0,len(token)-1)
def has_colon(self,token): #8
# s=time.time()
self.features[token][8]=binary_search(sorted(self.sentence[token]),':',0,len(self.sentence[token])-1)
# e=time.time()
# self.times.append(e-s)
#return binary_search(sorted(token),':',0,len(token)-1)
def is_etal(self,token): #9
# s=time.time()
self.features[token][9]=self.sentence[token]=='et' or self.sentence[token]=='al'
# e=time.time()
# self.times.append(e-s)
#return token=='et' or token=='al'
def is_valid_year(self,token): #10
# s=time.time()
self.features[token][10]=self.features[max(0,token-1)][11] or self.features[token][4] and self.features[token][3]<=4 and 1<=int(self.sentence[token])<=datetime.datetime.now().year or ((self.sentence[token][0]=='`' or self.sentence[token][0]=="'") and self.sentence[token][1:].isdigit() and self.features[token][3]==3 and 1<=int(self.sentence[token][1:])<=datetime.datetime.now().year)
# e=time.time()
# self.times.append(e-s)
#return (self.is_number(token) and self.word_length(token)<=4 and 1<=int(token)<=datetime.datetime.now().year) or ((token[0]=='`' or token[0]=="'") and self.word_length(token)==3 and 1<=int(token[1:])<=datetime.datetime.now().year)
def is_special_token(self,token): #11
# s=time.time()
self.features[token][11]=binary_search(SPCL_KEYS,self.sentence[token],0,len(SPCL_KEYS)-1)
# e=time.time()
# self.times.append(e-s)
#return binary_search(SPCL_KEYS,token,0,len(SPCL_KEYS)-1)
def has_period_period(self,token): #12
# s=time.time()
if ".." in self.sentence[token]:
self.features[token][12]=True
# e=time.time()
# self.times.append(e-s)
# if ".." in token:
# return True
def has_period_comma(self,token): #13
# s=time.time()
if ".," in self.sentence[token]:
self.features[token][13]=True
# # e=time.time()
# self.times.append(e-s)
def is_url(self,token): #14
# s=time.time()
if validators.url(self.sentence[token]):
self.features[token][14]=True
# e=time.time()
# self.times.append(e-s)
def is_email(self,token): #15
# s=time.time()
if validators.email(self.sentence[token]):
self.features[token][15]=True
# e=time.time()
# self.times.append(e-s)
def first_name_lexicon(self,token): #16
# s=time.time()
if len(self.sentence[token])==2 and self.features[token][1] and self.features[token][5]:
self.features[token][16]=True
# e=time.time()
# self.times.append(e-s)
return
arr=self.fname_list
start=0
end=len(arr)-1
self.features[token][16]=binary_search(arr,self.sentence[token].upper(),start,end)
# e=time.time()
# self.times.append(e-s)
def last_name_lexicon(self,token): #17
# s=time.time()
#arr=read_sorted_file_into_array(SORTED_LPERSON_FNAME)
arr=self.lname_list
start=0
end=len(arr)-1
self.features[token][17]=binary_search(arr,self.sentence[token].upper(),start,end)
# e=time.time()
# self.times.append(e-s)
# def journal_lexicon(self,token): #18
# # s=time.time()
# # if binary_search(self.jnames_vocab,self.sentence[token].lower(),0,len(self.jnames_vocab)-1):
# if self.sentence[token].lower() in self.jnames_vocab:
# self.features[token][18]=True
# else:
# for w in self.jnames_vocab.keys():
# if len(w)>=len(self.sentence[token]):
# if float(longest_common_substring(self.sentence[token].lower(),w))/max(len(self.sentence[token]),len(w))>=0.6:
# self.features[token][18]=True
# break
# e=time.time()
# self.times.append(e-s)
def journal_lexicon(self,token): #18
present=False
upper=token
for win in range(1,MAX_WINDOW):
#if token+win+1<=len(self.sentence):
ss=[s.lower() for s in self.sentence[token:min(token+win+1,len(self.sentence))] if s!="<UNK>"]
substr=' '.join(ss)
# present=binary_search_with_fuzzing(self.sorted_journals_1,str(substr),0,len(self.sorted_journals_1)-1,0.5)
# if present==True:
# #print "****",substr
# upper=win+token
if len(self.db.retrieve(str(substr)))>0:
upper=win+token
present=True
#print "****",str(substr)
if present:
#print token,upper
#if upper+1<=len(self.sentence):
for i in range(token,min(upper+1,len(self.sentence))):
self.features[i][18]=True
# else:
# upper-=1
# for i in range(token,upper+1):
# self.features[i][18]=True
def is_bio_term(self,token): #19
self.features[token][19]=self.sentence[token].lower() in self.bioterms_vocab
def word_embeddings(self,token): #20
try:
self.features[token][20:]=self.WV[self.sentence[token]].tolist()
except:
#print "No match",self.sentence[token]
self.features[token][20:]=[0]*EMD_SIZE
def get_features(self):
e=[0 for i in range(len(config_params["feature_names"]))]
c=0
for tok in range(len(self.sentence)):
if self.sentence[tok]=='<UNK>':
continue
else:
c+=1
s=time.time()
self.is_all_caps(tok)
e[0]+=(time.time()-s)
self.is_capitalized(tok)
e[1]+=(time.time()-s)
self.is_alpha_num(tok)
e[2]+=(time.time()-s)
self.word_length(tok)
e[3]+=(time.time()-s)
self.is_number(tok)
e[4]+=(time.time()-s)
self.ends_with_period(tok)
e[5]+=(time.time()-s)
self.enclosed_brackets(tok)
e[6]+=(time.time()-s)
self.has_hyphen(tok)
e[7]+=(time.time()-s)
self.has_colon(tok)
e[8]+=(time.time()-s)
self.is_etal(tok)
e[9]+=(time.time()-s)
self.is_valid_year(tok)
e[10]+=(time.time()-s)
self.is_special_token(tok)
e[11]+=(time.time()-s)
self.has_period_period(tok)
e[12]+=(time.time()-s)
self.has_period_comma(tok)
e[13]+=(time.time()-s)
self.is_url(tok)
e[14]+=(time.time()-s)
self.is_email(tok)
e[15]+=(time.time()-s)
self.first_name_lexicon(tok)
e[16]+=(time.time()-s)
self.last_name_lexicon(tok)
e[17]+=(time.time()-s)
if self.features[tok][18]==False:
self.journal_lexicon(tok)
e[18]+=(time.time()-s)
self.is_bio_term(tok)
e[19]+=(time.time()-s)
self.word_embeddings(tok)
e[20]+=(time.time()-s)
# print (e1-s),(e2-s),(e3-s),(e4-s),(e5-s),(e6-s),(e7-s),(e8-s),(e9-s),(e10-s),(e11-s),(e12-s),(e13-s),(e14-s),(e15-s),(e16-s),(e17-s),(e18-s),(e19-s),(e20-s),
# print
# print
#print e
return self.features
def vectorize(self):
v = np.array(self.features)
return v
| from config import *
from utils import *
import datetime
import numpy as np
import validators
import time
import simstring
class Features():
def __init__(self,sentence,fname_list,lname_list,vocab_bioterms,sorted_journals_db,WV):
#self.token=token
#self.jnames_vocab=vocab_journals
self.bioterms_vocab=vocab_bioterms
#len_sorted_journals=len(sorted_journals)
self.db=sorted_journals_db
self.WV=WV
#self.sorted_journals_2=sorted_journals[len_sorted_journals/2:]
#self.sorted_journals_3=sorted_journals[2*len_sorted_journals/3:]
#self.features={k:False for k in config_params['feature_names']}
self.features=[]
self.sentence=sentence
for tok in self.sentence:
self.features.append([False for i in range(len(config_params['feature_names'])+EMD_SIZE)])
self.fname_list=fname_list
self.lname_list=lname_list
#self.times=[]
def is_all_caps(self,token): #0
#return token.isupper()
#s=time.time()
self.features[token][0]=self.sentence[token].isupper()
# e=time.time()
# self.times.append(e-s)
def is_capitalized(self,token): #1
# s=time.time()
self.features[token][1]=self.sentence[token][0].isupper()
# e=time.time()
# self.times.append(e-s)
#return token[0].isupper()
def is_alpha_num(self,token): #2
# s=time.time()
self.features[token][2]=self.sentence[token].isalnum()
# e=time.time()
# self.times.append(e-s)
#return token.isalnum()
def word_length(self,token): #3
# s=time.time()
self.features[token][3]=len(self.sentence[token])
# e=time.time()
# self.times.append(e-s)
#return len(token)
def is_number(self,token): #4
# s=time.time()
self.features[token][4]=self.sentence[token].isdigit()
# e=time.time()
# self.times.append(e-s)
#return token.isdigit()
def ends_with_period(self,token): #5
# s=time.time()
self.features[token][5]=self.sentence[token][-1]=='.'
# e=time.time()
# self.times.append(e-s)
#return token[-1]=="."
def enclosed_brackets(self,token): #6
# s=time.time()
if self.sentence[token][0] in BRACKETS:
if self.sentence[token][-1]==BRACKETS[self.sentence[token][0]]:
self.features[token][6]=True
else:
self.features[token][6]=False
else:
self.features[token][6]=False
# e=time.time()
# self.times.append(e-s)
# if token[0] in BRACKETS:
# if token[-1]==BRACKETS[token[0]]:
# return True
# else:
# return False
# else:
# return False
def has_hyphen(self,token): #7
# s=time.time()
self.features[token][7]=binary_search(sorted(self.sentence[token]),'-',0,len(self.sentence[token])-1)
# e=time.time()
# self.times.append(e-s)
#return binary_search(sorted(token),"-",0,len(token)-1)
def has_colon(self,token): #8
# s=time.time()
self.features[token][8]=binary_search(sorted(self.sentence[token]),':',0,len(self.sentence[token])-1)
# e=time.time()
# self.times.append(e-s)
#return binary_search(sorted(token),':',0,len(token)-1)
def is_etal(self,token): #9
# s=time.time()
self.features[token][9]=self.sentence[token]=='et' or self.sentence[token]=='al'
# e=time.time()
# self.times.append(e-s)
#return token=='et' or token=='al'
def is_valid_year(self,token): #10
# s=time.time()
self.features[token][10]=self.features[max(0,token-1)][11] or self.features[token][4] and self.features[token][3]<=4 and 1<=int(self.sentence[token])<=datetime.datetime.now().year or ((self.sentence[token][0]=='`' or self.sentence[token][0]=="'") and self.sentence[token][1:].isdigit() and self.features[token][3]==3 and 1<=int(self.sentence[token][1:])<=datetime.datetime.now().year)
# e=time.time()
# self.times.append(e-s)
#return (self.is_number(token) and self.word_length(token)<=4 and 1<=int(token)<=datetime.datetime.now().year) or ((token[0]=='`' or token[0]=="'") and self.word_length(token)==3 and 1<=int(token[1:])<=datetime.datetime.now().year)
def is_special_token(self,token): #11
# s=time.time()
self.features[token][11]=binary_search(SPCL_KEYS,self.sentence[token],0,len(SPCL_KEYS)-1)
# e=time.time()
# self.times.append(e-s)
#return binary_search(SPCL_KEYS,token,0,len(SPCL_KEYS)-1)
def has_period_period(self,token): #12
# s=time.time()
if ".." in self.sentence[token]:
self.features[token][12]=True
# e=time.time()
# self.times.append(e-s)
# if ".." in token:
# return True
def has_period_comma(self,token): #13
# s=time.time()
if ".," in self.sentence[token]:
self.features[token][13]=True
# # e=time.time()
# self.times.append(e-s)
def is_url(self,token): #14
# s=time.time()
if validators.url(self.sentence[token]):
self.features[token][14]=True
# e=time.time()
# self.times.append(e-s)
def is_email(self,token): #15
# s=time.time()
if validators.email(self.sentence[token]):
self.features[token][15]=True
# e=time.time()
# self.times.append(e-s)
def first_name_lexicon(self,token): #16
# s=time.time()
if len(self.sentence[token])==2 and self.features[token][1] and self.features[token][5]:
self.features[token][16]=True
# e=time.time()
# self.times.append(e-s)
return
arr=self.fname_list
start=0
end=len(arr)-1
self.features[token][16]=binary_search(arr,self.sentence[token].upper(),start,end)
# e=time.time()
# self.times.append(e-s)
def last_name_lexicon(self,token): #17
# s=time.time()
#arr=read_sorted_file_into_array(SORTED_LPERSON_FNAME)
arr=self.lname_list
start=0
end=len(arr)-1
self.features[token][17]=binary_search(arr,self.sentence[token].upper(),start,end)
# e=time.time()
# self.times.append(e-s)
# def journal_lexicon(self,token): #18
# # s=time.time()
# # if binary_search(self.jnames_vocab,self.sentence[token].lower(),0,len(self.jnames_vocab)-1):
# if self.sentence[token].lower() in self.jnames_vocab:
# self.features[token][18]=True
# else:
# for w in self.jnames_vocab.keys():
# if len(w)>=len(self.sentence[token]):
# if float(longest_common_substring(self.sentence[token].lower(),w))/max(len(self.sentence[token]),len(w))>=0.6:
# self.features[token][18]=True
# break
# e=time.time()
# self.times.append(e-s)
def journal_lexicon(self,token): #18
present=False
upper=token
for win in range(1,MAX_WINDOW):
#if token+win+1<=len(self.sentence):
ss=[s.lower() for s in self.sentence[token:min(token+win+1,len(self.sentence))] if s!="<UNK>"]
substr=' '.join(ss)
# present=binary_search_with_fuzzing(self.sorted_journals_1,str(substr),0,len(self.sorted_journals_1)-1,0.5)
# if present==True:
# #print "****",substr
# upper=win+token
if len(self.db.retrieve(str(substr)))>0:
upper=win+token
present=True
#print "****",str(substr)
if present:
#print token,upper
#if upper+1<=len(self.sentence):
for i in range(token,min(upper+1,len(self.sentence))):
self.features[i][18]=True
# else:
# upper-=1
# for i in range(token,upper+1):
# self.features[i][18]=True
def is_bio_term(self,token): #19
self.features[token][19]=self.sentence[token].lower() in self.bioterms_vocab
def word_embeddings(self,token): #20
try:
self.features[token][20:]=self.WV[self.sentence[token]].tolist()
except:
#print "No match",self.sentence[token]
self.features[token][20:]=[0]*EMD_SIZE
def get_features(self):
e=[0 for i in range(len(config_params["feature_names"]))]
c=0
for tok in range(len(self.sentence)):
if self.sentence[tok]=='<UNK>':
continue
else:
c+=1
s=time.time()
self.is_all_caps(tok)
e[0]+=(time.time()-s)
self.is_capitalized(tok)
e[1]+=(time.time()-s)
self.is_alpha_num(tok)
e[2]+=(time.time()-s)
self.word_length(tok)
e[3]+=(time.time()-s)
self.is_number(tok)
e[4]+=(time.time()-s)
self.ends_with_period(tok)
e[5]+=(time.time()-s)
self.enclosed_brackets(tok)
e[6]+=(time.time()-s)
self.has_hyphen(tok)
e[7]+=(time.time()-s)
self.has_colon(tok)
e[8]+=(time.time()-s)
self.is_etal(tok)
e[9]+=(time.time()-s)
self.is_valid_year(tok)
e[10]+=(time.time()-s)
self.is_special_token(tok)
e[11]+=(time.time()-s)
self.has_period_period(tok)
e[12]+=(time.time()-s)
self.has_period_comma(tok)
e[13]+=(time.time()-s)
self.is_url(tok)
e[14]+=(time.time()-s)
self.is_email(tok)
e[15]+=(time.time()-s)
self.first_name_lexicon(tok)
e[16]+=(time.time()-s)
self.last_name_lexicon(tok)
e[17]+=(time.time()-s)
if self.features[tok][18]==False:
self.journal_lexicon(tok)
e[18]+=(time.time()-s)
self.is_bio_term(tok)
e[19]+=(time.time()-s)
self.word_embeddings(tok)
e[20]+=(time.time()-s)
# print (e1-s),(e2-s),(e3-s),(e4-s),(e5-s),(e6-s),(e7-s),(e8-s),(e9-s),(e10-s),(e11-s),(e12-s),(e13-s),(e14-s),(e15-s),(e16-s),(e17-s),(e18-s),(e19-s),(e20-s),
# print
# print
#print e
return self.features
def vectorize(self):
v = np.array(self.features)
return v | en | 0.205898 | #self.token=token #self.jnames_vocab=vocab_journals #len_sorted_journals=len(sorted_journals) #self.sorted_journals_2=sorted_journals[len_sorted_journals/2:] #self.sorted_journals_3=sorted_journals[2*len_sorted_journals/3:] #self.features={k:False for k in config_params['feature_names']} #self.times=[] #0 #return token.isupper() #s=time.time() # e=time.time() # self.times.append(e-s) #1 # s=time.time() # e=time.time() # self.times.append(e-s) #return token[0].isupper() #2 # s=time.time() # e=time.time() # self.times.append(e-s) #return token.isalnum() #3 # s=time.time() # e=time.time() # self.times.append(e-s) #return len(token) #4 # s=time.time() # e=time.time() # self.times.append(e-s) #return token.isdigit() #5 # s=time.time() # e=time.time() # self.times.append(e-s) #return token[-1]=="." #6 # s=time.time() # e=time.time() # self.times.append(e-s) # if token[0] in BRACKETS: # if token[-1]==BRACKETS[token[0]]: # return True # else: # return False # else: # return False #7 # s=time.time() # e=time.time() # self.times.append(e-s) #return binary_search(sorted(token),"-",0,len(token)-1) #8 # s=time.time() # e=time.time() # self.times.append(e-s) #return binary_search(sorted(token),':',0,len(token)-1) #9 # s=time.time() # e=time.time() # self.times.append(e-s) #return token=='et' or token=='al' #10 # s=time.time() # e=time.time() # self.times.append(e-s) #return (self.is_number(token) and self.word_length(token)<=4 and 1<=int(token)<=datetime.datetime.now().year) or ((token[0]=='`' or token[0]=="'") and self.word_length(token)==3 and 1<=int(token[1:])<=datetime.datetime.now().year) #11 # s=time.time() # e=time.time() # self.times.append(e-s) #return binary_search(SPCL_KEYS,token,0,len(SPCL_KEYS)-1) #12 # s=time.time() # e=time.time() # self.times.append(e-s) # if ".." in token: # return True #13 # s=time.time() # # e=time.time() # self.times.append(e-s) #14 # s=time.time() # e=time.time() # self.times.append(e-s) #15 # s=time.time() # e=time.time() # self.times.append(e-s) #16 # s=time.time() # e=time.time() # self.times.append(e-s) # e=time.time() # self.times.append(e-s) #17 # s=time.time() #arr=read_sorted_file_into_array(SORTED_LPERSON_FNAME) # e=time.time() # self.times.append(e-s) # def journal_lexicon(self,token): #18 # # s=time.time() # # if binary_search(self.jnames_vocab,self.sentence[token].lower(),0,len(self.jnames_vocab)-1): # if self.sentence[token].lower() in self.jnames_vocab: # self.features[token][18]=True # else: # for w in self.jnames_vocab.keys(): # if len(w)>=len(self.sentence[token]): # if float(longest_common_substring(self.sentence[token].lower(),w))/max(len(self.sentence[token]),len(w))>=0.6: # self.features[token][18]=True # break # e=time.time() # self.times.append(e-s) #18 #if token+win+1<=len(self.sentence): # present=binary_search_with_fuzzing(self.sorted_journals_1,str(substr),0,len(self.sorted_journals_1)-1,0.5) # if present==True: # #print "****",substr # upper=win+token #print "****",str(substr) #print token,upper #if upper+1<=len(self.sentence): # else: # upper-=1 # for i in range(token,upper+1): # self.features[i][18]=True #19 #20 #print "No match",self.sentence[token] # print (e1-s),(e2-s),(e3-s),(e4-s),(e5-s),(e6-s),(e7-s),(e8-s),(e9-s),(e10-s),(e11-s),(e12-s),(e13-s),(e14-s),(e15-s),(e16-s),(e17-s),(e18-s),(e19-s),(e20-s), # print # print #print e | 2.796818 | 3 |
lib/layers/torchdiffeq/_impl/heun_euler.py | hanhsienhuang/CNF-TPR | 0 | 6617660 | # Based on https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/integrate
import torch
from .misc import (
_scaled_dot_product, _convert_to_tensor, _is_finite, _select_initial_step, _handle_unused_kwargs, _is_iterable,
_optimal_step_size, _compute_error_ratio
)
from .solvers import AdaptiveStepsizeODESolver
from .rk_common import _RungeKuttaState, _ButcherTableau, _runge_kutta_step
_TABLEAU = _ButcherTableau(
alpha=[1.],
beta=[
[1.],
],
c_sol=[1/2, 1/2],
c_error=[
-1/2,
1/2
],
)
_TABLEAU = _ButcherTableau(
alpha=[1/2, 1.],
beta=[
[1/2],
[1/256, 255/256],
],
c_sol=[1/256, 255/256],
c_error=[
1/256 - 1/512,
0,
- 1/512,
],
)
def _interp_evaluate(t0, y0, t1, y1, t):
"""Fit an interpolating polynomial to the results of a Runge-Kutta step."""
t0 = t0.type_as(y0[0])
t1 = t1.type_as(y0[0])
t = t.type_as(y0[0])
dt = t1-t0
return tuple(y0_*((t1-t)/dt) + y1_*((t-t0)/dt) for y0_, y1_ in zip(y0, y1) )
#def _abs_square(x):
# return torch.mul(x, x)
#
#
#def _ta_append(list_of_tensors, value):
# """Append a value to the end of a list of PyTorch tensors."""
# list_of_tensors.append(value)
# return list_of_tensors
class HeunEuler(AdaptiveStepsizeODESolver):
def __init__(
self, func, y0, rtol, atol, first_step=None, safety=0.9, ifactor=10.0, dfactor=0.2, max_num_steps=2**31 - 1,
**unused_kwargs
):
_handle_unused_kwargs(self, unused_kwargs)
del unused_kwargs
self.func = func
self.y0 = y0
self.rtol = rtol if _is_iterable(rtol) else [rtol] * len(y0)
self.atol = atol if _is_iterable(atol) else [atol] * len(y0)
self.next_step = first_step
self.safety = _convert_to_tensor(safety, dtype=torch.float64, device=y0[0].device)
self.ifactor = _convert_to_tensor(ifactor, dtype=torch.float64, device=y0[0].device)
self.dfactor = _convert_to_tensor(dfactor, dtype=torch.float64, device=y0[0].device)
self.max_num_steps = _convert_to_tensor(max_num_steps, dtype=torch.int32, device=y0[0].device)
def before_integrate(self, t):
f0 = self.func(t[0].type_as(self.y0[0]), self.y0)
if self.next_step is None:
first_step = _select_initial_step(self.func, t[0], self.y0, 1, self.rtol[0], self.atol[0], f0=f0).to(t)
else:
first_step = self.next_step
self.rk_state = _RungeKuttaState(self.y0, f0, t[0], t[0], first_step, None)
def advance(self, next_t):
"""Interpolate through the next time point, integrating as necessary."""
n_steps = 0
while next_t > self.rk_state.t1:
assert n_steps < self.max_num_steps, 'max_num_steps exceeded ({}>={})'.format(n_steps, self.max_num_steps)
#print(self.rk_state.dt)
self.rk_state = self._adaptive_dopri5_step(self.rk_state)
n_steps += 1
self.next_step = self.rk_state.dt
return _interp_evaluate(self.rk_state.t0, self.rk_state.interp_coeff, self.rk_state.t1, self.rk_state.y1, next_t)
def _adaptive_dopri5_step(self, rk_state):
"""Take an adaptive Runge-Kutta step to integrate the ODE."""
y0, f0, _, t0, dt, interp_coeff = rk_state
#print(dt)
########################################################
# Assertions #
########################################################
assert t0 + dt > t0, 'underflow in dt {}'.format(dt.item())
for y0_ in y0:
assert _is_finite(torch.abs(y0_)), 'non-finite values in state `y`: {}'.format(y0_)
y1, f1, y1_error, k = _runge_kutta_step(self.func, y0, f0, t0, dt, tableau=_TABLEAU)
########################################################
# Error Ratio #
########################################################
mean_sq_error_ratio = _compute_error_ratio(y1_error, atol=self.atol, rtol=self.rtol, y0=y0, y1=y1)
accept_step = (torch.tensor(mean_sq_error_ratio) <= 1).all()
########################################################
# Update RK State #
########################################################
y_next = y1 if accept_step else y0
f_next = f1 if accept_step else f0
t_next = t0 + dt if accept_step else t0
interp_coeff = y0 if accept_step else interp_coeff
dt_next = _optimal_step_size(
dt, mean_sq_error_ratio, safety=self.safety, ifactor=self.ifactor, dfactor=self.dfactor, order=2
)
rk_state = _RungeKuttaState(y_next, f_next, t0, t_next, dt_next, interp_coeff)
return rk_state
| # Based on https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/integrate
import torch
from .misc import (
_scaled_dot_product, _convert_to_tensor, _is_finite, _select_initial_step, _handle_unused_kwargs, _is_iterable,
_optimal_step_size, _compute_error_ratio
)
from .solvers import AdaptiveStepsizeODESolver
from .rk_common import _RungeKuttaState, _ButcherTableau, _runge_kutta_step
_TABLEAU = _ButcherTableau(
alpha=[1.],
beta=[
[1.],
],
c_sol=[1/2, 1/2],
c_error=[
-1/2,
1/2
],
)
_TABLEAU = _ButcherTableau(
alpha=[1/2, 1.],
beta=[
[1/2],
[1/256, 255/256],
],
c_sol=[1/256, 255/256],
c_error=[
1/256 - 1/512,
0,
- 1/512,
],
)
def _interp_evaluate(t0, y0, t1, y1, t):
"""Fit an interpolating polynomial to the results of a Runge-Kutta step."""
t0 = t0.type_as(y0[0])
t1 = t1.type_as(y0[0])
t = t.type_as(y0[0])
dt = t1-t0
return tuple(y0_*((t1-t)/dt) + y1_*((t-t0)/dt) for y0_, y1_ in zip(y0, y1) )
#def _abs_square(x):
# return torch.mul(x, x)
#
#
#def _ta_append(list_of_tensors, value):
# """Append a value to the end of a list of PyTorch tensors."""
# list_of_tensors.append(value)
# return list_of_tensors
class HeunEuler(AdaptiveStepsizeODESolver):
def __init__(
self, func, y0, rtol, atol, first_step=None, safety=0.9, ifactor=10.0, dfactor=0.2, max_num_steps=2**31 - 1,
**unused_kwargs
):
_handle_unused_kwargs(self, unused_kwargs)
del unused_kwargs
self.func = func
self.y0 = y0
self.rtol = rtol if _is_iterable(rtol) else [rtol] * len(y0)
self.atol = atol if _is_iterable(atol) else [atol] * len(y0)
self.next_step = first_step
self.safety = _convert_to_tensor(safety, dtype=torch.float64, device=y0[0].device)
self.ifactor = _convert_to_tensor(ifactor, dtype=torch.float64, device=y0[0].device)
self.dfactor = _convert_to_tensor(dfactor, dtype=torch.float64, device=y0[0].device)
self.max_num_steps = _convert_to_tensor(max_num_steps, dtype=torch.int32, device=y0[0].device)
def before_integrate(self, t):
f0 = self.func(t[0].type_as(self.y0[0]), self.y0)
if self.next_step is None:
first_step = _select_initial_step(self.func, t[0], self.y0, 1, self.rtol[0], self.atol[0], f0=f0).to(t)
else:
first_step = self.next_step
self.rk_state = _RungeKuttaState(self.y0, f0, t[0], t[0], first_step, None)
def advance(self, next_t):
"""Interpolate through the next time point, integrating as necessary."""
n_steps = 0
while next_t > self.rk_state.t1:
assert n_steps < self.max_num_steps, 'max_num_steps exceeded ({}>={})'.format(n_steps, self.max_num_steps)
#print(self.rk_state.dt)
self.rk_state = self._adaptive_dopri5_step(self.rk_state)
n_steps += 1
self.next_step = self.rk_state.dt
return _interp_evaluate(self.rk_state.t0, self.rk_state.interp_coeff, self.rk_state.t1, self.rk_state.y1, next_t)
def _adaptive_dopri5_step(self, rk_state):
"""Take an adaptive Runge-Kutta step to integrate the ODE."""
y0, f0, _, t0, dt, interp_coeff = rk_state
#print(dt)
########################################################
# Assertions #
########################################################
assert t0 + dt > t0, 'underflow in dt {}'.format(dt.item())
for y0_ in y0:
assert _is_finite(torch.abs(y0_)), 'non-finite values in state `y`: {}'.format(y0_)
y1, f1, y1_error, k = _runge_kutta_step(self.func, y0, f0, t0, dt, tableau=_TABLEAU)
########################################################
# Error Ratio #
########################################################
mean_sq_error_ratio = _compute_error_ratio(y1_error, atol=self.atol, rtol=self.rtol, y0=y0, y1=y1)
accept_step = (torch.tensor(mean_sq_error_ratio) <= 1).all()
########################################################
# Update RK State #
########################################################
y_next = y1 if accept_step else y0
f_next = f1 if accept_step else f0
t_next = t0 + dt if accept_step else t0
interp_coeff = y0 if accept_step else interp_coeff
dt_next = _optimal_step_size(
dt, mean_sq_error_ratio, safety=self.safety, ifactor=self.ifactor, dfactor=self.dfactor, order=2
)
rk_state = _RungeKuttaState(y_next, f_next, t0, t_next, dt_next, interp_coeff)
return rk_state
| de | 0.391136 | # Based on https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/integrate Fit an interpolating polynomial to the results of a Runge-Kutta step. #def _abs_square(x): # return torch.mul(x, x) # # #def _ta_append(list_of_tensors, value): # """Append a value to the end of a list of PyTorch tensors.""" # list_of_tensors.append(value) # return list_of_tensors Interpolate through the next time point, integrating as necessary. #print(self.rk_state.dt) Take an adaptive Runge-Kutta step to integrate the ODE. #print(dt) ######################################################## # Assertions # ######################################################## ######################################################## # Error Ratio # ######################################################## ######################################################## # Update RK State # ######################################################## | 2.282558 | 2 |
MudConst.py | fhaynes/slithermud | 0 | 6617661 | """
This has a few constants the mud uses.
@author: <NAME>
@copyright: (c)2007 <NAME>, All rights reserved.
"""
import sys
import os
# Connection States
getAccountName = 1
getAccountPassword = 2
getNewAccountName = 3
getNewAccountPass = 4
confirmNewAccountName = 5
confirmNewAccountPass = 6
logedIn = 7
# Character ranks in the MUD
player = 1
enforcer = 2
builder = 3
administrator = 4
# Admin levels
player = 1
enforcer = 2
builder = 3
scripter = 4
implementor = 5
port = 5003
# Home directory
homeDir = os.path.abspath(os.getcwd()+os.sep)
# Zone directory
zoneDir = os.path.join(homeDir, 'zones'+os.sep)
# Location of the zone loadlist, i.e., the names of all the zones to load into
# the game
zoneList = zoneDir + 'zone_index.txt'
# Logic Directory
logicDir = homeDir+ os.sep + 'logics' + os.sep
logicIndex = logicDir + 'logic_index.txt'
playerDir = homeDir + os.sep + 'players' + os.sep
log_dir = homeDir + os.sep + 'logs' + os.sep
# Path to the database directory
databaseDir = homeDir+os.sep+'databases'+os.sep
# Path to the ID Database
idDatabasePath = databaseDir+'idDatabase.mdb'
# Path to the Template Database
templateDatabasePath = databaseDir+'templateDatabase.mdb'
# Path to the Timed Action database
timerDatabasePath = databaseDir+'timerDatabase.mdb'
# Path to the saved game time variable
gameTimePath = databaseDir+'currentGameTime.mdb'
# Path to the credits file
creditPath = homeDir+'credits.txt'
# Adds some stuff to the PATH
sys.path.append(zoneDir)
sys.path.append(os.path.join(homeDir, 'commands'))
sys.path.append(os.path.join(homeDir, 'logics'))
sys.path.append(os.path.join(homeDir, 'utils'))
greeting = '''<green>\r\n\r\n\tSlitherMUD\r\n
<r>\t<cyan>By: Kuros
<r>\r\n''' | """
This has a few constants the mud uses.
@author: <NAME>
@copyright: (c)2007 <NAME>, All rights reserved.
"""
import sys
import os
# Connection States
getAccountName = 1
getAccountPassword = 2
getNewAccountName = 3
getNewAccountPass = 4
confirmNewAccountName = 5
confirmNewAccountPass = 6
logedIn = 7
# Character ranks in the MUD
player = 1
enforcer = 2
builder = 3
administrator = 4
# Admin levels
player = 1
enforcer = 2
builder = 3
scripter = 4
implementor = 5
port = 5003
# Home directory
homeDir = os.path.abspath(os.getcwd()+os.sep)
# Zone directory
zoneDir = os.path.join(homeDir, 'zones'+os.sep)
# Location of the zone loadlist, i.e., the names of all the zones to load into
# the game
zoneList = zoneDir + 'zone_index.txt'
# Logic Directory
logicDir = homeDir+ os.sep + 'logics' + os.sep
logicIndex = logicDir + 'logic_index.txt'
playerDir = homeDir + os.sep + 'players' + os.sep
log_dir = homeDir + os.sep + 'logs' + os.sep
# Path to the database directory
databaseDir = homeDir+os.sep+'databases'+os.sep
# Path to the ID Database
idDatabasePath = databaseDir+'idDatabase.mdb'
# Path to the Template Database
templateDatabasePath = databaseDir+'templateDatabase.mdb'
# Path to the Timed Action database
timerDatabasePath = databaseDir+'timerDatabase.mdb'
# Path to the saved game time variable
gameTimePath = databaseDir+'currentGameTime.mdb'
# Path to the credits file
creditPath = homeDir+'credits.txt'
# Adds some stuff to the PATH
sys.path.append(zoneDir)
sys.path.append(os.path.join(homeDir, 'commands'))
sys.path.append(os.path.join(homeDir, 'logics'))
sys.path.append(os.path.join(homeDir, 'utils'))
greeting = '''<green>\r\n\r\n\tSlitherMUD\r\n
<r>\t<cyan>By: Kuros
<r>\r\n''' | en | 0.807583 | This has a few constants the mud uses. @author: <NAME> @copyright: (c)2007 <NAME>, All rights reserved. # Connection States # Character ranks in the MUD # Admin levels # Home directory # Zone directory # Location of the zone loadlist, i.e., the names of all the zones to load into # the game # Logic Directory # Path to the database directory # Path to the ID Database # Path to the Template Database # Path to the Timed Action database # Path to the saved game time variable # Path to the credits file # Adds some stuff to the PATH <green>\r\n\r\n\tSlitherMUD\r\n <r>\t<cyan>By: Kuros <r>\r\n | 2.077546 | 2 |
official/cv/crnn/postprocess.py | leelige/mindspore | 77 | 6617662 | <reponame>leelige/mindspore
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""post process for 310 inference"""
import os
import numpy as np
from src.metric import CRNNAccuracy
from src.model_utils.config import config
def read_annotation(ann_file):
file = open(ann_file)
ann = {}
for line in file.readlines():
img_info = line.rsplit("/")[-1].split(",")
img_path = img_info[0].split('/')[-1]
ann[img_path] = img_info[1].strip()
return ann
def read_ic13_annotation(ann_file):
file = open(ann_file)
ann = {}
for line in file.readlines():
img_info = line.split(",")
img_path = img_info[0].split('/')[-1]
ann[img_path] = img_info[1].strip().replace('\"', '')
return ann
def read_svt_annotation(ann_file):
file = open(ann_file)
ann = {}
for line in file.readlines():
img_info = line.split(",")
img_path = img_info[0].split('/')[-1]
ann[img_path] = img_info[1].strip()
return ann
def get_eval_result(result_path, ann_file):
"""
Calculate accuracy according to the annotation file and result file.
"""
metrics = CRNNAccuracy(config)
if config.dataset == "ic03" or config.dataset == "iiit5k":
ann = read_annotation(ann_file)
elif config.dataset == "ic13":
ann = read_ic13_annotation(ann_file)
elif config.dataset == "svt":
ann = read_svt_annotation(ann_file)
for img_name, label in ann.items():
result_file = os.path.join(result_path, img_name[:-4] + "_0.bin")
pred_y = np.fromfile(result_file, dtype=np.float16).reshape(config.num_step, -1, config.class_num)
metrics.update(pred_y, [label])
print("result CRNNAccuracy is: ", metrics.eval())
metrics.clear()
if __name__ == '__main__':
get_eval_result(config.result_path, config.ann_file)
| # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""post process for 310 inference"""
import os
import numpy as np
from src.metric import CRNNAccuracy
from src.model_utils.config import config
def read_annotation(ann_file):
file = open(ann_file)
ann = {}
for line in file.readlines():
img_info = line.rsplit("/")[-1].split(",")
img_path = img_info[0].split('/')[-1]
ann[img_path] = img_info[1].strip()
return ann
def read_ic13_annotation(ann_file):
file = open(ann_file)
ann = {}
for line in file.readlines():
img_info = line.split(",")
img_path = img_info[0].split('/')[-1]
ann[img_path] = img_info[1].strip().replace('\"', '')
return ann
def read_svt_annotation(ann_file):
file = open(ann_file)
ann = {}
for line in file.readlines():
img_info = line.split(",")
img_path = img_info[0].split('/')[-1]
ann[img_path] = img_info[1].strip()
return ann
def get_eval_result(result_path, ann_file):
"""
Calculate accuracy according to the annotation file and result file.
"""
metrics = CRNNAccuracy(config)
if config.dataset == "ic03" or config.dataset == "iiit5k":
ann = read_annotation(ann_file)
elif config.dataset == "ic13":
ann = read_ic13_annotation(ann_file)
elif config.dataset == "svt":
ann = read_svt_annotation(ann_file)
for img_name, label in ann.items():
result_file = os.path.join(result_path, img_name[:-4] + "_0.bin")
pred_y = np.fromfile(result_file, dtype=np.float16).reshape(config.num_step, -1, config.class_num)
metrics.update(pred_y, [label])
print("result CRNNAccuracy is: ", metrics.eval())
metrics.clear()
if __name__ == '__main__':
get_eval_result(config.result_path, config.ann_file) | en | 0.815844 | # Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ post process for 310 inference Calculate accuracy according to the annotation file and result file. | 2.324548 | 2 |
graphs_util.py | rottedBen/bot-charts | 0 | 6617663 | import datetime
import time
import pandas as pd
import requests_util
import numpy as np
import plotly.io as pio
import pprint
INCREASING_COLOR = '#228B22'
DECREASING_COLOR = '#FF0000'
def __moving_average(interval, window_size=10):
window = np.ones(int(window_size)) / float(window_size)
return np.convolve(interval, window, 'same')
def __bbands(price, window_size=10, num_of_std=5):
price_pd = pd.DataFrame(price)
rolling_mean = price_pd.rolling(window=window_size).mean()
rolling_std = price_pd.rolling(window=window_size).std()
upper_band = rolling_mean + (rolling_std * num_of_std)
lower_band = rolling_mean - (rolling_std * num_of_std)
return rolling_mean, upper_band, lower_band
# Visualisation inspired by https://chart-studio.plotly.com/~jackp/17421/plotly-candlestick-chart-in-python/#/
# Huge thanks to the author!
def __process_and_write_candlelight(dates, openings, closes, highs, lows, volumes, file_path, token_name):
data = [dict(
type='candlestick',
open=openings,
high=highs,
low=lows,
close=closes,
x=dates,
yaxis='y2',
name='GS',
increasing=dict(line=dict(color=INCREASING_COLOR)),
decreasing=dict(line=dict(color=DECREASING_COLOR)),
)]
# max_price = max(highs)
# max_y = max_price + max_price * 0.2
# min_price = min(lows)
# min_y = max(0, min_price - min_price * 0.2)
layout = dict()
fig = dict(data=data, layout=layout)
fig['layout'] = dict()
fig['layout']['plot_bgcolor'] = 'rgb(250, 250, 250)'
fig['layout']['autosize'] = False
fig['layout']['width'] = 1600
fig['layout']['height'] = 900
fig['layout']['xaxis'] = dict(rangeslider=dict(visible=False))
fig['layout']['yaxis'] = dict(domain=[0, 0.19], showticklabels=True, title='Volume ($)', side='right')
fig['layout']['yaxis2'] = dict(domain=[0.2, 1], title=token_name + ' price ($)', side='right')
fig['layout']['showlegend'] = False
fig['layout']['margin'] = dict(t=15, b=15, r=15, l=15)
# bb_avg, bb_upper, bb_lower = __bbands(closes)
#
# fig['data'].append(dict(x=dates, y=bb_upper[0].to_list(), type='scatter', yaxis='y2',
# line=dict(width=1),
# marker=dict(color='#ccc'), hoverinfo='none',
# legendgroup='Bollinger Bands', name='Bollinger Bands'))
#
#
# fig['data'].append(dict(x=dates, y=bb_lower[0].to_list(), type='scatter', yaxis='y2',
# line=dict(width=1),
# marker=dict(color='#ccc'), hoverinfo='none',
# legendgroup='Bollinger Bands', showlegend=False))
mv_y = __moving_average(closes)
mv_x = list(dates)
# Clip the ends
mv_x = mv_x[5:-5]
mv_y = mv_y[5:-5]
fig['data'].append(dict(x=mv_x, y=mv_y, type='scatter', mode='lines',
line=dict(width=2),
marker=dict(color='#E377C2'),
yaxis='y2', name='Moving Average'))
colors_volume = []
for i in range(len(closes)):
if i != 0:
if closes[i] > closes[i - 1]:
colors_volume.append(INCREASING_COLOR)
else:
colors_volume.append(DECREASING_COLOR)
else:
colors_volume.append(DECREASING_COLOR)
fig['data'].append(dict(x=dates, y=volumes,
marker=dict(color=colors_volume),
type='bar', yaxis='y', name='Volume'))
pio.write_image(fig=fig, file=file_path, scale=3)
# t_from and t_to should be numbers, not strings
def __calculate_resolution_from_time(t_from, t_to):
delta = round(t_to - t_from)
if delta < 6 * 3600:
return 1
elif delta < 13 * 3600:
return 5
elif delta < 24 * 3600:
return 15
elif delta < 24 * 3600 * 7 + 100:
return 30
else:
return 60
def __preprocess_chartex_data(values, resolution):
times_from_chartex = [datetime.datetime.fromtimestamp(round(x)) for x in values['t']]
closes = [float(x) for x in values['c']]
opens = [float(x) for x in values['o']]
highs = [float(x) for x in values['h']]
lows = [float(x) for x in values['l']]
volumes = [float(x) for x in values['v']]
frequency = str(resolution) + "min"
date_list = pd.date_range(start=times_from_chartex[0], end=times_from_chartex[-1],
freq=frequency).to_pydatetime().tolist()
last_index = 0
missing_dates_count = 0
for date in date_list:
if date in times_from_chartex:
index = times_from_chartex.index(date)
last_index = index + missing_dates_count
# check if "too big" value and remove it in this case
if index == 0:
if highs[0] > highs[1] * 2:
# print("reducing highs index 0")
highs[0] = min(highs[1] * 3, highs[0] / 2)
if lows[0] < lows[1] / 2:
# print("increasing lows index 0")
lows[0] = max(lows[0] * 2, lows[1] / 2)
else:
if highs[index] > highs[index - 1] * 2 and highs[index] > highs[index + 1] * 2:
# print("reducing highs")
highs[index] = (highs[index - 1] + highs[index + 1])
if lows[index] < lows[index - 1] / 2 and lows[index] < lows[index + 1] / 2:
# print("increasing lows: from " + str(lows[index]) + ' to ' + str(min(lows[index - 1] - lows[index], lows[index + 1] - lows[index])))
lows[index] = min(lows[index - 1] - lows[index], lows[index + 1] - lows[index])
else:
index = last_index + 1
price = closes[index - 1]
closes.insert(index, price)
highs.insert(index, price)
lows.insert(index, price)
opens.insert(index, price)
volumes.insert(index, 0.0)
last_index = last_index + 1
missing_dates_count += 1
return (date_list, opens, closes, highs, lows, volumes)
# t_from and t_to should be int epoch second
# return the last price
def print_candlestick(token, t_from, t_to, file_path):
resolution = __calculate_resolution_from_time(t_from, t_to)
values = requests_util.get_graphex_data(token, resolution, t_from, t_to).json()
(date_list, opens, closes, highs, lows, volumes) = __preprocess_chartex_data(values, resolution)
__process_and_write_candlelight(date_list, opens, closes, highs, lows, volumes, file_path, token)
return closes[-1]
#
# def test_print_candlestick(token, t_from, t_to, resolution=1):
# t_1 = time.time_ns() // 1000000
# values = requests_util.get_graphex_data(token, resolution, t_from, t_to).json()
# t_2 = time.time_ns() // 1000000
# (date_list, opens, closes, highs, lows, volumes) = __preprocess_chartex_data(values, resolution)
# print("0 = " + str(date_list[0]))
# print("last = " + str(date_list[-1]))
# print("size = " + str(len(date_list)))
# time_between = date_list[-1] - date_list[0]
# print("diff: " + str(time_between))
#
# # __process_and_write_candlelight(date_list, opens, closes, highs, lows, volumes, file_path, token)
# print("time chartex query = " + str(t_2 - t_1))
#
#
# def main():
# token = "ROT"
# t_to = int(time.time())
# t_from = 0
# print_candlestick(token, t_from, t_to, "testaaa2.png")
#
#
# if __name__ == '__main__':
# main()
| import datetime
import time
import pandas as pd
import requests_util
import numpy as np
import plotly.io as pio
import pprint
INCREASING_COLOR = '#228B22'
DECREASING_COLOR = '#FF0000'
def __moving_average(interval, window_size=10):
window = np.ones(int(window_size)) / float(window_size)
return np.convolve(interval, window, 'same')
def __bbands(price, window_size=10, num_of_std=5):
price_pd = pd.DataFrame(price)
rolling_mean = price_pd.rolling(window=window_size).mean()
rolling_std = price_pd.rolling(window=window_size).std()
upper_band = rolling_mean + (rolling_std * num_of_std)
lower_band = rolling_mean - (rolling_std * num_of_std)
return rolling_mean, upper_band, lower_band
# Visualisation inspired by https://chart-studio.plotly.com/~jackp/17421/plotly-candlestick-chart-in-python/#/
# Huge thanks to the author!
def __process_and_write_candlelight(dates, openings, closes, highs, lows, volumes, file_path, token_name):
data = [dict(
type='candlestick',
open=openings,
high=highs,
low=lows,
close=closes,
x=dates,
yaxis='y2',
name='GS',
increasing=dict(line=dict(color=INCREASING_COLOR)),
decreasing=dict(line=dict(color=DECREASING_COLOR)),
)]
# max_price = max(highs)
# max_y = max_price + max_price * 0.2
# min_price = min(lows)
# min_y = max(0, min_price - min_price * 0.2)
layout = dict()
fig = dict(data=data, layout=layout)
fig['layout'] = dict()
fig['layout']['plot_bgcolor'] = 'rgb(250, 250, 250)'
fig['layout']['autosize'] = False
fig['layout']['width'] = 1600
fig['layout']['height'] = 900
fig['layout']['xaxis'] = dict(rangeslider=dict(visible=False))
fig['layout']['yaxis'] = dict(domain=[0, 0.19], showticklabels=True, title='Volume ($)', side='right')
fig['layout']['yaxis2'] = dict(domain=[0.2, 1], title=token_name + ' price ($)', side='right')
fig['layout']['showlegend'] = False
fig['layout']['margin'] = dict(t=15, b=15, r=15, l=15)
# bb_avg, bb_upper, bb_lower = __bbands(closes)
#
# fig['data'].append(dict(x=dates, y=bb_upper[0].to_list(), type='scatter', yaxis='y2',
# line=dict(width=1),
# marker=dict(color='#ccc'), hoverinfo='none',
# legendgroup='Bollinger Bands', name='Bollinger Bands'))
#
#
# fig['data'].append(dict(x=dates, y=bb_lower[0].to_list(), type='scatter', yaxis='y2',
# line=dict(width=1),
# marker=dict(color='#ccc'), hoverinfo='none',
# legendgroup='Bollinger Bands', showlegend=False))
mv_y = __moving_average(closes)
mv_x = list(dates)
# Clip the ends
mv_x = mv_x[5:-5]
mv_y = mv_y[5:-5]
fig['data'].append(dict(x=mv_x, y=mv_y, type='scatter', mode='lines',
line=dict(width=2),
marker=dict(color='#E377C2'),
yaxis='y2', name='Moving Average'))
colors_volume = []
for i in range(len(closes)):
if i != 0:
if closes[i] > closes[i - 1]:
colors_volume.append(INCREASING_COLOR)
else:
colors_volume.append(DECREASING_COLOR)
else:
colors_volume.append(DECREASING_COLOR)
fig['data'].append(dict(x=dates, y=volumes,
marker=dict(color=colors_volume),
type='bar', yaxis='y', name='Volume'))
pio.write_image(fig=fig, file=file_path, scale=3)
# t_from and t_to should be numbers, not strings
def __calculate_resolution_from_time(t_from, t_to):
delta = round(t_to - t_from)
if delta < 6 * 3600:
return 1
elif delta < 13 * 3600:
return 5
elif delta < 24 * 3600:
return 15
elif delta < 24 * 3600 * 7 + 100:
return 30
else:
return 60
def __preprocess_chartex_data(values, resolution):
times_from_chartex = [datetime.datetime.fromtimestamp(round(x)) for x in values['t']]
closes = [float(x) for x in values['c']]
opens = [float(x) for x in values['o']]
highs = [float(x) for x in values['h']]
lows = [float(x) for x in values['l']]
volumes = [float(x) for x in values['v']]
frequency = str(resolution) + "min"
date_list = pd.date_range(start=times_from_chartex[0], end=times_from_chartex[-1],
freq=frequency).to_pydatetime().tolist()
last_index = 0
missing_dates_count = 0
for date in date_list:
if date in times_from_chartex:
index = times_from_chartex.index(date)
last_index = index + missing_dates_count
# check if "too big" value and remove it in this case
if index == 0:
if highs[0] > highs[1] * 2:
# print("reducing highs index 0")
highs[0] = min(highs[1] * 3, highs[0] / 2)
if lows[0] < lows[1] / 2:
# print("increasing lows index 0")
lows[0] = max(lows[0] * 2, lows[1] / 2)
else:
if highs[index] > highs[index - 1] * 2 and highs[index] > highs[index + 1] * 2:
# print("reducing highs")
highs[index] = (highs[index - 1] + highs[index + 1])
if lows[index] < lows[index - 1] / 2 and lows[index] < lows[index + 1] / 2:
# print("increasing lows: from " + str(lows[index]) + ' to ' + str(min(lows[index - 1] - lows[index], lows[index + 1] - lows[index])))
lows[index] = min(lows[index - 1] - lows[index], lows[index + 1] - lows[index])
else:
index = last_index + 1
price = closes[index - 1]
closes.insert(index, price)
highs.insert(index, price)
lows.insert(index, price)
opens.insert(index, price)
volumes.insert(index, 0.0)
last_index = last_index + 1
missing_dates_count += 1
return (date_list, opens, closes, highs, lows, volumes)
# t_from and t_to should be int epoch second
# return the last price
def print_candlestick(token, t_from, t_to, file_path):
resolution = __calculate_resolution_from_time(t_from, t_to)
values = requests_util.get_graphex_data(token, resolution, t_from, t_to).json()
(date_list, opens, closes, highs, lows, volumes) = __preprocess_chartex_data(values, resolution)
__process_and_write_candlelight(date_list, opens, closes, highs, lows, volumes, file_path, token)
return closes[-1]
#
# def test_print_candlestick(token, t_from, t_to, resolution=1):
# t_1 = time.time_ns() // 1000000
# values = requests_util.get_graphex_data(token, resolution, t_from, t_to).json()
# t_2 = time.time_ns() // 1000000
# (date_list, opens, closes, highs, lows, volumes) = __preprocess_chartex_data(values, resolution)
# print("0 = " + str(date_list[0]))
# print("last = " + str(date_list[-1]))
# print("size = " + str(len(date_list)))
# time_between = date_list[-1] - date_list[0]
# print("diff: " + str(time_between))
#
# # __process_and_write_candlelight(date_list, opens, closes, highs, lows, volumes, file_path, token)
# print("time chartex query = " + str(t_2 - t_1))
#
#
# def main():
# token = "ROT"
# t_to = int(time.time())
# t_from = 0
# print_candlestick(token, t_from, t_to, "testaaa2.png")
#
#
# if __name__ == '__main__':
# main()
| en | 0.444192 | # Visualisation inspired by https://chart-studio.plotly.com/~jackp/17421/plotly-candlestick-chart-in-python/#/ # Huge thanks to the author! # max_price = max(highs) # max_y = max_price + max_price * 0.2 # min_price = min(lows) # min_y = max(0, min_price - min_price * 0.2) # bb_avg, bb_upper, bb_lower = __bbands(closes) # # fig['data'].append(dict(x=dates, y=bb_upper[0].to_list(), type='scatter', yaxis='y2', # line=dict(width=1), # marker=dict(color='#ccc'), hoverinfo='none', # legendgroup='Bollinger Bands', name='Bollinger Bands')) # # # fig['data'].append(dict(x=dates, y=bb_lower[0].to_list(), type='scatter', yaxis='y2', # line=dict(width=1), # marker=dict(color='#ccc'), hoverinfo='none', # legendgroup='Bollinger Bands', showlegend=False)) # Clip the ends # t_from and t_to should be numbers, not strings # check if "too big" value and remove it in this case # print("reducing highs index 0") # print("increasing lows index 0") # print("reducing highs") # print("increasing lows: from " + str(lows[index]) + ' to ' + str(min(lows[index - 1] - lows[index], lows[index + 1] - lows[index]))) # t_from and t_to should be int epoch second # return the last price # # def test_print_candlestick(token, t_from, t_to, resolution=1): # t_1 = time.time_ns() // 1000000 # values = requests_util.get_graphex_data(token, resolution, t_from, t_to).json() # t_2 = time.time_ns() // 1000000 # (date_list, opens, closes, highs, lows, volumes) = __preprocess_chartex_data(values, resolution) # print("0 = " + str(date_list[0])) # print("last = " + str(date_list[-1])) # print("size = " + str(len(date_list))) # time_between = date_list[-1] - date_list[0] # print("diff: " + str(time_between)) # # # __process_and_write_candlelight(date_list, opens, closes, highs, lows, volumes, file_path, token) # print("time chartex query = " + str(t_2 - t_1)) # # # def main(): # token = "ROT" # t_to = int(time.time()) # t_from = 0 # print_candlestick(token, t_from, t_to, "testaaa2.png") # # # if __name__ == '__main__': # main() | 3.065077 | 3 |
feature_extraction/metadata_util.py | ramseylab/cerenkov | 1 | 6617664 | import os
import pandas
import numpy
from biomart_client import BiomartClient
from genome_browser_client import GenomeBrowserClient
import chrom_tool as CT
from allele_tool import flip_allele, build_allele_freq_map
def __read_id(src):
if not os.path.isfile(src):
raise OSError(src + " not found.")
rsid = pandas.read_csv(src, sep='\t').loc[:, "name"]
return rsid
def __to_csv(dfm, dest):
dfm.to_csv(dest, sep='\t', header=True)
def __to_bed(dfm, dest):
dfm.to_csv(dest, sep='\t', header=False, index=False, columns=['chrom', 'chromStart', 'chromEnd', 'name'])
def __print_summary(snp_dfm):
print("\nTotal # of SNPs: " + str(snp_dfm.shape[0]))
print("\n# of SNPs on different chromosome types: \n")
chrom_types = ["Regular Chromosomes", "Mito Sequence (chrM)", "Haplotype Chromosomes", "Unplaced Contigs", "Sum"]
chrom_series = snp_dfm["chrom"]
cnt_regular = sum(chrom_series.isin(CT.REGULAR_CHR))
cnt_mito_seq = sum(chrom_series == CT.HOMO_SAPIENS_MITO_SEQ)
cnt_haplotype = sum(chrom_series.isin(CT.HAPLOTYPE_CHR))
cnt_contig = sum(chrom_series.str.endswith(CT.CONTIG_LOCALIZED_SUFFIX) |
chrom_series.str.startswith(CT.CONTIG_UNKNOWN_PREFIX))
cnt_total = cnt_regular + cnt_mito_seq + cnt_haplotype + cnt_contig
counts = [cnt_regular, cnt_mito_seq, cnt_haplotype, cnt_contig, cnt_total]
summary = pandas.DataFrame(counts, chrom_types, ["count"])
print(summary)
print("\n")
def __remove_non_regular_chrom(snp_dfm, verbose=False):
"""
There are 92 distinct values in column "chrom" of table "snp142" in database "hg19":
- Regular (24): "chr1" ~ "chr22", "chrX", "chrY"
- The Homo sapiens mitochondrion sequence (1) : "chrM"
- Haplotype chromosomes (9) : E.g. "chr6_apd_hap1"
- Unplaced contigs (58 = 20 + 38):
- If an unplaced contig is localized to a chromosome,
the contig name is appended to the regular chromosome name, as in "chr1_gl000191_random".
- If the chromosome is unknown,
the contig is represented with the name "chrUn" followed by the contig identifier,
as in "chrUn_gl000211".
See http://hgdownload.cse.ucsc.edu/gbdb/hg19/html/description.html.
E.g. for cSNP "rs1130552", there are 1 record on regular "chr6" and 6 on haplotype chromosomes.
We only keep the record on "chr6".
name chrom
rs1130552 chr6
rs1130552 chr6_cox_hap2
rs1130552 chr6_dbb_hap3
rs1130552 chr6_mann_hap4
rs1130552 chr6_mcf_hap5
rs1130552 chr6_qbl_hap6
rs1130552 chr6_ssto_hap7
"""
is_regular = snp_dfm.loc[:, "chrom"].isin(CT.REGULAR_CHR)
if verbose:
print("__remove_non_regular_chrom: \r\n%s" % snp_dfm.loc[~is_regular, ["name", "chrom"]])
return snp_dfm.loc[is_regular, :]
def __remove_non_single_class(snp_dfm, verbose=False):
"""
We do not care about insertions, deletions, in-dels at present.
Just keep the "single" class.
"""
is_single = (snp_dfm["class"] == "single")
if verbose:
print("__remove_non_single_class: \r\n%s" % snp_dfm.loc[~is_single, ["name", "chrom"]])
return snp_dfm.loc[is_single, :]
def __normalize_allele_strand(snp_dfm):
"""
Keep all the alleles on FWD strand.
If `strand` is "-", flip every base in `alleles`; otherwise do not change `alleles`.
"""
on_rev = (snp_dfm.loc[:, "strand"] == "-")
has_alleles = (snp_dfm.loc[:, "alleles"].str.len() > 0)
condition = (on_rev & has_alleles)
if not snp_dfm.loc[condition, :].empty:
snp_dfm.loc[condition, "alleles"] = snp_dfm.loc[condition, "alleles"].apply(flip_allele)
return snp_dfm
def __build_allele_freq_map(snp_dfm):
snp_dfm.loc[:, "afMap"] = snp_dfm.apply(lambda row: build_allele_freq_map(row['alleles'], row['alleleFreqs']),
axis=1, reduce=True)
return snp_dfm
def __identify_major_minor_alleles(snp_dfm, verbose=False):
"""
Policies:
P-1. If allele frequency info are complete:
P-1-1. Mono-allelic: Query ensembl.
P-1-2. Bi-allelic:
P-1-2-1. If MAF=0, query ensembl;
P-1-2-2. otherwise calculate normally
P-1-3. Tri-allelic: Delete a allele with minimum freq if its freq < 0.05 and then treat it
as a bi-allelic one; discard otherwise
P-1-4. Quad-allelic: Delete 2 alleles with minimum freqs if both their freq < 0.05 and then treat it
as a bi-allelic one; discard otherwise
P-2. If allele frequency info are missing: Query ensembl.
Actions after querying ensembl:
A-1. If ensembl claimed that it is mono-allelic, discard;
A-2. If ensembl claimed that it is bi-allelic,
A-2-1. If MAF=0, discard;
A-2-2. otherwise calculate normally
A-3. If ensembl claimed that it is tri-allelic or quad-allelic, discard
because we cannot tell which is the major allele when ensembl only reports a minor one.
"""
maf_thld = 0.05 # MAF threshold
undetermined = pandas.DataFrame() # rsID in this data frame should be double-checked thru ensembl via biomart
excluded = pandas.DataFrame() # rsID in this data frame should excluded. just for information display
result = pandas.DataFrame() # rsID in this data frame is returned
# P-2
has_no_afmap = (snp_dfm.loc[:, "afMap"].str.len() == 0)
undetermined = undetermined.append(snp_dfm[has_no_afmap], ignore_index=True)
# Identify mono-, bi-, tri-, quad-allelic
afmap_len = snp_dfm.loc[:, "afMap"].str.len()
mono_allelic = snp_dfm[afmap_len == 1]
bi_allelic = snp_dfm[afmap_len == 2]
tri_allelic = snp_dfm[afmap_len == 3]
quad_allelic = snp_dfm[afmap_len == 4]
if verbose:
allele_types = ["Mono-allelic", "Bi-allelic", "Tri-allelic", "Quad-allelic", 'Total']
cnt_mono = mono_allelic.shape[0]
cnt_bi = bi_allelic.shape[0]
cnt_tri = tri_allelic.shape[0]
cnt_quad = quad_allelic.shape[0]
cnt_total = cnt_mono + cnt_bi + cnt_tri + cnt_quad
counts = [cnt_mono, cnt_bi, cnt_tri, cnt_quad, cnt_total]
summary = pandas.DataFrame(counts, allele_types, ["count"])
print(summary)
# P-1-1
if not mono_allelic.empty:
undetermined = undetermined.append(mono_allelic)
# P-1-3
if not tri_allelic.empty:
# An entry from "afMap" is like `[("A", 0.2), ("C", 0.3), ("G", 0.5)]`
# x[0][1] == 0.2 in this example
# If two smallest freqs are both greater than 5%, you cannot tell which should be the minor allele
has_ambig_maf = numpy.array([x[0][1] >= maf_thld
for x in tri_allelic.loc[:, "afMap"]])
ambig_tri_allelic = tri_allelic.loc[has_ambig_maf, :]
excluded = excluded.append(ambig_tri_allelic, ignore_index=True)
if verbose:
print("__identify_major_minor_alleles: {n} tri-allelic entries excluded \r\n{entries}".format(
n=sum(has_ambig_maf),
entries=ambig_tri_allelic.loc[:, ["name", "alleles", "afMap"]] if any(has_ambig_maf) else ""))
remainder = tri_allelic.loc[~has_ambig_maf, :].copy()
# delete the first element
remainder.loc[:, "afMap"] = remainder.loc[:, "afMap"].apply(lambda x: x[1:])
bi_allelic = bi_allelic.append(remainder, ignore_index=True)
# P-1-4
if not quad_allelic.empty:
has_ambig_maf = numpy.array([(x[0][1] >= maf_thld) or (x[1][1] >= maf_thld)
for x in quad_allelic.loc[:, "afMap"]])
ambig_quad_allelic = quad_allelic.loc[has_ambig_maf, :]
excluded = excluded.append(ambig_quad_allelic, ignore_index=True)
if verbose:
print("__identify_major_minor_alleles: {n} quad-allelic entries excluded \r\n{entries}".format(
n=sum(has_ambig_maf),
entries=ambig_quad_allelic.loc[:, ["name", "alleles", "afMap"]] if any(has_ambig_maf) else ""))
remainder = quad_allelic.loc[~has_ambig_maf, :].copy()
# delete the first 2 elements
remainder.loc[:, "afMap"] = quad_allelic.loc[:, "afMap"].apply(lambda x: x[2:])
bi_allelic = bi_allelic.append(remainder, ignore_index=True)
# P-1-2
if not bi_allelic.empty:
# P-1-2-1
freq_eq_zero = numpy.array([(x[0][1] == 0.0) or (x[1][1] == 1.0) for x in bi_allelic.loc[:, "afMap"]])
undetermined = undetermined.append(bi_allelic.loc[freq_eq_zero, :])
# P-1-2-2
remainder = bi_allelic.loc[~freq_eq_zero, :].copy()
remainder.loc[:, "minorAllele"] = remainder.loc[:, "afMap"].apply(lambda x: x[0][0])
remainder.loc[:, "minorAlleleFreq"] = remainder.loc[:, "afMap"].apply(lambda x: x[0][1])
remainder.loc[:, "majorAllele"] = remainder.loc[:, "afMap"].apply(lambda x: x[1][0])
remainder.loc[:, "majorAlleleFreq"] = remainder.loc[:, "afMap"].apply(lambda x: x[1][1])
result = result.append(remainder, ignore_index=True)
if not undetermined.empty: # list not empty
with BiomartClient() as bm_client:
response = bm_client.query_snp(undetermined.loc[:, "name"].tolist(), verbose)
determined = response.loc[:, ["name", "minorAllele", "minorAlleleFreq", "majorAllele", "majorAlleleFreq"]].\
merge(undetermined, on='name', how='left', left_index=True)
result = result.append(determined, ignore_index=True)
if verbose:
maf_le_thld = result.loc[result["minorAlleleFreq"] < maf_thld]
print("__identify_major_minor_alleles: applied 5%-MAF filter to {n} entries: \r\n{entries}".format(
n=maf_le_thld.shape[0],
entries=maf_le_thld.loc[:, ["name", "alleles", "afMap"]] if not maf_le_thld.empty else ""))
return result.loc[result["minorAlleleFreq"] >= maf_thld]
def __revise_alleles_with_equal_freqs(snp_dfm):
"""
There exist SNPs with majorAlleleFreq == minorAlleleFreq.
Steve:
> For those 57 SNPs, I would maybe use the following approach:
> if the last (least significant) digit of the chromosomal coordinate is even, select the first (out of two)
alleles listed as the minor allele.
> If the last (least significant) digit of the chromosomal coordinate is odd, select the second (out of two)
alleles listed as the minor allele.
> This approach is deterministic but should more or less "randomly" and with equal probability assign the
first or second allele to be the 'minor allele'.
"""
has_equal_freq = (snp_dfm.loc[:, "minorAlleleFreq"] == snp_dfm.loc[:, "majorAlleleFreq"])
print("__revise_alleles_with_equal_freqs: detected \r\n %s" %
snp_dfm.loc[has_equal_freq, ["name", "chrom", "chromStart", "chromEnd",
"majorAllele", "minorAllele", "majorAlleleFreq", "minorAlleleFreq"]])
has_odd_chrom_start = (snp_dfm.loc[:, "chromStart"] % 2 == 1)
idx = has_equal_freq & has_odd_chrom_start
print("__revise_alleles_with_equal_freqs: to swap \r\n %s" %
snp_dfm.loc[idx, ["name", "chrom", "chromStart", "chromEnd",
"majorAllele", "minorAllele", "majorAlleleFreq", "minorAlleleFreq"]])
# Swap
snp_dfm.loc[idx, ["majorAllele", "minorAllele"]] = snp_dfm.loc[idx, ["minorAllele", "majorAllele"]].values
return snp_dfm
def __drop_redundant_col(snp_dfm):
return snp_dfm.drop(['afMap', "alleleFreqs", "alleles"], axis=1)
def __normalize_chrom_coord(snp_dfm):
snp_dfm.loc[:, "normChromCoord"] = snp_dfm.apply(lambda row: row['chromStart'] / CT.CHR_LENGTH[row['chrom']],
axis=1)
return snp_dfm
def extract_metadata(src, dest_csv, dest_bed):
"""
Extract metadata for cSNPs or rSNPs by querying UCSC database
:param src: the rsID list
:param dest_csv: the feature matrix
:param dest_bed: the name of bed file to be generated
:return: None
"""
rsid = __read_id(src)
with GenomeBrowserClient('local_hg19') as gb_client:
snps = gb_client.fetch_metadata(rsid)
__print_summary(snps)
snps = __remove_non_regular_chrom(snps, verbose=True)
snps = __remove_non_single_class(snps, verbose=True)
snps = __normalize_allele_strand(snps)
snps = __build_allele_freq_map(snps)
snps = __identify_major_minor_alleles(snps, verbose=True)
snps = __revise_alleles_with_equal_freqs(snps)
snps = __drop_redundant_col(snps)
snps = __normalize_chrom_coord(snps)
snps = CT.remove_dup_on_chrY(snps)
snps = snps.set_index("name")
__to_csv(snps, dest_csv)
snps = snps.reset_index()
__to_bed(snps, dest_bed)
| import os
import pandas
import numpy
from biomart_client import BiomartClient
from genome_browser_client import GenomeBrowserClient
import chrom_tool as CT
from allele_tool import flip_allele, build_allele_freq_map
def __read_id(src):
if not os.path.isfile(src):
raise OSError(src + " not found.")
rsid = pandas.read_csv(src, sep='\t').loc[:, "name"]
return rsid
def __to_csv(dfm, dest):
dfm.to_csv(dest, sep='\t', header=True)
def __to_bed(dfm, dest):
dfm.to_csv(dest, sep='\t', header=False, index=False, columns=['chrom', 'chromStart', 'chromEnd', 'name'])
def __print_summary(snp_dfm):
print("\nTotal # of SNPs: " + str(snp_dfm.shape[0]))
print("\n# of SNPs on different chromosome types: \n")
chrom_types = ["Regular Chromosomes", "Mito Sequence (chrM)", "Haplotype Chromosomes", "Unplaced Contigs", "Sum"]
chrom_series = snp_dfm["chrom"]
cnt_regular = sum(chrom_series.isin(CT.REGULAR_CHR))
cnt_mito_seq = sum(chrom_series == CT.HOMO_SAPIENS_MITO_SEQ)
cnt_haplotype = sum(chrom_series.isin(CT.HAPLOTYPE_CHR))
cnt_contig = sum(chrom_series.str.endswith(CT.CONTIG_LOCALIZED_SUFFIX) |
chrom_series.str.startswith(CT.CONTIG_UNKNOWN_PREFIX))
cnt_total = cnt_regular + cnt_mito_seq + cnt_haplotype + cnt_contig
counts = [cnt_regular, cnt_mito_seq, cnt_haplotype, cnt_contig, cnt_total]
summary = pandas.DataFrame(counts, chrom_types, ["count"])
print(summary)
print("\n")
def __remove_non_regular_chrom(snp_dfm, verbose=False):
"""
There are 92 distinct values in column "chrom" of table "snp142" in database "hg19":
- Regular (24): "chr1" ~ "chr22", "chrX", "chrY"
- The Homo sapiens mitochondrion sequence (1) : "chrM"
- Haplotype chromosomes (9) : E.g. "chr6_apd_hap1"
- Unplaced contigs (58 = 20 + 38):
- If an unplaced contig is localized to a chromosome,
the contig name is appended to the regular chromosome name, as in "chr1_gl000191_random".
- If the chromosome is unknown,
the contig is represented with the name "chrUn" followed by the contig identifier,
as in "chrUn_gl000211".
See http://hgdownload.cse.ucsc.edu/gbdb/hg19/html/description.html.
E.g. for cSNP "rs1130552", there are 1 record on regular "chr6" and 6 on haplotype chromosomes.
We only keep the record on "chr6".
name chrom
rs1130552 chr6
rs1130552 chr6_cox_hap2
rs1130552 chr6_dbb_hap3
rs1130552 chr6_mann_hap4
rs1130552 chr6_mcf_hap5
rs1130552 chr6_qbl_hap6
rs1130552 chr6_ssto_hap7
"""
is_regular = snp_dfm.loc[:, "chrom"].isin(CT.REGULAR_CHR)
if verbose:
print("__remove_non_regular_chrom: \r\n%s" % snp_dfm.loc[~is_regular, ["name", "chrom"]])
return snp_dfm.loc[is_regular, :]
def __remove_non_single_class(snp_dfm, verbose=False):
"""
We do not care about insertions, deletions, in-dels at present.
Just keep the "single" class.
"""
is_single = (snp_dfm["class"] == "single")
if verbose:
print("__remove_non_single_class: \r\n%s" % snp_dfm.loc[~is_single, ["name", "chrom"]])
return snp_dfm.loc[is_single, :]
def __normalize_allele_strand(snp_dfm):
"""
Keep all the alleles on FWD strand.
If `strand` is "-", flip every base in `alleles`; otherwise do not change `alleles`.
"""
on_rev = (snp_dfm.loc[:, "strand"] == "-")
has_alleles = (snp_dfm.loc[:, "alleles"].str.len() > 0)
condition = (on_rev & has_alleles)
if not snp_dfm.loc[condition, :].empty:
snp_dfm.loc[condition, "alleles"] = snp_dfm.loc[condition, "alleles"].apply(flip_allele)
return snp_dfm
def __build_allele_freq_map(snp_dfm):
snp_dfm.loc[:, "afMap"] = snp_dfm.apply(lambda row: build_allele_freq_map(row['alleles'], row['alleleFreqs']),
axis=1, reduce=True)
return snp_dfm
def __identify_major_minor_alleles(snp_dfm, verbose=False):
"""
Policies:
P-1. If allele frequency info are complete:
P-1-1. Mono-allelic: Query ensembl.
P-1-2. Bi-allelic:
P-1-2-1. If MAF=0, query ensembl;
P-1-2-2. otherwise calculate normally
P-1-3. Tri-allelic: Delete a allele with minimum freq if its freq < 0.05 and then treat it
as a bi-allelic one; discard otherwise
P-1-4. Quad-allelic: Delete 2 alleles with minimum freqs if both their freq < 0.05 and then treat it
as a bi-allelic one; discard otherwise
P-2. If allele frequency info are missing: Query ensembl.
Actions after querying ensembl:
A-1. If ensembl claimed that it is mono-allelic, discard;
A-2. If ensembl claimed that it is bi-allelic,
A-2-1. If MAF=0, discard;
A-2-2. otherwise calculate normally
A-3. If ensembl claimed that it is tri-allelic or quad-allelic, discard
because we cannot tell which is the major allele when ensembl only reports a minor one.
"""
maf_thld = 0.05 # MAF threshold
undetermined = pandas.DataFrame() # rsID in this data frame should be double-checked thru ensembl via biomart
excluded = pandas.DataFrame() # rsID in this data frame should excluded. just for information display
result = pandas.DataFrame() # rsID in this data frame is returned
# P-2
has_no_afmap = (snp_dfm.loc[:, "afMap"].str.len() == 0)
undetermined = undetermined.append(snp_dfm[has_no_afmap], ignore_index=True)
# Identify mono-, bi-, tri-, quad-allelic
afmap_len = snp_dfm.loc[:, "afMap"].str.len()
mono_allelic = snp_dfm[afmap_len == 1]
bi_allelic = snp_dfm[afmap_len == 2]
tri_allelic = snp_dfm[afmap_len == 3]
quad_allelic = snp_dfm[afmap_len == 4]
if verbose:
allele_types = ["Mono-allelic", "Bi-allelic", "Tri-allelic", "Quad-allelic", 'Total']
cnt_mono = mono_allelic.shape[0]
cnt_bi = bi_allelic.shape[0]
cnt_tri = tri_allelic.shape[0]
cnt_quad = quad_allelic.shape[0]
cnt_total = cnt_mono + cnt_bi + cnt_tri + cnt_quad
counts = [cnt_mono, cnt_bi, cnt_tri, cnt_quad, cnt_total]
summary = pandas.DataFrame(counts, allele_types, ["count"])
print(summary)
# P-1-1
if not mono_allelic.empty:
undetermined = undetermined.append(mono_allelic)
# P-1-3
if not tri_allelic.empty:
# An entry from "afMap" is like `[("A", 0.2), ("C", 0.3), ("G", 0.5)]`
# x[0][1] == 0.2 in this example
# If two smallest freqs are both greater than 5%, you cannot tell which should be the minor allele
has_ambig_maf = numpy.array([x[0][1] >= maf_thld
for x in tri_allelic.loc[:, "afMap"]])
ambig_tri_allelic = tri_allelic.loc[has_ambig_maf, :]
excluded = excluded.append(ambig_tri_allelic, ignore_index=True)
if verbose:
print("__identify_major_minor_alleles: {n} tri-allelic entries excluded \r\n{entries}".format(
n=sum(has_ambig_maf),
entries=ambig_tri_allelic.loc[:, ["name", "alleles", "afMap"]] if any(has_ambig_maf) else ""))
remainder = tri_allelic.loc[~has_ambig_maf, :].copy()
# delete the first element
remainder.loc[:, "afMap"] = remainder.loc[:, "afMap"].apply(lambda x: x[1:])
bi_allelic = bi_allelic.append(remainder, ignore_index=True)
# P-1-4
if not quad_allelic.empty:
has_ambig_maf = numpy.array([(x[0][1] >= maf_thld) or (x[1][1] >= maf_thld)
for x in quad_allelic.loc[:, "afMap"]])
ambig_quad_allelic = quad_allelic.loc[has_ambig_maf, :]
excluded = excluded.append(ambig_quad_allelic, ignore_index=True)
if verbose:
print("__identify_major_minor_alleles: {n} quad-allelic entries excluded \r\n{entries}".format(
n=sum(has_ambig_maf),
entries=ambig_quad_allelic.loc[:, ["name", "alleles", "afMap"]] if any(has_ambig_maf) else ""))
remainder = quad_allelic.loc[~has_ambig_maf, :].copy()
# delete the first 2 elements
remainder.loc[:, "afMap"] = quad_allelic.loc[:, "afMap"].apply(lambda x: x[2:])
bi_allelic = bi_allelic.append(remainder, ignore_index=True)
# P-1-2
if not bi_allelic.empty:
# P-1-2-1
freq_eq_zero = numpy.array([(x[0][1] == 0.0) or (x[1][1] == 1.0) for x in bi_allelic.loc[:, "afMap"]])
undetermined = undetermined.append(bi_allelic.loc[freq_eq_zero, :])
# P-1-2-2
remainder = bi_allelic.loc[~freq_eq_zero, :].copy()
remainder.loc[:, "minorAllele"] = remainder.loc[:, "afMap"].apply(lambda x: x[0][0])
remainder.loc[:, "minorAlleleFreq"] = remainder.loc[:, "afMap"].apply(lambda x: x[0][1])
remainder.loc[:, "majorAllele"] = remainder.loc[:, "afMap"].apply(lambda x: x[1][0])
remainder.loc[:, "majorAlleleFreq"] = remainder.loc[:, "afMap"].apply(lambda x: x[1][1])
result = result.append(remainder, ignore_index=True)
if not undetermined.empty: # list not empty
with BiomartClient() as bm_client:
response = bm_client.query_snp(undetermined.loc[:, "name"].tolist(), verbose)
determined = response.loc[:, ["name", "minorAllele", "minorAlleleFreq", "majorAllele", "majorAlleleFreq"]].\
merge(undetermined, on='name', how='left', left_index=True)
result = result.append(determined, ignore_index=True)
if verbose:
maf_le_thld = result.loc[result["minorAlleleFreq"] < maf_thld]
print("__identify_major_minor_alleles: applied 5%-MAF filter to {n} entries: \r\n{entries}".format(
n=maf_le_thld.shape[0],
entries=maf_le_thld.loc[:, ["name", "alleles", "afMap"]] if not maf_le_thld.empty else ""))
return result.loc[result["minorAlleleFreq"] >= maf_thld]
def __revise_alleles_with_equal_freqs(snp_dfm):
"""
There exist SNPs with majorAlleleFreq == minorAlleleFreq.
Steve:
> For those 57 SNPs, I would maybe use the following approach:
> if the last (least significant) digit of the chromosomal coordinate is even, select the first (out of two)
alleles listed as the minor allele.
> If the last (least significant) digit of the chromosomal coordinate is odd, select the second (out of two)
alleles listed as the minor allele.
> This approach is deterministic but should more or less "randomly" and with equal probability assign the
first or second allele to be the 'minor allele'.
"""
has_equal_freq = (snp_dfm.loc[:, "minorAlleleFreq"] == snp_dfm.loc[:, "majorAlleleFreq"])
print("__revise_alleles_with_equal_freqs: detected \r\n %s" %
snp_dfm.loc[has_equal_freq, ["name", "chrom", "chromStart", "chromEnd",
"majorAllele", "minorAllele", "majorAlleleFreq", "minorAlleleFreq"]])
has_odd_chrom_start = (snp_dfm.loc[:, "chromStart"] % 2 == 1)
idx = has_equal_freq & has_odd_chrom_start
print("__revise_alleles_with_equal_freqs: to swap \r\n %s" %
snp_dfm.loc[idx, ["name", "chrom", "chromStart", "chromEnd",
"majorAllele", "minorAllele", "majorAlleleFreq", "minorAlleleFreq"]])
# Swap
snp_dfm.loc[idx, ["majorAllele", "minorAllele"]] = snp_dfm.loc[idx, ["minorAllele", "majorAllele"]].values
return snp_dfm
def __drop_redundant_col(snp_dfm):
return snp_dfm.drop(['afMap', "alleleFreqs", "alleles"], axis=1)
def __normalize_chrom_coord(snp_dfm):
snp_dfm.loc[:, "normChromCoord"] = snp_dfm.apply(lambda row: row['chromStart'] / CT.CHR_LENGTH[row['chrom']],
axis=1)
return snp_dfm
def extract_metadata(src, dest_csv, dest_bed):
"""
Extract metadata for cSNPs or rSNPs by querying UCSC database
:param src: the rsID list
:param dest_csv: the feature matrix
:param dest_bed: the name of bed file to be generated
:return: None
"""
rsid = __read_id(src)
with GenomeBrowserClient('local_hg19') as gb_client:
snps = gb_client.fetch_metadata(rsid)
__print_summary(snps)
snps = __remove_non_regular_chrom(snps, verbose=True)
snps = __remove_non_single_class(snps, verbose=True)
snps = __normalize_allele_strand(snps)
snps = __build_allele_freq_map(snps)
snps = __identify_major_minor_alleles(snps, verbose=True)
snps = __revise_alleles_with_equal_freqs(snps)
snps = __drop_redundant_col(snps)
snps = __normalize_chrom_coord(snps)
snps = CT.remove_dup_on_chrY(snps)
snps = snps.set_index("name")
__to_csv(snps, dest_csv)
snps = snps.reset_index()
__to_bed(snps, dest_bed)
| en | 0.808578 | # of SNPs: " + str(snp_dfm.shape[0])) # of SNPs on different chromosome types: \n") There are 92 distinct values in column "chrom" of table "snp142" in database "hg19": - Regular (24): "chr1" ~ "chr22", "chrX", "chrY" - The Homo sapiens mitochondrion sequence (1) : "chrM" - Haplotype chromosomes (9) : E.g. "chr6_apd_hap1" - Unplaced contigs (58 = 20 + 38): - If an unplaced contig is localized to a chromosome, the contig name is appended to the regular chromosome name, as in "chr1_gl000191_random". - If the chromosome is unknown, the contig is represented with the name "chrUn" followed by the contig identifier, as in "chrUn_gl000211". See http://hgdownload.cse.ucsc.edu/gbdb/hg19/html/description.html. E.g. for cSNP "rs1130552", there are 1 record on regular "chr6" and 6 on haplotype chromosomes. We only keep the record on "chr6". name chrom rs1130552 chr6 rs1130552 chr6_cox_hap2 rs1130552 chr6_dbb_hap3 rs1130552 chr6_mann_hap4 rs1130552 chr6_mcf_hap5 rs1130552 chr6_qbl_hap6 rs1130552 chr6_ssto_hap7 We do not care about insertions, deletions, in-dels at present. Just keep the "single" class. Keep all the alleles on FWD strand. If `strand` is "-", flip every base in `alleles`; otherwise do not change `alleles`. Policies: P-1. If allele frequency info are complete: P-1-1. Mono-allelic: Query ensembl. P-1-2. Bi-allelic: P-1-2-1. If MAF=0, query ensembl; P-1-2-2. otherwise calculate normally P-1-3. Tri-allelic: Delete a allele with minimum freq if its freq < 0.05 and then treat it as a bi-allelic one; discard otherwise P-1-4. Quad-allelic: Delete 2 alleles with minimum freqs if both their freq < 0.05 and then treat it as a bi-allelic one; discard otherwise P-2. If allele frequency info are missing: Query ensembl. Actions after querying ensembl: A-1. If ensembl claimed that it is mono-allelic, discard; A-2. If ensembl claimed that it is bi-allelic, A-2-1. If MAF=0, discard; A-2-2. otherwise calculate normally A-3. If ensembl claimed that it is tri-allelic or quad-allelic, discard because we cannot tell which is the major allele when ensembl only reports a minor one. # MAF threshold # rsID in this data frame should be double-checked thru ensembl via biomart # rsID in this data frame should excluded. just for information display # rsID in this data frame is returned # P-2 # Identify mono-, bi-, tri-, quad-allelic # P-1-1 # P-1-3 # An entry from "afMap" is like `[("A", 0.2), ("C", 0.3), ("G", 0.5)]` # x[0][1] == 0.2 in this example # If two smallest freqs are both greater than 5%, you cannot tell which should be the minor allele # delete the first element # P-1-4 # delete the first 2 elements # P-1-2 # P-1-2-1 # P-1-2-2 # list not empty There exist SNPs with majorAlleleFreq == minorAlleleFreq. Steve: > For those 57 SNPs, I would maybe use the following approach: > if the last (least significant) digit of the chromosomal coordinate is even, select the first (out of two) alleles listed as the minor allele. > If the last (least significant) digit of the chromosomal coordinate is odd, select the second (out of two) alleles listed as the minor allele. > This approach is deterministic but should more or less "randomly" and with equal probability assign the first or second allele to be the 'minor allele'. # Swap Extract metadata for cSNPs or rSNPs by querying UCSC database :param src: the rsID list :param dest_csv: the feature matrix :param dest_bed: the name of bed file to be generated :return: None | 2.553029 | 3 |
src/repos/measData/insertMetricsData.py | ShekharGupta5/wrldc_mis_state_files_ingestion | 0 | 6617665 | <gh_stars>0
from typing_extensions import final
import cx_Oracle
from typing import List
from src.typeDefs.metricsDataRecord import IMetricsDataRecord
def insertMetricsData(appDbConnStr: str, dataSamples: List[IMetricsDataRecord]) -> bool:
"""Inserts a entity metrics time series data into the app db
Args:
appDbConnStr (str): [description]
dataSamples (List[IMetricsDataRecord]): [description]
Returns:
bool: returns true if process is ok
"""
dbConn = None
dbCur = None
isInsertSuccess = True
try:
dbConn = cx_Oracle.connect(appDbConnStr)
dbCur = dbConn.cursor()
colsNames = [" "," "," "," "]
sqlPlaceHldrsTxt = ','.join([':{0}'.format(x+1)
for x in range(len(colsNames))])
for dataSample in dataSamples:
insertSql = "INSERT INTO MIS_WAREHOUSE.STATE_FILES_DATA({0}) VALUES ({1})".format(colsNames, sqlPlaceHldrsTxt)
dbCur.execute(insertSql,dataSample)
dbConn.commit()
except Exception as err:
isInsertSuccess = False
print('Error while insertion of Metric Data')
print(err)
finally:
if dbCur is not None:
dbCur.close()
if dbConn is not None:
dbConn.close()
return isInsertSuccess
| from typing_extensions import final
import cx_Oracle
from typing import List
from src.typeDefs.metricsDataRecord import IMetricsDataRecord
def insertMetricsData(appDbConnStr: str, dataSamples: List[IMetricsDataRecord]) -> bool:
"""Inserts a entity metrics time series data into the app db
Args:
appDbConnStr (str): [description]
dataSamples (List[IMetricsDataRecord]): [description]
Returns:
bool: returns true if process is ok
"""
dbConn = None
dbCur = None
isInsertSuccess = True
try:
dbConn = cx_Oracle.connect(appDbConnStr)
dbCur = dbConn.cursor()
colsNames = [" "," "," "," "]
sqlPlaceHldrsTxt = ','.join([':{0}'.format(x+1)
for x in range(len(colsNames))])
for dataSample in dataSamples:
insertSql = "INSERT INTO MIS_WAREHOUSE.STATE_FILES_DATA({0}) VALUES ({1})".format(colsNames, sqlPlaceHldrsTxt)
dbCur.execute(insertSql,dataSample)
dbConn.commit()
except Exception as err:
isInsertSuccess = False
print('Error while insertion of Metric Data')
print(err)
finally:
if dbCur is not None:
dbCur.close()
if dbConn is not None:
dbConn.close()
return isInsertSuccess | en | 0.555936 | Inserts a entity metrics time series data into the app db Args: appDbConnStr (str): [description] dataSamples (List[IMetricsDataRecord]): [description] Returns: bool: returns true if process is ok | 2.4803 | 2 |
AnimeFetcher/anime_merge.py | yuxiang-zhou/AnimeTracker | 0 | 6617666 | <reponame>yuxiang-zhou/AnimeTracker
# -*- coding: utf-8 -*-
import sys
import BaseHTTPServer
import cgi
import json
import threading
import urllib2
import time
import itertools
import numpy as np
from bs4 import BeautifulSoup
from pymongo import MongoClient
import datetime
from tools import *
from difflib import SequenceMatcher
from fuzzywuzzy import fuzz
reload(sys)
sys.setdefaultencoding('utf-8')
num_retry = 1
period = int(3600*12)
con = MongoClient('172.16.17.32')
db = con.animedb
animesDB = db.animes
# data format
# {
# title
# [titles]
# timestamp
# [videos]
# [nums]
# link
# size
# [batchdownloads]
# }
def mergeAnimes():
entries = animesDB.find({},{'title':1})
idtitles = [[entry['_id'],entry['title']] for entry in entries]
removelist = []
for j,(id1, t1) in enumerate(idtitles):
for id2,t2 in idtitles[j+1:]:
ratio = fuzz.ratio(t1, t2)
if ratio > 80:
removelist.append(id1)
source = animesDB.find_one({'_id':id1})
target = animesDB.find_one({'_id':id2})
if ratio < 100:
target['titles'].append(t1)
if len(t1) < len(t2):
target['title'] = t1
target['titles'] += [t for t in source['titles'] if not t in target['titles']]
target['timestamp'] = np.max([source['timestamp'],target['timestamp']])
for num in source['videos'].keys():
if not target['videos'].has_key(num):
target['videos'][num] = []
target['videos'][num] += [s for s in source['videos'][num] if not s in target['videos'][num]]
if not source.has_key('bunk'):
source['bunk'] = []
if not target.has_key('bunk'):
target['bunk'] = []
target['bunk'] += [b for b in source['bunk'] if not b in target['bunk']]
animesDB.update({'_id':id2},target)
print 'Merged: {} and {}'.format(t1,t2)
break
for id in removelist:
animesDB.remove({'_id':id})
if __name__ == '__main__':
mergeAnimes()
| # -*- coding: utf-8 -*-
import sys
import BaseHTTPServer
import cgi
import json
import threading
import urllib2
import time
import itertools
import numpy as np
from bs4 import BeautifulSoup
from pymongo import MongoClient
import datetime
from tools import *
from difflib import SequenceMatcher
from fuzzywuzzy import fuzz
reload(sys)
sys.setdefaultencoding('utf-8')
num_retry = 1
period = int(3600*12)
con = MongoClient('172.16.17.32')
db = con.animedb
animesDB = db.animes
# data format
# {
# title
# [titles]
# timestamp
# [videos]
# [nums]
# link
# size
# [batchdownloads]
# }
def mergeAnimes():
entries = animesDB.find({},{'title':1})
idtitles = [[entry['_id'],entry['title']] for entry in entries]
removelist = []
for j,(id1, t1) in enumerate(idtitles):
for id2,t2 in idtitles[j+1:]:
ratio = fuzz.ratio(t1, t2)
if ratio > 80:
removelist.append(id1)
source = animesDB.find_one({'_id':id1})
target = animesDB.find_one({'_id':id2})
if ratio < 100:
target['titles'].append(t1)
if len(t1) < len(t2):
target['title'] = t1
target['titles'] += [t for t in source['titles'] if not t in target['titles']]
target['timestamp'] = np.max([source['timestamp'],target['timestamp']])
for num in source['videos'].keys():
if not target['videos'].has_key(num):
target['videos'][num] = []
target['videos'][num] += [s for s in source['videos'][num] if not s in target['videos'][num]]
if not source.has_key('bunk'):
source['bunk'] = []
if not target.has_key('bunk'):
target['bunk'] = []
target['bunk'] += [b for b in source['bunk'] if not b in target['bunk']]
animesDB.update({'_id':id2},target)
print 'Merged: {} and {}'.format(t1,t2)
break
for id in removelist:
animesDB.remove({'_id':id})
if __name__ == '__main__':
mergeAnimes() | en | 0.514101 | # -*- coding: utf-8 -*- # data format # { # title # [titles] # timestamp # [videos] # [nums] # link # size # [batchdownloads] # } | 2.352683 | 2 |
Week 02/P2 - Futval - Nalundasan.py | andrewn488/OMSBA-5061 | 0 | 6617667 | """
P2 - Futval
<NAME>
9/23/2020
Write a Python program that reads in investment amount, annual interest rate,
and number of years, and displays the future investment value using the
following formula (called monthly compounding):
For example, if you enter amount 1000, annual interest rate 3.25%, and number
of years 1, the future investment value is 1032.99
"""
# what we know
investment = int(input('Enter investment amount: ')) # get investment amount
annual_interest_rate = float(input('Enter annual interest rate: ')) # get annual interest rate
annual_percentage = annual_interest_rate / 100 # convert number to percentage
years = int(input('Enter number of years: '))
monthly_interest_rate = annual_percentage / 12 # convert annual % to monthly %
number_months = years * 12 # convert years to months
# calculate
future_value = investment * (1 + monthly_interest_rate) ** number_months
# output
print(f'Accumulated value is ${future_value:.2f}')
| """
P2 - Futval
<NAME>
9/23/2020
Write a Python program that reads in investment amount, annual interest rate,
and number of years, and displays the future investment value using the
following formula (called monthly compounding):
For example, if you enter amount 1000, annual interest rate 3.25%, and number
of years 1, the future investment value is 1032.99
"""
# what we know
investment = int(input('Enter investment amount: ')) # get investment amount
annual_interest_rate = float(input('Enter annual interest rate: ')) # get annual interest rate
annual_percentage = annual_interest_rate / 100 # convert number to percentage
years = int(input('Enter number of years: '))
monthly_interest_rate = annual_percentage / 12 # convert annual % to monthly %
number_months = years * 12 # convert years to months
# calculate
future_value = investment * (1 + monthly_interest_rate) ** number_months
# output
print(f'Accumulated value is ${future_value:.2f}')
| en | 0.851324 | P2 - Futval
<NAME>
9/23/2020
Write a Python program that reads in investment amount, annual interest rate,
and number of years, and displays the future investment value using the
following formula (called monthly compounding):
For example, if you enter amount 1000, annual interest rate 3.25%, and number
of years 1, the future investment value is 1032.99 # what we know # get investment amount # get annual interest rate # convert number to percentage # convert annual % to monthly % # convert years to months # calculate # output | 4.005799 | 4 |
tls/agents/agent_apex.py | goshaQ/adaptive-tls | 30 | 6617668 | import ray
from argparse import ArgumentParser
from ray.rllib.agents.dqn import ApexTrainer
from ray.tune.logger import pretty_print
from ray.tune.registry import register_env
from ray.tune import function
from tls.agents.models import register_model
from tls.environment.sumo import SUMOEnv
_NETWORK_PATH = '/home/gosha/workspace/pycharm/adaptive-tls/tls/networks/montgomery_county/'
def on_episode_end(info):
env = info['env'].envs[0]
env.close()
def train(num_iters, checkpoint_freq):
trainer = ApexTrainer(
env='SUMOEnv-v0',
config={
'model': {
'custom_model': 'adaptive-trafficlight',
"custom_options": {},
},
'hiddens': [], # Don't postprocess the action scores
'callbacks': {
'on_episode_end': function(on_episode_end),
},
'num_workers': 8,
'timesteps_per_iteration': 16000,
}
)
for i in range(num_iters):
print(f'== Iteration {i}==')
print(pretty_print(trainer.train()))
if i % checkpoint_freq:
checkpoint = trainer.save()
print(f'\nCheckpoint saved at {checkpoint}\n')
if __name__ == '__main__':
parser = ArgumentParser(description='Training script of Proximal Policy Optimization Agent')
parser.add_argument('--net-file', default=_NETWORK_PATH + 'moco.net.xml',
help='Path to the .net.xml file')
parser.add_argument('--config-file', default=_NETWORK_PATH + 'testmap.sumocfg',
help='Path to the .sumocfg file')
parser.add_argument('--additional-file', default=_NETWORK_PATH + 'moco.det.xml',
help='Path to the .det.xml file')
parser.add_argument('--num-iters', type=int, default=1000,
help='Number of optimization iterations')
parser.add_argument('--checkpoint-freq', type=int, default=100,
help='Frequence with which a checkpoint will be created')
args = parser.parse_args()
# Register the model and environment
register_env('SUMOEnv-v0', lambda _: SUMOEnv(net_file=args.net_file,
config_file=args.config_file,
additional_file=args.additional_file,
use_gui=True))
register_model()
# Initialize ray
ray.init()
# Train the agent
train(args.num_iters, args.checkpoint_freq) | import ray
from argparse import ArgumentParser
from ray.rllib.agents.dqn import ApexTrainer
from ray.tune.logger import pretty_print
from ray.tune.registry import register_env
from ray.tune import function
from tls.agents.models import register_model
from tls.environment.sumo import SUMOEnv
_NETWORK_PATH = '/home/gosha/workspace/pycharm/adaptive-tls/tls/networks/montgomery_county/'
def on_episode_end(info):
env = info['env'].envs[0]
env.close()
def train(num_iters, checkpoint_freq):
trainer = ApexTrainer(
env='SUMOEnv-v0',
config={
'model': {
'custom_model': 'adaptive-trafficlight',
"custom_options": {},
},
'hiddens': [], # Don't postprocess the action scores
'callbacks': {
'on_episode_end': function(on_episode_end),
},
'num_workers': 8,
'timesteps_per_iteration': 16000,
}
)
for i in range(num_iters):
print(f'== Iteration {i}==')
print(pretty_print(trainer.train()))
if i % checkpoint_freq:
checkpoint = trainer.save()
print(f'\nCheckpoint saved at {checkpoint}\n')
if __name__ == '__main__':
parser = ArgumentParser(description='Training script of Proximal Policy Optimization Agent')
parser.add_argument('--net-file', default=_NETWORK_PATH + 'moco.net.xml',
help='Path to the .net.xml file')
parser.add_argument('--config-file', default=_NETWORK_PATH + 'testmap.sumocfg',
help='Path to the .sumocfg file')
parser.add_argument('--additional-file', default=_NETWORK_PATH + 'moco.det.xml',
help='Path to the .det.xml file')
parser.add_argument('--num-iters', type=int, default=1000,
help='Number of optimization iterations')
parser.add_argument('--checkpoint-freq', type=int, default=100,
help='Frequence with which a checkpoint will be created')
args = parser.parse_args()
# Register the model and environment
register_env('SUMOEnv-v0', lambda _: SUMOEnv(net_file=args.net_file,
config_file=args.config_file,
additional_file=args.additional_file,
use_gui=True))
register_model()
# Initialize ray
ray.init()
# Train the agent
train(args.num_iters, args.checkpoint_freq) | en | 0.797622 | # Don't postprocess the action scores # Register the model and environment # Initialize ray # Train the agent | 2.019924 | 2 |
src/iwant_bot/start.py | kiwicom/iwant-bot | 3 | 6617669 | import asyncio
from aiohttp import web
from os import getenv
import re
import time
import json
from iwant_bot.slack_communicator import SlackCommunicator
from iwant_bot.iwant_process import IwantRequest
VERIFICATION = getenv('VERIFICATION')
if VERIFICATION is None:
print('Warning: Unknown "Verification Token".')
BOT_TOKEN = getenv('BOT_TOKEN')
if BOT_TOKEN is None:
print('Warning: Unknown BOT_TOKEN "Bot User OAuth Access Token".')
elif not re.match('xoxb', BOT_TOKEN):
print('Warning: "Bot User OAuth Access Token" does not begin with "xoxb".')
SUPER_TOKEN = getenv('SUPER_TOKEN')
if SUPER_TOKEN is None:
print('Warning: Unknown SUPER_TOKEN "OAuth Access Token".')
elif not re.match('xoxp', SUPER_TOKEN):
print('Warning: "OAuth Access Token" does not begin with "xoxp".')
_iwant_activities = ('coffee', )
_iwant_behest = ('list', 'help')
# other_words are expected words in the user message, which should be removed before dateparse.
_other_words = ('iwant', 'with', 'invite', 'or', 'and') # uppercase will be problem.
_default_duration = 900.0 # Implicit duration of activity in seconds (15 min).
_max_duration = 43200.0 # 12 hours is maximal duration of any request.
# Expect expanded Slack format like <@U1234|user> <#C1234|general>.
# Turn on 'Escape channels, users, and links sent to your app'.
_slack_user_pattern = '<@([A-Z0-9]+)\|[a-z0-9][-_.a-z0-9]{1,20}>'
class TokenError(Exception):
pass
async def handle_get(request):
"""Handle GET request, can be display at http://localhost:8080"""
text = (f'Server is running at {request.url}.\n'
f'Try `curl -X POST --data "text=test" {request.url}example`\n')
return web.Response(text=text)
async def handle_other_posts(request):
"""Handle all other POST requests.
For testing purpose, `curl -X POST --data "text=test" http://localhost:8080/example`"""
body = multidict_to_dict(await request.post())
print(f"INFO: The post to endpoint /{request.match_info['post']} contained:\n {body}")
return web.json_response({'text': f"POST to /{request.match_info['post']} is not resolved."})
def multidict_to_dict(multidict) -> dict:
if not len(set(multidict.keys())) == len(multidict):
print('WARNING: MultiDict contains duplicate keys, last occurrence was used.')
print(multidict)
return {key: multidict[key] for key in multidict}
async def handle_slack_button(request):
payload = multidict_to_dict(await request.post())
body = json.loads(payload['payload'])
print(f'INFO: Button request body:\n{body}.')
try:
verify_request_token(body)
except (KeyError, TokenError) as err:
print(f'INFO: Invalid token: {err}')
return web.json_response({'text': 'Unverified message.'})
if body['actions'][0]['name'] == 'Cancel':
if 'text' not in body:
body['text'] = ''
if 'user_id' not in body:
body['user_id'] = body['user']['id']
iwant_object = IwantRequest(body, (), (), _slack_user_pattern)
iwant_object.cancel_iwant_task()
return web.json_response({'text': 'Request was cancelled.'})
async def handle_slack_iwant(request):
body = multidict_to_dict(await request.post())
body['incoming_ts'] = time.time()
print(f'INFO: iwant request body:\n{body}.')
try:
verify_request_token(body)
except (KeyError, TokenError) as err:
print(f'INFO: Invalid token: {err}')
return web.json_response({'text': 'Unverified message.'})
if 'command' in body:
print(f"INFO: iwant handler handles command '{body['command']}'")
else:
print("WARNING: Request does not specify 'command'.")
return web.json_response({'text': 'Tried to handle command, but none found.'})
iwant_object = IwantRequest(body, _iwant_activities, _iwant_behest, _slack_user_pattern,
_other_words, _default_duration, _max_duration)
print(f'INFO: iwant parsed request:\n{iwant_object.data}')
# Process behests
res = solve_iwant_behest(iwant_object)
if res is not None:
return web.json_response(res)
# If no behest, then resolve activities
return web.json_response(solve_iwant_activity(iwant_object))
def complain(what: str, iwant_object) -> dict:
print(f'INFO: More than 1 {what} was found.')
if what == 'behest':
listing = f"`{'`, `'.join(iwant_object.possible_behests)}`"
elif what == 'activity':
listing = f"`{'`, `'.join(iwant_object.possible_activities)}`"
else:
print(f'WARNING: Someone complain to "{what}", but unknown meaning.')
return {'text': 'You cannot want this.'}
return {'text': f'You can use only one {what} from {listing} at the same time.'}
def solve_iwant_behest(iwant_object) -> dict or None:
if len(iwant_object.data['behests']) == 1:
print(f"INFO: iwant request found behest '{iwant_object.data['behests'][0]}'.")
if iwant_object.data['behests'] == ['list']:
return iwant_object.return_list_of_parameters()
elif iwant_object.data['behests'] == ['help']:
return iwant_object.create_help_message()
# other behests
else:
return {'text': f"{iwant_object.data['behests'][0]} is not implemented yet."}
elif len(iwant_object.data['behests']) > 1:
return complain('behest', iwant_object)
else:
return None
def solve_iwant_activity(iwant_object) -> dict:
if len(iwant_object.data['activities']) == 1:
print(f'INFO: iwant request found activities {iwant_object.data["activities"][0]}.')
try:
callback_id = iwant_object.store_iwant_task(iwant_object.data["activities"][0])
iwant_object.data['callback_id'] = callback_id
except Exception as e:
print(f'ERROR: "{iwant_object.data["activities"][0]}" did not get callback_id.')
print(e)
print(f"INFO: iwant request obtained callback_id {iwant_object.data['callback_id']}")
return iwant_object.create_accepted_response()
elif len(iwant_object.data['activities']) > 1:
return complain('activity', iwant_object)
else:
print('INFO: No activities or behests, return help.')
return iwant_object.create_help_message()
def verify_request_token(body: dict) -> None:
"""Raise KeyError, if body does not have any key 'token'.
Raise TokenError, if token does not match."""
if not body['token'] == VERIFICATION:
raise TokenError(f"Token {body['token']} is not valid.")
app = web.Application()
app.router.add_get(r'/{get:\w*}', handle_get)
app.router.add_post('/slack/iwant', handle_slack_iwant)
app.router.add_post('/slack/button', handle_slack_button)
app.router.add_post(r'/{post:[\w/]*}', handle_other_posts)
loop = asyncio.get_event_loop()
# Created channel iwant_group10 - id: G65FE8M6K.
# (1..9 were created and archived, but still cannot be recreate and I cannot delete them.)
# So, we should not create to many channels?
# test = SlackCommunicator(SUPER_TOKEN, 'U51RKKATS', 'Create channel')
# loop.run_until_complete(asyncio.gather(test.create_private_channel('iwant_group11'),
# test.invite_people_in_private_channel())
# )
# sent_message_to_each can send message even to channels and users
test1 = SlackCommunicator(BOT_TOKEN, '<PASSWORD>', 'Initial message.')
loop.run_until_complete(test1.send_message_to_each())
# sent message to multiparty group of 2 to 7 people (+ 1 iwant-bot). Need BOT_TOKEN.
# So, this is preferable variant...
# test2 = SlackCommunicator(BOT_TOKEN, ['U<PASSWORD>ATS', 'U52FUHD98', 'U52FU3ZTL'], 'Sorry spam :).')
# loop.run_until_complete(test2.send_message_to_multiparty())
if __name__ == '__main__':
web.run_app(app)
| import asyncio
from aiohttp import web
from os import getenv
import re
import time
import json
from iwant_bot.slack_communicator import SlackCommunicator
from iwant_bot.iwant_process import IwantRequest
VERIFICATION = getenv('VERIFICATION')
if VERIFICATION is None:
print('Warning: Unknown "Verification Token".')
BOT_TOKEN = getenv('BOT_TOKEN')
if BOT_TOKEN is None:
print('Warning: Unknown BOT_TOKEN "Bot User OAuth Access Token".')
elif not re.match('xoxb', BOT_TOKEN):
print('Warning: "Bot User OAuth Access Token" does not begin with "xoxb".')
SUPER_TOKEN = getenv('SUPER_TOKEN')
if SUPER_TOKEN is None:
print('Warning: Unknown SUPER_TOKEN "OAuth Access Token".')
elif not re.match('xoxp', SUPER_TOKEN):
print('Warning: "OAuth Access Token" does not begin with "xoxp".')
_iwant_activities = ('coffee', )
_iwant_behest = ('list', 'help')
# other_words are expected words in the user message, which should be removed before dateparse.
_other_words = ('iwant', 'with', 'invite', 'or', 'and') # uppercase will be problem.
_default_duration = 900.0 # Implicit duration of activity in seconds (15 min).
_max_duration = 43200.0 # 12 hours is maximal duration of any request.
# Expect expanded Slack format like <@U1234|user> <#C1234|general>.
# Turn on 'Escape channels, users, and links sent to your app'.
_slack_user_pattern = '<@([A-Z0-9]+)\|[a-z0-9][-_.a-z0-9]{1,20}>'
class TokenError(Exception):
pass
async def handle_get(request):
"""Handle GET request, can be display at http://localhost:8080"""
text = (f'Server is running at {request.url}.\n'
f'Try `curl -X POST --data "text=test" {request.url}example`\n')
return web.Response(text=text)
async def handle_other_posts(request):
"""Handle all other POST requests.
For testing purpose, `curl -X POST --data "text=test" http://localhost:8080/example`"""
body = multidict_to_dict(await request.post())
print(f"INFO: The post to endpoint /{request.match_info['post']} contained:\n {body}")
return web.json_response({'text': f"POST to /{request.match_info['post']} is not resolved."})
def multidict_to_dict(multidict) -> dict:
if not len(set(multidict.keys())) == len(multidict):
print('WARNING: MultiDict contains duplicate keys, last occurrence was used.')
print(multidict)
return {key: multidict[key] for key in multidict}
async def handle_slack_button(request):
payload = multidict_to_dict(await request.post())
body = json.loads(payload['payload'])
print(f'INFO: Button request body:\n{body}.')
try:
verify_request_token(body)
except (KeyError, TokenError) as err:
print(f'INFO: Invalid token: {err}')
return web.json_response({'text': 'Unverified message.'})
if body['actions'][0]['name'] == 'Cancel':
if 'text' not in body:
body['text'] = ''
if 'user_id' not in body:
body['user_id'] = body['user']['id']
iwant_object = IwantRequest(body, (), (), _slack_user_pattern)
iwant_object.cancel_iwant_task()
return web.json_response({'text': 'Request was cancelled.'})
async def handle_slack_iwant(request):
body = multidict_to_dict(await request.post())
body['incoming_ts'] = time.time()
print(f'INFO: iwant request body:\n{body}.')
try:
verify_request_token(body)
except (KeyError, TokenError) as err:
print(f'INFO: Invalid token: {err}')
return web.json_response({'text': 'Unverified message.'})
if 'command' in body:
print(f"INFO: iwant handler handles command '{body['command']}'")
else:
print("WARNING: Request does not specify 'command'.")
return web.json_response({'text': 'Tried to handle command, but none found.'})
iwant_object = IwantRequest(body, _iwant_activities, _iwant_behest, _slack_user_pattern,
_other_words, _default_duration, _max_duration)
print(f'INFO: iwant parsed request:\n{iwant_object.data}')
# Process behests
res = solve_iwant_behest(iwant_object)
if res is not None:
return web.json_response(res)
# If no behest, then resolve activities
return web.json_response(solve_iwant_activity(iwant_object))
def complain(what: str, iwant_object) -> dict:
print(f'INFO: More than 1 {what} was found.')
if what == 'behest':
listing = f"`{'`, `'.join(iwant_object.possible_behests)}`"
elif what == 'activity':
listing = f"`{'`, `'.join(iwant_object.possible_activities)}`"
else:
print(f'WARNING: Someone complain to "{what}", but unknown meaning.')
return {'text': 'You cannot want this.'}
return {'text': f'You can use only one {what} from {listing} at the same time.'}
def solve_iwant_behest(iwant_object) -> dict or None:
if len(iwant_object.data['behests']) == 1:
print(f"INFO: iwant request found behest '{iwant_object.data['behests'][0]}'.")
if iwant_object.data['behests'] == ['list']:
return iwant_object.return_list_of_parameters()
elif iwant_object.data['behests'] == ['help']:
return iwant_object.create_help_message()
# other behests
else:
return {'text': f"{iwant_object.data['behests'][0]} is not implemented yet."}
elif len(iwant_object.data['behests']) > 1:
return complain('behest', iwant_object)
else:
return None
def solve_iwant_activity(iwant_object) -> dict:
if len(iwant_object.data['activities']) == 1:
print(f'INFO: iwant request found activities {iwant_object.data["activities"][0]}.')
try:
callback_id = iwant_object.store_iwant_task(iwant_object.data["activities"][0])
iwant_object.data['callback_id'] = callback_id
except Exception as e:
print(f'ERROR: "{iwant_object.data["activities"][0]}" did not get callback_id.')
print(e)
print(f"INFO: iwant request obtained callback_id {iwant_object.data['callback_id']}")
return iwant_object.create_accepted_response()
elif len(iwant_object.data['activities']) > 1:
return complain('activity', iwant_object)
else:
print('INFO: No activities or behests, return help.')
return iwant_object.create_help_message()
def verify_request_token(body: dict) -> None:
"""Raise KeyError, if body does not have any key 'token'.
Raise TokenError, if token does not match."""
if not body['token'] == VERIFICATION:
raise TokenError(f"Token {body['token']} is not valid.")
app = web.Application()
app.router.add_get(r'/{get:\w*}', handle_get)
app.router.add_post('/slack/iwant', handle_slack_iwant)
app.router.add_post('/slack/button', handle_slack_button)
app.router.add_post(r'/{post:[\w/]*}', handle_other_posts)
loop = asyncio.get_event_loop()
# Created channel iwant_group10 - id: G65FE8M6K.
# (1..9 were created and archived, but still cannot be recreate and I cannot delete them.)
# So, we should not create to many channels?
# test = SlackCommunicator(SUPER_TOKEN, 'U51RKKATS', 'Create channel')
# loop.run_until_complete(asyncio.gather(test.create_private_channel('iwant_group11'),
# test.invite_people_in_private_channel())
# )
# sent_message_to_each can send message even to channels and users
test1 = SlackCommunicator(BOT_TOKEN, '<PASSWORD>', 'Initial message.')
loop.run_until_complete(test1.send_message_to_each())
# sent message to multiparty group of 2 to 7 people (+ 1 iwant-bot). Need BOT_TOKEN.
# So, this is preferable variant...
# test2 = SlackCommunicator(BOT_TOKEN, ['U<PASSWORD>ATS', 'U52FUHD98', 'U52FU3ZTL'], 'Sorry spam :).')
# loop.run_until_complete(test2.send_message_to_multiparty())
if __name__ == '__main__':
web.run_app(app)
| en | 0.714161 | # other_words are expected words in the user message, which should be removed before dateparse. # uppercase will be problem. # Implicit duration of activity in seconds (15 min). # 12 hours is maximal duration of any request. # Expect expanded Slack format like <@U1234|user> <#C1234|general>. # Turn on 'Escape channels, users, and links sent to your app'. Handle GET request, can be display at http://localhost:8080 Handle all other POST requests. For testing purpose, `curl -X POST --data "text=test" http://localhost:8080/example` # Process behests # If no behest, then resolve activities # other behests Raise KeyError, if body does not have any key 'token'. Raise TokenError, if token does not match. # Created channel iwant_group10 - id: G65FE8M6K. # (1..9 were created and archived, but still cannot be recreate and I cannot delete them.) # So, we should not create to many channels? # test = SlackCommunicator(SUPER_TOKEN, 'U51RKKATS', 'Create channel') # loop.run_until_complete(asyncio.gather(test.create_private_channel('iwant_group11'), # test.invite_people_in_private_channel()) # ) # sent_message_to_each can send message even to channels and users # sent message to multiparty group of 2 to 7 people (+ 1 iwant-bot). Need BOT_TOKEN. # So, this is preferable variant... # test2 = SlackCommunicator(BOT_TOKEN, ['U<PASSWORD>ATS', 'U52FUHD98', 'U52FU3ZTL'], 'Sorry spam :).') # loop.run_until_complete(test2.send_message_to_multiparty()) | 2.524037 | 3 |
toir/formats/dat/items.py | FistingUranus/innocence-r | 2 | 6617670 | from .sections import read_sections, read_dat_header, append_section
import struct
from collections import namedtuple
from ...text import decode_text, encode_text
import csv
ItemCategory = namedtuple('ItemCategory', ['name', 'recordSize'])
_ITEM_CATEGORIES = [
ItemCategory('Use', 0x4C),
ItemCategory('Weapon', 0x54),
ItemCategory('Armor', 0x54),
ItemCategory('Helm', 0x54),
ItemCategory('Acc', 0x5C),
ItemCategory('Material', 0x3C),
ItemCategory('Event', 0x3C),
ItemCategory('DLC', 0x54),
ItemCategory('CodeName', 0x50),
ItemCategory('Recipe', 0x80),
ItemCategory('RaveAbility', 0x48),
ItemCategory('OperationCond', 0x3c),
]
def read_items(category, names, descriptions):
count, = struct.unpack_from('<L', names, 0)
items = []
for i in range(count):
name = decode_text(names, 4 + i * category.recordSize + 0xf)
description = decode_text(descriptions, 4 + i * 0x92)
items.append({
'name': name,
'description': description,
})
return items
def _extract_items(binary):
items = {}
sections = read_sections(binary)
for i in range(0, len(_ITEM_CATEGORIES)):
items[_ITEM_CATEGORIES[i].name] = read_items(_ITEM_CATEGORIES[i],
sections[2*i],
sections[2*i+1])
return items
def extract_items(l7cdir, outputdir):
with open(l7cdir / '_Data/System/ItemDataPack.dat', 'rb') as f:
binary = f.read()
items = _extract_items(binary)
with open(outputdir / 'ItemDataPack.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, ['category', 'index', 'field', 'text'])
for category, items in items.items():
for i, item in enumerate(items):
writer.writerow({
'category': category,
'index': i,
'field': 'name',
'text': item['name'],
})
writer.writerow({
'category': category,
'index': i,
'field': 'description',
'text': item['description'],
})
def read_item_csv(csvdir):
items = {}
with open(csvdir / 'ItemDataPack.csv', 'r', encoding='utf-8', newline='') as f:
reader = csv.DictReader(f, ['category', 'index', 'field', 'japanese', 'translation'])
for row in reader:
category = row['category']
if not category:
continue
index = int(row['index'])
field = row['field']
translation = row['translation']
if category not in items:
items[category] = {}
if index not in items[category]:
items[category][index] = {}
if field == 'name':
items[category][index]['name'] = translation
elif field == 'description':
items[category][index]['description'] = translation
else:
raise ValueError('unknown field in ItemDataPack.csv')
return items
def write_items(category, names, descriptions, items):
count, = struct.unpack_from('<L', names, 0)
if count != len(items):
raise ValueError('number of items does not match original')
for i in range(count):
name = encode_text(items[i]['name'])
if len(name) > 0x2C:
print(f'"{category.name},{i},name" is too long (44 bytes allowed), truncating...')
name = name[:0x2B] # one less for trailing zero
name += bytes(0x2C - len(name))
name_start = 4 + i * category.recordSize + 0xf
names[name_start:name_start+0x2C] = name
description = encode_text(items[i]['description'])
if len(description) > 0x92:
print(f'"{category.name},{i},description" is too long (144 bytes allowed), truncating...')
description = description[:0x91] # one less for trailing zero
description += bytes(0x92 - len(description))
desc_start = 4 + i * 0x92
descriptions[desc_start:desc_start+0x92] = description
def insert_items(binary, items):
newbinary = read_dat_header(binary)
sections = [bytearray(section) for section in read_sections(binary)]
for i in range(0, len(_ITEM_CATEGORIES)):
write_items(_ITEM_CATEGORIES[i], sections[2*i], sections[2*i+1],
items[_ITEM_CATEGORIES[i].name])
newbinary = append_section(newbinary, sections[2*i])
newbinary = append_section(newbinary, sections[2*i+1])
newbinary = append_section(newbinary, sections[-1])
assert(len(binary) == len(newbinary))
return newbinary
def recompile_items(l7cdir, csvdir, outputdir):
items = read_item_csv(csvdir)
with open(l7cdir / '_Data/System/ItemDataPack.dat', 'rb') as f:
binary = f.read()
binary = insert_items(binary, items)
outputdir = outputdir / '_Data/System'
outputdir.mkdir(parents=True, exist_ok=True)
with open(outputdir / 'ItemDataPack.dat', 'wb') as f:
f.write(binary)
| from .sections import read_sections, read_dat_header, append_section
import struct
from collections import namedtuple
from ...text import decode_text, encode_text
import csv
ItemCategory = namedtuple('ItemCategory', ['name', 'recordSize'])
_ITEM_CATEGORIES = [
ItemCategory('Use', 0x4C),
ItemCategory('Weapon', 0x54),
ItemCategory('Armor', 0x54),
ItemCategory('Helm', 0x54),
ItemCategory('Acc', 0x5C),
ItemCategory('Material', 0x3C),
ItemCategory('Event', 0x3C),
ItemCategory('DLC', 0x54),
ItemCategory('CodeName', 0x50),
ItemCategory('Recipe', 0x80),
ItemCategory('RaveAbility', 0x48),
ItemCategory('OperationCond', 0x3c),
]
def read_items(category, names, descriptions):
count, = struct.unpack_from('<L', names, 0)
items = []
for i in range(count):
name = decode_text(names, 4 + i * category.recordSize + 0xf)
description = decode_text(descriptions, 4 + i * 0x92)
items.append({
'name': name,
'description': description,
})
return items
def _extract_items(binary):
items = {}
sections = read_sections(binary)
for i in range(0, len(_ITEM_CATEGORIES)):
items[_ITEM_CATEGORIES[i].name] = read_items(_ITEM_CATEGORIES[i],
sections[2*i],
sections[2*i+1])
return items
def extract_items(l7cdir, outputdir):
with open(l7cdir / '_Data/System/ItemDataPack.dat', 'rb') as f:
binary = f.read()
items = _extract_items(binary)
with open(outputdir / 'ItemDataPack.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, ['category', 'index', 'field', 'text'])
for category, items in items.items():
for i, item in enumerate(items):
writer.writerow({
'category': category,
'index': i,
'field': 'name',
'text': item['name'],
})
writer.writerow({
'category': category,
'index': i,
'field': 'description',
'text': item['description'],
})
def read_item_csv(csvdir):
items = {}
with open(csvdir / 'ItemDataPack.csv', 'r', encoding='utf-8', newline='') as f:
reader = csv.DictReader(f, ['category', 'index', 'field', 'japanese', 'translation'])
for row in reader:
category = row['category']
if not category:
continue
index = int(row['index'])
field = row['field']
translation = row['translation']
if category not in items:
items[category] = {}
if index not in items[category]:
items[category][index] = {}
if field == 'name':
items[category][index]['name'] = translation
elif field == 'description':
items[category][index]['description'] = translation
else:
raise ValueError('unknown field in ItemDataPack.csv')
return items
def write_items(category, names, descriptions, items):
count, = struct.unpack_from('<L', names, 0)
if count != len(items):
raise ValueError('number of items does not match original')
for i in range(count):
name = encode_text(items[i]['name'])
if len(name) > 0x2C:
print(f'"{category.name},{i},name" is too long (44 bytes allowed), truncating...')
name = name[:0x2B] # one less for trailing zero
name += bytes(0x2C - len(name))
name_start = 4 + i * category.recordSize + 0xf
names[name_start:name_start+0x2C] = name
description = encode_text(items[i]['description'])
if len(description) > 0x92:
print(f'"{category.name},{i},description" is too long (144 bytes allowed), truncating...')
description = description[:0x91] # one less for trailing zero
description += bytes(0x92 - len(description))
desc_start = 4 + i * 0x92
descriptions[desc_start:desc_start+0x92] = description
def insert_items(binary, items):
newbinary = read_dat_header(binary)
sections = [bytearray(section) for section in read_sections(binary)]
for i in range(0, len(_ITEM_CATEGORIES)):
write_items(_ITEM_CATEGORIES[i], sections[2*i], sections[2*i+1],
items[_ITEM_CATEGORIES[i].name])
newbinary = append_section(newbinary, sections[2*i])
newbinary = append_section(newbinary, sections[2*i+1])
newbinary = append_section(newbinary, sections[-1])
assert(len(binary) == len(newbinary))
return newbinary
def recompile_items(l7cdir, csvdir, outputdir):
items = read_item_csv(csvdir)
with open(l7cdir / '_Data/System/ItemDataPack.dat', 'rb') as f:
binary = f.read()
binary = insert_items(binary, items)
outputdir = outputdir / '_Data/System'
outputdir.mkdir(parents=True, exist_ok=True)
with open(outputdir / 'ItemDataPack.dat', 'wb') as f:
f.write(binary)
| en | 0.880814 | # one less for trailing zero # one less for trailing zero | 2.817613 | 3 |
GPU_Computer/catkin_ws/src/dji_pkg/scripts/gps_dist_bear.py | HYEON-JIN-KWON/Drone_Project | 0 | 6617671 | #!/usr/bin/env python
import rospy
from math import pow, degrees, radians, atan2
from scipy import cos, sin, arctan, sqrt, arctan2
from haversine import haversine
'''
|<-- 100(m)-->|<-- 100(m)-->|
--- p8------------p1-------------p2-> 35.234694 (35.233795+0.0008993204)
^ | .-45 |0 . |
| | . | . 45|
100 | . | . |
(m) | . | . |
| | . | . |
v |-90 . | . |
--- p7------------p0-------------p3-> 35.233795
^ | . | . 90|
| | . | . |
100 | . | . |
(m) | . | . |
| -135. | . |
v | . | 135 . |
--- p6------------p5-------------p4-> 35.232895 (35.233795-0.0008993204)
v v v
129.081752 129.082850 129.083947
(129.082850-0.0010978720) (129.082850+0.0010978720)
distance of latitude 1(deg) = 111195.0802340(m/deg) p1( 35, 129) p2( 36, 129)
distance of longtitude 1(deg) = 91085.2969372(m/deg) p1( 35, 129) p2( 35, 130)
latitude of distance 1(m) = 0.00000899320363720(deg/m)
longitude of distance 1(m) = 0.00001097872031629(deg/m)
-------------+-----------------+-----------------
Distance(m) | latitude(deg) | longitude(deg)
-------------+-----------------+-----------------
1.0 | 0.0000089932 | 0.0000109787
10.0 | 0.0000899320 | 0.0001097872
100.0 | 0.0008993204 | 0.0010978720
-------------+-----------------+-----------------
p0 = (35.233795, 129.082850)
p1 = (35.234694, 129.082850); p5 = (35.232895, 129.082850)
p2 = (35.234694, 129.083947); p6 = (35.232895, 129.081752)
p3 = (35.233795, 129.083947); p7 = (35.233795, 129.081752)
p4 = (35.232895, 129.083947); p8 = (35.234694, 129.081752)
'''
def bearing((lat1, long1), (lat2, long2)):
Lat1, Lat2 = radians(lat1), radians(lat2)
Long1, Long2 = radians(long1), radians(long2)
y = sin(Long2-Long1)*cos(Lat2)
x = cos(Lat1)*sin(Lat2) - sin(Lat1)*cos(Lat2)*cos(Long2-Long1)
return degrees(atan2(y, x))
if __name__ == '__main__':
try:
rospy.init_node('get_distance_n_bearing_from_gps', anonymous = True)
a = (35, 129); b = (36, 129); c = (35, 130)
print "latitude 1(deg) is %s(m)" %(haversine(a,b) * 1000)
print "longitude 1(deg) is %s(m)" %(haversine(a,c) * 1000)
p0 = (35.233795, 129.082850)
p1 = (35.234694, 129.082850); p5 = (35.232895, 129.082850)
p2 = (35.234694, 129.083947); p6 = (35.232895, 129.081752)
p3 = (35.233795, 129.083947); p7 = (35.233795, 129.081752)
p4 = (35.232895, 129.083947); p8 = (35.234694, 129.081752)
print "p1: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p1)*1000, bearing(p0,p1))
print "p2: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p2)*1000, bearing(p0,p2))
print "p3: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p3)*1000, bearing(p0,p3))
print "p4: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p4)*1000, bearing(p0,p4))
print "p5: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p5)*1000, bearing(p0,p5))
print "p6: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p6)*1000, bearing(p0,p6))
print "p7: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p7)*1000, bearing(p0,p7))
print "p8: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p8)*1000, bearing(p0,p8))
except rospy.ROSInterruptException: pass
| #!/usr/bin/env python
import rospy
from math import pow, degrees, radians, atan2
from scipy import cos, sin, arctan, sqrt, arctan2
from haversine import haversine
'''
|<-- 100(m)-->|<-- 100(m)-->|
--- p8------------p1-------------p2-> 35.234694 (35.233795+0.0008993204)
^ | .-45 |0 . |
| | . | . 45|
100 | . | . |
(m) | . | . |
| | . | . |
v |-90 . | . |
--- p7------------p0-------------p3-> 35.233795
^ | . | . 90|
| | . | . |
100 | . | . |
(m) | . | . |
| -135. | . |
v | . | 135 . |
--- p6------------p5-------------p4-> 35.232895 (35.233795-0.0008993204)
v v v
129.081752 129.082850 129.083947
(129.082850-0.0010978720) (129.082850+0.0010978720)
distance of latitude 1(deg) = 111195.0802340(m/deg) p1( 35, 129) p2( 36, 129)
distance of longtitude 1(deg) = 91085.2969372(m/deg) p1( 35, 129) p2( 35, 130)
latitude of distance 1(m) = 0.00000899320363720(deg/m)
longitude of distance 1(m) = 0.00001097872031629(deg/m)
-------------+-----------------+-----------------
Distance(m) | latitude(deg) | longitude(deg)
-------------+-----------------+-----------------
1.0 | 0.0000089932 | 0.0000109787
10.0 | 0.0000899320 | 0.0001097872
100.0 | 0.0008993204 | 0.0010978720
-------------+-----------------+-----------------
p0 = (35.233795, 129.082850)
p1 = (35.234694, 129.082850); p5 = (35.232895, 129.082850)
p2 = (35.234694, 129.083947); p6 = (35.232895, 129.081752)
p3 = (35.233795, 129.083947); p7 = (35.233795, 129.081752)
p4 = (35.232895, 129.083947); p8 = (35.234694, 129.081752)
'''
def bearing((lat1, long1), (lat2, long2)):
Lat1, Lat2 = radians(lat1), radians(lat2)
Long1, Long2 = radians(long1), radians(long2)
y = sin(Long2-Long1)*cos(Lat2)
x = cos(Lat1)*sin(Lat2) - sin(Lat1)*cos(Lat2)*cos(Long2-Long1)
return degrees(atan2(y, x))
if __name__ == '__main__':
try:
rospy.init_node('get_distance_n_bearing_from_gps', anonymous = True)
a = (35, 129); b = (36, 129); c = (35, 130)
print "latitude 1(deg) is %s(m)" %(haversine(a,b) * 1000)
print "longitude 1(deg) is %s(m)" %(haversine(a,c) * 1000)
p0 = (35.233795, 129.082850)
p1 = (35.234694, 129.082850); p5 = (35.232895, 129.082850)
p2 = (35.234694, 129.083947); p6 = (35.232895, 129.081752)
p3 = (35.233795, 129.083947); p7 = (35.233795, 129.081752)
p4 = (35.232895, 129.083947); p8 = (35.234694, 129.081752)
print "p1: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p1)*1000, bearing(p0,p1))
print "p2: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p2)*1000, bearing(p0,p2))
print "p3: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p3)*1000, bearing(p0,p3))
print "p4: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p4)*1000, bearing(p0,p4))
print "p5: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p5)*1000, bearing(p0,p5))
print "p6: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p6)*1000, bearing(p0,p6))
print "p7: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p7)*1000, bearing(p0,p7))
print "p8: dist = %s(m),\tbearing = %s(deg)" %(haversine(p0,p8)*1000, bearing(p0,p8))
except rospy.ROSInterruptException: pass
| en | 0.287833 | #!/usr/bin/env python |<-- 100(m)-->|<-- 100(m)-->| --- p8------------p1-------------p2-> 35.234694 (35.233795+0.0008993204) ^ | .-45 |0 . | | | . | . 45| 100 | . | . | (m) | . | . | | | . | . | v |-90 . | . | --- p7------------p0-------------p3-> 35.233795 ^ | . | . 90| | | . | . | 100 | . | . | (m) | . | . | | -135. | . | v | . | 135 . | --- p6------------p5-------------p4-> 35.232895 (35.233795-0.0008993204) v v v 129.081752 129.082850 129.083947 (129.082850-0.0010978720) (129.082850+0.0010978720) distance of latitude 1(deg) = 111195.0802340(m/deg) p1( 35, 129) p2( 36, 129) distance of longtitude 1(deg) = 91085.2969372(m/deg) p1( 35, 129) p2( 35, 130) latitude of distance 1(m) = 0.00000899320363720(deg/m) longitude of distance 1(m) = 0.00001097872031629(deg/m) -------------+-----------------+----------------- Distance(m) | latitude(deg) | longitude(deg) -------------+-----------------+----------------- 1.0 | 0.0000089932 | 0.0000109787 10.0 | 0.0000899320 | 0.0001097872 100.0 | 0.0008993204 | 0.0010978720 -------------+-----------------+----------------- p0 = (35.233795, 129.082850) p1 = (35.234694, 129.082850); p5 = (35.232895, 129.082850) p2 = (35.234694, 129.083947); p6 = (35.232895, 129.081752) p3 = (35.233795, 129.083947); p7 = (35.233795, 129.081752) p4 = (35.232895, 129.083947); p8 = (35.234694, 129.081752) | 2.955888 | 3 |
quoridor/client/src/coord.py | joshmal9999/Quoridor-Online | 2 | 6617672 | <gh_stars>1-10
"""
Quoridor Online
<NAME>, 2020
"""
import pygame
from quoridor.client.src.wall import Wall
class Coord:
"""Create a coord"""
def __init__(self, x, y, win, coords):
self.win = win
self.coords = coords
self.x = x
self.y = y
self.tuple = (x, y)
self.is_occuped = False
# Window attributs
self.top_left = self.make_top_left()
self.middle = self.make_middle()
self.rect = self.make_rect()
# Links
self.north = None
self.east = None
self.south = None
self.west = None
self.wall_east = None
self.wall_south = None
def coord_north(self):
"""Return the coord on the north"""
if self.y - 1 >= 0:
return self.coords.find_coord(self.x, self.y - 1)
return None
def coord_east(self):
"""Return the coord on the east"""
if self.x + 1 <= 8:
return self.coords.find_coord(self.x + 1, self.y)
return None
def coord_south(self):
"""Return the coord on the south"""
if self.y + 1 <= 8:
return self.coords.find_coord(self.x, self.y + 1)
return None
def coord_west(self):
"""Return the coord on the west"""
if self.x - 1 >= 0:
return self.coords.find_coord(self.x - 1, self.y)
return None
def make_top_left(self):
"""Return the top left point of a coord on a window"""
win = self.win
x = ((win.wall_width + win.case_side)*self.x
+ win.wall_width + win.top_left[0])
y = ((win.wall_width + win.case_side)*self.y
+ win.wall_width + win.top_left[1])
return (x, y)
def make_middle(self):
"""Return the middle point of a coord on a window"""
win = self.win
x = ((win.wall_width + win.case_side)*self.x
+ (win.wall_width + win.case_side // 2)
+ win.top_left[0])
y = ((win.wall_width + win.case_side)*self.y
+ (win.wall_width + win.case_side // 2)
+ win.top_left[1])
return (x, y)
def make_rect(self):
"""Return the rectangle of the coord"""
win = self.win
x, y = self.top_left
return (x, y, win.case_side, win.case_side)
def make_wall_east(self):
"""Return the east wall of the coord"""
if self.east is not None and self.y != 8:
return Wall(self, self.east, self.win)
return None
def make_wall_south(self):
"""Return the south wall of the coord"""
if self.south is not None and self.x != 8:
return Wall(self, self.south, self.win)
return None
def link_coord(self):
"""Link the coords"""
self.north = self.coord_north()
self.east = self.coord_east()
self.south = self.coord_south()
self.west = self.coord_west()
def make_walls(self):
"""Make the walls around the coord"""
self.wall_east = self.make_wall_east()
self.wall_south = self.make_wall_south()
def make_cross_walls(self):
"""Make the cross walls of the walls of the coord"""
if self.wall_east is not None:
self.wall_east.make_cross_wall()
if self.wall_south is not None:
self.wall_south.make_cross_wall()
def same_row(self, other):
"""Return True if the two coords are on the same row"""
return self.y == other.y
def same_column(self, other):
"""Return True if the two coords are on the same column"""
return self.x == other.x
def __str__(self):
"""String format of a coord"""
return f"({self.x}, {self.y})"
def __eq__(self, other):
"""Operator == between two coords"""
return self.x == other.x and self.y == other.y
def draw(self, color):
"""Draw the rectangle of a coord"""
pygame.draw.rect(self.win.win, color, self.rect)
class Coords:
"""Manage the coords"""
def __init__(self, win):
self.win = win
self.coords = self.make_coords()
self.link_coords()
self.make_walls()
def make_coords(self):
"""Make coords"""
coords = []
for x in range(9):
for y in range(9):
coords.append(Coord(x, y, self.win, self))
return coords
def link_coords(self):
"""Link coords"""
for c in self.coords:
c.link_coord()
def make_walls(self):
"""Make walls"""
for c in self.coords:
c.make_walls()
for c in self.coords:
c.make_cross_walls()
def find_coord(self, x, y):
"""Find the coord corresponding to x and y"""
return self.coords[x * 9 + y]
def reset(self):
"""Reset coords"""
for c in self.coords:
c.is_occuped = False
| """
Quoridor Online
<NAME>, 2020
"""
import pygame
from quoridor.client.src.wall import Wall
class Coord:
"""Create a coord"""
def __init__(self, x, y, win, coords):
self.win = win
self.coords = coords
self.x = x
self.y = y
self.tuple = (x, y)
self.is_occuped = False
# Window attributs
self.top_left = self.make_top_left()
self.middle = self.make_middle()
self.rect = self.make_rect()
# Links
self.north = None
self.east = None
self.south = None
self.west = None
self.wall_east = None
self.wall_south = None
def coord_north(self):
"""Return the coord on the north"""
if self.y - 1 >= 0:
return self.coords.find_coord(self.x, self.y - 1)
return None
def coord_east(self):
"""Return the coord on the east"""
if self.x + 1 <= 8:
return self.coords.find_coord(self.x + 1, self.y)
return None
def coord_south(self):
"""Return the coord on the south"""
if self.y + 1 <= 8:
return self.coords.find_coord(self.x, self.y + 1)
return None
def coord_west(self):
"""Return the coord on the west"""
if self.x - 1 >= 0:
return self.coords.find_coord(self.x - 1, self.y)
return None
def make_top_left(self):
"""Return the top left point of a coord on a window"""
win = self.win
x = ((win.wall_width + win.case_side)*self.x
+ win.wall_width + win.top_left[0])
y = ((win.wall_width + win.case_side)*self.y
+ win.wall_width + win.top_left[1])
return (x, y)
def make_middle(self):
"""Return the middle point of a coord on a window"""
win = self.win
x = ((win.wall_width + win.case_side)*self.x
+ (win.wall_width + win.case_side // 2)
+ win.top_left[0])
y = ((win.wall_width + win.case_side)*self.y
+ (win.wall_width + win.case_side // 2)
+ win.top_left[1])
return (x, y)
def make_rect(self):
"""Return the rectangle of the coord"""
win = self.win
x, y = self.top_left
return (x, y, win.case_side, win.case_side)
def make_wall_east(self):
"""Return the east wall of the coord"""
if self.east is not None and self.y != 8:
return Wall(self, self.east, self.win)
return None
def make_wall_south(self):
"""Return the south wall of the coord"""
if self.south is not None and self.x != 8:
return Wall(self, self.south, self.win)
return None
def link_coord(self):
"""Link the coords"""
self.north = self.coord_north()
self.east = self.coord_east()
self.south = self.coord_south()
self.west = self.coord_west()
def make_walls(self):
"""Make the walls around the coord"""
self.wall_east = self.make_wall_east()
self.wall_south = self.make_wall_south()
def make_cross_walls(self):
"""Make the cross walls of the walls of the coord"""
if self.wall_east is not None:
self.wall_east.make_cross_wall()
if self.wall_south is not None:
self.wall_south.make_cross_wall()
def same_row(self, other):
"""Return True if the two coords are on the same row"""
return self.y == other.y
def same_column(self, other):
"""Return True if the two coords are on the same column"""
return self.x == other.x
def __str__(self):
"""String format of a coord"""
return f"({self.x}, {self.y})"
def __eq__(self, other):
"""Operator == between two coords"""
return self.x == other.x and self.y == other.y
def draw(self, color):
"""Draw the rectangle of a coord"""
pygame.draw.rect(self.win.win, color, self.rect)
class Coords:
"""Manage the coords"""
def __init__(self, win):
self.win = win
self.coords = self.make_coords()
self.link_coords()
self.make_walls()
def make_coords(self):
"""Make coords"""
coords = []
for x in range(9):
for y in range(9):
coords.append(Coord(x, y, self.win, self))
return coords
def link_coords(self):
"""Link coords"""
for c in self.coords:
c.link_coord()
def make_walls(self):
"""Make walls"""
for c in self.coords:
c.make_walls()
for c in self.coords:
c.make_cross_walls()
def find_coord(self, x, y):
"""Find the coord corresponding to x and y"""
return self.coords[x * 9 + y]
def reset(self):
"""Reset coords"""
for c in self.coords:
c.is_occuped = False | en | 0.6498 | Quoridor Online <NAME>, 2020 Create a coord # Window attributs # Links Return the coord on the north Return the coord on the east Return the coord on the south Return the coord on the west Return the top left point of a coord on a window Return the middle point of a coord on a window Return the rectangle of the coord Return the east wall of the coord Return the south wall of the coord Link the coords Make the walls around the coord Make the cross walls of the walls of the coord Return True if the two coords are on the same row Return True if the two coords are on the same column String format of a coord Operator == between two coords Draw the rectangle of a coord Manage the coords Make coords Link coords Make walls Find the coord corresponding to x and y Reset coords | 3.955842 | 4 |
keystone/controllers/token.py | admiyo/keystone | 0 | 6617673 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2010-2011 OpenStack, LLC.
#
# 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.
"""
Token Controller
This module contains the TokenController class which receives token-related
calls from the request routers.
"""
import logging
from keystone import config
from keystone import utils
from keystone.controllers.base_controller import BaseController
from keystone.logic import extension_reader
from keystone.logic.types import auth
from keystone.logic.types import fault
from keystone.logic import service
CONF = config.CONF
logger = logging.getLogger(__name__) # pylint: disable=C0103
class TokenController(BaseController):
"""Controller for token related operations"""
def __init__(self):
self.identity_service = service.IdentityService()
logger.debug("Token controller init with HP-IDM extension: %s" % \
extension_reader.is_extension_supported('hpidm'))
@utils.wrap_error
def authenticate(self, req):
credential_type = utils.detect_credential_type(req)
if credential_type == "passwordCredentials":
auth_with_credentials = utils.get_normalized_request_content(
auth.AuthWithPasswordCredentials, req)
result = self.identity_service.authenticate(
auth_with_credentials)
return utils.send_result(200, req, result)
elif credential_type == "token":
unscoped = utils.get_normalized_request_content(
auth.AuthWithUnscopedToken, req)
result = self.identity_service.\
authenticate_with_unscoped_token(unscoped)
return utils.send_result(200, req, result)
elif credential_type == "OS-KSEC2:ec2Credentials":
return self._authenticate_ec2(req)
elif credential_type == "OS-KSS3:s3Credentials":
return self._authenticate_s3(req)
elif credential_type in ["ec2Credentials", "OS-KSEC2-ec2Credentials"]:
logger.warning('Received EC2 credentials in %s format. Processing '
'may fail. Update the client code sending this '
'format' % credential_type)
return self._authenticate_ec2(req)
else:
raise fault.BadRequestFault("Invalid credentials %s" %
credential_type)
@utils.wrap_error
def authenticate_ec2(self, req):
return self._authenticate_ec2(req)
def _authenticate_ec2(self, req):
"""Undecorated EC2 handler"""
creds = utils.get_normalized_request_content(auth.Ec2Credentials, req)
return utils.send_result(200, req,
self.identity_service.authenticate_ec2(creds))
@utils.wrap_error
def authenticate_s3(self, req):
return self._authenticate_s3(req)
def _authenticate_s3(self, req):
"""Undecorated S3 handler"""
creds = utils.get_normalized_request_content(auth.S3Credentials, req)
return utils.send_result(200, req,
self.identity_service.authenticate_s3(creds))
def _validate_token(self, req, token_id):
"""Validates the token, and that it belongs to the specified tenant"""
belongs_to = req.GET.get('belongsTo')
service_ids = None
if extension_reader.is_extension_supported('hpidm'):
# service IDs are only relevant if hpidm extension is enabled
service_ids = req.GET.get('HP-IDM-serviceId')
return self.identity_service.validate_token(
utils.get_auth_token(req), token_id, belongs_to, service_ids)
@utils.wrap_error
def validate_token(self, req, token_id):
if CONF.disable_tokens_in_url:
fault.ServiceUnavailableFault()
else:
result = self._validate_token(req, token_id)
return utils.send_result(200, req, result)
@utils.wrap_error
def check_token(self, req, token_id):
"""Validates the token, but only returns a status code (HEAD)"""
if CONF.disable_tokens_in_url:
fault.ServiceUnavailableFault()
else:
self._validate_token(req, token_id)
return utils.send_result(200, req)
@utils.wrap_error
def delete_token(self, req, token_id):
if CONF.disable_tokens_in_url:
fault.ServiceUnavailableFault()
else:
return utils.send_result(204, req,
self.identity_service.revoke_token(
utils.get_auth_token(req), token_id))
@utils.wrap_error
def endpoints(self, req, token_id):
if CONF.disable_tokens_in_url:
fault.ServiceUnavailableFault()
else:
marker, limit, url = self.get_marker_limit_and_url(req)
return utils.send_result(200, req,
self.identity_service.get_endpoints_for_token(
utils.get_auth_token(req),
token_id, marker, limit, url))
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2010-2011 OpenStack, LLC.
#
# 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.
"""
Token Controller
This module contains the TokenController class which receives token-related
calls from the request routers.
"""
import logging
from keystone import config
from keystone import utils
from keystone.controllers.base_controller import BaseController
from keystone.logic import extension_reader
from keystone.logic.types import auth
from keystone.logic.types import fault
from keystone.logic import service
CONF = config.CONF
logger = logging.getLogger(__name__) # pylint: disable=C0103
class TokenController(BaseController):
"""Controller for token related operations"""
def __init__(self):
self.identity_service = service.IdentityService()
logger.debug("Token controller init with HP-IDM extension: %s" % \
extension_reader.is_extension_supported('hpidm'))
@utils.wrap_error
def authenticate(self, req):
credential_type = utils.detect_credential_type(req)
if credential_type == "passwordCredentials":
auth_with_credentials = utils.get_normalized_request_content(
auth.AuthWithPasswordCredentials, req)
result = self.identity_service.authenticate(
auth_with_credentials)
return utils.send_result(200, req, result)
elif credential_type == "token":
unscoped = utils.get_normalized_request_content(
auth.AuthWithUnscopedToken, req)
result = self.identity_service.\
authenticate_with_unscoped_token(unscoped)
return utils.send_result(200, req, result)
elif credential_type == "OS-KSEC2:ec2Credentials":
return self._authenticate_ec2(req)
elif credential_type == "OS-KSS3:s3Credentials":
return self._authenticate_s3(req)
elif credential_type in ["ec2Credentials", "OS-KSEC2-ec2Credentials"]:
logger.warning('Received EC2 credentials in %s format. Processing '
'may fail. Update the client code sending this '
'format' % credential_type)
return self._authenticate_ec2(req)
else:
raise fault.BadRequestFault("Invalid credentials %s" %
credential_type)
@utils.wrap_error
def authenticate_ec2(self, req):
return self._authenticate_ec2(req)
def _authenticate_ec2(self, req):
"""Undecorated EC2 handler"""
creds = utils.get_normalized_request_content(auth.Ec2Credentials, req)
return utils.send_result(200, req,
self.identity_service.authenticate_ec2(creds))
@utils.wrap_error
def authenticate_s3(self, req):
return self._authenticate_s3(req)
def _authenticate_s3(self, req):
"""Undecorated S3 handler"""
creds = utils.get_normalized_request_content(auth.S3Credentials, req)
return utils.send_result(200, req,
self.identity_service.authenticate_s3(creds))
def _validate_token(self, req, token_id):
"""Validates the token, and that it belongs to the specified tenant"""
belongs_to = req.GET.get('belongsTo')
service_ids = None
if extension_reader.is_extension_supported('hpidm'):
# service IDs are only relevant if hpidm extension is enabled
service_ids = req.GET.get('HP-IDM-serviceId')
return self.identity_service.validate_token(
utils.get_auth_token(req), token_id, belongs_to, service_ids)
@utils.wrap_error
def validate_token(self, req, token_id):
if CONF.disable_tokens_in_url:
fault.ServiceUnavailableFault()
else:
result = self._validate_token(req, token_id)
return utils.send_result(200, req, result)
@utils.wrap_error
def check_token(self, req, token_id):
"""Validates the token, but only returns a status code (HEAD)"""
if CONF.disable_tokens_in_url:
fault.ServiceUnavailableFault()
else:
self._validate_token(req, token_id)
return utils.send_result(200, req)
@utils.wrap_error
def delete_token(self, req, token_id):
if CONF.disable_tokens_in_url:
fault.ServiceUnavailableFault()
else:
return utils.send_result(204, req,
self.identity_service.revoke_token(
utils.get_auth_token(req), token_id))
@utils.wrap_error
def endpoints(self, req, token_id):
if CONF.disable_tokens_in_url:
fault.ServiceUnavailableFault()
else:
marker, limit, url = self.get_marker_limit_and_url(req)
return utils.send_result(200, req,
self.identity_service.get_endpoints_for_token(
utils.get_auth_token(req),
token_id, marker, limit, url))
| en | 0.788916 | # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2010-2011 OpenStack, LLC. # # 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. Token Controller This module contains the TokenController class which receives token-related calls from the request routers. # pylint: disable=C0103 Controller for token related operations Undecorated EC2 handler Undecorated S3 handler Validates the token, and that it belongs to the specified tenant # service IDs are only relevant if hpidm extension is enabled Validates the token, but only returns a status code (HEAD) | 1.92607 | 2 |
ostruct/__init__.py | jzaleski/python-ostruct | 6 | 6617674 | <reponame>jzaleski/python-ostruct<gh_stars>1-10
from .openstruct import OpenStruct # NOQA
| from .openstruct import OpenStruct # NOQA | none | 1 | 1.022025 | 1 | |
src/baseline.py | Avonite/context-project | 0 | 6617675 | <gh_stars>0
import torch.nn as nn
import torch.optim as optim
import torchvision
from sklearn.metrics import mean_squared_error, r2_score
from torch.utils.data import DataLoader
from torchvision.transforms import Compose
from datasets import MeanFashionMNIST
from networks.network import Net
from settings import *
# Code from: https://nextjournal.com/gkoehler/pytorch-mnist
# momentum is omitted in this example
def main():
train_dataset = MeanFashionMNIST(root='../data',
train=True,
transform=Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.1307,), (0.3081,))
]),
download=True)
test_dataset = MeanFashionMNIST(root='../data',
train=False,
transform=Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.1307,), (0.3081,))
]),
download=True)
train_loader = DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE_TRAIN, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=BATCH_SIZE_TEST, shuffle=True)
network = Net()
optimizer = optim.Adam(network.parameters(), lr=learning_rate)
criterion = nn.MSELoss()
train_losses = []
train_counter = []
network.train()
def train(epoch):
for batch_idx, (data, means) in enumerate(train_loader):
optimizer.zero_grad()
outputs = network(data.unsqueeze(1).float())
loss = criterion(outputs, means.unsqueeze(1).float())
loss.backward()
optimizer.step()
if batch_idx % log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
train_losses.append(loss.item())
train_counter.append(
(batch_idx * 64) + ((epoch - 1) * len(train_loader.dataset)))
torch.save(network.state_dict(), './results/model.pth')
torch.save(optimizer.state_dict(), './results/optimizer.pth')
def test():
test_predicted = []
test_actual_means = []
network.eval()
with torch.no_grad():
for data, means in test_loader:
output = network(data.unsqueeze(1).float())
test_predicted.append(output.numpy())
test_actual_means.append(means.numpy())
test_predicted = [a.squeeze().tolist() for a in test_predicted]
flat_predicted = [item for sublist in test_predicted for item in sublist]
test_actual_means = [a.squeeze().tolist() for a in test_actual_means]
flat_actual_means = [item for sublist in test_actual_means for item in sublist]
mse = mean_squared_error(flat_actual_means, flat_predicted)
r_square = r2_score(flat_actual_means, flat_predicted)
print(f'The Mean Squared Error: {mse}, and the R^2: {r_square}')
test()
for epoch in range(1, n_epochs + 1):
train(epoch)
test()
if __name__ == '__main__':
main()
| import torch.nn as nn
import torch.optim as optim
import torchvision
from sklearn.metrics import mean_squared_error, r2_score
from torch.utils.data import DataLoader
from torchvision.transforms import Compose
from datasets import MeanFashionMNIST
from networks.network import Net
from settings import *
# Code from: https://nextjournal.com/gkoehler/pytorch-mnist
# momentum is omitted in this example
def main():
train_dataset = MeanFashionMNIST(root='../data',
train=True,
transform=Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.1307,), (0.3081,))
]),
download=True)
test_dataset = MeanFashionMNIST(root='../data',
train=False,
transform=Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.1307,), (0.3081,))
]),
download=True)
train_loader = DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE_TRAIN, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=BATCH_SIZE_TEST, shuffle=True)
network = Net()
optimizer = optim.Adam(network.parameters(), lr=learning_rate)
criterion = nn.MSELoss()
train_losses = []
train_counter = []
network.train()
def train(epoch):
for batch_idx, (data, means) in enumerate(train_loader):
optimizer.zero_grad()
outputs = network(data.unsqueeze(1).float())
loss = criterion(outputs, means.unsqueeze(1).float())
loss.backward()
optimizer.step()
if batch_idx % log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
train_losses.append(loss.item())
train_counter.append(
(batch_idx * 64) + ((epoch - 1) * len(train_loader.dataset)))
torch.save(network.state_dict(), './results/model.pth')
torch.save(optimizer.state_dict(), './results/optimizer.pth')
def test():
test_predicted = []
test_actual_means = []
network.eval()
with torch.no_grad():
for data, means in test_loader:
output = network(data.unsqueeze(1).float())
test_predicted.append(output.numpy())
test_actual_means.append(means.numpy())
test_predicted = [a.squeeze().tolist() for a in test_predicted]
flat_predicted = [item for sublist in test_predicted for item in sublist]
test_actual_means = [a.squeeze().tolist() for a in test_actual_means]
flat_actual_means = [item for sublist in test_actual_means for item in sublist]
mse = mean_squared_error(flat_actual_means, flat_predicted)
r_square = r2_score(flat_actual_means, flat_predicted)
print(f'The Mean Squared Error: {mse}, and the R^2: {r_square}')
test()
for epoch in range(1, n_epochs + 1):
train(epoch)
test()
if __name__ == '__main__':
main() | en | 0.716067 | # Code from: https://nextjournal.com/gkoehler/pytorch-mnist # momentum is omitted in this example | 2.778764 | 3 |
iCCF/chromatic.py | Kamuish/iCCF | 6 | 6617676 | import os
import bisect
import warnings
from astropy.timeseries import periodograms
from pkg_resources import resource_stream
import numpy as np
from numpy import sqrt, sum
import matplotlib.pyplot as plt
from astropy.io import fits
from cached_property import cached_property
from .iCCF import Indicators
from .gaussian import gaussfit, RV, RVerror, FWHM, FWHMerror
from .keywords import getRV, getRVarray
from .utils import find_myself
# from .utils import get_orders_mean_wavelength
def read_spectral_format():
sf_red_stream = resource_stream(__name__, 'data/spectral_format_red.dat')
red = np.loadtxt(sf_red_stream)
sf_blue_stream = resource_stream(__name__, 'data/spectral_format_blue.dat')
blue = np.loadtxt(sf_blue_stream)
col_start_wave = 7
col_end_wave = 8
order_wave_range = {}
for i, order in enumerate(blue[::-1]):
order_range = [order[col_start_wave], order[col_end_wave]]
order_wave_range[i] = order_range
for i, order in enumerate(red[::-1], start=i+1):
order_range = [order[col_start_wave], order[col_end_wave]]
order_wave_range[i] = order_range
return order_wave_range
class chromaticRV():
def __init__(self, indicators):
"""
indicators : Indicators or list
Instance or list of instances of iCCF.Indicators
"""
self.order_wave_range = read_spectral_format()
self.wave_starts = [v[0] for v in self.order_wave_range.values()]
self.wave_ends = [v[1] for v in self.order_wave_range.values()]
self._blue_wave_limits = (440, 570)
self._mid_wave_limits = (570, 690)
self._red_wave_limits = (730, 790)
self._slice_policy = 0 # by default use both slices
self.blue_orders = self._find_orders(self._blue_wave_limits)
self.mid_orders = self._find_orders(self._mid_wave_limits)
self.red_orders = self._find_orders(self._red_wave_limits)
self._blueRV = None
self._midRV = None
self._redRV = None
self._blueRVerror = None
self._midRVerror = None
self._redRVerror = None
self.n = len(indicators)
if self.n == 1:
indicators = [indicators, ]
self.I = self.indicators = indicators
# store all but the last CCF for each of the Indicators instances
self.ccfs = [i.HDU[i._hdu_number].data[:-1] for i in self.I]
# store the last CCFs separately
self.ccf = [i.HDU[i._hdu_number].data[-1] for i in self.I]
# try storing the CCF uncertainties as well
self.eccfs = []
for i in self.I:
try:
self.eccfs.append(i.HDU[2].data[:-1])
except IndexError:
self.eccfs.append(None)
def __repr__(self):
bands = ', '.join(map(repr, self.bands))
nb = len(self.bands)
return f'chromaticRV({self.n} CCFs; {nb} bands: {bands} nm)'
@property
def blue_wave_limits(self):
""" Wavelength limits for the blue RV calculations [nm] """
return self._blue_wave_limits
@blue_wave_limits.setter
def blue_wave_limits(self, vals):
assert len(vals) == 2, 'provide two wavelengths (start and end) in nm'
self.blue_orders = self._find_orders(vals)
self._blue_wave_limits = vals
self._blueRV, self._midRV, self._redRV = None, None, None
@property
def mid_wave_limits(self):
""" Wavelength limits for the mid RV calculations [nm] """
return self._mid_wave_limits
@mid_wave_limits.setter
def mid_wave_limits(self, vals):
assert len(vals) == 2, 'provide two wavelengths (start and end) in nm'
self.mid_orders = self._find_orders(vals)
self._mid_wave_limits = vals
self._blueRV, self._midRV, self._redRV = None, None, None
@property
def red_wave_limits(self):
""" Wavelength limits for the red RV calculations [nm] """
return self._red_wave_limits
@red_wave_limits.setter
def red_wave_limits(self, vals):
assert len(vals) == 2, 'provide two wavelengths (start and end) in nm'
self.red_orders = self._find_orders(vals)
self._red_wave_limits = vals
self._blueRV, self._midRV, self._redRV = None, None, None
@property
def slice_policy(self):
""" How to deal with the two order slices.
0: use both slices by adding the corresponding CCFs (default)
1: use only the first slice
2: use only the second slice
"""
return self._slice_policy
@slice_policy.setter
def slice_policy(self, val):
self._slice_policy = val
self.blue_orders = self._find_orders(self._blue_wave_limits)
self.mid_orders = self._find_orders(self._mid_wave_limits)
self.red_orders = self._find_orders(self._red_wave_limits)
self._blueRV, self._midRV, self._redRV = None, None, None
def _find_orders(self, wave_limits):
order_start = bisect.bisect(self.wave_starts, wave_limits[0])
order_end = bisect.bisect(self.wave_ends, wave_limits[1])
order_start = order_start * 2
order_end = order_end * 2 + 1
if self.slice_policy == 0: # using both order slices
step = 1
return slice(order_start, order_end+1, step)
elif self.slice_policy == 1: # using first slice only
step = 2
return slice(order_start, order_end+1, step)
elif self.slice_policy == 2: # using second slice only
step = 2
return slice(order_start+1, order_end+1, step)
def get_rv(self, orders):
""" Get radial velocity, FWHM and uncertainties for specific orders
orders : int, slice, tuple, array
The CCFs of these orders will be summed to calculate the RV.
If int, only the CCF at that index will be used.
If slice, orders in the slice's range will be used.
If tuple, should have length 2 or 3 and correspond to minimum index,
maximum index and possibly step, for which orders to use
If array, should contain indices of orders to use
"""
if isinstance(orders, int):
orders = slice(orders, orders + 1)
elif isinstance(orders, tuple):
orders = slice(*orders)
rv, rve = [], []
fwhm, fwhme = [], []
for i, full_ccf, full_eccf in zip(self.I, self.ccfs, self.eccfs):
# create the CCF
ccf = full_ccf[orders].sum(axis=0)
if full_eccf is not None:
eccf = np.sqrt(np.square(full_eccf[orders]).sum(axis=0))
else:
eccf = None
# calculate RV and RV error
rv.append(RV(i.rv, ccf, eccf))
rve.append(RVerror(i.rv, ccf, eccf))
# rve.append(np.nan)
# calculate FWHM and FWHM error
fwhm.append(FWHM(i.rv, ccf))
fwhme.append(FWHMerror(i.rv, ccf, eccf))
# if not has_errors:
# warnings.warn(
# 'Cannot access CCF uncertainties to calculate RV error')
# return np.array(rv), None
# else:
return map(np.array, (rv, rve, fwhm, fwhme))
@property
def bands(self):
""" Wavelength limits of blue, mid, and red bands """
b = self.blue_wave_limits, self.mid_wave_limits, self.red_wave_limits
return b
@cached_property
def time(self):
""" BJD of observations """
return np.fromiter((i.bjd for i in self.I), np.float, self.n)
@property
def blueRV(self):
if self._blueRV is None:
out = self.get_rv(self.blue_orders)
self._blueRV, self._blueRVerror, self._blueFWHM, self._blueFWHMerror = out
return self._blueRV
@property
def midRV(self):
if self._midRV is None:
out = self.get_rv(self.mid_orders)
self._midRV, self._midRVerror, self._midFWHM, self._midFWHMerror = out
return self._midRV
@property
def redRV(self):
if self._redRV is None:
out = self.get_rv(self.red_orders)
self._redRV, self._redRVerror, self._redFWHM, self._redFWHMerror = out
return self._redRV
@property
def fullRV(self):
return np.fromiter((i.RV for i in self.I), np.float, self.n)
@property
def fullRVerror(self):
return np.fromiter((i.RVerror for i in self.I), np.float, self.n)
def bin(self, night_indices):
u = np.unique(night_indices)
ccfs = np.array(self.ccfs) # shape: (Nobs, Norders, Nrv)
ccfsb = [ccfs[night_indices == i].mean(axis=0) for i in u]
ccfsb = np.array(ccfsb) # shape: (Nobs_binned, Norders, Nrv)
self.ccfs = ccfsb
eccfs = np.array(self.eccfs) # shape: (Nobs, Norders, Nrv)
eccfsb = [sqrt(sum(eccfs[night_indices == i]**2, axis=0)) for i in u]
eccfsb = np.array(eccfsb) # shape: (Nobs_binned, Norders, Nrv)
self.eccfs = eccfsb
ccf = np.array(self.ccf) # shape: (Nobs, Nrv)
ccfb = [ccf[night_indices == i].mean(axis=0) for i in u]
ccfb = np.array(ccfb) # shape: (Nobs_binned, Nrv)
self.ccf = ccfb
rv = self.I[0].rv
self.indicators = [Indicators(rv, ccf.sum(axis=0)) for ccf in ccfsb]
self.I = self.indicators
self.n = len(self.I)
def plot(self, periodogram=False, mask=None, obs=None):
ncols = 2 if periodogram else 1
fig, axs = plt.subplots(3 + 1, ncols, constrained_layout=True)
axs = axs.ravel()
if periodogram:
indices_plots = np.arange(0, 8, 2)
indices_pers = np.arange(1, 8, 2)
for ax in axs[indices_pers[1:]]:
ax.sharex(axs[indices_pers[0]])
ax.sharey(axs[indices_pers[0]])
else:
indices_plots = np.arange(0, 4)
for ax in axs[indices_plots[1:]]:
ax.sharex(axs[indices_plots[0]])
ax.sharey(axs[indices_plots[0]])
kw = dict(fmt='o', ms=2)
if mask is None:
mask = np.ones_like(self.time, dtype=bool)
axs[indices_plots[0]].errorbar(self.time[mask],
1e3*(self.fullRV[mask] - self.fullRV[mask].mean()),
self.fullRVerror[mask], color='k', **kw)
axs[indices_plots[1]].errorbar(self.time[mask],
1e3*(self.blueRV[mask] - self.blueRV[mask].mean()),
self._blueRVerror[mask], color='b', **kw)
axs[indices_plots[2]].errorbar(self.time[mask],
1e3*(self.midRV[mask] - self.midRV[mask].mean()),
self._midRVerror[mask], color='g', **kw)
axs[indices_plots[3]].errorbar(self.time[mask],
1e3*(self.redRV[mask] - self.redRV[mask].mean()),
self._redRVerror[mask], color='r', **kw)
if periodogram:
periods = np.logspace(np.log10(1), np.log10(2 * self.time.ptp()),
1000)
kwfap = dict(alpha=0.2, ls='--')
if obs is None:
from astropy.timeseries import LombScargle
def gls(t, y, e, *args):
model = LombScargle(t, y, e)
return model, model.power(1 / periods)
else:
from gatspy import periodic
def gls(t, y, e, obs):
model = periodic.LombScargleMultiband(Nterms_base=1, Nterms_band=0)
model.fit(t, y, e, filts=obs)
power = model.periodogram(periods)
model.false_alarm_level = lambda x: np.zeros_like(x)
return model, power
models = []
model, power = gls(self.time[mask], self.fullRV[mask], self.fullRVerror[mask], obs[mask])
models.append(model)
axs[1].semilogx(periods, power, color='k')
if hasattr(model, 'false_alarm_level'):
axs[1].hlines(model.false_alarm_level([0.1, 0.01]),
*axs[1].get_xlim(), **kwfap)
if obs is not None:
axs[indices_plots[0]].plot(self.time[mask], 1e3*(model.ymean_ - self.fullRV[mask].mean()), ls='--')
model, power = gls(self.time[mask], self.blueRV[mask], self._blueRVerror[mask], obs[mask])
models.append(model)
axs[3].semilogx(periods, power, color='b')
if hasattr(model, 'false_alarm_level'):
axs[3].hlines(model.false_alarm_level([0.1, 0.01]),
*axs[1].get_xlim(), **kwfap)
if obs is not None:
axs[indices_plots[1]].plot(self.time[mask], 1e3*(model.ymean_ - self.blueRV[mask].mean()), ls='--')
model, power = gls(self.time[mask], self.midRV[mask], self._midRVerror[mask], obs[mask])
models.append(model)
axs[5].semilogx(periods, power, color='g')
if hasattr(model, 'false_alarm_level'):
axs[5].hlines(model.false_alarm_level([0.1, 0.01]),
*axs[1].get_xlim(), **kwfap)
if obs is not None:
axs[indices_plots[2]].plot(self.time[mask], 1e3*(model.ymean_ - self.midRV[mask].mean()), ls='--')
model, power = gls(self.time[mask], self.redRV[mask], self._redRVerror[mask], obs[mask])
models.append(model)
axs[7].semilogx(periods, power, color='r')
if hasattr(model, 'false_alarm_level'):
axs[7].hlines(model.false_alarm_level([0.1, 0.01]),
*axs[1].get_xlim(), **kwfap)
if obs is not None:
axs[indices_plots[3]].plot(self.time[mask], 1e3*(model.ymean_ - self.redRV[mask].mean()), ls='--')
for ax in axs[indices_plots]:
ax.set_ylabel('RV [m/s]')
axs[indices_plots[-1]].set_xlabel('Time [BJD]')
if periodogram:
axs[indices_pers[0]].set_xlim((periods.min(), periods.max()))
axs[indices_pers[-1]].set_xlabel('Period [days]')
kw = dict(fontsize=8)
axs[indices_pers[0]].set_title('full $\lambda$ range', loc='right', **kw)
axs[indices_pers[1]].set_title(f'blue $\lambda={self.bands[0]}$ nm', loc='right', **kw)
axs[indices_pers[2]].set_title(f'mid $\lambda={self.bands[1]}$ nm', loc='right', **kw)
axs[indices_pers[3]].set_title(f'red $\lambda={self.bands[2]}$ nm', loc='right', **kw)
for ax in axs[indices_pers]:
ax.axvline(5.12, alpha=0.2, color='k', ls='--', zorder=-1)
ax.axvline(11.19, alpha=0.2, color='k', ls='--', zorder=-1)
axs[indices_pers[0]].set_xlim(0.9, 200)
return fig, axs, models
def plot_ccfs(self, orders=None, show_filenames=False):
if orders is None:
orders = slice(None, None)
elif isinstance(orders, int):
orders = slice(orders, orders + 1)
elif isinstance(orders, tuple):
orders = slice(*orders)
fig, ax = plt.subplots(1, 1) #, constrained_layout=True)
for i in self.I:
line = ax.plot(i.rv, i._SCIDATA[orders].T)
if show_filenames:
color = line[0].get_color()
ax.text(i.rv[0], i.ccf[0], i.filename, fontsize=8, color=color)
ax.set(xlabel='RV', ylabel='CCF')
def each_order_rv(rv, ccfs, exclude_last=True):
"""
Calculate RVs for each spectral order by fitting Gaussians to individual CCFs
Parameters
----------
rv : array
Radial velocities where each CCF is defined
ccfs : array
The CCFs for each spectral order (order o, radial velocity rv)
exclude_last : bool
Whether to exclude the last index of ccfs (usually the sum of all other
CCFs) from the calculation.
Returns
-------
rvs : array
The center of a Gaussian fit to each order's CCF
"""
last = -1 if exclude_last else None
gen = (gaussfit(rv, ccf)[1] for ccf in ccfs[:last])
rvs = np.fromiter(gen, dtype=float)
return rvs
def rv_color(rv, ccfs, blue=slice(0,80), red=slice(80,-1), avoid_blue=0, gap=0):
"""
Calculate the RV color by combining blue and red CCFs
Parameters
----------
rv : array
Radial velocities where each CCF is defined
ccfs : array
The CCFs for each spectral order (order o, radial velocity rv)
blue : slice
A slice object with the start and stop indices of the blue orders. The
default (0:80) is for ESPRESSO. For HARPS, use ...
red : slice
A slice object with the start and stop indices of the red orders. The
default (80:-1) is for ESPRESSO. For HARPS, use ...
avoid_blue : int
How many orders to skip in the bluest part of the spectrum. This will
be added to the beginning of the `blue` slice
gap : int or tuple
If an integer, the number of orders to remove from the "middle" for both
blue and red parts. If a tuple, the number of orders to remove from the
blue and red, respectively
"""
if isinstance(gap, tuple):
gap_blue, gap_red = gap
elif isinstance(gap, int):
gap_blue = gap_red = gap
else:
raise ValueError(f"`gap` should be int or tuple, got {gap}")
blue = slice(blue.start + avoid_blue, blue.stop - gap_blue)
red = slice(red.start + gap_red, red.stop)
ccf_blue = ccfs[blue, :].sum(axis=0)
ccf_red = ccfs[red, :].sum(axis=0)
rv_blue = gaussfit(rv, ccf_blue)[1]
rv_red = gaussfit(rv, ccf_red)[1]
print(rv_blue, rv_red)
# def chromatic_index(rv, ccfs, wave, rvpipe=None):
# """
# Calculate the chromatic index, as described in Zechmeister et al. (2018).
# Parameters
# ----------
# rv : array
# Radial velocities where each CCF is defined
# """
# if isinstance(wave, str): # assume it's a filename
# wave = get_wave(wave)
# elif isinstance(wave, np.ndarray):
# pass
# else:
# raise ValueError('`wave` should be filename or array with wavelengths')
# mean_wave = get_orders_mean_wavelength(wave, log=True)
# rvs = each_order_rv(rv, ccfs)
# ind = ~np.isnan(rvs)
# p = np.polyfit(np.log(mean_wave[ind]), rvs[ind], 1)
# if rvpipe is None:
# rvpipe = gaussfit(rv, ccfs[-1])[1]
# beta = p[0]
# lv = np.exp(abs((p[1] - rvpipe)/p[0]))
# return beta, lv
# def chromatic_index_from_files(s2dfile, ccffile):
# """
# Calculate the chromatic index, as described in Zechmeister et al. (2018).
# Parameters
# ----------
# s2dfile : str
# Filename of the S2D fits file
# ccffile : str
# Filename of the CCF fits file
# """
# wave = get_wave(s2dfile)
# mean_wave = get_orders_mean_wavelength(wave, log=True)
# rvpipe = getRV(ccffile)
# rv = getRVarray(ccffile)
# ccfs = fits.open(ccffile)[1].data
# rvs = each_order_rv(rv, ccfs)
# return chromatic_index(rv, ccfs, wave, rvpipe)
| import os
import bisect
import warnings
from astropy.timeseries import periodograms
from pkg_resources import resource_stream
import numpy as np
from numpy import sqrt, sum
import matplotlib.pyplot as plt
from astropy.io import fits
from cached_property import cached_property
from .iCCF import Indicators
from .gaussian import gaussfit, RV, RVerror, FWHM, FWHMerror
from .keywords import getRV, getRVarray
from .utils import find_myself
# from .utils import get_orders_mean_wavelength
def read_spectral_format():
sf_red_stream = resource_stream(__name__, 'data/spectral_format_red.dat')
red = np.loadtxt(sf_red_stream)
sf_blue_stream = resource_stream(__name__, 'data/spectral_format_blue.dat')
blue = np.loadtxt(sf_blue_stream)
col_start_wave = 7
col_end_wave = 8
order_wave_range = {}
for i, order in enumerate(blue[::-1]):
order_range = [order[col_start_wave], order[col_end_wave]]
order_wave_range[i] = order_range
for i, order in enumerate(red[::-1], start=i+1):
order_range = [order[col_start_wave], order[col_end_wave]]
order_wave_range[i] = order_range
return order_wave_range
class chromaticRV():
def __init__(self, indicators):
"""
indicators : Indicators or list
Instance or list of instances of iCCF.Indicators
"""
self.order_wave_range = read_spectral_format()
self.wave_starts = [v[0] for v in self.order_wave_range.values()]
self.wave_ends = [v[1] for v in self.order_wave_range.values()]
self._blue_wave_limits = (440, 570)
self._mid_wave_limits = (570, 690)
self._red_wave_limits = (730, 790)
self._slice_policy = 0 # by default use both slices
self.blue_orders = self._find_orders(self._blue_wave_limits)
self.mid_orders = self._find_orders(self._mid_wave_limits)
self.red_orders = self._find_orders(self._red_wave_limits)
self._blueRV = None
self._midRV = None
self._redRV = None
self._blueRVerror = None
self._midRVerror = None
self._redRVerror = None
self.n = len(indicators)
if self.n == 1:
indicators = [indicators, ]
self.I = self.indicators = indicators
# store all but the last CCF for each of the Indicators instances
self.ccfs = [i.HDU[i._hdu_number].data[:-1] for i in self.I]
# store the last CCFs separately
self.ccf = [i.HDU[i._hdu_number].data[-1] for i in self.I]
# try storing the CCF uncertainties as well
self.eccfs = []
for i in self.I:
try:
self.eccfs.append(i.HDU[2].data[:-1])
except IndexError:
self.eccfs.append(None)
def __repr__(self):
bands = ', '.join(map(repr, self.bands))
nb = len(self.bands)
return f'chromaticRV({self.n} CCFs; {nb} bands: {bands} nm)'
@property
def blue_wave_limits(self):
""" Wavelength limits for the blue RV calculations [nm] """
return self._blue_wave_limits
@blue_wave_limits.setter
def blue_wave_limits(self, vals):
assert len(vals) == 2, 'provide two wavelengths (start and end) in nm'
self.blue_orders = self._find_orders(vals)
self._blue_wave_limits = vals
self._blueRV, self._midRV, self._redRV = None, None, None
@property
def mid_wave_limits(self):
""" Wavelength limits for the mid RV calculations [nm] """
return self._mid_wave_limits
@mid_wave_limits.setter
def mid_wave_limits(self, vals):
assert len(vals) == 2, 'provide two wavelengths (start and end) in nm'
self.mid_orders = self._find_orders(vals)
self._mid_wave_limits = vals
self._blueRV, self._midRV, self._redRV = None, None, None
@property
def red_wave_limits(self):
""" Wavelength limits for the red RV calculations [nm] """
return self._red_wave_limits
@red_wave_limits.setter
def red_wave_limits(self, vals):
assert len(vals) == 2, 'provide two wavelengths (start and end) in nm'
self.red_orders = self._find_orders(vals)
self._red_wave_limits = vals
self._blueRV, self._midRV, self._redRV = None, None, None
@property
def slice_policy(self):
""" How to deal with the two order slices.
0: use both slices by adding the corresponding CCFs (default)
1: use only the first slice
2: use only the second slice
"""
return self._slice_policy
@slice_policy.setter
def slice_policy(self, val):
self._slice_policy = val
self.blue_orders = self._find_orders(self._blue_wave_limits)
self.mid_orders = self._find_orders(self._mid_wave_limits)
self.red_orders = self._find_orders(self._red_wave_limits)
self._blueRV, self._midRV, self._redRV = None, None, None
def _find_orders(self, wave_limits):
order_start = bisect.bisect(self.wave_starts, wave_limits[0])
order_end = bisect.bisect(self.wave_ends, wave_limits[1])
order_start = order_start * 2
order_end = order_end * 2 + 1
if self.slice_policy == 0: # using both order slices
step = 1
return slice(order_start, order_end+1, step)
elif self.slice_policy == 1: # using first slice only
step = 2
return slice(order_start, order_end+1, step)
elif self.slice_policy == 2: # using second slice only
step = 2
return slice(order_start+1, order_end+1, step)
def get_rv(self, orders):
""" Get radial velocity, FWHM and uncertainties for specific orders
orders : int, slice, tuple, array
The CCFs of these orders will be summed to calculate the RV.
If int, only the CCF at that index will be used.
If slice, orders in the slice's range will be used.
If tuple, should have length 2 or 3 and correspond to minimum index,
maximum index and possibly step, for which orders to use
If array, should contain indices of orders to use
"""
if isinstance(orders, int):
orders = slice(orders, orders + 1)
elif isinstance(orders, tuple):
orders = slice(*orders)
rv, rve = [], []
fwhm, fwhme = [], []
for i, full_ccf, full_eccf in zip(self.I, self.ccfs, self.eccfs):
# create the CCF
ccf = full_ccf[orders].sum(axis=0)
if full_eccf is not None:
eccf = np.sqrt(np.square(full_eccf[orders]).sum(axis=0))
else:
eccf = None
# calculate RV and RV error
rv.append(RV(i.rv, ccf, eccf))
rve.append(RVerror(i.rv, ccf, eccf))
# rve.append(np.nan)
# calculate FWHM and FWHM error
fwhm.append(FWHM(i.rv, ccf))
fwhme.append(FWHMerror(i.rv, ccf, eccf))
# if not has_errors:
# warnings.warn(
# 'Cannot access CCF uncertainties to calculate RV error')
# return np.array(rv), None
# else:
return map(np.array, (rv, rve, fwhm, fwhme))
@property
def bands(self):
""" Wavelength limits of blue, mid, and red bands """
b = self.blue_wave_limits, self.mid_wave_limits, self.red_wave_limits
return b
@cached_property
def time(self):
""" BJD of observations """
return np.fromiter((i.bjd for i in self.I), np.float, self.n)
@property
def blueRV(self):
if self._blueRV is None:
out = self.get_rv(self.blue_orders)
self._blueRV, self._blueRVerror, self._blueFWHM, self._blueFWHMerror = out
return self._blueRV
@property
def midRV(self):
if self._midRV is None:
out = self.get_rv(self.mid_orders)
self._midRV, self._midRVerror, self._midFWHM, self._midFWHMerror = out
return self._midRV
@property
def redRV(self):
if self._redRV is None:
out = self.get_rv(self.red_orders)
self._redRV, self._redRVerror, self._redFWHM, self._redFWHMerror = out
return self._redRV
@property
def fullRV(self):
return np.fromiter((i.RV for i in self.I), np.float, self.n)
@property
def fullRVerror(self):
return np.fromiter((i.RVerror for i in self.I), np.float, self.n)
def bin(self, night_indices):
u = np.unique(night_indices)
ccfs = np.array(self.ccfs) # shape: (Nobs, Norders, Nrv)
ccfsb = [ccfs[night_indices == i].mean(axis=0) for i in u]
ccfsb = np.array(ccfsb) # shape: (Nobs_binned, Norders, Nrv)
self.ccfs = ccfsb
eccfs = np.array(self.eccfs) # shape: (Nobs, Norders, Nrv)
eccfsb = [sqrt(sum(eccfs[night_indices == i]**2, axis=0)) for i in u]
eccfsb = np.array(eccfsb) # shape: (Nobs_binned, Norders, Nrv)
self.eccfs = eccfsb
ccf = np.array(self.ccf) # shape: (Nobs, Nrv)
ccfb = [ccf[night_indices == i].mean(axis=0) for i in u]
ccfb = np.array(ccfb) # shape: (Nobs_binned, Nrv)
self.ccf = ccfb
rv = self.I[0].rv
self.indicators = [Indicators(rv, ccf.sum(axis=0)) for ccf in ccfsb]
self.I = self.indicators
self.n = len(self.I)
def plot(self, periodogram=False, mask=None, obs=None):
ncols = 2 if periodogram else 1
fig, axs = plt.subplots(3 + 1, ncols, constrained_layout=True)
axs = axs.ravel()
if periodogram:
indices_plots = np.arange(0, 8, 2)
indices_pers = np.arange(1, 8, 2)
for ax in axs[indices_pers[1:]]:
ax.sharex(axs[indices_pers[0]])
ax.sharey(axs[indices_pers[0]])
else:
indices_plots = np.arange(0, 4)
for ax in axs[indices_plots[1:]]:
ax.sharex(axs[indices_plots[0]])
ax.sharey(axs[indices_plots[0]])
kw = dict(fmt='o', ms=2)
if mask is None:
mask = np.ones_like(self.time, dtype=bool)
axs[indices_plots[0]].errorbar(self.time[mask],
1e3*(self.fullRV[mask] - self.fullRV[mask].mean()),
self.fullRVerror[mask], color='k', **kw)
axs[indices_plots[1]].errorbar(self.time[mask],
1e3*(self.blueRV[mask] - self.blueRV[mask].mean()),
self._blueRVerror[mask], color='b', **kw)
axs[indices_plots[2]].errorbar(self.time[mask],
1e3*(self.midRV[mask] - self.midRV[mask].mean()),
self._midRVerror[mask], color='g', **kw)
axs[indices_plots[3]].errorbar(self.time[mask],
1e3*(self.redRV[mask] - self.redRV[mask].mean()),
self._redRVerror[mask], color='r', **kw)
if periodogram:
periods = np.logspace(np.log10(1), np.log10(2 * self.time.ptp()),
1000)
kwfap = dict(alpha=0.2, ls='--')
if obs is None:
from astropy.timeseries import LombScargle
def gls(t, y, e, *args):
model = LombScargle(t, y, e)
return model, model.power(1 / periods)
else:
from gatspy import periodic
def gls(t, y, e, obs):
model = periodic.LombScargleMultiband(Nterms_base=1, Nterms_band=0)
model.fit(t, y, e, filts=obs)
power = model.periodogram(periods)
model.false_alarm_level = lambda x: np.zeros_like(x)
return model, power
models = []
model, power = gls(self.time[mask], self.fullRV[mask], self.fullRVerror[mask], obs[mask])
models.append(model)
axs[1].semilogx(periods, power, color='k')
if hasattr(model, 'false_alarm_level'):
axs[1].hlines(model.false_alarm_level([0.1, 0.01]),
*axs[1].get_xlim(), **kwfap)
if obs is not None:
axs[indices_plots[0]].plot(self.time[mask], 1e3*(model.ymean_ - self.fullRV[mask].mean()), ls='--')
model, power = gls(self.time[mask], self.blueRV[mask], self._blueRVerror[mask], obs[mask])
models.append(model)
axs[3].semilogx(periods, power, color='b')
if hasattr(model, 'false_alarm_level'):
axs[3].hlines(model.false_alarm_level([0.1, 0.01]),
*axs[1].get_xlim(), **kwfap)
if obs is not None:
axs[indices_plots[1]].plot(self.time[mask], 1e3*(model.ymean_ - self.blueRV[mask].mean()), ls='--')
model, power = gls(self.time[mask], self.midRV[mask], self._midRVerror[mask], obs[mask])
models.append(model)
axs[5].semilogx(periods, power, color='g')
if hasattr(model, 'false_alarm_level'):
axs[5].hlines(model.false_alarm_level([0.1, 0.01]),
*axs[1].get_xlim(), **kwfap)
if obs is not None:
axs[indices_plots[2]].plot(self.time[mask], 1e3*(model.ymean_ - self.midRV[mask].mean()), ls='--')
model, power = gls(self.time[mask], self.redRV[mask], self._redRVerror[mask], obs[mask])
models.append(model)
axs[7].semilogx(periods, power, color='r')
if hasattr(model, 'false_alarm_level'):
axs[7].hlines(model.false_alarm_level([0.1, 0.01]),
*axs[1].get_xlim(), **kwfap)
if obs is not None:
axs[indices_plots[3]].plot(self.time[mask], 1e3*(model.ymean_ - self.redRV[mask].mean()), ls='--')
for ax in axs[indices_plots]:
ax.set_ylabel('RV [m/s]')
axs[indices_plots[-1]].set_xlabel('Time [BJD]')
if periodogram:
axs[indices_pers[0]].set_xlim((periods.min(), periods.max()))
axs[indices_pers[-1]].set_xlabel('Period [days]')
kw = dict(fontsize=8)
axs[indices_pers[0]].set_title('full $\lambda$ range', loc='right', **kw)
axs[indices_pers[1]].set_title(f'blue $\lambda={self.bands[0]}$ nm', loc='right', **kw)
axs[indices_pers[2]].set_title(f'mid $\lambda={self.bands[1]}$ nm', loc='right', **kw)
axs[indices_pers[3]].set_title(f'red $\lambda={self.bands[2]}$ nm', loc='right', **kw)
for ax in axs[indices_pers]:
ax.axvline(5.12, alpha=0.2, color='k', ls='--', zorder=-1)
ax.axvline(11.19, alpha=0.2, color='k', ls='--', zorder=-1)
axs[indices_pers[0]].set_xlim(0.9, 200)
return fig, axs, models
def plot_ccfs(self, orders=None, show_filenames=False):
if orders is None:
orders = slice(None, None)
elif isinstance(orders, int):
orders = slice(orders, orders + 1)
elif isinstance(orders, tuple):
orders = slice(*orders)
fig, ax = plt.subplots(1, 1) #, constrained_layout=True)
for i in self.I:
line = ax.plot(i.rv, i._SCIDATA[orders].T)
if show_filenames:
color = line[0].get_color()
ax.text(i.rv[0], i.ccf[0], i.filename, fontsize=8, color=color)
ax.set(xlabel='RV', ylabel='CCF')
def each_order_rv(rv, ccfs, exclude_last=True):
"""
Calculate RVs for each spectral order by fitting Gaussians to individual CCFs
Parameters
----------
rv : array
Radial velocities where each CCF is defined
ccfs : array
The CCFs for each spectral order (order o, radial velocity rv)
exclude_last : bool
Whether to exclude the last index of ccfs (usually the sum of all other
CCFs) from the calculation.
Returns
-------
rvs : array
The center of a Gaussian fit to each order's CCF
"""
last = -1 if exclude_last else None
gen = (gaussfit(rv, ccf)[1] for ccf in ccfs[:last])
rvs = np.fromiter(gen, dtype=float)
return rvs
def rv_color(rv, ccfs, blue=slice(0,80), red=slice(80,-1), avoid_blue=0, gap=0):
"""
Calculate the RV color by combining blue and red CCFs
Parameters
----------
rv : array
Radial velocities where each CCF is defined
ccfs : array
The CCFs for each spectral order (order o, radial velocity rv)
blue : slice
A slice object with the start and stop indices of the blue orders. The
default (0:80) is for ESPRESSO. For HARPS, use ...
red : slice
A slice object with the start and stop indices of the red orders. The
default (80:-1) is for ESPRESSO. For HARPS, use ...
avoid_blue : int
How many orders to skip in the bluest part of the spectrum. This will
be added to the beginning of the `blue` slice
gap : int or tuple
If an integer, the number of orders to remove from the "middle" for both
blue and red parts. If a tuple, the number of orders to remove from the
blue and red, respectively
"""
if isinstance(gap, tuple):
gap_blue, gap_red = gap
elif isinstance(gap, int):
gap_blue = gap_red = gap
else:
raise ValueError(f"`gap` should be int or tuple, got {gap}")
blue = slice(blue.start + avoid_blue, blue.stop - gap_blue)
red = slice(red.start + gap_red, red.stop)
ccf_blue = ccfs[blue, :].sum(axis=0)
ccf_red = ccfs[red, :].sum(axis=0)
rv_blue = gaussfit(rv, ccf_blue)[1]
rv_red = gaussfit(rv, ccf_red)[1]
print(rv_blue, rv_red)
# def chromatic_index(rv, ccfs, wave, rvpipe=None):
# """
# Calculate the chromatic index, as described in Zechmeister et al. (2018).
# Parameters
# ----------
# rv : array
# Radial velocities where each CCF is defined
# """
# if isinstance(wave, str): # assume it's a filename
# wave = get_wave(wave)
# elif isinstance(wave, np.ndarray):
# pass
# else:
# raise ValueError('`wave` should be filename or array with wavelengths')
# mean_wave = get_orders_mean_wavelength(wave, log=True)
# rvs = each_order_rv(rv, ccfs)
# ind = ~np.isnan(rvs)
# p = np.polyfit(np.log(mean_wave[ind]), rvs[ind], 1)
# if rvpipe is None:
# rvpipe = gaussfit(rv, ccfs[-1])[1]
# beta = p[0]
# lv = np.exp(abs((p[1] - rvpipe)/p[0]))
# return beta, lv
# def chromatic_index_from_files(s2dfile, ccffile):
# """
# Calculate the chromatic index, as described in Zechmeister et al. (2018).
# Parameters
# ----------
# s2dfile : str
# Filename of the S2D fits file
# ccffile : str
# Filename of the CCF fits file
# """
# wave = get_wave(s2dfile)
# mean_wave = get_orders_mean_wavelength(wave, log=True)
# rvpipe = getRV(ccffile)
# rv = getRVarray(ccffile)
# ccfs = fits.open(ccffile)[1].data
# rvs = each_order_rv(rv, ccfs)
# return chromatic_index(rv, ccfs, wave, rvpipe)
| en | 0.711381 | # from .utils import get_orders_mean_wavelength indicators : Indicators or list Instance or list of instances of iCCF.Indicators # by default use both slices # store all but the last CCF for each of the Indicators instances # store the last CCFs separately # try storing the CCF uncertainties as well Wavelength limits for the blue RV calculations [nm] Wavelength limits for the mid RV calculations [nm] Wavelength limits for the red RV calculations [nm] How to deal with the two order slices. 0: use both slices by adding the corresponding CCFs (default) 1: use only the first slice 2: use only the second slice # using both order slices # using first slice only # using second slice only Get radial velocity, FWHM and uncertainties for specific orders orders : int, slice, tuple, array The CCFs of these orders will be summed to calculate the RV. If int, only the CCF at that index will be used. If slice, orders in the slice's range will be used. If tuple, should have length 2 or 3 and correspond to minimum index, maximum index and possibly step, for which orders to use If array, should contain indices of orders to use # create the CCF # calculate RV and RV error # rve.append(np.nan) # calculate FWHM and FWHM error # if not has_errors: # warnings.warn( # 'Cannot access CCF uncertainties to calculate RV error') # return np.array(rv), None # else: Wavelength limits of blue, mid, and red bands BJD of observations # shape: (Nobs, Norders, Nrv) # shape: (Nobs_binned, Norders, Nrv) # shape: (Nobs, Norders, Nrv) # shape: (Nobs_binned, Norders, Nrv) # shape: (Nobs, Nrv) # shape: (Nobs_binned, Nrv) #, constrained_layout=True) Calculate RVs for each spectral order by fitting Gaussians to individual CCFs Parameters ---------- rv : array Radial velocities where each CCF is defined ccfs : array The CCFs for each spectral order (order o, radial velocity rv) exclude_last : bool Whether to exclude the last index of ccfs (usually the sum of all other CCFs) from the calculation. Returns ------- rvs : array The center of a Gaussian fit to each order's CCF Calculate the RV color by combining blue and red CCFs Parameters ---------- rv : array Radial velocities where each CCF is defined ccfs : array The CCFs for each spectral order (order o, radial velocity rv) blue : slice A slice object with the start and stop indices of the blue orders. The default (0:80) is for ESPRESSO. For HARPS, use ... red : slice A slice object with the start and stop indices of the red orders. The default (80:-1) is for ESPRESSO. For HARPS, use ... avoid_blue : int How many orders to skip in the bluest part of the spectrum. This will be added to the beginning of the `blue` slice gap : int or tuple If an integer, the number of orders to remove from the "middle" for both blue and red parts. If a tuple, the number of orders to remove from the blue and red, respectively # def chromatic_index(rv, ccfs, wave, rvpipe=None): # """ # Calculate the chromatic index, as described in Zechmeister et al. (2018). # Parameters # ---------- # rv : array # Radial velocities where each CCF is defined # """ # if isinstance(wave, str): # assume it's a filename # wave = get_wave(wave) # elif isinstance(wave, np.ndarray): # pass # else: # raise ValueError('`wave` should be filename or array with wavelengths') # mean_wave = get_orders_mean_wavelength(wave, log=True) # rvs = each_order_rv(rv, ccfs) # ind = ~np.isnan(rvs) # p = np.polyfit(np.log(mean_wave[ind]), rvs[ind], 1) # if rvpipe is None: # rvpipe = gaussfit(rv, ccfs[-1])[1] # beta = p[0] # lv = np.exp(abs((p[1] - rvpipe)/p[0])) # return beta, lv # def chromatic_index_from_files(s2dfile, ccffile): # """ # Calculate the chromatic index, as described in Zechmeister et al. (2018). # Parameters # ---------- # s2dfile : str # Filename of the S2D fits file # ccffile : str # Filename of the CCF fits file # """ # wave = get_wave(s2dfile) # mean_wave = get_orders_mean_wavelength(wave, log=True) # rvpipe = getRV(ccffile) # rv = getRVarray(ccffile) # ccfs = fits.open(ccffile)[1].data # rvs = each_order_rv(rv, ccfs) # return chromatic_index(rv, ccfs, wave, rvpipe) | 2.251388 | 2 |
core/data/DataReader.py | berendkleinhaneveld/Registrationshop | 25 | 6617677 | """
DataReader
:Authors:
<NAME>
"""
from vtk import vtkImageData
from vtk import vtkMetaImageReader
from vtk import vtkXMLImageDataReader
from vtk import vtkDICOMImageReader
from vtk import vtkNrrdReader
from DataController import DataController
import os
class DataReader(DataController):
"""
DataReader is a class that tries to figure out what kind of data type a
given file is. From the extension it will try to choose the correct reader
from vtk.
"""
# File extensions
TypeMHA = "mha" # vtkMetaImageReader
TypeMHD = "mhd" # vtkMetaImageReader
TypeVTI = "vti" # vtkXMLImageDataReader
TypeMRB = "mrb" # Unreadable at the moment (Slicer stuff)
TypeVTK = "vtk" # No real volume data... but might be used for polygon stuff
TypeRaw = "raw" # needs a mhd file... maybe choose some standard stuff
TypeDAT = "dat" # should be read byte by byte
TypeDICOM = "dcm" # Dicom does not really have an extension?
TypeNRRD = "nrrd" # Nearly Raw Raster Data
def __init__(self):
super(DataReader, self).__init__()
self.supportedExtensions = [DataReader.TypeMHA,
DataReader.TypeMHD,
DataReader.TypeVTI,
DataReader.TypeDICOM,
DataReader.TypeNRRD]
def GetImageData(self, fileName):
"""
:type fileName: basestr
:rtype: vtkImageData
"""
# First, check if it is a directory, that is used for dicom images
if os.path.isdir(fileName):
# Check if the directory really contains DICOM images
files = [f for f in os.listdir(fileName) if f.endswith("."+DataReader.TypeDICOM)]
if len(files) > 0:
return self.GetImageDataFromDirectory(fileName)
else:
# TODO: make this a proper Exception
print "Warning: directory does not contain DICOM files:", fileName
return None
baseFileName, extension = fileName.rsplit(".", 1)
if not self.IsExtensionSupported(extension):
raise Exception(extension + " is not supported.")
imageData = self.GetImageDataForBaseAndExtension(fileName, extension)
return imageData
def GetImageDataForBaseAndExtension(self, fileName, extension):
"""
:type fileName: basestring
:type extension: basestring
:rtype: vtkImageData
"""
if extension == DataReader.TypeMHA or extension == DataReader.TypeMHD:
# Use a vktMetaImageReader
imageReader = vtkMetaImageReader()
imageReader.SetFileName(fileName)
imageReader.Update()
return imageReader.GetOutput()
elif extension == DataReader.TypeDICOM:
# Use a dicom reader
dirName = os.path.dirname(fileName)
return self.GetImageDataFromDirectory(dirName)
elif extension == DataReader.TypeDAT:
raise Exception("Support for .dat files is not implemented.")
# Read in the .dat file byte by byte
imageData = None
import numpy as np
with open(fileName, "rb") as f:
dimensions = np.fromfile(f, np.int16, count=3)
imageData = vtkImageData()
imageData.SetDimensions(int(dimensions[0]), int(dimensions[1]), int(dimensions[2]))
imageData.SetScalarTypeToFloat()
imageData.SetNumberOfScalarComponents(1)
imageData.AllocateScalars()
imageData.Update()
imageData.PrepareForNewData()
fileData = np.fromfile(f, np.int16)
dataIndex = 0
for z in range(int(dimensions[2])):
for y in range(int(dimensions[1])):
for x in range(int(dimensions[0])):
imageData.SetScalarComponentFromFloat(x, y, z, 0, float(fileData[dataIndex]))
dataIndex += 1
return imageData
elif extension == DataReader.TypeVTI:
# Use a XMLImageReader
imageReader = vtkXMLImageDataReader()
imageReader.SetFileName(fileName)
imageReader.Update()
return imageReader.GetOutput()
elif extension == DataReader.TypeNRRD:
# Use a NrrdReader
imageReader = vtkNrrdReader()
imageReader.SetFileName(fileName)
imageReader.Update()
return imageReader.GetOutput()
else:
assert False
def GetImageDataFromDirectory(self, dirName):
"""
This method is just for DICOM image data. So input is a directory name
and it will output an vtkImageData object.
:type dirName: basestr
:rtype: vtkImageData
"""
imageReader = vtkDICOMImageReader()
imageReader.SetDirectoryName(dirName)
imageReader.Update()
imageData = imageReader.GetOutput()
self.SanitizeImageData(imageReader, imageData)
return imageData
def SanitizeImageData(self, reader, imageData):
"""
Sanitizes the given imageData. At the moment it just checks the
spacings to see if there are spacings that zero. This gives problems
with rendering the data.
"""
# Check the image data to see if the spacings are correct
spacing = list(imageData.GetSpacing())
# TODO: make this more pythonic...
for x in range(len(spacing)):
if spacing[x] == 0.0:
spacing[x] = 1.0
# TODO: instead of 1.0, use a more sane value...
# Or at least check whether it is the right thing to do
imageData.SetSpacing(spacing)
| """
DataReader
:Authors:
<NAME>
"""
from vtk import vtkImageData
from vtk import vtkMetaImageReader
from vtk import vtkXMLImageDataReader
from vtk import vtkDICOMImageReader
from vtk import vtkNrrdReader
from DataController import DataController
import os
class DataReader(DataController):
"""
DataReader is a class that tries to figure out what kind of data type a
given file is. From the extension it will try to choose the correct reader
from vtk.
"""
# File extensions
TypeMHA = "mha" # vtkMetaImageReader
TypeMHD = "mhd" # vtkMetaImageReader
TypeVTI = "vti" # vtkXMLImageDataReader
TypeMRB = "mrb" # Unreadable at the moment (Slicer stuff)
TypeVTK = "vtk" # No real volume data... but might be used for polygon stuff
TypeRaw = "raw" # needs a mhd file... maybe choose some standard stuff
TypeDAT = "dat" # should be read byte by byte
TypeDICOM = "dcm" # Dicom does not really have an extension?
TypeNRRD = "nrrd" # Nearly Raw Raster Data
def __init__(self):
super(DataReader, self).__init__()
self.supportedExtensions = [DataReader.TypeMHA,
DataReader.TypeMHD,
DataReader.TypeVTI,
DataReader.TypeDICOM,
DataReader.TypeNRRD]
def GetImageData(self, fileName):
"""
:type fileName: basestr
:rtype: vtkImageData
"""
# First, check if it is a directory, that is used for dicom images
if os.path.isdir(fileName):
# Check if the directory really contains DICOM images
files = [f for f in os.listdir(fileName) if f.endswith("."+DataReader.TypeDICOM)]
if len(files) > 0:
return self.GetImageDataFromDirectory(fileName)
else:
# TODO: make this a proper Exception
print "Warning: directory does not contain DICOM files:", fileName
return None
baseFileName, extension = fileName.rsplit(".", 1)
if not self.IsExtensionSupported(extension):
raise Exception(extension + " is not supported.")
imageData = self.GetImageDataForBaseAndExtension(fileName, extension)
return imageData
def GetImageDataForBaseAndExtension(self, fileName, extension):
"""
:type fileName: basestring
:type extension: basestring
:rtype: vtkImageData
"""
if extension == DataReader.TypeMHA or extension == DataReader.TypeMHD:
# Use a vktMetaImageReader
imageReader = vtkMetaImageReader()
imageReader.SetFileName(fileName)
imageReader.Update()
return imageReader.GetOutput()
elif extension == DataReader.TypeDICOM:
# Use a dicom reader
dirName = os.path.dirname(fileName)
return self.GetImageDataFromDirectory(dirName)
elif extension == DataReader.TypeDAT:
raise Exception("Support for .dat files is not implemented.")
# Read in the .dat file byte by byte
imageData = None
import numpy as np
with open(fileName, "rb") as f:
dimensions = np.fromfile(f, np.int16, count=3)
imageData = vtkImageData()
imageData.SetDimensions(int(dimensions[0]), int(dimensions[1]), int(dimensions[2]))
imageData.SetScalarTypeToFloat()
imageData.SetNumberOfScalarComponents(1)
imageData.AllocateScalars()
imageData.Update()
imageData.PrepareForNewData()
fileData = np.fromfile(f, np.int16)
dataIndex = 0
for z in range(int(dimensions[2])):
for y in range(int(dimensions[1])):
for x in range(int(dimensions[0])):
imageData.SetScalarComponentFromFloat(x, y, z, 0, float(fileData[dataIndex]))
dataIndex += 1
return imageData
elif extension == DataReader.TypeVTI:
# Use a XMLImageReader
imageReader = vtkXMLImageDataReader()
imageReader.SetFileName(fileName)
imageReader.Update()
return imageReader.GetOutput()
elif extension == DataReader.TypeNRRD:
# Use a NrrdReader
imageReader = vtkNrrdReader()
imageReader.SetFileName(fileName)
imageReader.Update()
return imageReader.GetOutput()
else:
assert False
def GetImageDataFromDirectory(self, dirName):
"""
This method is just for DICOM image data. So input is a directory name
and it will output an vtkImageData object.
:type dirName: basestr
:rtype: vtkImageData
"""
imageReader = vtkDICOMImageReader()
imageReader.SetDirectoryName(dirName)
imageReader.Update()
imageData = imageReader.GetOutput()
self.SanitizeImageData(imageReader, imageData)
return imageData
def SanitizeImageData(self, reader, imageData):
"""
Sanitizes the given imageData. At the moment it just checks the
spacings to see if there are spacings that zero. This gives problems
with rendering the data.
"""
# Check the image data to see if the spacings are correct
spacing = list(imageData.GetSpacing())
# TODO: make this more pythonic...
for x in range(len(spacing)):
if spacing[x] == 0.0:
spacing[x] = 1.0
# TODO: instead of 1.0, use a more sane value...
# Or at least check whether it is the right thing to do
imageData.SetSpacing(spacing)
| en | 0.712688 | DataReader :Authors: <NAME> DataReader is a class that tries to figure out what kind of data type a given file is. From the extension it will try to choose the correct reader from vtk. # File extensions # vtkMetaImageReader # vtkMetaImageReader # vtkXMLImageDataReader # Unreadable at the moment (Slicer stuff) # No real volume data... but might be used for polygon stuff # needs a mhd file... maybe choose some standard stuff # should be read byte by byte # Dicom does not really have an extension? # Nearly Raw Raster Data :type fileName: basestr :rtype: vtkImageData # First, check if it is a directory, that is used for dicom images # Check if the directory really contains DICOM images # TODO: make this a proper Exception :type fileName: basestring :type extension: basestring :rtype: vtkImageData # Use a vktMetaImageReader # Use a dicom reader # Read in the .dat file byte by byte # Use a XMLImageReader # Use a NrrdReader This method is just for DICOM image data. So input is a directory name and it will output an vtkImageData object. :type dirName: basestr :rtype: vtkImageData Sanitizes the given imageData. At the moment it just checks the spacings to see if there are spacings that zero. This gives problems with rendering the data. # Check the image data to see if the spacings are correct # TODO: make this more pythonic... # TODO: instead of 1.0, use a more sane value... # Or at least check whether it is the right thing to do | 2.839071 | 3 |
camper/handlers/users/profile.py | mrtopf/camper | 13 | 6617678 | #encoding=utf8
from starflyer import Handler, redirect
from camper import BaseForm, db, BaseHandler
from camper import logged_in, is_admin
from wtforms import *
from camper.handlers.forms import *
import werkzeug.exceptions
class ProfileView(BaseHandler):
"""shows the profile of a user"""
template = "users/profile.html"
def get(self, username = None):
"""render the view"""
user = self.app.module_map.userbase.get_user_by_username(username)
if user is None or user.deleted:
raise werkzeug.exceptions.NotFound()
is_logged_in_user = user == self.user
asset_id = user.image
if asset_id is not None:
try:
asset = self.app.module_map.uploader.get(asset_id)
image = self.url_for("asset", asset_id = asset.variants['medium_user']._id)
except:
image = None
else:
image = None
return self.render(
profile_user = user,
is_logged_in_user = is_logged_in_user,
image = image
)
| #encoding=utf8
from starflyer import Handler, redirect
from camper import BaseForm, db, BaseHandler
from camper import logged_in, is_admin
from wtforms import *
from camper.handlers.forms import *
import werkzeug.exceptions
class ProfileView(BaseHandler):
"""shows the profile of a user"""
template = "users/profile.html"
def get(self, username = None):
"""render the view"""
user = self.app.module_map.userbase.get_user_by_username(username)
if user is None or user.deleted:
raise werkzeug.exceptions.NotFound()
is_logged_in_user = user == self.user
asset_id = user.image
if asset_id is not None:
try:
asset = self.app.module_map.uploader.get(asset_id)
image = self.url_for("asset", asset_id = asset.variants['medium_user']._id)
except:
image = None
else:
image = None
return self.render(
profile_user = user,
is_logged_in_user = is_logged_in_user,
image = image
)
| en | 0.790251 | #encoding=utf8 shows the profile of a user render the view | 2.139066 | 2 |
07_gashlycrumb/gashlycrumb.py | FreshGrill/tiny_python_projects | 0 | 6617679 | #!/usr/bin/env python3
"""
Author : <NAME> <<EMAIL>>
Date : 2021-03-22
Purpose: Rock the Casbah
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Gashlycrumb',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('letter',
metavar='letter',
nargs='+',
help='Letter(s)')
parser.add_argument(
"-f",
"--file",
help="Input FIle",
metavar="FILE",
type=argparse.FileType('rt'),
default='gashlycrumb.txt',
)
return parser.parse_args()
# --------------------------------------------------
def main():
"""Make a jazz noise here"""
args = get_args()
sentance={}
for line in args.file:
# print(line[0],line,end='')
sentance[line[0].lower()] = line
for letter in args.letter:
if letter.lower() in sentance:
print (sentance[letter.lower()],end='')
else:
print (f'I do not know "{letter}".')
# --------------------------------------------------
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
"""
Author : <NAME> <<EMAIL>>
Date : 2021-03-22
Purpose: Rock the Casbah
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Gashlycrumb',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('letter',
metavar='letter',
nargs='+',
help='Letter(s)')
parser.add_argument(
"-f",
"--file",
help="Input FIle",
metavar="FILE",
type=argparse.FileType('rt'),
default='gashlycrumb.txt',
)
return parser.parse_args()
# --------------------------------------------------
def main():
"""Make a jazz noise here"""
args = get_args()
sentance={}
for line in args.file:
# print(line[0],line,end='')
sentance[line[0].lower()] = line
for letter in args.letter:
if letter.lower() in sentance:
print (sentance[letter.lower()],end='')
else:
print (f'I do not know "{letter}".')
# --------------------------------------------------
if __name__ == '__main__':
main()
| en | 0.190598 | #!/usr/bin/env python3 Author : <NAME> <<EMAIL>> Date : 2021-03-22 Purpose: Rock the Casbah # -------------------------------------------------- Get command-line arguments # -------------------------------------------------- Make a jazz noise here # print(line[0],line,end='') # -------------------------------------------------- | 3.652548 | 4 |
nmdc_runtime/pipelines/jgi.py | polyneme/nmdc-runtime | 0 | 6617680 | from dagster import ModeDefinition, pipeline, PresetDefinition
from nmdc_runtime.solids.jgi import get_json_db
from nmdc_runtime.solids.core import hello
from nmdc_runtime.pipelines.core import (
mode_dev,
mode_prod,
preset_prod_env,
preset_dev_env,
)
@pipeline(
mode_defs=[mode_dev, mode_prod], preset_defs=[preset_dev_env, preset_prod_env]
)
def gold_etl():
hello()
get_json_db()
| from dagster import ModeDefinition, pipeline, PresetDefinition
from nmdc_runtime.solids.jgi import get_json_db
from nmdc_runtime.solids.core import hello
from nmdc_runtime.pipelines.core import (
mode_dev,
mode_prod,
preset_prod_env,
preset_dev_env,
)
@pipeline(
mode_defs=[mode_dev, mode_prod], preset_defs=[preset_dev_env, preset_prod_env]
)
def gold_etl():
hello()
get_json_db()
| none | 1 | 1.811479 | 2 | |
setup.py | sumiya11/ttax | 0 | 6617681 | from setuptools import setup
setup(name='ttax',
version='0.0.1',
description='Tensor Train decomposition on Jax',
url='https://github.com/fasghq/ttax',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['ttax'],
install_requires=[
'numpy',
'dm-tree',
'jax',
'flax'
],
zip_safe=False)
| from setuptools import setup
setup(name='ttax',
version='0.0.1',
description='Tensor Train decomposition on Jax',
url='https://github.com/fasghq/ttax',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['ttax'],
install_requires=[
'numpy',
'dm-tree',
'jax',
'flax'
],
zip_safe=False)
| none | 1 | 1.088158 | 1 | |
Inheritance/mix_it_new/project/vehicle/vehicle.py | MNikov/Python-OOP-October-2020 | 0 | 6617682 | from project.capacity_mixin import CapacityMixin
class Vehicle(CapacityMixin):
def __init__(self, available_seats):
self.available_seats = available_seats
| from project.capacity_mixin import CapacityMixin
class Vehicle(CapacityMixin):
def __init__(self, available_seats):
self.available_seats = available_seats
| none | 1 | 2.080669 | 2 | |
pycamunda/endpoints/common.py | belvedere-trading/pycamunda | 5 | 6617683 | <filename>pycamunda/endpoints/common.py
"""@ingroup endpoints
@file
Common schema definitions shared across multiple endpoint types.
"""
from enum import Enum, IntEnum
from dateutil.parser import parse
from voluptuous import Schema
from pycamunda.entity import JsonEntity, Number
## A schema validator for Camunda timestamp objects.
Timestamp = parse # pylint: disable=invalid-name
class ContentType(Enum):
"""Models HTTP content types.
"""
OctetStream = 'application/octet-stream'
Plain = 'text/plain'
class SortOrder(Enum):
"""Models sorting orders for REST queries.
"""
Ascending = 'asc'
Descending = 'desc'
class ResourceType(IntEnum):
"""Models the integer representation of Camunda resource types.
@see https://docs.camunda.org/manual/7.8/user-guide/process-engine/authorization-service/#resources
"""
Application = 0
Authorization = 4
Batch = 13
DecisionDefinition = 10
DecisionRequirementsDefinition = 14
Deployment = 9
Filter = 5
Group = 2
GroupMembership = 3
ProcessDefinition = 6
ProcessInstance = 8
Task = 7
Tenant = 11
TenantMembership = 12
User = 1
class Count(JsonEntity):
"""Models a count of Camunda objects.
Many different Camunda endpoints return simple counts; these should all return the Count type.
"""
@property
def schema(self):
return Schema({'count': Number}, required=True)
| <filename>pycamunda/endpoints/common.py
"""@ingroup endpoints
@file
Common schema definitions shared across multiple endpoint types.
"""
from enum import Enum, IntEnum
from dateutil.parser import parse
from voluptuous import Schema
from pycamunda.entity import JsonEntity, Number
## A schema validator for Camunda timestamp objects.
Timestamp = parse # pylint: disable=invalid-name
class ContentType(Enum):
"""Models HTTP content types.
"""
OctetStream = 'application/octet-stream'
Plain = 'text/plain'
class SortOrder(Enum):
"""Models sorting orders for REST queries.
"""
Ascending = 'asc'
Descending = 'desc'
class ResourceType(IntEnum):
"""Models the integer representation of Camunda resource types.
@see https://docs.camunda.org/manual/7.8/user-guide/process-engine/authorization-service/#resources
"""
Application = 0
Authorization = 4
Batch = 13
DecisionDefinition = 10
DecisionRequirementsDefinition = 14
Deployment = 9
Filter = 5
Group = 2
GroupMembership = 3
ProcessDefinition = 6
ProcessInstance = 8
Task = 7
Tenant = 11
TenantMembership = 12
User = 1
class Count(JsonEntity):
"""Models a count of Camunda objects.
Many different Camunda endpoints return simple counts; these should all return the Count type.
"""
@property
def schema(self):
return Schema({'count': Number}, required=True)
| en | 0.651149 | @ingroup endpoints @file Common schema definitions shared across multiple endpoint types. ## A schema validator for Camunda timestamp objects. # pylint: disable=invalid-name Models HTTP content types. Models sorting orders for REST queries. Models the integer representation of Camunda resource types. @see https://docs.camunda.org/manual/7.8/user-guide/process-engine/authorization-service/#resources Models a count of Camunda objects. Many different Camunda endpoints return simple counts; these should all return the Count type. | 2.333272 | 2 |
result/reporter.py | narmaku/cloud-image-val | 4 | 6617684 | <gh_stars>1-10
import os
class Reporter:
def __init__(self, junit_report_path):
self.report_path = junit_report_path
def generate_html_report(self, destination_path):
os.system(f'junit2html {self.report_path} --report-matrix {destination_path}')
print(f'HTML report generated: {destination_path}')
| import os
class Reporter:
def __init__(self, junit_report_path):
self.report_path = junit_report_path
def generate_html_report(self, destination_path):
os.system(f'junit2html {self.report_path} --report-matrix {destination_path}')
print(f'HTML report generated: {destination_path}') | none | 1 | 2.566277 | 3 | |
script/multiprocessing.py | mscheltienne/cardio-audio-sleep | 0 | 6617685 | <filename>script/multiprocessing.py
"""Test for suspending and resuming a process."""
import multiprocessing as mp
import time
import psutil
from bsl.triggers import ParallelPortTrigger
from cardio_audio_sleep.config import load_triggers
from cardio_audio_sleep.tasks import isochronous
from cardio_audio_sleep.utils import generate_sequence, search_ANT_amplifier
if __name__ == "__main__":
trigger = ParallelPortTrigger("/dev/parport0")
tdef = load_triggers()
stream_name = search_ANT_amplifier()
ecg_ch_name = "AUX7"
sequence = generate_sequence(20, 0, 10, tdef)
delay = 0.5
process = mp.Process(
target=isochronous, args=(trigger, tdef, sequence, delay)
)
process.start()
psutil_process = psutil.Process(process.pid)
time.sleep(5)
psutil_process.suspend()
time.sleep(2)
psutil_process.resume()
process.join()
| <filename>script/multiprocessing.py
"""Test for suspending and resuming a process."""
import multiprocessing as mp
import time
import psutil
from bsl.triggers import ParallelPortTrigger
from cardio_audio_sleep.config import load_triggers
from cardio_audio_sleep.tasks import isochronous
from cardio_audio_sleep.utils import generate_sequence, search_ANT_amplifier
if __name__ == "__main__":
trigger = ParallelPortTrigger("/dev/parport0")
tdef = load_triggers()
stream_name = search_ANT_amplifier()
ecg_ch_name = "AUX7"
sequence = generate_sequence(20, 0, 10, tdef)
delay = 0.5
process = mp.Process(
target=isochronous, args=(trigger, tdef, sequence, delay)
)
process.start()
psutil_process = psutil.Process(process.pid)
time.sleep(5)
psutil_process.suspend()
time.sleep(2)
psutil_process.resume()
process.join()
| en | 0.889324 | Test for suspending and resuming a process. | 2.611326 | 3 |
topk/rs.py | xwang233/code-snippe | 0 | 6617686 | import torch
print([int(1e4), int(5e4), int(1e5), int(5e5), int(1e6), int(5e6), int(1e7)] \
+ torch.randint(int(1e5), int(5e6), (7, )).tolist()) | import torch
print([int(1e4), int(5e4), int(1e5), int(5e5), int(1e6), int(5e6), int(1e7)] \
+ torch.randint(int(1e5), int(5e6), (7, )).tolist()) | none | 1 | 2.397795 | 2 | |
__init__.py | mn1del/rpigpio | 0 | 6617687 | #!/usr/bin/env python3
"""
Classes handling GPIO interactions using RPi.GPIO library
"""
from rpigpio.hx711 import HX711
from rpigpio.lcd1602 import LCD1602
from rpigpio.rotaryencoder import RotaryEncoder
from rpigpio.fourdigitdisplay import Display4s7s
from rpigpio.toggle import Toggle
from rpigpio.button import Button
from rpigpio.stepper import Stepper
| #!/usr/bin/env python3
"""
Classes handling GPIO interactions using RPi.GPIO library
"""
from rpigpio.hx711 import HX711
from rpigpio.lcd1602 import LCD1602
from rpigpio.rotaryencoder import RotaryEncoder
from rpigpio.fourdigitdisplay import Display4s7s
from rpigpio.toggle import Toggle
from rpigpio.button import Button
from rpigpio.stepper import Stepper
| en | 0.390723 | #!/usr/bin/env python3 Classes handling GPIO interactions using RPi.GPIO library | 2.138311 | 2 |
view/psToolbar.py | FiRMLAB-Pisa/pySynthMRI | 0 | 6617688 | <filename>view/psToolbar.py
from PyQt5 import QtCore
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QPixmap, QIcon, QCursor
from PyQt5.QtWidgets import QToolBar, QLabel, QPushButton, QButtonGroup, QComboBox
import resources.resources
class PsToolbar(QToolBar):
"""
ToolBar used in Visual Page.
"""
BUTTON_SIZE = QSize(24, 24)
def __init__(self, model, parent=None):
super(QToolBar, self).__init__(parent)
self.model = model
self.setContextMenuPolicy(Qt.PreventContextMenu)
self.setMovable(True)
self.setStyleSheet(
"""
QToolBar
{
background-color: #2c2633;
color: #999;
}
QToolBar::item
{
background-color: #2c2633;
color: #999;
}
QToolBar::item::selected
{
background-color: "red";
color: #fff;
}
QMenu
{
background-color: #2c2633;
color: #fff;
}
QMenu::item::selected
{
background-color: "red";
color: #999;
}
# QToolBar::separator
# {
# background-color: "white";
# }
""")
# MOUSE GROUP LABEL
self.label_mouse = QLabel(" Mouse: ")
self.label_mouse.setStyleSheet("QLabel {color : #999; }")
# WINDOW SCALE MOUSE
self.button_window_grayscale = QPushButton()
self.button_window_grayscale.setIconSize(self.BUTTON_SIZE)
self.button_window_grayscale.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.button_window_grayscale.setCheckable(True)
icon_window_grayscale = QIcon()
icon_window_grayscale.addPixmap(QPixmap(":/icons/gradient_linear_40.png"), QIcon.Normal, QIcon.On)
self.button_window_grayscale.setIcon(icon_window_grayscale)
self.button_window_grayscale.setToolTip("Use mouse to change:\n window width (\u2194)\n window center (\u2195)")
# WINDOW SCALE DEFAULT
self.button_window_grayscale_default = QPushButton()
self.button_window_grayscale_default.setIconSize(self.BUTTON_SIZE)
self.button_window_grayscale_default.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_window_grayscale = QIcon()
icon_window_grayscale.addPixmap(QPixmap(":/icons/gradient_linear_refresh.png"), QIcon.Normal, QIcon.On)
self.button_window_grayscale_default.setIcon(icon_window_grayscale)
self.button_window_grayscale_default.setToolTip("Reset window scale value")
# ZOOM MOUSE
self.button_zoom = QPushButton()
self.button_zoom.setIconSize(self.BUTTON_SIZE)
self.button_zoom.setCheckable(True)
self.button_zoom.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_zoom = QIcon()
icon_zoom.addPixmap(QPixmap(":/icons/zoom_icon.png"), QIcon.Normal, QIcon.On)
self.button_zoom.setIcon(icon_zoom)
self.button_zoom.setToolTip("Use mouse to Zoom:\n zoom in (\u2193)\n zoom out (\u2191)")
# TRANSLATE MOUSE
self.button_translate = QPushButton()
self.button_translate.setIconSize(self.BUTTON_SIZE)
self.button_translate.setCheckable(True)
self.button_translate.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_translate = QIcon()
icon_translate.addPixmap(QPixmap(":/icons/move_icon.png"), QIcon.Normal, QIcon.On)
self.button_translate.setIcon(icon_translate)
self.button_translate.setToolTip("Use mouse to translate image:\n vertival axis (\u2195)\n horizontal axis (\u2194)")
# DEFAULT ZOOM
self.button_default_zoom = QPushButton()
self.button_default_zoom.setIconSize(self.BUTTON_SIZE)
self.button_default_zoom.setCheckable(False)
self.button_default_zoom.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_default_zoom = QIcon()
icon_default_zoom.addPixmap(QPixmap(":/icons/zoom_refresh_40.png"), QIcon.Normal, QIcon.On)
self.button_default_zoom.setIcon(icon_default_zoom)
self.button_default_zoom.setToolTip("Reset zoom value")
# SLICER MOUSE
self.button_slicer = QPushButton()
self.button_slicer.setIconSize(self.BUTTON_SIZE)
self.button_slicer.setCheckable(True)
self.button_slicer.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_zoom = QIcon()
icon_zoom.addPixmap(QPixmap(":/icons/three_layers.png"), QIcon.Normal, QIcon.On)
self.button_slicer.setIcon(icon_zoom)
self.button_slicer.setToolTip("Use mouse to change slice:\n next slice (\u2193)\n previous slice (\u2191)")
# PARAMS GROUP LABEL
self.label_parameters = QLabel(" Parameters: ")
self.label_parameters.setStyleSheet("QLabel {color : #999; }")
# DEFAULT PARAMS
self.button_default_param = QPushButton()
self.button_default_param.setIconSize(self.BUTTON_SIZE)
icon_default_params = QIcon()
icon_default_params.addPixmap(QPixmap(":/icons/default_24.png"), QIcon.Normal, QIcon.On)
self.button_default_param.setIcon(icon_default_params)
self.button_default_param.setToolTip("Set scanner parameters \nto default values")
# ORIENTATION
# self.combo_orientation = QComboBox()
# self.combo_orientation.setIconSize(self.BUTTON_SIZE)
#
# self.combo_orientation.addItem(QIcon(":icons/three_layers.png"), "Axial")
#
# self.combo_orientation.addItem(QIcon(":icons/translate_icon.png"), "Sagittal")
# self.combo_orientation.addItem(QIcon(":icons/gradient_linear_refresh.png"), "Coronal")
# SYNTH IMAGES
self.synth_images_buttons = dict()
smaps = self.model.get_smap_list()
# self.smap_group_buttons = QButtonGroup(self)
self.smap_group_buttons = QButtonGroup(self, exclusive=True)
for synth_map in smaps:
smap_button = QPushButton(synth_map)
smap_button.setFixedHeight(self.BUTTON_SIZE.height())
smap_button.setIconSize(self.BUTTON_SIZE)
smap_button.setStyleSheet("QPushButton:pressed { background-color: red }"
"QPushButton:checked { background-color: red }")
smap_button.setCheckable(True)
smap_button.setToolTip("{} ({})\nModel: {}".format(synth_map,
smaps[synth_map]["title"],
smaps[synth_map]["equation_string"]))
self.synth_images_buttons[synth_map] = smap_button
self.smap_group_buttons.addButton(smap_button)
# SAVE NIFTII
self.button_save_niftii = QPushButton()
self.button_save_niftii.setIconSize(self.BUTTON_SIZE)
self.button_save_niftii.setCheckable(False)
self.button_save_niftii.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_save_niftii = QIcon()
icon_save_niftii.addPixmap(QPixmap(":/icons/save_niftii.png"), QIcon.Normal, QIcon.On)
self.button_save_niftii.setIcon(icon_save_niftii)
self.button_save_niftii.setToolTip("Save current synthetic image as Niftii file")
# SAVE DICOM
self.button_save_dicom = QPushButton()
self.button_save_dicom.setIconSize(self.BUTTON_SIZE)
self.button_save_dicom.setCheckable(False)
self.button_save_dicom.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_save_dicom = QIcon()
icon_save_dicom.addPixmap(QPixmap(":/icons/save_dicom.png"), QIcon.Normal, QIcon.On)
self.button_save_dicom.setIcon(icon_save_dicom)
self.button_save_dicom.setToolTip("Save current synthetic image as Dicom folder")
# LAYOUT
self.addWidget(self.button_save_niftii)
self.addWidget(self.button_save_dicom)
self.addSeparator()
# self.addWidget(self.label_mouse)
self.addWidget(self.button_window_grayscale)
self.addWidget(self.button_window_grayscale_default)
self.addSeparator()
self.addWidget(self.button_zoom)
self.addWidget(self.button_translate)
self.addWidget(self.button_default_zoom)
self.addSeparator()
self.addWidget(self.button_slicer)
self.addSeparator()
# self.addWidget(self.label_parameters)
self.addWidget(self.button_default_param)
# self.addSeparator()
# self.addWidget(self.combo_orientation)
self.addSeparator()
for sib in self.synth_images_buttons:
self.addWidget(self.synth_images_buttons[sib])
def activate_unique_smap_button(self, smap):
self.synth_images_buttons[smap].setChecked(True)
# for s in self.synth_images_buttons:
# self.synth_images_buttons[s].setChecked(False)
# self.synth_images_buttons[smap].setChecked(True)
def add_new_synthetic_map_button(self, smap_type):
smap = self.model.get_smap_list()[smap_type]
smap_button = QPushButton(smap_type)
smap_button.setFixedHeight(self.BUTTON_SIZE.height())
smap_button.setIconSize(self.BUTTON_SIZE)
smap_button.setStyleSheet("QPushButton:pressed { background-color: red }"
"QPushButton:checked { background-color: red }")
smap_button.setCheckable(True)
smap_button.setToolTip("{} ({})\nModel: {}".format(smap_type,
smap["title"],
smap["equation_string"]))
self.synth_images_buttons[smap_type] = smap_button
self.smap_group_buttons.addButton(smap_button)
self.addWidget(smap_button)
| <filename>view/psToolbar.py
from PyQt5 import QtCore
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QPixmap, QIcon, QCursor
from PyQt5.QtWidgets import QToolBar, QLabel, QPushButton, QButtonGroup, QComboBox
import resources.resources
class PsToolbar(QToolBar):
"""
ToolBar used in Visual Page.
"""
BUTTON_SIZE = QSize(24, 24)
def __init__(self, model, parent=None):
super(QToolBar, self).__init__(parent)
self.model = model
self.setContextMenuPolicy(Qt.PreventContextMenu)
self.setMovable(True)
self.setStyleSheet(
"""
QToolBar
{
background-color: #2c2633;
color: #999;
}
QToolBar::item
{
background-color: #2c2633;
color: #999;
}
QToolBar::item::selected
{
background-color: "red";
color: #fff;
}
QMenu
{
background-color: #2c2633;
color: #fff;
}
QMenu::item::selected
{
background-color: "red";
color: #999;
}
# QToolBar::separator
# {
# background-color: "white";
# }
""")
# MOUSE GROUP LABEL
self.label_mouse = QLabel(" Mouse: ")
self.label_mouse.setStyleSheet("QLabel {color : #999; }")
# WINDOW SCALE MOUSE
self.button_window_grayscale = QPushButton()
self.button_window_grayscale.setIconSize(self.BUTTON_SIZE)
self.button_window_grayscale.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.button_window_grayscale.setCheckable(True)
icon_window_grayscale = QIcon()
icon_window_grayscale.addPixmap(QPixmap(":/icons/gradient_linear_40.png"), QIcon.Normal, QIcon.On)
self.button_window_grayscale.setIcon(icon_window_grayscale)
self.button_window_grayscale.setToolTip("Use mouse to change:\n window width (\u2194)\n window center (\u2195)")
# WINDOW SCALE DEFAULT
self.button_window_grayscale_default = QPushButton()
self.button_window_grayscale_default.setIconSize(self.BUTTON_SIZE)
self.button_window_grayscale_default.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_window_grayscale = QIcon()
icon_window_grayscale.addPixmap(QPixmap(":/icons/gradient_linear_refresh.png"), QIcon.Normal, QIcon.On)
self.button_window_grayscale_default.setIcon(icon_window_grayscale)
self.button_window_grayscale_default.setToolTip("Reset window scale value")
# ZOOM MOUSE
self.button_zoom = QPushButton()
self.button_zoom.setIconSize(self.BUTTON_SIZE)
self.button_zoom.setCheckable(True)
self.button_zoom.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_zoom = QIcon()
icon_zoom.addPixmap(QPixmap(":/icons/zoom_icon.png"), QIcon.Normal, QIcon.On)
self.button_zoom.setIcon(icon_zoom)
self.button_zoom.setToolTip("Use mouse to Zoom:\n zoom in (\u2193)\n zoom out (\u2191)")
# TRANSLATE MOUSE
self.button_translate = QPushButton()
self.button_translate.setIconSize(self.BUTTON_SIZE)
self.button_translate.setCheckable(True)
self.button_translate.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_translate = QIcon()
icon_translate.addPixmap(QPixmap(":/icons/move_icon.png"), QIcon.Normal, QIcon.On)
self.button_translate.setIcon(icon_translate)
self.button_translate.setToolTip("Use mouse to translate image:\n vertival axis (\u2195)\n horizontal axis (\u2194)")
# DEFAULT ZOOM
self.button_default_zoom = QPushButton()
self.button_default_zoom.setIconSize(self.BUTTON_SIZE)
self.button_default_zoom.setCheckable(False)
self.button_default_zoom.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_default_zoom = QIcon()
icon_default_zoom.addPixmap(QPixmap(":/icons/zoom_refresh_40.png"), QIcon.Normal, QIcon.On)
self.button_default_zoom.setIcon(icon_default_zoom)
self.button_default_zoom.setToolTip("Reset zoom value")
# SLICER MOUSE
self.button_slicer = QPushButton()
self.button_slicer.setIconSize(self.BUTTON_SIZE)
self.button_slicer.setCheckable(True)
self.button_slicer.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_zoom = QIcon()
icon_zoom.addPixmap(QPixmap(":/icons/three_layers.png"), QIcon.Normal, QIcon.On)
self.button_slicer.setIcon(icon_zoom)
self.button_slicer.setToolTip("Use mouse to change slice:\n next slice (\u2193)\n previous slice (\u2191)")
# PARAMS GROUP LABEL
self.label_parameters = QLabel(" Parameters: ")
self.label_parameters.setStyleSheet("QLabel {color : #999; }")
# DEFAULT PARAMS
self.button_default_param = QPushButton()
self.button_default_param.setIconSize(self.BUTTON_SIZE)
icon_default_params = QIcon()
icon_default_params.addPixmap(QPixmap(":/icons/default_24.png"), QIcon.Normal, QIcon.On)
self.button_default_param.setIcon(icon_default_params)
self.button_default_param.setToolTip("Set scanner parameters \nto default values")
# ORIENTATION
# self.combo_orientation = QComboBox()
# self.combo_orientation.setIconSize(self.BUTTON_SIZE)
#
# self.combo_orientation.addItem(QIcon(":icons/three_layers.png"), "Axial")
#
# self.combo_orientation.addItem(QIcon(":icons/translate_icon.png"), "Sagittal")
# self.combo_orientation.addItem(QIcon(":icons/gradient_linear_refresh.png"), "Coronal")
# SYNTH IMAGES
self.synth_images_buttons = dict()
smaps = self.model.get_smap_list()
# self.smap_group_buttons = QButtonGroup(self)
self.smap_group_buttons = QButtonGroup(self, exclusive=True)
for synth_map in smaps:
smap_button = QPushButton(synth_map)
smap_button.setFixedHeight(self.BUTTON_SIZE.height())
smap_button.setIconSize(self.BUTTON_SIZE)
smap_button.setStyleSheet("QPushButton:pressed { background-color: red }"
"QPushButton:checked { background-color: red }")
smap_button.setCheckable(True)
smap_button.setToolTip("{} ({})\nModel: {}".format(synth_map,
smaps[synth_map]["title"],
smaps[synth_map]["equation_string"]))
self.synth_images_buttons[synth_map] = smap_button
self.smap_group_buttons.addButton(smap_button)
# SAVE NIFTII
self.button_save_niftii = QPushButton()
self.button_save_niftii.setIconSize(self.BUTTON_SIZE)
self.button_save_niftii.setCheckable(False)
self.button_save_niftii.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_save_niftii = QIcon()
icon_save_niftii.addPixmap(QPixmap(":/icons/save_niftii.png"), QIcon.Normal, QIcon.On)
self.button_save_niftii.setIcon(icon_save_niftii)
self.button_save_niftii.setToolTip("Save current synthetic image as Niftii file")
# SAVE DICOM
self.button_save_dicom = QPushButton()
self.button_save_dicom.setIconSize(self.BUTTON_SIZE)
self.button_save_dicom.setCheckable(False)
self.button_save_dicom.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
icon_save_dicom = QIcon()
icon_save_dicom.addPixmap(QPixmap(":/icons/save_dicom.png"), QIcon.Normal, QIcon.On)
self.button_save_dicom.setIcon(icon_save_dicom)
self.button_save_dicom.setToolTip("Save current synthetic image as Dicom folder")
# LAYOUT
self.addWidget(self.button_save_niftii)
self.addWidget(self.button_save_dicom)
self.addSeparator()
# self.addWidget(self.label_mouse)
self.addWidget(self.button_window_grayscale)
self.addWidget(self.button_window_grayscale_default)
self.addSeparator()
self.addWidget(self.button_zoom)
self.addWidget(self.button_translate)
self.addWidget(self.button_default_zoom)
self.addSeparator()
self.addWidget(self.button_slicer)
self.addSeparator()
# self.addWidget(self.label_parameters)
self.addWidget(self.button_default_param)
# self.addSeparator()
# self.addWidget(self.combo_orientation)
self.addSeparator()
for sib in self.synth_images_buttons:
self.addWidget(self.synth_images_buttons[sib])
def activate_unique_smap_button(self, smap):
self.synth_images_buttons[smap].setChecked(True)
# for s in self.synth_images_buttons:
# self.synth_images_buttons[s].setChecked(False)
# self.synth_images_buttons[smap].setChecked(True)
def add_new_synthetic_map_button(self, smap_type):
smap = self.model.get_smap_list()[smap_type]
smap_button = QPushButton(smap_type)
smap_button.setFixedHeight(self.BUTTON_SIZE.height())
smap_button.setIconSize(self.BUTTON_SIZE)
smap_button.setStyleSheet("QPushButton:pressed { background-color: red }"
"QPushButton:checked { background-color: red }")
smap_button.setCheckable(True)
smap_button.setToolTip("{} ({})\nModel: {}".format(smap_type,
smap["title"],
smap["equation_string"]))
self.synth_images_buttons[smap_type] = smap_button
self.smap_group_buttons.addButton(smap_button)
self.addWidget(smap_button)
| en | 0.232782 | ToolBar used in Visual Page. QToolBar { background-color: #2c2633; color: #999; } QToolBar::item { background-color: #2c2633; color: #999; } QToolBar::item::selected { background-color: "red"; color: #fff; } QMenu { background-color: #2c2633; color: #fff; } QMenu::item::selected { background-color: "red"; color: #999; } # QToolBar::separator # { # background-color: "white"; # } # MOUSE GROUP LABEL #999; }") # WINDOW SCALE MOUSE # WINDOW SCALE DEFAULT # ZOOM MOUSE # TRANSLATE MOUSE # DEFAULT ZOOM # SLICER MOUSE # PARAMS GROUP LABEL #999; }") # DEFAULT PARAMS # ORIENTATION # self.combo_orientation = QComboBox() # self.combo_orientation.setIconSize(self.BUTTON_SIZE) # # self.combo_orientation.addItem(QIcon(":icons/three_layers.png"), "Axial") # # self.combo_orientation.addItem(QIcon(":icons/translate_icon.png"), "Sagittal") # self.combo_orientation.addItem(QIcon(":icons/gradient_linear_refresh.png"), "Coronal") # SYNTH IMAGES # self.smap_group_buttons = QButtonGroup(self) # SAVE NIFTII # SAVE DICOM # LAYOUT # self.addWidget(self.label_mouse) # self.addWidget(self.label_parameters) # self.addSeparator() # self.addWidget(self.combo_orientation) # for s in self.synth_images_buttons: # self.synth_images_buttons[s].setChecked(False) # self.synth_images_buttons[smap].setChecked(True) | 2.547439 | 3 |
gainz/totalReturn.py | jwfu/gainz | 0 | 6617689 | import pandas as pd
import pandas_datareader as pdr
import datetime as dt
import requests
import json
import random
import sys
# surpress SettingWithCopyWarning warnings. I could not determine a slick vectorized way of doing the computations since it had to be done row-wise; rationale behind this is implementation is in this SO thread: https://stackoverflow.com/questions/34855859/is-there-a-way-in-pandas-to-use-previous-row-value-in-dataframe-apply-when-previ/34856727#34856727
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
def totalReturn(startDate, endDate, ticker, apiKey):
numYears = (endDate - startDate).days/365
# hit api for dataset
df = pdr.av.time_series.AVTimeSeriesReader(symbols=ticker, function='TIME_SERIES_DAILY_ADJUSTED', start=None, end=None, retry_count=3, pause=0.1, session=None, chunksize=25, api_key=apiKey).read()
df = df[['close','dividend amount']]
# df
# shorten dataset and precalculate number of shares purchased per period with dividend
dg = df[df['dividend amount'] > 0]
dg.index = pd.to_datetime(dg.index)
dg['shares purchased'] = dg['dividend amount']/ dg['close']
# dg
dgTruncated = dg[startDate:endDate]
dgTruncated['total shares'] = 1
dgTruncated['total shares'] = 1 + dgTruncated['shares purchased']
# dgTruncated.to_csv('output.csv')
for row in range(1, len(dgTruncated)):
dgTruncated.iloc[row, 3] = dgTruncated.iloc[row-1, 3] + dgTruncated.iloc[row, 2]
# dgTruncated
# determine money from stock appreciation
stockAppreciation = dgTruncated['close'].iloc[-1] - dgTruncated['close'].iloc[0]
stockAppreciation/dgTruncated['close'].iloc[0]/numYears
# determine money from sale of drip
dripSale = (dgTruncated['total shares'].iloc[-1]-1)*dgTruncated['close'].iloc[-1]
dripSale/dgTruncated['close'].iloc[0]/numYears
# determine total gainz
return (stockAppreciation + dripSale)/dgTruncated['close'].iloc[0]/numYears
| import pandas as pd
import pandas_datareader as pdr
import datetime as dt
import requests
import json
import random
import sys
# surpress SettingWithCopyWarning warnings. I could not determine a slick vectorized way of doing the computations since it had to be done row-wise; rationale behind this is implementation is in this SO thread: https://stackoverflow.com/questions/34855859/is-there-a-way-in-pandas-to-use-previous-row-value-in-dataframe-apply-when-previ/34856727#34856727
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
def totalReturn(startDate, endDate, ticker, apiKey):
numYears = (endDate - startDate).days/365
# hit api for dataset
df = pdr.av.time_series.AVTimeSeriesReader(symbols=ticker, function='TIME_SERIES_DAILY_ADJUSTED', start=None, end=None, retry_count=3, pause=0.1, session=None, chunksize=25, api_key=apiKey).read()
df = df[['close','dividend amount']]
# df
# shorten dataset and precalculate number of shares purchased per period with dividend
dg = df[df['dividend amount'] > 0]
dg.index = pd.to_datetime(dg.index)
dg['shares purchased'] = dg['dividend amount']/ dg['close']
# dg
dgTruncated = dg[startDate:endDate]
dgTruncated['total shares'] = 1
dgTruncated['total shares'] = 1 + dgTruncated['shares purchased']
# dgTruncated.to_csv('output.csv')
for row in range(1, len(dgTruncated)):
dgTruncated.iloc[row, 3] = dgTruncated.iloc[row-1, 3] + dgTruncated.iloc[row, 2]
# dgTruncated
# determine money from stock appreciation
stockAppreciation = dgTruncated['close'].iloc[-1] - dgTruncated['close'].iloc[0]
stockAppreciation/dgTruncated['close'].iloc[0]/numYears
# determine money from sale of drip
dripSale = (dgTruncated['total shares'].iloc[-1]-1)*dgTruncated['close'].iloc[-1]
dripSale/dgTruncated['close'].iloc[0]/numYears
# determine total gainz
return (stockAppreciation + dripSale)/dgTruncated['close'].iloc[0]/numYears
| en | 0.829369 | # surpress SettingWithCopyWarning warnings. I could not determine a slick vectorized way of doing the computations since it had to be done row-wise; rationale behind this is implementation is in this SO thread: https://stackoverflow.com/questions/34855859/is-there-a-way-in-pandas-to-use-previous-row-value-in-dataframe-apply-when-previ/34856727#34856727 # hit api for dataset # df # shorten dataset and precalculate number of shares purchased per period with dividend # dg # dgTruncated.to_csv('output.csv') # dgTruncated # determine money from stock appreciation # determine money from sale of drip # determine total gainz | 2.631796 | 3 |
2019-09-08-fda-optimization-dataset-1/01_generate.py | btjanaka/qca-dataset-submission | 15 | 6617690 | <gh_stars>10-100
import fragmenter
import cmiles
import json
import warnings
import logging
from openeye import oechem
from openeye import oemolprop
def save_smiles(smiles, filename):
"""Write smiles str to smi file"""
if filename.endswith('.gz'):
import gzip
with gzip.open(filename, 'w') as f:
for smi in smiles:
f.write( (smi + '\n').encode('utf-8') )
else:
with open(filename, 'w') as f:
for smi in smiles:
f.write(smi + '\n')
def read_smiles(filename):
with open(filename, 'r') as f:
smiles = f.read().split('\n')
print(smiles)
return smiles
logging.getLogger().setLevel(logging.INFO)
filterfile = oechem.oeifstream('oechem-filterfile')
filter = oemolprop.OEFilter(filterfile)
MAX_CONFS = 20
# Read SMILES
oemols = fragmenter.chemi.file_to_oemols('fda.mol2.gz')
optimization_input = []
processed_smiles = []
skipped = []
duplicates = [] # duplicate protonation/tautomeric states
omega_failures = []
cmiles_failures = []
# Write out SDF file of all conformations
ofs = oechem.oemolostream('optimization_inputs.sdf.gz')
# Drop duplicate input molecules
print('De-duplicating input molecules')
smiles_set = set()
new_oemols = list()
for oemol in oemols:
smiles = oechem.OEMolToSmiles(oemol)
if oemol not in smiles_set:
new_oemols.append(oemol)
smiles_set.add(smiles)
else:
duplicates.append(smiles)
print(f'Retained {len(new_oemols)} unique molecules out of {len(oemols)}')
oemols = new_oemols
for index, input_oemol in enumerate(oemols):
# Apply filter criteria
if not filter(input_oemol):
skipped.append(smiles)
continue
smiles = oechem.OEMolToSmiles(input_oemol)
print(f'input molecule {index} / {len(oemols)} : {smiles}')
# Generate SMILES to use for CMILES
try:
smiles = cmiles.utils.mol_to_smiles(input_oemol, isomeric=True, mapped=False, explicit_hydrogen=True)
except Exception as e:
cmiles_failures.append(smiles)
print(e)
continue
# Generate mapped CMILES for molecules with all explicit hydrogens
try:
cmiles_ids = cmiles.get_molecule_ids(smiles)
except Exception as e:
cmiles_failures.append(smiles)
continue
# Generate molecule using mapped SMILES
mapped_smiles = cmiles_ids['canonical_isomeric_explicit_hydrogen_mapped_smiles']
oemol = cmiles.utils.load_molecule(mapped_smiles)
# Generate conformers
try:
# Omega fails for some molecules.
conformers = fragmenter.chemi.generate_conformers(oemol, max_confs=MAX_CONFS)
except RuntimeError:
logging.info('Omega failed to generate conformers for {}'.format(cmiles_ids['canonical_isomeric_smiles']))
# Omega failed
omega_failures.append(cmiles_ids['canonical_isomeric_smiles'])
continue
print(f' {conformers.NumConfs()} confomers generated')
# Convert to QCSchema
qcschema_molecules = [cmiles.utils.mol_to_map_ordered_qcschema(conf, mapped_smiles) for conf in conformers.GetConfs()]
# Append to QCSchema-based optimization input
optimization_input.append({'initial_molecules': qcschema_molecules,
'cmiles_identifiers': cmiles_ids})
# Write to SDF
oechem.OEWriteMolecule(ofs, conformers)
processed_smiles.append(mapped_smiles)
import gzip
with gzip.open('optimization_inputs.json.gz', 'w') as f:
f.write(json.dumps(optimization_input, indent=2, sort_keys=True).encode('utf-8'))
ofs.close()
save_smiles(processed_smiles, 'optimization_inputs.smi.gz')
save_smiles(duplicates, 'duplicates.smi.gz')
save_smiles(omega_failures, 'omega_failures.smi.gz')
save_smiles(cmiles_failures, 'cmiles_failures.smi.gz')
save_smiles(skipped, 'skipped.smi.gz')
| import fragmenter
import cmiles
import json
import warnings
import logging
from openeye import oechem
from openeye import oemolprop
def save_smiles(smiles, filename):
"""Write smiles str to smi file"""
if filename.endswith('.gz'):
import gzip
with gzip.open(filename, 'w') as f:
for smi in smiles:
f.write( (smi + '\n').encode('utf-8') )
else:
with open(filename, 'w') as f:
for smi in smiles:
f.write(smi + '\n')
def read_smiles(filename):
with open(filename, 'r') as f:
smiles = f.read().split('\n')
print(smiles)
return smiles
logging.getLogger().setLevel(logging.INFO)
filterfile = oechem.oeifstream('oechem-filterfile')
filter = oemolprop.OEFilter(filterfile)
MAX_CONFS = 20
# Read SMILES
oemols = fragmenter.chemi.file_to_oemols('fda.mol2.gz')
optimization_input = []
processed_smiles = []
skipped = []
duplicates = [] # duplicate protonation/tautomeric states
omega_failures = []
cmiles_failures = []
# Write out SDF file of all conformations
ofs = oechem.oemolostream('optimization_inputs.sdf.gz')
# Drop duplicate input molecules
print('De-duplicating input molecules')
smiles_set = set()
new_oemols = list()
for oemol in oemols:
smiles = oechem.OEMolToSmiles(oemol)
if oemol not in smiles_set:
new_oemols.append(oemol)
smiles_set.add(smiles)
else:
duplicates.append(smiles)
print(f'Retained {len(new_oemols)} unique molecules out of {len(oemols)}')
oemols = new_oemols
for index, input_oemol in enumerate(oemols):
# Apply filter criteria
if not filter(input_oemol):
skipped.append(smiles)
continue
smiles = oechem.OEMolToSmiles(input_oemol)
print(f'input molecule {index} / {len(oemols)} : {smiles}')
# Generate SMILES to use for CMILES
try:
smiles = cmiles.utils.mol_to_smiles(input_oemol, isomeric=True, mapped=False, explicit_hydrogen=True)
except Exception as e:
cmiles_failures.append(smiles)
print(e)
continue
# Generate mapped CMILES for molecules with all explicit hydrogens
try:
cmiles_ids = cmiles.get_molecule_ids(smiles)
except Exception as e:
cmiles_failures.append(smiles)
continue
# Generate molecule using mapped SMILES
mapped_smiles = cmiles_ids['canonical_isomeric_explicit_hydrogen_mapped_smiles']
oemol = cmiles.utils.load_molecule(mapped_smiles)
# Generate conformers
try:
# Omega fails for some molecules.
conformers = fragmenter.chemi.generate_conformers(oemol, max_confs=MAX_CONFS)
except RuntimeError:
logging.info('Omega failed to generate conformers for {}'.format(cmiles_ids['canonical_isomeric_smiles']))
# Omega failed
omega_failures.append(cmiles_ids['canonical_isomeric_smiles'])
continue
print(f' {conformers.NumConfs()} confomers generated')
# Convert to QCSchema
qcschema_molecules = [cmiles.utils.mol_to_map_ordered_qcschema(conf, mapped_smiles) for conf in conformers.GetConfs()]
# Append to QCSchema-based optimization input
optimization_input.append({'initial_molecules': qcschema_molecules,
'cmiles_identifiers': cmiles_ids})
# Write to SDF
oechem.OEWriteMolecule(ofs, conformers)
processed_smiles.append(mapped_smiles)
import gzip
with gzip.open('optimization_inputs.json.gz', 'w') as f:
f.write(json.dumps(optimization_input, indent=2, sort_keys=True).encode('utf-8'))
ofs.close()
save_smiles(processed_smiles, 'optimization_inputs.smi.gz')
save_smiles(duplicates, 'duplicates.smi.gz')
save_smiles(omega_failures, 'omega_failures.smi.gz')
save_smiles(cmiles_failures, 'cmiles_failures.smi.gz')
save_smiles(skipped, 'skipped.smi.gz') | en | 0.726958 | Write smiles str to smi file # Read SMILES # duplicate protonation/tautomeric states # Write out SDF file of all conformations # Drop duplicate input molecules # Apply filter criteria # Generate SMILES to use for CMILES # Generate mapped CMILES for molecules with all explicit hydrogens # Generate molecule using mapped SMILES # Generate conformers # Omega fails for some molecules. # Omega failed # Convert to QCSchema # Append to QCSchema-based optimization input # Write to SDF | 2.39207 | 2 |
diagnostic.py | petedodd/homebrewdx | 0 | 6617691 | <filename>diagnostic.py<gh_stars>0
# CODE EXAMPLE FOR: 'Simple inclusion of complex diagnostic algorithms
# in infectious disease models for economic evaluation'
#
# (C) <NAME>, <NAME>, <NAME> & <NAME>
# Code released under Creative Commons Attribution 4.0 International (CC BY 4.0) license
# http://creativecommons.org/licenses/by/4.0/
# You are free to use and adapt the code subject to this license
#
# This file defines a base diagnostic class and imports some libraries (2 next lines)
import numpy as np #for arrays
from copy import deepcopy as dcpy #for copying classes
class Diagnostic:
def __init__(self,sens,spec,cost,delay,ltfu): #initialize
self.sens = sens; self.spec = spec;
self.cost = cost; self.delay = delay;
self.ltfu = ltfu; # loss to follow-up
self.root = True # by default, this is a root
self.next = [0,1] # default as treatments, can be next diagnostics
self.transition = np.array([[spec,(1-spec) ],
[1-sens,sens ]])
def setnext(self,k,newdx): # next test
self.next[k] = dcpy(newdx) # add to tree, as copy
self.next[k].root = False # record that this is no longer a root
def getTables(self): # get matrices by recursion
txo = np.zeros((2,2)); cost = np.zeros((2,2)); delay = np.zeros((2,2))
if self.root:
cost += self.cost*self.transition # add on own costs if root
for k in [0,1]:
if isinstance(self.next[k],Diagnostic):
txon, costn, delayn = self.next[k].getTables()
for j in [0,1]:
nextbit = self.transition[:,k] * txon[:,j]
txo[:,j] += (1-self.ltfu) * nextbit
cost[:,j] += self.next[k].cost * (1-self.ltfu) * nextbit
delay[:,j] += self.delay * (1-self.ltfu) * nextbit
elif self.next[k] == k:
txo[:,k] += (1-self.ltfu) * self.transition[:,k]
cost[:,k] += 0
delay[:,k] += self.delay * (1-self.ltfu) * self.transition[:,k]
return txo, cost, delay
| <filename>diagnostic.py<gh_stars>0
# CODE EXAMPLE FOR: 'Simple inclusion of complex diagnostic algorithms
# in infectious disease models for economic evaluation'
#
# (C) <NAME>, <NAME>, <NAME> & <NAME>
# Code released under Creative Commons Attribution 4.0 International (CC BY 4.0) license
# http://creativecommons.org/licenses/by/4.0/
# You are free to use and adapt the code subject to this license
#
# This file defines a base diagnostic class and imports some libraries (2 next lines)
import numpy as np #for arrays
from copy import deepcopy as dcpy #for copying classes
class Diagnostic:
def __init__(self,sens,spec,cost,delay,ltfu): #initialize
self.sens = sens; self.spec = spec;
self.cost = cost; self.delay = delay;
self.ltfu = ltfu; # loss to follow-up
self.root = True # by default, this is a root
self.next = [0,1] # default as treatments, can be next diagnostics
self.transition = np.array([[spec,(1-spec) ],
[1-sens,sens ]])
def setnext(self,k,newdx): # next test
self.next[k] = dcpy(newdx) # add to tree, as copy
self.next[k].root = False # record that this is no longer a root
def getTables(self): # get matrices by recursion
txo = np.zeros((2,2)); cost = np.zeros((2,2)); delay = np.zeros((2,2))
if self.root:
cost += self.cost*self.transition # add on own costs if root
for k in [0,1]:
if isinstance(self.next[k],Diagnostic):
txon, costn, delayn = self.next[k].getTables()
for j in [0,1]:
nextbit = self.transition[:,k] * txon[:,j]
txo[:,j] += (1-self.ltfu) * nextbit
cost[:,j] += self.next[k].cost * (1-self.ltfu) * nextbit
delay[:,j] += self.delay * (1-self.ltfu) * nextbit
elif self.next[k] == k:
txo[:,k] += (1-self.ltfu) * self.transition[:,k]
cost[:,k] += 0
delay[:,k] += self.delay * (1-self.ltfu) * self.transition[:,k]
return txo, cost, delay
| en | 0.81082 | # CODE EXAMPLE FOR: 'Simple inclusion of complex diagnostic algorithms # in infectious disease models for economic evaluation' # # (C) <NAME>, <NAME>, <NAME> & <NAME> # Code released under Creative Commons Attribution 4.0 International (CC BY 4.0) license # http://creativecommons.org/licenses/by/4.0/ # You are free to use and adapt the code subject to this license # # This file defines a base diagnostic class and imports some libraries (2 next lines) #for arrays #for copying classes #initialize # loss to follow-up # by default, this is a root # default as treatments, can be next diagnostics # next test # add to tree, as copy # record that this is no longer a root # get matrices by recursion # add on own costs if root | 2.36622 | 2 |
tailorpad/admin/doctype/sales_form/sales_form.py | LaganJ/Tailoring | 2 | 6617692 | <reponame>LaganJ/Tailoring
# -*- coding: utf-8 -*-
# Copyright (c) 2018, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cint
from erpnext.selling.doctype.sales_order.sales_order import make_delivery_note, make_sales_invoice
from frappe.model.document import Document
class SalesForm(Document):
def update_photo(self):
self.validate_customer()
images = {}
for field in ['attach_front_side', 'attach_back_side', 'side_view']:
if self.get(field):
images.setdefault(field, self.get(field))
if images:
doc = frappe.get_doc('Customer', self.customer)
doc.update(images)
doc.save(ignore_permissions=True)
frappe.msgprint("Photo uploaded successfully")
def update_measurement(self):
self.validate_customer()
update_measurement_data(self)
def update_style(self):
self.validate_customer()
update_style_data(self)
def validate_customer(self):
if not self.customer:
frappe.throw(_("Select customer"))
def submit_sales_order(self):
so = frappe.new_doc('Sales Order')
for d in ['customer', 'transaction_date', 'currency', 'selling_price_list',
'apply_discount_on', 'additional_discount_percentage', 'discount_amount', 'mode_of_payment',
'advance_amount', 'taxes_and_charges']:
so.set(d, self.get(d))
so.advance_payment_amount = self.advance_amount
so.set('items', self.items)
so.set('taxes', self.taxes)
if self.mode_of_payment == 'Stripe':
so.on_submit_make_payment_request = 1
so.save()
so.submit()
self.sales_order_link = so.name
self.sales_order = '<a target="_blank" href="#Form/Sales Order/{0}">{0}</a>'.format(so.name)
frappe.msgprint("Sales order {0} created successfully".format(so.name))
for d in frappe.get_all("Work Order",
fields = ["*"], filters= {'sales_order': so.name}):
self.append('sales_work_order', {
'work_order': d.name,
'item_code': d.item_code,
'item_name': d.item_name,
'fabric_code': d.fabric_code,
'fabric_name': d.fabric_name,
'tailoring_supplier': d.tailoring_supplier,
'fabric_supplier_name': d.fabric_supplier
})
def submit_sales_invoice(self):
if frappe.db.get_value('Work Order', filters = {'sales_order': self.sales_order_link, 'docstatus': 0}):
frappe.throw("Submit the work order against the sales order {0} first".format(self.sales_order_link))
si = make_sales_invoice(self.sales_order_link)
si.insert()
si.submit()
self.sales_invoice = '<a target="_blank" href="#Form/Sales Invoice/{0}">{0}</a>'.format(si.name)
frappe.msgprint("Sales invoice {0} created successfully".format(si.name))
def update_measurement_data(doc):
customer_doc = frappe.get_doc('Customer', doc.customer)
if doc.type_of_measurement == "New" and doc.new_measurement_template:
for v in doc.measurement_fields_1:
mfs = customer_doc.append("customer_measurement_data", {})
mfs.measurement_template = doc.new_measurement_template
mfs.measurement_field = v.measurement_field
mfs.note = v.note
mfs.measurement_value = v.measurement_value
mfs.image = v.image
mfs.image_html = v.image_html
doc.measurement_template = doc.new_measurement_template
doc.new_measurement_template = ''
elif doc.type_of_measurement == "Update" and doc.measurement_template:
m_fields = {}
updated_mt = []
for f in doc.measurement_fields_1:
m_fields[f.measurement_field] = [f.measurement_value, f.image_html, f.note, f.image]
for h in customer_doc.customer_measurement_data:
if h.measurement_template == doc.measurement_template and h.measurement_field in m_fields:
h.measurement_value = m_fields[h.measurement_field][0]
h.image_html = m_fields[h.measurement_field][1]
h.note = m_fields[h.measurement_field][2]
updated_mt.append(h.name)
del m_fields[h.measurement_field]
if m_fields:
for key, val in m_fields.items():
mfs = customer_doc.append("customer_measurement_data", {})
mfs.measurement_template = doc.measurement_template
mfs.measurement_field = key
mfs.note = val[2]
mfs.measurement_value = val[0]
mfs.image = val[3]
mfs.image_html = val[1]
if len(updated_mt) > 0:
frappe.db.sql(""" delete from `tabCustomer Measurement Data`
where parent = '%s' and measurement_template = '%s' and name not in (%s)
"""%(customer_doc.name, doc.measurement_template, ','.join(['%s'] * len(updated_mt))), tuple(updated_mt))
customer_doc.flags.ignore_mandatory = True
customer_doc.save()
frappe.msgprint("Measurement updated sucessfully")
def update_style_data(doc):
customer_doc = frappe.get_doc('Customer', doc.customer)
if doc.type_of_style == "New" and doc.new_style_template:
for v in doc.styles:
mfs = customer_doc.append("customer_style_data", {})
mfs.style_template = doc.new_style_template
mfs.style_field = v.style_field
mfs.note = v.note
mfs.style_value = v.style_name
mfs.image = v.image
mfs.image_html = v.html_image
doc.style_template = doc.new_style_template
doc.new_style_template = ''
elif doc.type_of_style == "Update" and doc.style_template:
m_fields = {}
updated_mt = []
for v in doc.styles:
m_fields[v.style_field] = [v.style_name, v.html_image, v.note, v.style_field, v.image, v.cost_to_customer]
for h in customer_doc.customer_style_data:
if h.style_template == doc.style_template and h.style_field in m_fields:
frappe.errprint([m_fields[h.style_field][2], m_fields[h.style_field][5]])
h.style_value = m_fields[h.style_field][0]
h.image_html = m_fields[h.style_field][1]
h.image = m_fields[h.style_field][4]
h.note = m_fields[h.style_field][2]
h.cost_to_customer = m_fields[h.style_field][5]
updated_mt.append(h.name)
del m_fields[h.style_field]
if m_fields:
for key, val in m_fields.items():
mfs = customer_doc.append("customer_style_data", {})
mfs.style_template = doc.style_template
mfs.style_field = key
mfs.note = val[2]
mfs.style_value = val[0]
mfs.image = val[4]
mfs.image_html = val[1]
mfs.flags.ignore_mandatory = True
mfs.save()
if len(updated_mt) > 0:
frappe.db.sql(""" delete from `tabCustomer Style Data`
where parent = '%s' and style_template = '%s' and name not in (%s)
"""%(customer_doc.name, doc.style_template, ','.join(['%s'] * len(updated_mt))), tuple(updated_mt))
customer_doc.flags.ignore_mandatory = True
customer_doc.save()
frappe.msgprint("Style updated sucessfully")
def get_rm_items(doctype, txt, searchfield, start, page_len, filters):
if not filters:
return []
filters = frappe._dict(filters)
doc = frappe.get_doc('Item', filters.item_code)
if doc.allowed_raw_materials:
item_codes = doc.allowed_raw_materials.split('\n')
return frappe.get_all('Item', fields = ["name", "item_name"],
filters={'name': ('in', item_codes)}, as_list=1)
else:
return frappe.db.sql(""" select name, item_name from `tabItem` where item_group = 'Raw Material'
and (name like %(txt)s or item_name like %(txt)s) and disabled = 0""", {'txt': '%%%s%%' % (txt)}, as_list=1)
@frappe.whitelist()
def get_item_details(item_code):
return frappe.db.get_value('Item', item_code, ['default_supplier', 'default_warehouse'])
@frappe.whitelist()
def get_delivery_days():
return cint(frappe.db.get_single_value("Selling Settings", "delivery_days")) or 0 | # -*- coding: utf-8 -*-
# Copyright (c) 2018, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cint
from erpnext.selling.doctype.sales_order.sales_order import make_delivery_note, make_sales_invoice
from frappe.model.document import Document
class SalesForm(Document):
def update_photo(self):
self.validate_customer()
images = {}
for field in ['attach_front_side', 'attach_back_side', 'side_view']:
if self.get(field):
images.setdefault(field, self.get(field))
if images:
doc = frappe.get_doc('Customer', self.customer)
doc.update(images)
doc.save(ignore_permissions=True)
frappe.msgprint("Photo uploaded successfully")
def update_measurement(self):
self.validate_customer()
update_measurement_data(self)
def update_style(self):
self.validate_customer()
update_style_data(self)
def validate_customer(self):
if not self.customer:
frappe.throw(_("Select customer"))
def submit_sales_order(self):
so = frappe.new_doc('Sales Order')
for d in ['customer', 'transaction_date', 'currency', 'selling_price_list',
'apply_discount_on', 'additional_discount_percentage', 'discount_amount', 'mode_of_payment',
'advance_amount', 'taxes_and_charges']:
so.set(d, self.get(d))
so.advance_payment_amount = self.advance_amount
so.set('items', self.items)
so.set('taxes', self.taxes)
if self.mode_of_payment == 'Stripe':
so.on_submit_make_payment_request = 1
so.save()
so.submit()
self.sales_order_link = so.name
self.sales_order = '<a target="_blank" href="#Form/Sales Order/{0}">{0}</a>'.format(so.name)
frappe.msgprint("Sales order {0} created successfully".format(so.name))
for d in frappe.get_all("Work Order",
fields = ["*"], filters= {'sales_order': so.name}):
self.append('sales_work_order', {
'work_order': d.name,
'item_code': d.item_code,
'item_name': d.item_name,
'fabric_code': d.fabric_code,
'fabric_name': d.fabric_name,
'tailoring_supplier': d.tailoring_supplier,
'fabric_supplier_name': d.fabric_supplier
})
def submit_sales_invoice(self):
if frappe.db.get_value('Work Order', filters = {'sales_order': self.sales_order_link, 'docstatus': 0}):
frappe.throw("Submit the work order against the sales order {0} first".format(self.sales_order_link))
si = make_sales_invoice(self.sales_order_link)
si.insert()
si.submit()
self.sales_invoice = '<a target="_blank" href="#Form/Sales Invoice/{0}">{0}</a>'.format(si.name)
frappe.msgprint("Sales invoice {0} created successfully".format(si.name))
def update_measurement_data(doc):
customer_doc = frappe.get_doc('Customer', doc.customer)
if doc.type_of_measurement == "New" and doc.new_measurement_template:
for v in doc.measurement_fields_1:
mfs = customer_doc.append("customer_measurement_data", {})
mfs.measurement_template = doc.new_measurement_template
mfs.measurement_field = v.measurement_field
mfs.note = v.note
mfs.measurement_value = v.measurement_value
mfs.image = v.image
mfs.image_html = v.image_html
doc.measurement_template = doc.new_measurement_template
doc.new_measurement_template = ''
elif doc.type_of_measurement == "Update" and doc.measurement_template:
m_fields = {}
updated_mt = []
for f in doc.measurement_fields_1:
m_fields[f.measurement_field] = [f.measurement_value, f.image_html, f.note, f.image]
for h in customer_doc.customer_measurement_data:
if h.measurement_template == doc.measurement_template and h.measurement_field in m_fields:
h.measurement_value = m_fields[h.measurement_field][0]
h.image_html = m_fields[h.measurement_field][1]
h.note = m_fields[h.measurement_field][2]
updated_mt.append(h.name)
del m_fields[h.measurement_field]
if m_fields:
for key, val in m_fields.items():
mfs = customer_doc.append("customer_measurement_data", {})
mfs.measurement_template = doc.measurement_template
mfs.measurement_field = key
mfs.note = val[2]
mfs.measurement_value = val[0]
mfs.image = val[3]
mfs.image_html = val[1]
if len(updated_mt) > 0:
frappe.db.sql(""" delete from `tabCustomer Measurement Data`
where parent = '%s' and measurement_template = '%s' and name not in (%s)
"""%(customer_doc.name, doc.measurement_template, ','.join(['%s'] * len(updated_mt))), tuple(updated_mt))
customer_doc.flags.ignore_mandatory = True
customer_doc.save()
frappe.msgprint("Measurement updated sucessfully")
def update_style_data(doc):
customer_doc = frappe.get_doc('Customer', doc.customer)
if doc.type_of_style == "New" and doc.new_style_template:
for v in doc.styles:
mfs = customer_doc.append("customer_style_data", {})
mfs.style_template = doc.new_style_template
mfs.style_field = v.style_field
mfs.note = v.note
mfs.style_value = v.style_name
mfs.image = v.image
mfs.image_html = v.html_image
doc.style_template = doc.new_style_template
doc.new_style_template = ''
elif doc.type_of_style == "Update" and doc.style_template:
m_fields = {}
updated_mt = []
for v in doc.styles:
m_fields[v.style_field] = [v.style_name, v.html_image, v.note, v.style_field, v.image, v.cost_to_customer]
for h in customer_doc.customer_style_data:
if h.style_template == doc.style_template and h.style_field in m_fields:
frappe.errprint([m_fields[h.style_field][2], m_fields[h.style_field][5]])
h.style_value = m_fields[h.style_field][0]
h.image_html = m_fields[h.style_field][1]
h.image = m_fields[h.style_field][4]
h.note = m_fields[h.style_field][2]
h.cost_to_customer = m_fields[h.style_field][5]
updated_mt.append(h.name)
del m_fields[h.style_field]
if m_fields:
for key, val in m_fields.items():
mfs = customer_doc.append("customer_style_data", {})
mfs.style_template = doc.style_template
mfs.style_field = key
mfs.note = val[2]
mfs.style_value = val[0]
mfs.image = val[4]
mfs.image_html = val[1]
mfs.flags.ignore_mandatory = True
mfs.save()
if len(updated_mt) > 0:
frappe.db.sql(""" delete from `tabCustomer Style Data`
where parent = '%s' and style_template = '%s' and name not in (%s)
"""%(customer_doc.name, doc.style_template, ','.join(['%s'] * len(updated_mt))), tuple(updated_mt))
customer_doc.flags.ignore_mandatory = True
customer_doc.save()
frappe.msgprint("Style updated sucessfully")
def get_rm_items(doctype, txt, searchfield, start, page_len, filters):
if not filters:
return []
filters = frappe._dict(filters)
doc = frappe.get_doc('Item', filters.item_code)
if doc.allowed_raw_materials:
item_codes = doc.allowed_raw_materials.split('\n')
return frappe.get_all('Item', fields = ["name", "item_name"],
filters={'name': ('in', item_codes)}, as_list=1)
else:
return frappe.db.sql(""" select name, item_name from `tabItem` where item_group = 'Raw Material'
and (name like %(txt)s or item_name like %(txt)s) and disabled = 0""", {'txt': '%%%s%%' % (txt)}, as_list=1)
@frappe.whitelist()
def get_item_details(item_code):
return frappe.db.get_value('Item', item_code, ['default_supplier', 'default_warehouse'])
@frappe.whitelist()
def get_delivery_days():
return cint(frappe.db.get_single_value("Selling Settings", "delivery_days")) or 0 | en | 0.780279 | # -*- coding: utf-8 -*- # Copyright (c) 2018, <NAME> and contributors # For license information, please see license.txt delete from `tabCustomer Measurement Data` where parent = '%s' and measurement_template = '%s' and name not in (%s) delete from `tabCustomer Style Data` where parent = '%s' and style_template = '%s' and name not in (%s) select name, item_name from `tabItem` where item_group = 'Raw Material' and (name like %(txt)s or item_name like %(txt)s) and disabled = 0 | 1.758896 | 2 |
sqlalchemy_utils/i18n.py | jd/sqlalchemy-utils | 0 | 6617693 | from .exceptions import ImproperlyConfigured
try:
from babel.dates import get_day_names
except ImportError:
def get_day_names():
raise ImproperlyConfigured(
'Could not load get_day_names function from babel. Either install '
' babel or make a similar function and override it in this '
'module.'
)
try:
from flask.ext.babel import get_locale
except ImportError:
def get_locale():
raise ImproperlyConfigured(
'Could not load get_locale function from Flask-Babel. Either '
'install babel or make a similar function and override it '
'in this module.'
)
| from .exceptions import ImproperlyConfigured
try:
from babel.dates import get_day_names
except ImportError:
def get_day_names():
raise ImproperlyConfigured(
'Could not load get_day_names function from babel. Either install '
' babel or make a similar function and override it in this '
'module.'
)
try:
from flask.ext.babel import get_locale
except ImportError:
def get_locale():
raise ImproperlyConfigured(
'Could not load get_locale function from Flask-Babel. Either '
'install babel or make a similar function and override it '
'in this module.'
)
| none | 1 | 2.32455 | 2 | |
build.py | DuniaAch/mesconseilscovid | 0 | 6617694 | <filename>build.py
#!/usr/bin/env python3
import fnmatch
import os
from pathlib import Path
from time import perf_counter
import mistune
from jinja2 import Environment as JinjaEnv
from jinja2 import FileSystemLoader, StrictUndefined
from minicli import cli, run, wrap
HERE = Path(__file__).parent
SRC_DIR = HERE / "src"
CONTENUS_DIR = HERE / "contenus"
jinja_env = JinjaEnv(loader=FileSystemLoader(str(SRC_DIR)), undefined=StrictUndefined)
markdown = mistune.create_markdown(escape=False)
@cli
def all():
index()
readmes()
def each_folder_from(source_dir, exclude=None):
"""Walk across the `source_dir` and return the folder paths."""
for direntry in os.scandir(source_dir):
if direntry.is_dir():
if exclude is not None and direntry.name in exclude:
continue
yield direntry
def each_file_from(source_dir, file_name="*", exclude=None):
"""Walk across the `source_dir` and return the md file paths."""
for filename in fnmatch.filter(sorted(os.listdir(source_dir)), file_name):
if exclude is not None and filename in exclude:
continue
yield os.path.join(source_dir, filename), filename
def build_responses(source_dir):
"""Extract and convert markdown from a `source_dir` directory into a dict."""
responses = {}
for folder in each_folder_from(source_dir):
for file_path, filename in each_file_from(folder, file_name="*.md"):
html_content = markdown.read(file_path)
# Remove empty comments set to hack markdown rendering
# when we do not want paragraphs.
html_content = html_content.replace("<!---->", "")
responses[filename[: -len(".md")]] = html_content
return responses
@cli
def index():
"""Build the index with contents from markdown dedicated folder."""
responses = build_responses(CONTENUS_DIR)
render_template("template.html", SRC_DIR / "index.html", **responses)
def me_or_them(value):
separator = "<hr />"
if separator in value:
me, them = (part.strip() for part in value.split(separator))
value = f'<span class="me visible">{me}</span><span class="them" hidden>{them}</span>'
return value
def render_template(src, output, **context):
jinja_env.filters["me_or_them"] = me_or_them
template = jinja_env.get_template(src)
content = template.render(**context,)
output.open("w").write(content)
@cli
def readmes():
"""Build the readmes with all content from markdown files in it."""
for folder in each_folder_from(CONTENUS_DIR):
folder_content = f"""
# {folder.name.title()}
*Ce fichier est généré automatiquement pour pouvoir accéder rapidement aux contenus,\
il ne doit pas être édité !*
"""
for file_path, filename in each_file_from(folder):
if filename in ("README.md", ".DS_Store"):
continue
file_content = open(file_path).read()
folder_content += f"""
## [{filename}]({filename})
{file_content}
"""
(Path(folder.path) / "README.md").open("w").write(folder_content)
@wrap
def perf_wrapper():
start = perf_counter()
yield
elapsed = perf_counter() - start
print(f"Done in {elapsed:.5f} seconds.")
if __name__ == "__main__":
run()
| <filename>build.py
#!/usr/bin/env python3
import fnmatch
import os
from pathlib import Path
from time import perf_counter
import mistune
from jinja2 import Environment as JinjaEnv
from jinja2 import FileSystemLoader, StrictUndefined
from minicli import cli, run, wrap
HERE = Path(__file__).parent
SRC_DIR = HERE / "src"
CONTENUS_DIR = HERE / "contenus"
jinja_env = JinjaEnv(loader=FileSystemLoader(str(SRC_DIR)), undefined=StrictUndefined)
markdown = mistune.create_markdown(escape=False)
@cli
def all():
index()
readmes()
def each_folder_from(source_dir, exclude=None):
"""Walk across the `source_dir` and return the folder paths."""
for direntry in os.scandir(source_dir):
if direntry.is_dir():
if exclude is not None and direntry.name in exclude:
continue
yield direntry
def each_file_from(source_dir, file_name="*", exclude=None):
"""Walk across the `source_dir` and return the md file paths."""
for filename in fnmatch.filter(sorted(os.listdir(source_dir)), file_name):
if exclude is not None and filename in exclude:
continue
yield os.path.join(source_dir, filename), filename
def build_responses(source_dir):
"""Extract and convert markdown from a `source_dir` directory into a dict."""
responses = {}
for folder in each_folder_from(source_dir):
for file_path, filename in each_file_from(folder, file_name="*.md"):
html_content = markdown.read(file_path)
# Remove empty comments set to hack markdown rendering
# when we do not want paragraphs.
html_content = html_content.replace("<!---->", "")
responses[filename[: -len(".md")]] = html_content
return responses
@cli
def index():
"""Build the index with contents from markdown dedicated folder."""
responses = build_responses(CONTENUS_DIR)
render_template("template.html", SRC_DIR / "index.html", **responses)
def me_or_them(value):
separator = "<hr />"
if separator in value:
me, them = (part.strip() for part in value.split(separator))
value = f'<span class="me visible">{me}</span><span class="them" hidden>{them}</span>'
return value
def render_template(src, output, **context):
jinja_env.filters["me_or_them"] = me_or_them
template = jinja_env.get_template(src)
content = template.render(**context,)
output.open("w").write(content)
@cli
def readmes():
"""Build the readmes with all content from markdown files in it."""
for folder in each_folder_from(CONTENUS_DIR):
folder_content = f"""
# {folder.name.title()}
*Ce fichier est généré automatiquement pour pouvoir accéder rapidement aux contenus,\
il ne doit pas être édité !*
"""
for file_path, filename in each_file_from(folder):
if filename in ("README.md", ".DS_Store"):
continue
file_content = open(file_path).read()
folder_content += f"""
## [{filename}]({filename})
{file_content}
"""
(Path(folder.path) / "README.md").open("w").write(folder_content)
@wrap
def perf_wrapper():
start = perf_counter()
yield
elapsed = perf_counter() - start
print(f"Done in {elapsed:.5f} seconds.")
if __name__ == "__main__":
run()
| en | 0.366999 | #!/usr/bin/env python3 Walk across the `source_dir` and return the folder paths. Walk across the `source_dir` and return the md file paths. Extract and convert markdown from a `source_dir` directory into a dict. # Remove empty comments set to hack markdown rendering # when we do not want paragraphs. Build the index with contents from markdown dedicated folder. Build the readmes with all content from markdown files in it. # {folder.name.title()} *Ce fichier est généré automatiquement pour pouvoir accéder rapidement aux contenus,\ il ne doit pas être édité !* ## [{filename}]({filename}) {file_content} | 2.493408 | 2 |
sdk/python/pulumi_alicloud/vpc/route_table.py | pulumi/pulumi-alicloud | 42 | 6617695 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['RouteTableArgs', 'RouteTable']
@pulumi.input_type
class RouteTableArgs:
def __init__(__self__, *,
vpc_id: pulumi.Input[str],
description: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
route_table_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, Any]]] = None):
"""
The set of arguments for constructing a RouteTable resource.
:param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed.
:param pulumi.Input[str] description: The description of the route table instance.
:param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
:param pulumi.Input[str] route_table_name: The name of the route table.
:param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource.
"""
pulumi.set(__self__, "vpc_id", vpc_id)
if description is not None:
pulumi.set(__self__, "description", description)
if name is not None:
warnings.warn("""Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""", DeprecationWarning)
pulumi.log.warn("""name is deprecated: Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""")
if name is not None:
pulumi.set(__self__, "name", name)
if route_table_name is not None:
pulumi.set(__self__, "route_table_name", route_table_name)
if tags is not None:
pulumi.set(__self__, "tags", tags)
@property
@pulumi.getter(name="vpcId")
def vpc_id(self) -> pulumi.Input[str]:
"""
The vpc_id of the route table, the field can't be changed.
"""
return pulumi.get(self, "vpc_id")
@vpc_id.setter
def vpc_id(self, value: pulumi.Input[str]):
pulumi.set(self, "vpc_id", value)
@property
@pulumi.getter
def description(self) -> Optional[pulumi.Input[str]]:
"""
The description of the route table instance.
"""
return pulumi.get(self, "description")
@description.setter
def description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "description", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="routeTableName")
def route_table_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the route table.
"""
return pulumi.get(self, "route_table_name")
@route_table_name.setter
def route_table_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "route_table_name", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
A mapping of tags to assign to the resource.
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "tags", value)
@pulumi.input_type
class _RouteTableState:
def __init__(__self__, *,
description: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
route_table_name: Optional[pulumi.Input[str]] = None,
status: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, Any]]] = None,
vpc_id: Optional[pulumi.Input[str]] = None):
"""
Input properties used for looking up and filtering RouteTable resources.
:param pulumi.Input[str] description: The description of the route table instance.
:param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
:param pulumi.Input[str] route_table_name: The name of the route table.
:param pulumi.Input[str] status: (Available in v1.119.1+) The status of the route table.
:param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource.
:param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed.
"""
if description is not None:
pulumi.set(__self__, "description", description)
if name is not None:
warnings.warn("""Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""", DeprecationWarning)
pulumi.log.warn("""name is deprecated: Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""")
if name is not None:
pulumi.set(__self__, "name", name)
if route_table_name is not None:
pulumi.set(__self__, "route_table_name", route_table_name)
if status is not None:
pulumi.set(__self__, "status", status)
if tags is not None:
pulumi.set(__self__, "tags", tags)
if vpc_id is not None:
pulumi.set(__self__, "vpc_id", vpc_id)
@property
@pulumi.getter
def description(self) -> Optional[pulumi.Input[str]]:
"""
The description of the route table instance.
"""
return pulumi.get(self, "description")
@description.setter
def description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "description", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="routeTableName")
def route_table_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the route table.
"""
return pulumi.get(self, "route_table_name")
@route_table_name.setter
def route_table_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "route_table_name", value)
@property
@pulumi.getter
def status(self) -> Optional[pulumi.Input[str]]:
"""
(Available in v1.119.1+) The status of the route table.
"""
return pulumi.get(self, "status")
@status.setter
def status(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "status", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
A mapping of tags to assign to the resource.
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "tags", value)
@property
@pulumi.getter(name="vpcId")
def vpc_id(self) -> Optional[pulumi.Input[str]]:
"""
The vpc_id of the route table, the field can't be changed.
"""
return pulumi.get(self, "vpc_id")
@vpc_id.setter
def vpc_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "vpc_id", value)
class RouteTable(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
description: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
route_table_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, Any]]] = None,
vpc_id: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
## Import
The route table can be imported using the id, e.g.
```sh
$ pulumi import alicloud:vpc/routeTable:RouteTable foo vtb-abc123456
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] description: The description of the route table instance.
:param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
:param pulumi.Input[str] route_table_name: The name of the route table.
:param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource.
:param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: RouteTableArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
## Import
The route table can be imported using the id, e.g.
```sh
$ pulumi import alicloud:vpc/routeTable:RouteTable foo vtb-abc123456
```
:param str resource_name: The name of the resource.
:param RouteTableArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(RouteTableArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
description: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
route_table_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, Any]]] = None,
vpc_id: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = RouteTableArgs.__new__(RouteTableArgs)
__props__.__dict__["description"] = description
if name is not None and not opts.urn:
warnings.warn("""Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""", DeprecationWarning)
pulumi.log.warn("""name is deprecated: Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""")
__props__.__dict__["name"] = name
__props__.__dict__["route_table_name"] = route_table_name
__props__.__dict__["tags"] = tags
if vpc_id is None and not opts.urn:
raise TypeError("Missing required property 'vpc_id'")
__props__.__dict__["vpc_id"] = vpc_id
__props__.__dict__["status"] = None
super(RouteTable, __self__).__init__(
'alicloud:vpc/routeTable:RouteTable',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
description: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
route_table_name: Optional[pulumi.Input[str]] = None,
status: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, Any]]] = None,
vpc_id: Optional[pulumi.Input[str]] = None) -> 'RouteTable':
"""
Get an existing RouteTable resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] description: The description of the route table instance.
:param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
:param pulumi.Input[str] route_table_name: The name of the route table.
:param pulumi.Input[str] status: (Available in v1.119.1+) The status of the route table.
:param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource.
:param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _RouteTableState.__new__(_RouteTableState)
__props__.__dict__["description"] = description
__props__.__dict__["name"] = name
__props__.__dict__["route_table_name"] = route_table_name
__props__.__dict__["status"] = status
__props__.__dict__["tags"] = tags
__props__.__dict__["vpc_id"] = vpc_id
return RouteTable(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def description(self) -> pulumi.Output[Optional[str]]:
"""
The description of the route table instance.
"""
return pulumi.get(self, "description")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="routeTableName")
def route_table_name(self) -> pulumi.Output[str]:
"""
The name of the route table.
"""
return pulumi.get(self, "route_table_name")
@property
@pulumi.getter
def status(self) -> pulumi.Output[str]:
"""
(Available in v1.119.1+) The status of the route table.
"""
return pulumi.get(self, "status")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, Any]]]:
"""
A mapping of tags to assign to the resource.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter(name="vpcId")
def vpc_id(self) -> pulumi.Output[str]:
"""
The vpc_id of the route table, the field can't be changed.
"""
return pulumi.get(self, "vpc_id")
| # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['RouteTableArgs', 'RouteTable']
@pulumi.input_type
class RouteTableArgs:
def __init__(__self__, *,
vpc_id: pulumi.Input[str],
description: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
route_table_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, Any]]] = None):
"""
The set of arguments for constructing a RouteTable resource.
:param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed.
:param pulumi.Input[str] description: The description of the route table instance.
:param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
:param pulumi.Input[str] route_table_name: The name of the route table.
:param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource.
"""
pulumi.set(__self__, "vpc_id", vpc_id)
if description is not None:
pulumi.set(__self__, "description", description)
if name is not None:
warnings.warn("""Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""", DeprecationWarning)
pulumi.log.warn("""name is deprecated: Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""")
if name is not None:
pulumi.set(__self__, "name", name)
if route_table_name is not None:
pulumi.set(__self__, "route_table_name", route_table_name)
if tags is not None:
pulumi.set(__self__, "tags", tags)
@property
@pulumi.getter(name="vpcId")
def vpc_id(self) -> pulumi.Input[str]:
"""
The vpc_id of the route table, the field can't be changed.
"""
return pulumi.get(self, "vpc_id")
@vpc_id.setter
def vpc_id(self, value: pulumi.Input[str]):
pulumi.set(self, "vpc_id", value)
@property
@pulumi.getter
def description(self) -> Optional[pulumi.Input[str]]:
"""
The description of the route table instance.
"""
return pulumi.get(self, "description")
@description.setter
def description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "description", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="routeTableName")
def route_table_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the route table.
"""
return pulumi.get(self, "route_table_name")
@route_table_name.setter
def route_table_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "route_table_name", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
A mapping of tags to assign to the resource.
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "tags", value)
@pulumi.input_type
class _RouteTableState:
def __init__(__self__, *,
description: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
route_table_name: Optional[pulumi.Input[str]] = None,
status: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, Any]]] = None,
vpc_id: Optional[pulumi.Input[str]] = None):
"""
Input properties used for looking up and filtering RouteTable resources.
:param pulumi.Input[str] description: The description of the route table instance.
:param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
:param pulumi.Input[str] route_table_name: The name of the route table.
:param pulumi.Input[str] status: (Available in v1.119.1+) The status of the route table.
:param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource.
:param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed.
"""
if description is not None:
pulumi.set(__self__, "description", description)
if name is not None:
warnings.warn("""Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""", DeprecationWarning)
pulumi.log.warn("""name is deprecated: Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""")
if name is not None:
pulumi.set(__self__, "name", name)
if route_table_name is not None:
pulumi.set(__self__, "route_table_name", route_table_name)
if status is not None:
pulumi.set(__self__, "status", status)
if tags is not None:
pulumi.set(__self__, "tags", tags)
if vpc_id is not None:
pulumi.set(__self__, "vpc_id", vpc_id)
@property
@pulumi.getter
def description(self) -> Optional[pulumi.Input[str]]:
"""
The description of the route table instance.
"""
return pulumi.get(self, "description")
@description.setter
def description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "description", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="routeTableName")
def route_table_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the route table.
"""
return pulumi.get(self, "route_table_name")
@route_table_name.setter
def route_table_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "route_table_name", value)
@property
@pulumi.getter
def status(self) -> Optional[pulumi.Input[str]]:
"""
(Available in v1.119.1+) The status of the route table.
"""
return pulumi.get(self, "status")
@status.setter
def status(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "status", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
A mapping of tags to assign to the resource.
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "tags", value)
@property
@pulumi.getter(name="vpcId")
def vpc_id(self) -> Optional[pulumi.Input[str]]:
"""
The vpc_id of the route table, the field can't be changed.
"""
return pulumi.get(self, "vpc_id")
@vpc_id.setter
def vpc_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "vpc_id", value)
class RouteTable(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
description: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
route_table_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, Any]]] = None,
vpc_id: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
## Import
The route table can be imported using the id, e.g.
```sh
$ pulumi import alicloud:vpc/routeTable:RouteTable foo vtb-abc123456
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] description: The description of the route table instance.
:param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
:param pulumi.Input[str] route_table_name: The name of the route table.
:param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource.
:param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: RouteTableArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
## Import
The route table can be imported using the id, e.g.
```sh
$ pulumi import alicloud:vpc/routeTable:RouteTable foo vtb-abc123456
```
:param str resource_name: The name of the resource.
:param RouteTableArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(RouteTableArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
description: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
route_table_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, Any]]] = None,
vpc_id: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = RouteTableArgs.__new__(RouteTableArgs)
__props__.__dict__["description"] = description
if name is not None and not opts.urn:
warnings.warn("""Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""", DeprecationWarning)
pulumi.log.warn("""name is deprecated: Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.""")
__props__.__dict__["name"] = name
__props__.__dict__["route_table_name"] = route_table_name
__props__.__dict__["tags"] = tags
if vpc_id is None and not opts.urn:
raise TypeError("Missing required property 'vpc_id'")
__props__.__dict__["vpc_id"] = vpc_id
__props__.__dict__["status"] = None
super(RouteTable, __self__).__init__(
'alicloud:vpc/routeTable:RouteTable',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
description: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
route_table_name: Optional[pulumi.Input[str]] = None,
status: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, Any]]] = None,
vpc_id: Optional[pulumi.Input[str]] = None) -> 'RouteTable':
"""
Get an existing RouteTable resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] description: The description of the route table instance.
:param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
:param pulumi.Input[str] route_table_name: The name of the route table.
:param pulumi.Input[str] status: (Available in v1.119.1+) The status of the route table.
:param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource.
:param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _RouteTableState.__new__(_RouteTableState)
__props__.__dict__["description"] = description
__props__.__dict__["name"] = name
__props__.__dict__["route_table_name"] = route_table_name
__props__.__dict__["status"] = status
__props__.__dict__["tags"] = tags
__props__.__dict__["vpc_id"] = vpc_id
return RouteTable(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def description(self) -> pulumi.Output[Optional[str]]:
"""
The description of the route table instance.
"""
return pulumi.get(self, "description")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="routeTableName")
def route_table_name(self) -> pulumi.Output[str]:
"""
The name of the route table.
"""
return pulumi.get(self, "route_table_name")
@property
@pulumi.getter
def status(self) -> pulumi.Output[str]:
"""
(Available in v1.119.1+) The status of the route table.
"""
return pulumi.get(self, "status")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, Any]]]:
"""
A mapping of tags to assign to the resource.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter(name="vpcId")
def vpc_id(self) -> pulumi.Output[str]:
"""
The vpc_id of the route table, the field can't be changed.
"""
return pulumi.get(self, "vpc_id")
| en | 0.733292 | # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** The set of arguments for constructing a RouteTable resource. :param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed. :param pulumi.Input[str] description: The description of the route table instance. :param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead. :param pulumi.Input[str] route_table_name: The name of the route table. :param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource. Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead. name is deprecated: Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead. The vpc_id of the route table, the field can't be changed. The description of the route table instance. Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead. The name of the route table. A mapping of tags to assign to the resource. Input properties used for looking up and filtering RouteTable resources. :param pulumi.Input[str] description: The description of the route table instance. :param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead. :param pulumi.Input[str] route_table_name: The name of the route table. :param pulumi.Input[str] status: (Available in v1.119.1+) The status of the route table. :param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource. :param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed. Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead. name is deprecated: Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead. The description of the route table instance. Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead. The name of the route table. (Available in v1.119.1+) The status of the route table. A mapping of tags to assign to the resource. The vpc_id of the route table, the field can't be changed. ## Import The route table can be imported using the id, e.g. ```sh $ pulumi import alicloud:vpc/routeTable:RouteTable foo vtb-abc123456 ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] description: The description of the route table instance. :param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead. :param pulumi.Input[str] route_table_name: The name of the route table. :param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource. :param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed. ## Import The route table can be imported using the id, e.g. ```sh $ pulumi import alicloud:vpc/routeTable:RouteTable foo vtb-abc123456 ``` :param str resource_name: The name of the resource. :param RouteTableArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead. name is deprecated: Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead. Get an existing RouteTable resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] description: The description of the route table instance. :param pulumi.Input[str] name: Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead. :param pulumi.Input[str] route_table_name: The name of the route table. :param pulumi.Input[str] status: (Available in v1.119.1+) The status of the route table. :param pulumi.Input[Mapping[str, Any]] tags: A mapping of tags to assign to the resource. :param pulumi.Input[str] vpc_id: The vpc_id of the route table, the field can't be changed. The description of the route table instance. Field `name` has been deprecated from provider version 1.119.1. New field `route_table_name` instead. The name of the route table. (Available in v1.119.1+) The status of the route table. A mapping of tags to assign to the resource. The vpc_id of the route table, the field can't be changed. | 1.759937 | 2 |
hacker-rank/implementation/flatland_space_stations.py | denisrmp/hacker-rank | 0 | 6617696 | # https://www.hackerrank.com/challenges/flatland-space-stations
def flatland_space_stations(n, c):
d1 = c[0]
d2 = 0 if len(c) < 2 else max(a - b for a, b in zip(c[1:], c[:-1])) // 2
d3 = n - c[-1] - 1
return max(d1, d2, d3)
n, _ = [int(i) for i in input().split()]
c = sorted(int(i) for i in input().split())
print(flatland_space_stations(n, c))
| # https://www.hackerrank.com/challenges/flatland-space-stations
def flatland_space_stations(n, c):
d1 = c[0]
d2 = 0 if len(c) < 2 else max(a - b for a, b in zip(c[1:], c[:-1])) // 2
d3 = n - c[-1] - 1
return max(d1, d2, d3)
n, _ = [int(i) for i in input().split()]
c = sorted(int(i) for i in input().split())
print(flatland_space_stations(n, c))
| en | 0.577438 | # https://www.hackerrank.com/challenges/flatland-space-stations | 3.513031 | 4 |
Encapsulation - Exercise/WildCatZoo/caretaker.py | DiyanKalaydzhiev23/OOP---Python | 0 | 6617697 | <gh_stars>0
from WildCatZoo.worker import Worker
class Caretaker(Worker):
pass
| from WildCatZoo.worker import Worker
class Caretaker(Worker):
pass | none | 1 | 1.138926 | 1 | |
Caesar_Shift.py | abhatia25/Cryptography | 0 | 6617698 | <reponame>abhatia25/Cryptography
plaintext = 'one small step for man' # text to encrypt
ciphertext = '' # encrypted text
key = 14 # key number
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # letters of alphabet
plaintext = plaintext.upper() # this will make your message all caps
for i in plaintext:
if i in LETTERS:
cleanedtext += i
plaintext = cleanedtext
for letter in plaintext: # for loop
newposition = LETTERS.find(letter) + key # find new position of letter
newposition = newposition % 26 # ensure new position is between 0 and 25
newletter = LETTERS[newposition] # find letter that corresponds to the new position
ciphertext = ciphertext + newletter # add new letter to ciphertext
print(ciphertext) # display encrypted text
| plaintext = 'one small step for man' # text to encrypt
ciphertext = '' # encrypted text
key = 14 # key number
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # letters of alphabet
plaintext = plaintext.upper() # this will make your message all caps
for i in plaintext:
if i in LETTERS:
cleanedtext += i
plaintext = cleanedtext
for letter in plaintext: # for loop
newposition = LETTERS.find(letter) + key # find new position of letter
newposition = newposition % 26 # ensure new position is between 0 and 25
newletter = LETTERS[newposition] # find letter that corresponds to the new position
ciphertext = ciphertext + newletter # add new letter to ciphertext
print(ciphertext) # display encrypted text | en | 0.765884 | # text to encrypt # encrypted text # key number # letters of alphabet # this will make your message all caps # for loop # find new position of letter # ensure new position is between 0 and 25 # find letter that corresponds to the new position # add new letter to ciphertext # display encrypted text | 4.223115 | 4 |
2016/Day 08 - Python/screeningTheRotations.py | AndreasDL/AdventOfCode | 0 | 6617699 | <gh_stars>0
OFF = "."
ON = "#"
class field:
width, height = None, None
field = None
def __init__(self, width, height):
self.width = width
self.height = height
self.field = [[OFF for i in range(self.width)] for j in range(self.height)]
def print(self):
for line in self.field:
for char in line:
print(char,end="")
print()
print()
def rect(self,x,y):
for j in range(y):
for i in range(x):
self.field[j][i] = ON
def rotateColumn(self,x,b):
oldCol = [self.field[j][x] for j in range(self.height)]
for j in range(self.height):
self.field[(j+b)%self.height][x] = oldCol[j]
def rotateRow(self,y,b):
oldRow = self.field[y][:]
for i in range(self.width):
self.field[y][(i+b)%self.width] = oldRow[i]
def countON(self):
count = 0
for j in range(self.height):
for i in range(self.width):
if self.field[j][i] == ON:
count += 1
return count
def testInput():
f = field(7,3)
f.rect(3,2)
f.print()
f.rotateColumn(1,1)
f.print()
f.rotateRow(0,4)
f.print()
f.rotateColumn(1,1)
f.print()
def realInput():
f = field(width=50, height=6)
with open("realInput.txt") as file:
lines = file.readlines()
for line in lines:
instructions = line.split(" ")
if instructions[0] == "rect":
args = instructions[1].split("x")
f.rect(int(args[0]), int(args[1]))
elif instructions[0] == "rotate":
index = int(instructions[2].split("=")[1])
by = int(instructions[4])
if instructions[1] == "row":
f.rotateRow(index,by)
elif instructions[1] == "column":
f.rotateColumn(index,by)
else:
print(instructions[0], " not found !", line)
f.print()
print(f.countON())
realInput() | OFF = "."
ON = "#"
class field:
width, height = None, None
field = None
def __init__(self, width, height):
self.width = width
self.height = height
self.field = [[OFF for i in range(self.width)] for j in range(self.height)]
def print(self):
for line in self.field:
for char in line:
print(char,end="")
print()
print()
def rect(self,x,y):
for j in range(y):
for i in range(x):
self.field[j][i] = ON
def rotateColumn(self,x,b):
oldCol = [self.field[j][x] for j in range(self.height)]
for j in range(self.height):
self.field[(j+b)%self.height][x] = oldCol[j]
def rotateRow(self,y,b):
oldRow = self.field[y][:]
for i in range(self.width):
self.field[y][(i+b)%self.width] = oldRow[i]
def countON(self):
count = 0
for j in range(self.height):
for i in range(self.width):
if self.field[j][i] == ON:
count += 1
return count
def testInput():
f = field(7,3)
f.rect(3,2)
f.print()
f.rotateColumn(1,1)
f.print()
f.rotateRow(0,4)
f.print()
f.rotateColumn(1,1)
f.print()
def realInput():
f = field(width=50, height=6)
with open("realInput.txt") as file:
lines = file.readlines()
for line in lines:
instructions = line.split(" ")
if instructions[0] == "rect":
args = instructions[1].split("x")
f.rect(int(args[0]), int(args[1]))
elif instructions[0] == "rotate":
index = int(instructions[2].split("=")[1])
by = int(instructions[4])
if instructions[1] == "row":
f.rotateRow(index,by)
elif instructions[1] == "column":
f.rotateColumn(index,by)
else:
print(instructions[0], " not found !", line)
f.print()
print(f.countON())
realInput() | none | 1 | 3.343426 | 3 | |
dime.py | sartorius-research/dime.pytorch | 2 | 6617700 | <reponame>sartorius-research/dime.pytorch
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from typing import Union, Tuple
import torch
import numpy as np
__version__ = '1.0.1'
class NotFitted(Exception):
""" Exception indicating that DIME hyperplane-approximation is not fitted. """
class NotCalibrated(Exception):
""" Exception indicating that DIME percentiles are not calibrated. """
class DIME:
""" Distance to Modelled Embedding (DIME)
This is a scikit-learn-esque PyTorch-implementation of DIME as described by Sjögren & Trygg and
is used to enable ANNs detect out-of distribution observations.
Parameters
----------
explained_variance_threshold : float, int (default 0.99)
Either a float between 0 and 1, which indicate the ratio of explained
variance threshold used to determine the rank of the hyperplane approximation,
or an int that specifies the rank directly.
n_percentiles : int (default 5000)
Number of discrete percentiles that will be used for probability lookups. A higher
number indicate more fine-grained probability estimation. A value of 100 indicate
that percentiles correspond to whole percentages.
Examples
--------
Given a 2D-tensor, fit the hyperplane.
>>> x = torch.tensor(...) # N x P torch 2D float-tensor.
>>> modelled_embedding = DIME().fit(x)
To obtain probabilities, calibrate percentiles. Preferably against
separate dataset. Chaining is fine.:
>>> x_cal = torch.tensor(...) # N_cal x P torch 2D float-tensor.
>>> modelled_embedding = DIME().fit(x).calibrate(x_cal)
Given fitted hyperplane, you can calculate distances on new observations:
>>> x_new = torch.tensor(...) # N_new x P 2D float-tensor.
>>> modelled_embedding.distance_to_hyperplane(x_new) # -> 1D float-tensor, length N_new
To obtain probabilities of that the new observations have a distance
calibration set observations are equal or less than the new distance,
you need to have calibrated the percentiles as shown above. Then you
receive the probablities by passing `return_probablities`-keyword:
>>> modelled_embedding.distance_to_hyperplane(x_new, return_probabilites=True) # -> 1D float-tensor, length N_new
You can also use the alternative formulation of distance within the hyperplane, optionally as probabilities:
>>> modelled_embedding.distance_within_hyperplane(x_new) # -> 1D float-tensor, length N_new
"""
def __init__(self, explained_variance_threshold: Union[float, int] = 0.99, n_percentiles: int = 5000):
if isinstance(explained_variance_threshold, float) and not (0 <= explained_variance_threshold <= 1):
raise ValueError('float param explained_variance_threshold should be between 0 and 1 when float')
if isinstance(explained_variance_threshold, int) and explained_variance_threshold < 1:
raise ValueError('integer param explained_variance_threshold should be positive')
if isinstance(n_percentiles, int) and n_percentiles < 1:
raise ValueError('param n_percentiles should be positive')
self.explained_variance_threshold = explained_variance_threshold
self.hyperplane_basis_vectors = None
self.explained_variance = None
self._embedded_mean = None
self._d_within_histogram = None
self._d_from_histogram = None
self._precision = None
# Specify the percentiles that will be available for probability lookups.
self._histogram_percentiles = torch.linspace(0, 100, n_percentiles)
def fit(self, x: torch.Tensor, calibrate_against_trainingset: bool = False) -> "DIME":
""" Fit hyperplane and optionally calibrate percentiles against training-set. """
scores, self.hyperplane_basis_vectors, self.explained_variance = fit_svd(x, self.explained_variance_threshold)
self._embedded_mean = torch.mean(scores, dim=0)
cov = covariance(scores - self._embedded_mean[None], assume_centered=True)
self._precision = torch.inverse(cov)
if calibrate_against_trainingset:
self.calibrate(x)
return self
def calibrate(self, x: torch.Tensor) -> "DIME":
""" Calibrate percentiles to enable probabilities. """
percentiles = self._histogram_percentiles.cpu().numpy()
rss = self.residual_sum_of_squares(x, dim=1).detach().cpu().numpy()
rss_histogram = torch.FloatTensor(np.percentile(np.sqrt(rss), percentiles))
# Add dtype-max value to end to handle new observations larger than every calibration
# set distance. If we don't do it like this, the percentile-index of said observation
# will be 0, which is interpreted like that there are NO calibration set distances
# smaller than observed. This is opposite of what we want.
self._d_from_histogram = _append_dtype_max(rss_histogram)
scores = self.transform(x) - self._embedded_mean[None]
mahal = squared_mahalanobis_distance(scores, self._precision).detach().cpu().numpy()
mahal_histogram = torch.FloatTensor(np.percentile(np.sqrt(mahal), percentiles))
self._d_within_histogram = _append_dtype_max(mahal_histogram)
return self
def transform(self, x: torch.Tensor) -> torch.Tensor:
""" Project observations on hyperplane. """
return torch.mm(x, self.hyperplane_basis_vectors)
def inverse_transform(self, scores: torch.Tensor) -> torch.Tensor:
""" Project observations projected on hyperplane back to data-space. """
return torch.mm(scores, self.hyperplane_basis_vectors.t())
def residual_sum_of_squares(self, x: torch.Tensor, dim: int = 1) -> torch.Tensor:
""" Calculate sum-of-squares residual of reconstruction based on hyperplane. """
residuals = x - self.inverse_transform(self.transform(x))
rss = (residuals ** 2).sum(dim=dim)
return rss
def distance_to_hyperplane(self, x: torch.Tensor, return_probabilities: bool = False) -> torch.Tensor:
""" Distance to hyperplane (DIME), optionally given as probabilities. """
if not self._is_fitted:
raise NotFitted('Hyperplane-approximation must be fitted using DIME.fit(x: torch.Tensor) before '
'obtaining distance to hyperplane')
dime = torch.sqrt(self.residual_sum_of_squares(x, dim=1))
if return_probabilities:
return self._calculate_probability(dime, self._d_from_histogram)
else:
return dime
def distance_within_hyperplane(self, x: torch.Tensor, return_probabilities: bool = False) -> torch.Tensor:
""" Distance withing hyperplane (D-within), optionally given as probabilities. """
if not self._is_fitted:
raise NotFitted('Hyperplane-approximation must be fitted using DIME.fit(x: torch.Tensor) before '
'obtaining distance within hyperplane')
scores = self.transform(x) - self._embedded_mean[None]
squared_mahal = squared_mahalanobis_distance(scores, self._precision)
mahal = torch.sqrt(squared_mahal)
if return_probabilities:
return self._calculate_probability(mahal, self._d_within_histogram)
else:
return mahal
def _calculate_probability(self, distances: torch.Tensor, distance_histogram: torch.Tensor) -> torch.Tensor:
if not self._is_calibrated:
raise NotCalibrated('Percentiles must be calibrated using DIME.calibrate(x: torch.Tensor) before '
'obtaining probability estimates.')
n_bins = len(distance_histogram)
repeated_distances = distances.repeat(n_bins, 1)
histogram_thresholded_distances = (repeated_distances < distance_histogram[:, None])
cdf_indices = histogram_thresholded_distances.int().argmax(0)
# Observerations with distance larger than every calibration distance will get an out-of-range
# index, so we set the indexes of those observations to last available. This will cause the an
# estimated probability of observing an observation with smaller distance than observed to be
# equal to 1.0, which is exactly what we want anyway.
cdf_indices[cdf_indices == len(self._histogram_percentiles)] = -1
probabilities = self._histogram_percentiles[cdf_indices] / 100
return probabilities
@property
def _is_calibrated(self):
is_calibrated = (self._d_within_histogram is not None) and (self._d_from_histogram is not None)
return is_calibrated
@property
def _is_fitted(self):
is_fitted = self.hyperplane_basis_vectors is not None
return is_fitted
def covariance(x: torch.Tensor, assume_centered: bool = False) -> torch.Tensor:
""" Calculate empirical covariance matrix.. """
n_samples, n_features = x.shape
if not assume_centered:
x = x - torch.mean(x, 0).view(-1, n_features)
cov = (1 / (n_samples - 1)) * torch.mm(x.t(), x)
return cov
def squared_mahalanobis_distance(x: torch.Tensor, precision: torch.Tensor) -> torch.Tensor:
mahal = (torch.mm(x, precision) * x).sum(dim=1)
return mahal
def fit_svd(x: torch.Tensor, n_components: Union[int, float]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
""" Fit hyperplane using singular value decomposition.
Parameters
----------
x : tensor
2D N x C tensor of observations.
n_components : float, int
Either a float between 0 and 1, which indicate the ratio of explained
variance threshold used to determine the rank of the hyperplane approximation,
or an int that specifies the rank directly.
"""
u, s, v = torch.svd(x)
explained_variance = (s.data ** 2) / (len(x) - 1)
r2 = explained_variance / explained_variance.sum()
if isinstance(n_components, float):
cumulative_r2 = torch.cumsum(r2, 0)
if n_components > r2[0]:
n_components = (cumulative_r2 < n_components).int().argmax() + 1
else:
n_components = 1
v = v[:, :n_components]
scores = (u * s)[:, :n_components]
return scores, v, r2[:n_components]
def _append_dtype_max(tensor: torch.Tensor):
assert tensor.ndim == 1, 'input must be 1D'
max_value = torch.finfo(tensor.dtype).max
new_tensor = torch.cat((tensor, torch.tensor([max_value])))
return new_tensor | # Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from typing import Union, Tuple
import torch
import numpy as np
__version__ = '1.0.1'
class NotFitted(Exception):
""" Exception indicating that DIME hyperplane-approximation is not fitted. """
class NotCalibrated(Exception):
""" Exception indicating that DIME percentiles are not calibrated. """
class DIME:
""" Distance to Modelled Embedding (DIME)
This is a scikit-learn-esque PyTorch-implementation of DIME as described by Sjögren & Trygg and
is used to enable ANNs detect out-of distribution observations.
Parameters
----------
explained_variance_threshold : float, int (default 0.99)
Either a float between 0 and 1, which indicate the ratio of explained
variance threshold used to determine the rank of the hyperplane approximation,
or an int that specifies the rank directly.
n_percentiles : int (default 5000)
Number of discrete percentiles that will be used for probability lookups. A higher
number indicate more fine-grained probability estimation. A value of 100 indicate
that percentiles correspond to whole percentages.
Examples
--------
Given a 2D-tensor, fit the hyperplane.
>>> x = torch.tensor(...) # N x P torch 2D float-tensor.
>>> modelled_embedding = DIME().fit(x)
To obtain probabilities, calibrate percentiles. Preferably against
separate dataset. Chaining is fine.:
>>> x_cal = torch.tensor(...) # N_cal x P torch 2D float-tensor.
>>> modelled_embedding = DIME().fit(x).calibrate(x_cal)
Given fitted hyperplane, you can calculate distances on new observations:
>>> x_new = torch.tensor(...) # N_new x P 2D float-tensor.
>>> modelled_embedding.distance_to_hyperplane(x_new) # -> 1D float-tensor, length N_new
To obtain probabilities of that the new observations have a distance
calibration set observations are equal or less than the new distance,
you need to have calibrated the percentiles as shown above. Then you
receive the probablities by passing `return_probablities`-keyword:
>>> modelled_embedding.distance_to_hyperplane(x_new, return_probabilites=True) # -> 1D float-tensor, length N_new
You can also use the alternative formulation of distance within the hyperplane, optionally as probabilities:
>>> modelled_embedding.distance_within_hyperplane(x_new) # -> 1D float-tensor, length N_new
"""
def __init__(self, explained_variance_threshold: Union[float, int] = 0.99, n_percentiles: int = 5000):
if isinstance(explained_variance_threshold, float) and not (0 <= explained_variance_threshold <= 1):
raise ValueError('float param explained_variance_threshold should be between 0 and 1 when float')
if isinstance(explained_variance_threshold, int) and explained_variance_threshold < 1:
raise ValueError('integer param explained_variance_threshold should be positive')
if isinstance(n_percentiles, int) and n_percentiles < 1:
raise ValueError('param n_percentiles should be positive')
self.explained_variance_threshold = explained_variance_threshold
self.hyperplane_basis_vectors = None
self.explained_variance = None
self._embedded_mean = None
self._d_within_histogram = None
self._d_from_histogram = None
self._precision = None
# Specify the percentiles that will be available for probability lookups.
self._histogram_percentiles = torch.linspace(0, 100, n_percentiles)
def fit(self, x: torch.Tensor, calibrate_against_trainingset: bool = False) -> "DIME":
""" Fit hyperplane and optionally calibrate percentiles against training-set. """
scores, self.hyperplane_basis_vectors, self.explained_variance = fit_svd(x, self.explained_variance_threshold)
self._embedded_mean = torch.mean(scores, dim=0)
cov = covariance(scores - self._embedded_mean[None], assume_centered=True)
self._precision = torch.inverse(cov)
if calibrate_against_trainingset:
self.calibrate(x)
return self
def calibrate(self, x: torch.Tensor) -> "DIME":
""" Calibrate percentiles to enable probabilities. """
percentiles = self._histogram_percentiles.cpu().numpy()
rss = self.residual_sum_of_squares(x, dim=1).detach().cpu().numpy()
rss_histogram = torch.FloatTensor(np.percentile(np.sqrt(rss), percentiles))
# Add dtype-max value to end to handle new observations larger than every calibration
# set distance. If we don't do it like this, the percentile-index of said observation
# will be 0, which is interpreted like that there are NO calibration set distances
# smaller than observed. This is opposite of what we want.
self._d_from_histogram = _append_dtype_max(rss_histogram)
scores = self.transform(x) - self._embedded_mean[None]
mahal = squared_mahalanobis_distance(scores, self._precision).detach().cpu().numpy()
mahal_histogram = torch.FloatTensor(np.percentile(np.sqrt(mahal), percentiles))
self._d_within_histogram = _append_dtype_max(mahal_histogram)
return self
def transform(self, x: torch.Tensor) -> torch.Tensor:
""" Project observations on hyperplane. """
return torch.mm(x, self.hyperplane_basis_vectors)
def inverse_transform(self, scores: torch.Tensor) -> torch.Tensor:
""" Project observations projected on hyperplane back to data-space. """
return torch.mm(scores, self.hyperplane_basis_vectors.t())
def residual_sum_of_squares(self, x: torch.Tensor, dim: int = 1) -> torch.Tensor:
""" Calculate sum-of-squares residual of reconstruction based on hyperplane. """
residuals = x - self.inverse_transform(self.transform(x))
rss = (residuals ** 2).sum(dim=dim)
return rss
def distance_to_hyperplane(self, x: torch.Tensor, return_probabilities: bool = False) -> torch.Tensor:
""" Distance to hyperplane (DIME), optionally given as probabilities. """
if not self._is_fitted:
raise NotFitted('Hyperplane-approximation must be fitted using DIME.fit(x: torch.Tensor) before '
'obtaining distance to hyperplane')
dime = torch.sqrt(self.residual_sum_of_squares(x, dim=1))
if return_probabilities:
return self._calculate_probability(dime, self._d_from_histogram)
else:
return dime
def distance_within_hyperplane(self, x: torch.Tensor, return_probabilities: bool = False) -> torch.Tensor:
""" Distance withing hyperplane (D-within), optionally given as probabilities. """
if not self._is_fitted:
raise NotFitted('Hyperplane-approximation must be fitted using DIME.fit(x: torch.Tensor) before '
'obtaining distance within hyperplane')
scores = self.transform(x) - self._embedded_mean[None]
squared_mahal = squared_mahalanobis_distance(scores, self._precision)
mahal = torch.sqrt(squared_mahal)
if return_probabilities:
return self._calculate_probability(mahal, self._d_within_histogram)
else:
return mahal
def _calculate_probability(self, distances: torch.Tensor, distance_histogram: torch.Tensor) -> torch.Tensor:
if not self._is_calibrated:
raise NotCalibrated('Percentiles must be calibrated using DIME.calibrate(x: torch.Tensor) before '
'obtaining probability estimates.')
n_bins = len(distance_histogram)
repeated_distances = distances.repeat(n_bins, 1)
histogram_thresholded_distances = (repeated_distances < distance_histogram[:, None])
cdf_indices = histogram_thresholded_distances.int().argmax(0)
# Observerations with distance larger than every calibration distance will get an out-of-range
# index, so we set the indexes of those observations to last available. This will cause the an
# estimated probability of observing an observation with smaller distance than observed to be
# equal to 1.0, which is exactly what we want anyway.
cdf_indices[cdf_indices == len(self._histogram_percentiles)] = -1
probabilities = self._histogram_percentiles[cdf_indices] / 100
return probabilities
@property
def _is_calibrated(self):
is_calibrated = (self._d_within_histogram is not None) and (self._d_from_histogram is not None)
return is_calibrated
@property
def _is_fitted(self):
is_fitted = self.hyperplane_basis_vectors is not None
return is_fitted
def covariance(x: torch.Tensor, assume_centered: bool = False) -> torch.Tensor:
""" Calculate empirical covariance matrix.. """
n_samples, n_features = x.shape
if not assume_centered:
x = x - torch.mean(x, 0).view(-1, n_features)
cov = (1 / (n_samples - 1)) * torch.mm(x.t(), x)
return cov
def squared_mahalanobis_distance(x: torch.Tensor, precision: torch.Tensor) -> torch.Tensor:
mahal = (torch.mm(x, precision) * x).sum(dim=1)
return mahal
def fit_svd(x: torch.Tensor, n_components: Union[int, float]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
""" Fit hyperplane using singular value decomposition.
Parameters
----------
x : tensor
2D N x C tensor of observations.
n_components : float, int
Either a float between 0 and 1, which indicate the ratio of explained
variance threshold used to determine the rank of the hyperplane approximation,
or an int that specifies the rank directly.
"""
u, s, v = torch.svd(x)
explained_variance = (s.data ** 2) / (len(x) - 1)
r2 = explained_variance / explained_variance.sum()
if isinstance(n_components, float):
cumulative_r2 = torch.cumsum(r2, 0)
if n_components > r2[0]:
n_components = (cumulative_r2 < n_components).int().argmax() + 1
else:
n_components = 1
v = v[:, :n_components]
scores = (u * s)[:, :n_components]
return scores, v, r2[:n_components]
def _append_dtype_max(tensor: torch.Tensor):
assert tensor.ndim == 1, 'input must be 1D'
max_value = torch.finfo(tensor.dtype).max
new_tensor = torch.cat((tensor, torch.tensor([max_value])))
return new_tensor | en | 0.7957 | # Copyright (c) 2021 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. Exception indicating that DIME hyperplane-approximation is not fitted. Exception indicating that DIME percentiles are not calibrated. Distance to Modelled Embedding (DIME) This is a scikit-learn-esque PyTorch-implementation of DIME as described by Sjögren & Trygg and is used to enable ANNs detect out-of distribution observations. Parameters ---------- explained_variance_threshold : float, int (default 0.99) Either a float between 0 and 1, which indicate the ratio of explained variance threshold used to determine the rank of the hyperplane approximation, or an int that specifies the rank directly. n_percentiles : int (default 5000) Number of discrete percentiles that will be used for probability lookups. A higher number indicate more fine-grained probability estimation. A value of 100 indicate that percentiles correspond to whole percentages. Examples -------- Given a 2D-tensor, fit the hyperplane. >>> x = torch.tensor(...) # N x P torch 2D float-tensor. >>> modelled_embedding = DIME().fit(x) To obtain probabilities, calibrate percentiles. Preferably against separate dataset. Chaining is fine.: >>> x_cal = torch.tensor(...) # N_cal x P torch 2D float-tensor. >>> modelled_embedding = DIME().fit(x).calibrate(x_cal) Given fitted hyperplane, you can calculate distances on new observations: >>> x_new = torch.tensor(...) # N_new x P 2D float-tensor. >>> modelled_embedding.distance_to_hyperplane(x_new) # -> 1D float-tensor, length N_new To obtain probabilities of that the new observations have a distance calibration set observations are equal or less than the new distance, you need to have calibrated the percentiles as shown above. Then you receive the probablities by passing `return_probablities`-keyword: >>> modelled_embedding.distance_to_hyperplane(x_new, return_probabilites=True) # -> 1D float-tensor, length N_new You can also use the alternative formulation of distance within the hyperplane, optionally as probabilities: >>> modelled_embedding.distance_within_hyperplane(x_new) # -> 1D float-tensor, length N_new # Specify the percentiles that will be available for probability lookups. Fit hyperplane and optionally calibrate percentiles against training-set. Calibrate percentiles to enable probabilities. # Add dtype-max value to end to handle new observations larger than every calibration # set distance. If we don't do it like this, the percentile-index of said observation # will be 0, which is interpreted like that there are NO calibration set distances # smaller than observed. This is opposite of what we want. Project observations on hyperplane. Project observations projected on hyperplane back to data-space. Calculate sum-of-squares residual of reconstruction based on hyperplane. Distance to hyperplane (DIME), optionally given as probabilities. Distance withing hyperplane (D-within), optionally given as probabilities. # Observerations with distance larger than every calibration distance will get an out-of-range # index, so we set the indexes of those observations to last available. This will cause the an # estimated probability of observing an observation with smaller distance than observed to be # equal to 1.0, which is exactly what we want anyway. Calculate empirical covariance matrix.. Fit hyperplane using singular value decomposition. Parameters ---------- x : tensor 2D N x C tensor of observations. n_components : float, int Either a float between 0 and 1, which indicate the ratio of explained variance threshold used to determine the rank of the hyperplane approximation, or an int that specifies the rank directly. | 1.915752 | 2 |
tests/test_api.py | churnik/async-feedback-bot | 0 | 6617701 | import pytest
from lunch_bot import app
VERSION_PREFIX = app.config.get("APP_VERSION", "/v0/")
@pytest.fixture()
def client():
with app.test_client() as test_client:
yield test_client
def test_ping(client):
resp = client.get(f"{VERSION_PREFIX}ping")
assert resp.status_code == 200
assert resp.data.decode() == "pong"
| import pytest
from lunch_bot import app
VERSION_PREFIX = app.config.get("APP_VERSION", "/v0/")
@pytest.fixture()
def client():
with app.test_client() as test_client:
yield test_client
def test_ping(client):
resp = client.get(f"{VERSION_PREFIX}ping")
assert resp.status_code == 200
assert resp.data.decode() == "pong"
| none | 1 | 2.111305 | 2 | |
sample/redis_smaple.py | deuxksy/bta | 0 | 6617702 | <filename>sample/redis_smaple.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
__title__ = 'py35'
__author__ = '<NAME><<EMAIL>>'
__status__ = 'develoment'
__version__ = '0.0.1'
__date__ = '2017-03-15'
__license__ = 'MIT'
__copyright__ = 'Copyright 2017 SeokYoung Kim'
import redis
from bta.settings import redis_pool_bta
key = 'www.humblebundle.com'
r = redis.Redis(connection_pool=redis_pool_bta)
data = r.hscan('bta_site:{site}'.format(site=key))
print (data) | <filename>sample/redis_smaple.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
__title__ = 'py35'
__author__ = '<NAME><<EMAIL>>'
__status__ = 'develoment'
__version__ = '0.0.1'
__date__ = '2017-03-15'
__license__ = 'MIT'
__copyright__ = 'Copyright 2017 SeokYoung Kim'
import redis
from bta.settings import redis_pool_bta
key = 'www.humblebundle.com'
r = redis.Redis(connection_pool=redis_pool_bta)
data = r.hscan('bta_site:{site}'.format(site=key))
print (data) | en | 0.352855 | #!/usr/bin/env python # -*- coding: utf-8 -*- | 2.456399 | 2 |
udidata/plot/plot_utils.py | udiy/udidata | 0 | 6617703 | <gh_stars>0
from .. import utils
#######################################################################################################################
def scatter_geo(ds, prop="pressure", stat="count"):
"""
Takes in xarray Dataset and creates a tidy and clean pandas DataFrame for plotting with plotly
Parameters
----------
ds : xarray Dataset
A dataset of aggregated data with a specified format
prop : str, default 'pressure'
Atmospheric property of interest
stat : str, default 'count'
A statistic of interest to show on the plot. Options: count, mean, median, std, min, max
Returns
-------
df : pandas DataFrame
A 'tidy' dataframe suitable for plotting data
"""
if stat.lower()=="total count":
stat = "count"
da = ds.sel(stat=stat)[prop]
da = da.sum(dim="date")
else:
da = ds.sel(stat=stat)[prop]
# transform data to pandas DataFrame so it's easier to plot with plotly. And clean dataframe
df = da.to_dataframe(name=stat)
df = df.dropna().drop(["stat"], axis=1)
df = df[df[stat]>0]
if (df[stat].max() - df[stat].min()) > 100: # if values range is bigger than 2 orders of magnitude then scale column
df = df.scale_column(col=stat)
df = df.reset_index()
return df
#######################################################################################################################
def lines(ds, prop="pressure", stat="mean"):
"""
Takes in xarray Dataset and creates a pandas DataFrame suitable for line chart, with x axis as date dimension.
Parameters
----------
ds : xarray Dataset
A dataset of aggregated data with a specified format
prop : str, default 'pressure'
Atmospheric property of interest
stat : str, default 'count'
A statistic of interest to show on the plot. Options: count, mean, median, std, min, max
Returns
-------
df : pandas DataFrame
A 'tidy' dataframe suitable for plotting data
"""
da = ds.sel(stat=stat)[prop]
df = da.to_dataframe(name=stat).drop(["stat"], axis=1)
df = df.dropna().reset_index()
df = df.zip_columns(["lat","lng"])
return df | from .. import utils
#######################################################################################################################
def scatter_geo(ds, prop="pressure", stat="count"):
"""
Takes in xarray Dataset and creates a tidy and clean pandas DataFrame for plotting with plotly
Parameters
----------
ds : xarray Dataset
A dataset of aggregated data with a specified format
prop : str, default 'pressure'
Atmospheric property of interest
stat : str, default 'count'
A statistic of interest to show on the plot. Options: count, mean, median, std, min, max
Returns
-------
df : pandas DataFrame
A 'tidy' dataframe suitable for plotting data
"""
if stat.lower()=="total count":
stat = "count"
da = ds.sel(stat=stat)[prop]
da = da.sum(dim="date")
else:
da = ds.sel(stat=stat)[prop]
# transform data to pandas DataFrame so it's easier to plot with plotly. And clean dataframe
df = da.to_dataframe(name=stat)
df = df.dropna().drop(["stat"], axis=1)
df = df[df[stat]>0]
if (df[stat].max() - df[stat].min()) > 100: # if values range is bigger than 2 orders of magnitude then scale column
df = df.scale_column(col=stat)
df = df.reset_index()
return df
#######################################################################################################################
def lines(ds, prop="pressure", stat="mean"):
"""
Takes in xarray Dataset and creates a pandas DataFrame suitable for line chart, with x axis as date dimension.
Parameters
----------
ds : xarray Dataset
A dataset of aggregated data with a specified format
prop : str, default 'pressure'
Atmospheric property of interest
stat : str, default 'count'
A statistic of interest to show on the plot. Options: count, mean, median, std, min, max
Returns
-------
df : pandas DataFrame
A 'tidy' dataframe suitable for plotting data
"""
da = ds.sel(stat=stat)[prop]
df = da.to_dataframe(name=stat).drop(["stat"], axis=1)
df = df.dropna().reset_index()
df = df.zip_columns(["lat","lng"])
return df | en | 0.342158 | ####################################################################################################################### Takes in xarray Dataset and creates a tidy and clean pandas DataFrame for plotting with plotly Parameters ---------- ds : xarray Dataset A dataset of aggregated data with a specified format prop : str, default 'pressure' Atmospheric property of interest stat : str, default 'count' A statistic of interest to show on the plot. Options: count, mean, median, std, min, max Returns ------- df : pandas DataFrame A 'tidy' dataframe suitable for plotting data # transform data to pandas DataFrame so it's easier to plot with plotly. And clean dataframe # if values range is bigger than 2 orders of magnitude then scale column ####################################################################################################################### Takes in xarray Dataset and creates a pandas DataFrame suitable for line chart, with x axis as date dimension. Parameters ---------- ds : xarray Dataset A dataset of aggregated data with a specified format prop : str, default 'pressure' Atmospheric property of interest stat : str, default 'count' A statistic of interest to show on the plot. Options: count, mean, median, std, min, max Returns ------- df : pandas DataFrame A 'tidy' dataframe suitable for plotting data | 3.622613 | 4 |
zee/zee5.py | Waga43/Zee5 | 2 | 6617704 | <filename>zee/zee5.py
import flask
import re
import requests
from headers import headers
import urls
a = flask.Flask(__name__)
@a.route('/')
def home():
return flask.render_template("c/home.html")
@a.route("/", methods=["GET", "POST"])
def post():
l = flask.request.form["q"]
if flask.request.method == "POST":
with open("_", "wb") as a1:
a1.write(bytes(l.encode()))
return flask.render_template("c/home.html") and flask.redirect("/content/play")
@a.route('/about')
def about():
return flask.render_template("x/about.html")
@a.route("/contact")
def contact():
return flask.render_template("z/contact.html")
@a.route("/favicon.ico")
def con():
return flask.render_template("v/ico.html")
@a.route("/content/play")
def api():
with open("_", 'r') as q1:
try:
w = q1.read()
req1 = requests.get(urls.token_url1).json()
rgx = re.findall("([0-9]?\w+)", w)[-3:]
req2 = requests.get(urls.platform_token).json()["token"]
headers["X-Access-Token"] = req2
req3 = requests.get(urls.token_url2).json()
htm = """
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title> {} </title>
<body>
<div align = "center">
<body style="background-color:black;">
<div id = "img" align = "center">
<img src = '{}'/>
</div>
<div id = "text" style = "color:grey">
{} ¤ {}
<p <b> Rating : {} | Duration : {} secs</b></br></br>
{} </b></p></br>
</div>
<button onclick="document.location='{}'">play</button>
</div>
</body>
</html>
"""
if "movies" in w:
r1 = requests.get(urls.search_api_endpoint + "-".join(rgx),
headers=headers,
params={"translation":"en", "country":"IN"}).json()
g1 = (r1["hls"][0].replace("drm", "hls") + req1["video_token"])
return htm.format(r1["title"], r1["image_url"], r1["title"],
r1["age_rating"], r1["rating"], r1["duration"],
r1["description"], urls.stream_baseurl + g1)
elif "tvshows" or "originals" in w:
r2 = requests.get(urls.search_api_endpoint + "-".join(rgx),
headers=headers,
params={"translation":"en", "country":"IN"}).json()
g2 = (r2["hls"][0].replace("drm", "hls"))
if "netst" in g2:
return htm.format(r2["title"], r2["image_url"], r2["title"], r2["age_rating"],
r2["rating"], r2["duration"], r2["description"],
g2 + req3["video_token"])
else:
return htm.format(r2["title"], r2["image_url"], r2["title"], r2["age_rating"],
r2["rating"], r2["duration"], r2["description"],
urls.stream_baseurl + g2 + req1["video_token"])
else:
pass
except requests.exceptions.ConnectionError:
return flask.jsonify({ "message" : "No connection" })
except KeyError:
return { "message" : "No Url Specified", "status" : "error" }, 200
if __name__ == "__main__":
a.run("127.0.0.1", 8080)
| <filename>zee/zee5.py
import flask
import re
import requests
from headers import headers
import urls
a = flask.Flask(__name__)
@a.route('/')
def home():
return flask.render_template("c/home.html")
@a.route("/", methods=["GET", "POST"])
def post():
l = flask.request.form["q"]
if flask.request.method == "POST":
with open("_", "wb") as a1:
a1.write(bytes(l.encode()))
return flask.render_template("c/home.html") and flask.redirect("/content/play")
@a.route('/about')
def about():
return flask.render_template("x/about.html")
@a.route("/contact")
def contact():
return flask.render_template("z/contact.html")
@a.route("/favicon.ico")
def con():
return flask.render_template("v/ico.html")
@a.route("/content/play")
def api():
with open("_", 'r') as q1:
try:
w = q1.read()
req1 = requests.get(urls.token_url1).json()
rgx = re.findall("([0-9]?\w+)", w)[-3:]
req2 = requests.get(urls.platform_token).json()["token"]
headers["X-Access-Token"] = req2
req3 = requests.get(urls.token_url2).json()
htm = """
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title> {} </title>
<body>
<div align = "center">
<body style="background-color:black;">
<div id = "img" align = "center">
<img src = '{}'/>
</div>
<div id = "text" style = "color:grey">
{} ¤ {}
<p <b> Rating : {} | Duration : {} secs</b></br></br>
{} </b></p></br>
</div>
<button onclick="document.location='{}'">play</button>
</div>
</body>
</html>
"""
if "movies" in w:
r1 = requests.get(urls.search_api_endpoint + "-".join(rgx),
headers=headers,
params={"translation":"en", "country":"IN"}).json()
g1 = (r1["hls"][0].replace("drm", "hls") + req1["video_token"])
return htm.format(r1["title"], r1["image_url"], r1["title"],
r1["age_rating"], r1["rating"], r1["duration"],
r1["description"], urls.stream_baseurl + g1)
elif "tvshows" or "originals" in w:
r2 = requests.get(urls.search_api_endpoint + "-".join(rgx),
headers=headers,
params={"translation":"en", "country":"IN"}).json()
g2 = (r2["hls"][0].replace("drm", "hls"))
if "netst" in g2:
return htm.format(r2["title"], r2["image_url"], r2["title"], r2["age_rating"],
r2["rating"], r2["duration"], r2["description"],
g2 + req3["video_token"])
else:
return htm.format(r2["title"], r2["image_url"], r2["title"], r2["age_rating"],
r2["rating"], r2["duration"], r2["description"],
urls.stream_baseurl + g2 + req1["video_token"])
else:
pass
except requests.exceptions.ConnectionError:
return flask.jsonify({ "message" : "No connection" })
except KeyError:
return { "message" : "No Url Specified", "status" : "error" }, 200
if __name__ == "__main__":
a.run("127.0.0.1", 8080)
| en | 0.258076 | <!DOCTYPE html> <html> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title> {} </title> <body> <div align = "center"> <body style="background-color:black;"> <div id = "img" align = "center"> <img src = '{}'/> </div> <div id = "text" style = "color:grey"> {} ¤ {} <p <b> Rating : {} | Duration : {} secs</b></br></br> {} </b></p></br> </div> <button onclick="document.location='{}'">play</button> </div> </body> </html> | 2.663929 | 3 |
app/user/serializers.py | vitsyrovat/conference | 0 | 6617705 | from django.contrib.auth import get_user_model, password_validation, \
authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name')
extra_kwargs = {
'password': {
'write_only': True,
# 'min_length': 8 # this is replaced by validate_password
}
}
# def validate_password(self, value):
# if len(value) < 5:
# raise serializers.ValidationError(
# 'Password must have at least 5 characters.')
# return value
def validate_password(self, value):
try:
password_validation.validate_password(value)
except serializers.ValidationError as exception:
raise serializers.ValidationError(exception)
return value
def create(self, validated_data):
return get_user_model().objects.create_user(**validated_data)
def update(self, instance, validated_data):
"""Update and return user setting password correctly"""
password = validated_data.pop('password', None)
user = super().update(instance, validated_data)
if password:
user.set_password(password)
user.save()
return user
class AuthTokenSerializer(serializers.Serializer):
"""Serializer for the user token authtentication"""
email = serializers.CharField(label=_("Email"))
password = serializers.CharField(
label=_("Password"),
style={'input_type': 'password'},
trim_whitespace=False
)
def validate(self, attrs):
"""Validate and authtenticate user"""
email = attrs.get('email')
password = attrs.get('password')
if email and password:
user = authenticate(
request=self.context.get('request'),
username=email,
password=password
)
if not user:
msg = _('Unable to authtenticate with provided credentials.')
raise serializers.ValidationError(msg, code='authorization')
else:
msg = _('Must include "email" and "password".')
raise serializers.ValidationError(msg, code='authorization')
attrs['user'] = user
return attrs
| from django.contrib.auth import get_user_model, password_validation, \
authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name')
extra_kwargs = {
'password': {
'write_only': True,
# 'min_length': 8 # this is replaced by validate_password
}
}
# def validate_password(self, value):
# if len(value) < 5:
# raise serializers.ValidationError(
# 'Password must have at least 5 characters.')
# return value
def validate_password(self, value):
try:
password_validation.validate_password(value)
except serializers.ValidationError as exception:
raise serializers.ValidationError(exception)
return value
def create(self, validated_data):
return get_user_model().objects.create_user(**validated_data)
def update(self, instance, validated_data):
"""Update and return user setting password correctly"""
password = validated_data.pop('password', None)
user = super().update(instance, validated_data)
if password:
user.set_password(password)
user.save()
return user
class AuthTokenSerializer(serializers.Serializer):
"""Serializer for the user token authtentication"""
email = serializers.CharField(label=_("Email"))
password = serializers.CharField(
label=_("Password"),
style={'input_type': 'password'},
trim_whitespace=False
)
def validate(self, attrs):
"""Validate and authtenticate user"""
email = attrs.get('email')
password = attrs.get('password')
if email and password:
user = authenticate(
request=self.context.get('request'),
username=email,
password=password
)
if not user:
msg = _('Unable to authtenticate with provided credentials.')
raise serializers.ValidationError(msg, code='authorization')
else:
msg = _('Must include "email" and "password".')
raise serializers.ValidationError(msg, code='authorization')
attrs['user'] = user
return attrs
| en | 0.686926 | # 'min_length': 8 # this is replaced by validate_password # def validate_password(self, value): # if len(value) < 5: # raise serializers.ValidationError( # 'Password must have at least 5 characters.') # return value Update and return user setting password correctly Serializer for the user token authtentication Validate and authtenticate user | 2.435749 | 2 |
animatedledstrip/__init__.py | AnimatedLEDStrip/client-python | 0 | 6617706 | <filename>animatedledstrip/__init__.py
from .als_http_client import ALSHttpClient
from .animation_info import AnimationInfo
from .animation_to_run_params import AnimationToRunParams
from .color_container import ColorContainer, PreparedColorContainer
from .distance import AbsoluteDistance, PercentDistance
from .equation import Equation
from .location import Location
from .rotation import DegreesRotation, RadiansRotation
from .running_animation_params import RunningAnimationParams
from .section import Section
from .strip_info import StripInfo
| <filename>animatedledstrip/__init__.py
from .als_http_client import ALSHttpClient
from .animation_info import AnimationInfo
from .animation_to_run_params import AnimationToRunParams
from .color_container import ColorContainer, PreparedColorContainer
from .distance import AbsoluteDistance, PercentDistance
from .equation import Equation
from .location import Location
from .rotation import DegreesRotation, RadiansRotation
from .running_animation_params import RunningAnimationParams
from .section import Section
from .strip_info import StripInfo
| none | 1 | 1.433947 | 1 | |
lib/textparser.py | tyler-entner/DS5001-2022-01 | 0 | 6617707 | import pandas as pd
import numpy as np
import nltk
class TextParser():
"""
A class to parse a single Gutenberg-type text files into a TOKENS dataframe with
an OHCO index. Also has methods to extract a VOCAB table, although vocabulary
tables out to be generated at the corpus level.
Sample parameter values:
ohco_pats = [
('chapter', r"^\s*(chapter|letter)\s+(\d+)", 'm')
]
clip_pats = [
r'START OF GUTENBERG PROJECT',
r'^\s*THE END'
]
"""
# TODO: Make these private
src_imported:bool = False
src_clipped:bool = False
src_col_suffix:str ='_str'
join_pat:str = r'\n'
strip_hyphens:bool = False
strip_whitespace:bool = False
verbose:bool = False
# We assume all OHCOs have sentences and tokens
# and that there are terminal in the list.
ohco_pats:[] = [
('para', r"\n\n", 'd'),
('sent', r"[.?!;:]+", 'd'),
('token', r"[\s',-]+", 'd')
]
_ohco_type:{} = {
'd': '_num',
'm': '_id'
}
def __init__(self, src_file:str, ohco_pats:[], clip_pats:[], use_nltk=True):
"""Initialize the object and extract config info. If using NLTK, download resources."""
self.src_file = src_file
self.clip_pats = clip_pats # TODO: Validate
self.ohco_pats = ohco_pats + self.ohco_pats # TODO: Validate
self.OHCO = [item[0]+self._ohco_type[item[2]] for item in self.ohco_pats]
self.ohco_names = [item[0] for item in self.ohco_pats]
self.use_nltk = use_nltk
if self.use_nltk:
# Override the last two OHCO items
self.ohco_pats[-2] = ('sent', None, 'nltk')
self.ohco_pats[-1] = ('token', None, 'nltk')
# Make sure you have the NLTK stuff
for package in [
'tokenizers/punkt',
'taggers/averaged_perceptron_tagger',
'corpora/stopwords',
'help/tagsets'
]:
if self.verbose: print("Checking", package)
try:
nltk.data.find(package)
except IndexError:
nltk.download(package)
def import_source(self, strip:bool=True, char_encoding:str="utf-8-sig"):
"""Convert a raw text file into a dataframe of lines."""
if self.verbose: print("Importing ", self.src_file)
text_lines = open(self.src_file,'r', encoding=char_encoding).readlines()
self.LINES = pd.DataFrame({'line_str':text_lines})
self.LINES.index.name = 'line_id'
if strip:
self.LINES.line_str = self.LINES.line_str.str.strip()
self.src_imported = True
if self.verbose: print("Clipping text")
self._clip_lines()
return self
def _clip_lines(self):
"""Remove cruft lines from beginning and/or end of file."""
start_pat = self.clip_pats[0]
end_pat = self.clip_pats[1]
start = self.LINES.line_str.str.contains(start_pat, regex=True)
end = self.LINES.line_str.str.contains(end_pat, regex=True)
try:
start_line_num = self.LINES.loc[start].index[0]
except IndexError:
raise ValueError("Clip start pattern not found.")
try:
end_line_num = self.LINES.loc[end].index[0]
except IndexError:
raise ValueError("Clip end pattern not found.")
self.LINES = self.LINES.loc[start_line_num + 1 : end_line_num - 2]
self.src_clipped == True
def parse_tokens(self):
"""Convert lines to tokens based on OHCO."""
if self.src_imported:
# Start with the LINES df
self.TOKENS = self.LINES.copy()
# Walk through each level of the OHCO to build out TOKENS
for i, level in enumerate(self.OHCO):
if self.verbose: print(f"Parsing OHCO level {i} {level}", end=' ')
# Define level-specific variables
parse_type = self.ohco_pats[i][2]
div_name = self.ohco_pats[i][0]
div_pat = self.ohco_pats[i][1]
if i == 0:
src_div_name = 'line'
else:
src_div_name = self.ohco_names[i - 1]
src_col = f"{src_div_name}{self.src_col_suffix}"
dst_col = f"{div_name}{self.src_col_suffix}"
# By Milestone
if parse_type == 'm':
if self.verbose: print(f"by milestone {div_pat}")
div_lines = self.TOKENS[src_col].str.contains(div_pat, regex=True, case=True) # TODO: Parametize case
self.TOKENS.loc[div_lines, div_name] = [i+1 for i in range(self.TOKENS.loc[div_lines].shape[0])]
self.TOKENS[div_name] = self.TOKENS[div_name].ffill()
self.TOKENS = self.TOKENS.loc[~self.TOKENS[div_name].isna()]
self.TOKENS = self.TOKENS.loc[~div_lines]
self.TOKENS[div_name] = self.TOKENS[div_name].astype('int')
self.TOKENS = self.TOKENS.groupby(self.ohco_names[:i+1])[src_col]\
.apply(lambda x: '\n'.join(x)).to_frame(dst_col)
# print(self.TOKENS[dst_col].str.count(r'\n\n'))
print(src_col, dst_col)
print(self.TOKENS.columns)
# By Delimitter
elif parse_type == 'd':
if self.verbose: print(f"by delimitter {div_pat}")
self.TOKENS = self.TOKENS[src_col].str.split(div_pat, expand=True).stack().to_frame(dst_col)
# By NLTK
elif parse_type == 'nltk':
if self.verbose: print(f"by NLTK model")
if level == 'sent_num':
self.TOKENS = self.TOKENS.para_str\
.apply(lambda x: pd.Series(nltk.sent_tokenize(x)))\
.stack()\
.to_frame('sent_str')
if level == 'token_num':
if self.strip_hyphens == True:
self.TOKENS.sent_str = self.TOKENS.sent_str.str.replace(r"-", ' ')
if self.strip_whitespace == True:
self.TOKENS = self.TOKENS.sent_str\
.apply(lambda x: pd.Series(nltk.pos_tag(nltk.WhitespaceTokenizer().tokenize(x))))
else:
self.TOKENS = self.TOKENS.sent_str\
.apply(lambda x: pd.Series(nltk.pos_tag(nltk.word_tokenize(x))))
self.TOKENS = self.TOKENS.stack().to_frame('pos_tuple')
self.TOKENS['pos'] = self.TOKENS.pos_tuple.apply(lambda x: x[1])
self.TOKENS['token_str'] = self.TOKENS.pos_tuple.apply(lambda x: x[0])
self.TOKENS['term_str'] = self.TOKENS.token_str.str.lower()
else:
raise ValueError(f"Invalid parse option: {parse_type}.")
# After creating the current OHCO level
self.TOKENS.index.names = self.OHCO[:i+1]
# After iterating through the OHCO
# Not sure if needed anymore
# self.TOKENS[dst_col] = self.TOKENS[dst_col].str.strip()
# self.TOKENS[dst_col] = self.TOKENS[dst_col].str.replace(self.join_pat, ' ', regex=True)
# self.TOKENS = self.TOKENS[~self.TOKENS[dst_col].str.contains(r'^\s*$', regex=True)]
if not self.use_nltk:
self.TOKENS['term_str'] = self.TOKENS.token_str.str.replace(r'[\W_]+', '', regex=True).str.lower()
else:
punc_pos = ['$', "''", '(', ')', ',', '--', '.', ':', '``']
self.TOKENS['term_str'] = self.TOKENS[~self.TOKENS.pos.isin(punc_pos)].token_str\
.str.replace(r'[\W_]+', '', regex=True).str.lower()
else:
raise RuntimeError("Source not imported. Please run .import_source()")
def extract_vocab(self):
"""This should also be done at the corpus level."""
self.VOCAB = self.TOKENS.term_str.value_counts().to_frame('n')
self.VOCAB.index.name = 'term_str'
self.VOCAB['n_chars'] = self.VOCAB.index.str.len()
self.VOCAB['p'] = self.VOCAB['n'] / self.VOCAB['n'].sum()
self.VOCAB['s'] = 1 / self.VOCAB['p']
self.VOCAB['i'] = np.log2(self.VOCAB['s']) # Same as negative log probability (i.e. log likelihood)
self.VOCAB['h'] = self.VOCAB['p'] * self.VOCAB['i']
self.H = self.VOCAB['h'].sum()
return self
def annotate_vocab(self):
"""This should be done at the corpus level."""
# Stopwords
# Max POS
# POS variability
# Porter Stems
pass
def extract_pos_data(self):
# TODO: Create dataframe for POS info, including Penn Treebank info
pass
def extract_named_entities(self):
# TODO: Create dataframe of named entities
pass
def gather_tokens(self, level=0, grouping_col='term_str', cat_sep=' '):
"""Gather tokens into strings for arbitrary OHCO level."""
max_level = len(self.OHCO) - 2 # Can't gather tokens at the token level :)
if level > max_level:
raise ValueError(f"Level {level} too high. Try between 0 and {max_level}")
else:
level_name = self.OHCO[level].split('_')[0]
idx = self.TOKENS.index.names[:level+1]
return self.TOKENS.groupby(idx)[grouping_col].apply(lambda x: x.str.cat(sep=cat_sep))\
.to_frame(f'{level_name}_str')
if __name__ == '__main__':
pass | import pandas as pd
import numpy as np
import nltk
class TextParser():
"""
A class to parse a single Gutenberg-type text files into a TOKENS dataframe with
an OHCO index. Also has methods to extract a VOCAB table, although vocabulary
tables out to be generated at the corpus level.
Sample parameter values:
ohco_pats = [
('chapter', r"^\s*(chapter|letter)\s+(\d+)", 'm')
]
clip_pats = [
r'START OF GUTENBERG PROJECT',
r'^\s*THE END'
]
"""
# TODO: Make these private
src_imported:bool = False
src_clipped:bool = False
src_col_suffix:str ='_str'
join_pat:str = r'\n'
strip_hyphens:bool = False
strip_whitespace:bool = False
verbose:bool = False
# We assume all OHCOs have sentences and tokens
# and that there are terminal in the list.
ohco_pats:[] = [
('para', r"\n\n", 'd'),
('sent', r"[.?!;:]+", 'd'),
('token', r"[\s',-]+", 'd')
]
_ohco_type:{} = {
'd': '_num',
'm': '_id'
}
def __init__(self, src_file:str, ohco_pats:[], clip_pats:[], use_nltk=True):
"""Initialize the object and extract config info. If using NLTK, download resources."""
self.src_file = src_file
self.clip_pats = clip_pats # TODO: Validate
self.ohco_pats = ohco_pats + self.ohco_pats # TODO: Validate
self.OHCO = [item[0]+self._ohco_type[item[2]] for item in self.ohco_pats]
self.ohco_names = [item[0] for item in self.ohco_pats]
self.use_nltk = use_nltk
if self.use_nltk:
# Override the last two OHCO items
self.ohco_pats[-2] = ('sent', None, 'nltk')
self.ohco_pats[-1] = ('token', None, 'nltk')
# Make sure you have the NLTK stuff
for package in [
'tokenizers/punkt',
'taggers/averaged_perceptron_tagger',
'corpora/stopwords',
'help/tagsets'
]:
if self.verbose: print("Checking", package)
try:
nltk.data.find(package)
except IndexError:
nltk.download(package)
def import_source(self, strip:bool=True, char_encoding:str="utf-8-sig"):
"""Convert a raw text file into a dataframe of lines."""
if self.verbose: print("Importing ", self.src_file)
text_lines = open(self.src_file,'r', encoding=char_encoding).readlines()
self.LINES = pd.DataFrame({'line_str':text_lines})
self.LINES.index.name = 'line_id'
if strip:
self.LINES.line_str = self.LINES.line_str.str.strip()
self.src_imported = True
if self.verbose: print("Clipping text")
self._clip_lines()
return self
def _clip_lines(self):
"""Remove cruft lines from beginning and/or end of file."""
start_pat = self.clip_pats[0]
end_pat = self.clip_pats[1]
start = self.LINES.line_str.str.contains(start_pat, regex=True)
end = self.LINES.line_str.str.contains(end_pat, regex=True)
try:
start_line_num = self.LINES.loc[start].index[0]
except IndexError:
raise ValueError("Clip start pattern not found.")
try:
end_line_num = self.LINES.loc[end].index[0]
except IndexError:
raise ValueError("Clip end pattern not found.")
self.LINES = self.LINES.loc[start_line_num + 1 : end_line_num - 2]
self.src_clipped == True
def parse_tokens(self):
"""Convert lines to tokens based on OHCO."""
if self.src_imported:
# Start with the LINES df
self.TOKENS = self.LINES.copy()
# Walk through each level of the OHCO to build out TOKENS
for i, level in enumerate(self.OHCO):
if self.verbose: print(f"Parsing OHCO level {i} {level}", end=' ')
# Define level-specific variables
parse_type = self.ohco_pats[i][2]
div_name = self.ohco_pats[i][0]
div_pat = self.ohco_pats[i][1]
if i == 0:
src_div_name = 'line'
else:
src_div_name = self.ohco_names[i - 1]
src_col = f"{src_div_name}{self.src_col_suffix}"
dst_col = f"{div_name}{self.src_col_suffix}"
# By Milestone
if parse_type == 'm':
if self.verbose: print(f"by milestone {div_pat}")
div_lines = self.TOKENS[src_col].str.contains(div_pat, regex=True, case=True) # TODO: Parametize case
self.TOKENS.loc[div_lines, div_name] = [i+1 for i in range(self.TOKENS.loc[div_lines].shape[0])]
self.TOKENS[div_name] = self.TOKENS[div_name].ffill()
self.TOKENS = self.TOKENS.loc[~self.TOKENS[div_name].isna()]
self.TOKENS = self.TOKENS.loc[~div_lines]
self.TOKENS[div_name] = self.TOKENS[div_name].astype('int')
self.TOKENS = self.TOKENS.groupby(self.ohco_names[:i+1])[src_col]\
.apply(lambda x: '\n'.join(x)).to_frame(dst_col)
# print(self.TOKENS[dst_col].str.count(r'\n\n'))
print(src_col, dst_col)
print(self.TOKENS.columns)
# By Delimitter
elif parse_type == 'd':
if self.verbose: print(f"by delimitter {div_pat}")
self.TOKENS = self.TOKENS[src_col].str.split(div_pat, expand=True).stack().to_frame(dst_col)
# By NLTK
elif parse_type == 'nltk':
if self.verbose: print(f"by NLTK model")
if level == 'sent_num':
self.TOKENS = self.TOKENS.para_str\
.apply(lambda x: pd.Series(nltk.sent_tokenize(x)))\
.stack()\
.to_frame('sent_str')
if level == 'token_num':
if self.strip_hyphens == True:
self.TOKENS.sent_str = self.TOKENS.sent_str.str.replace(r"-", ' ')
if self.strip_whitespace == True:
self.TOKENS = self.TOKENS.sent_str\
.apply(lambda x: pd.Series(nltk.pos_tag(nltk.WhitespaceTokenizer().tokenize(x))))
else:
self.TOKENS = self.TOKENS.sent_str\
.apply(lambda x: pd.Series(nltk.pos_tag(nltk.word_tokenize(x))))
self.TOKENS = self.TOKENS.stack().to_frame('pos_tuple')
self.TOKENS['pos'] = self.TOKENS.pos_tuple.apply(lambda x: x[1])
self.TOKENS['token_str'] = self.TOKENS.pos_tuple.apply(lambda x: x[0])
self.TOKENS['term_str'] = self.TOKENS.token_str.str.lower()
else:
raise ValueError(f"Invalid parse option: {parse_type}.")
# After creating the current OHCO level
self.TOKENS.index.names = self.OHCO[:i+1]
# After iterating through the OHCO
# Not sure if needed anymore
# self.TOKENS[dst_col] = self.TOKENS[dst_col].str.strip()
# self.TOKENS[dst_col] = self.TOKENS[dst_col].str.replace(self.join_pat, ' ', regex=True)
# self.TOKENS = self.TOKENS[~self.TOKENS[dst_col].str.contains(r'^\s*$', regex=True)]
if not self.use_nltk:
self.TOKENS['term_str'] = self.TOKENS.token_str.str.replace(r'[\W_]+', '', regex=True).str.lower()
else:
punc_pos = ['$', "''", '(', ')', ',', '--', '.', ':', '``']
self.TOKENS['term_str'] = self.TOKENS[~self.TOKENS.pos.isin(punc_pos)].token_str\
.str.replace(r'[\W_]+', '', regex=True).str.lower()
else:
raise RuntimeError("Source not imported. Please run .import_source()")
def extract_vocab(self):
"""This should also be done at the corpus level."""
self.VOCAB = self.TOKENS.term_str.value_counts().to_frame('n')
self.VOCAB.index.name = 'term_str'
self.VOCAB['n_chars'] = self.VOCAB.index.str.len()
self.VOCAB['p'] = self.VOCAB['n'] / self.VOCAB['n'].sum()
self.VOCAB['s'] = 1 / self.VOCAB['p']
self.VOCAB['i'] = np.log2(self.VOCAB['s']) # Same as negative log probability (i.e. log likelihood)
self.VOCAB['h'] = self.VOCAB['p'] * self.VOCAB['i']
self.H = self.VOCAB['h'].sum()
return self
def annotate_vocab(self):
"""This should be done at the corpus level."""
# Stopwords
# Max POS
# POS variability
# Porter Stems
pass
def extract_pos_data(self):
# TODO: Create dataframe for POS info, including Penn Treebank info
pass
def extract_named_entities(self):
# TODO: Create dataframe of named entities
pass
def gather_tokens(self, level=0, grouping_col='term_str', cat_sep=' '):
"""Gather tokens into strings for arbitrary OHCO level."""
max_level = len(self.OHCO) - 2 # Can't gather tokens at the token level :)
if level > max_level:
raise ValueError(f"Level {level} too high. Try between 0 and {max_level}")
else:
level_name = self.OHCO[level].split('_')[0]
idx = self.TOKENS.index.names[:level+1]
return self.TOKENS.groupby(idx)[grouping_col].apply(lambda x: x.str.cat(sep=cat_sep))\
.to_frame(f'{level_name}_str')
if __name__ == '__main__':
pass | en | 0.661149 | A class to parse a single Gutenberg-type text files into a TOKENS dataframe with an OHCO index. Also has methods to extract a VOCAB table, although vocabulary tables out to be generated at the corpus level. Sample parameter values: ohco_pats = [ ('chapter', r"^\s*(chapter|letter)\s+(\d+)", 'm') ] clip_pats = [ r'START OF GUTENBERG PROJECT', r'^\s*THE END' ] # TODO: Make these private # We assume all OHCOs have sentences and tokens # and that there are terminal in the list. Initialize the object and extract config info. If using NLTK, download resources. # TODO: Validate # TODO: Validate # Override the last two OHCO items # Make sure you have the NLTK stuff Convert a raw text file into a dataframe of lines. Remove cruft lines from beginning and/or end of file. Convert lines to tokens based on OHCO. # Start with the LINES df # Walk through each level of the OHCO to build out TOKENS # Define level-specific variables # By Milestone # TODO: Parametize case # print(self.TOKENS[dst_col].str.count(r'\n\n')) # By Delimitter # By NLTK # After creating the current OHCO level # After iterating through the OHCO # Not sure if needed anymore # self.TOKENS[dst_col] = self.TOKENS[dst_col].str.strip() # self.TOKENS[dst_col] = self.TOKENS[dst_col].str.replace(self.join_pat, ' ', regex=True) # self.TOKENS = self.TOKENS[~self.TOKENS[dst_col].str.contains(r'^\s*$', regex=True)] This should also be done at the corpus level. # Same as negative log probability (i.e. log likelihood) This should be done at the corpus level. # Stopwords # Max POS # POS variability # Porter Stems # TODO: Create dataframe for POS info, including Penn Treebank info # TODO: Create dataframe of named entities Gather tokens into strings for arbitrary OHCO level. # Can't gather tokens at the token level :) | 3.397743 | 3 |
migrations/versions/0d3d93f1c2e0_add_domain_id_to_history_table.py | ajax10g/PowerDNS-Admin | 1,431 | 6617708 | <reponame>ajax10g/PowerDNS-Admin<gh_stars>1000+
"""Add domain_id to history table
Revision ID: 0d3d93f1c2e0
Revises: <KEY>
Create Date: 2021-02-15 17:23:05.688241
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0d3d93f1c2e0'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('history', schema=None) as batch_op:
batch_op.add_column(sa.Column('domain_id', sa.Integer(), nullable=True))
batch_op.create_foreign_key('fk_domain_id', 'domain', ['domain_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('history', schema=None) as batch_op:
batch_op.drop_constraint('fk_domain_id', type_='foreignkey')
batch_op.drop_column('domain_id')
# ### end Alembic commands ###
| """Add domain_id to history table
Revision ID: 0d3d93f1c2e0
Revises: <KEY>
Create Date: 2021-02-15 17:23:05.688241
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0d3d93f1c2e0'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('history', schema=None) as batch_op:
batch_op.add_column(sa.Column('domain_id', sa.Integer(), nullable=True))
batch_op.create_foreign_key('fk_domain_id', 'domain', ['domain_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('history', schema=None) as batch_op:
batch_op.drop_constraint('fk_domain_id', type_='foreignkey')
batch_op.drop_column('domain_id')
# ### end Alembic commands ### | en | 0.487532 | Add domain_id to history table Revision ID: 0d3d93f1c2e0 Revises: <KEY> Create Date: 2021-02-15 17:23:05.688241 # revision identifiers, used by Alembic. # ### commands auto generated by Alembic - please adjust! ### # ### end Alembic commands ### # ### commands auto generated by Alembic - please adjust! ### # ### end Alembic commands ### | 1.669522 | 2 |
polyaxon/libs/paths/outputs_paths.py | wbuchwalter/polyaxon | 0 | 6617709 | <reponame>wbuchwalter/polyaxon
from django.conf import settings
from libs.paths.exceptions import VolumeNotFoundError
def validate_persistence_outputs(persistence_outputs):
# If no persistence is defined we mount the first one as default
return persistence_outputs or list(settings.PERSISTENCE_OUTPUTS.keys())[0]
def get_outputs_paths(persistence_outputs):
persistence_outputs = validate_persistence_outputs(persistence_outputs=persistence_outputs)
if persistence_outputs not in settings.PERSISTENCE_OUTPUTS:
raise VolumeNotFoundError('Outputs volume with name `{}` was defined in specification, '
'but was not found'.format(persistence_outputs))
if 'mountPath' not in settings.PERSISTENCE_OUTPUTS[persistence_outputs]:
raise VolumeNotFoundError('Outputs volume with name `{}` '
'does not define a mountPath.'.format(persistence_outputs))
return settings.PERSISTENCE_OUTPUTS[persistence_outputs]['mountPath']
| from django.conf import settings
from libs.paths.exceptions import VolumeNotFoundError
def validate_persistence_outputs(persistence_outputs):
# If no persistence is defined we mount the first one as default
return persistence_outputs or list(settings.PERSISTENCE_OUTPUTS.keys())[0]
def get_outputs_paths(persistence_outputs):
persistence_outputs = validate_persistence_outputs(persistence_outputs=persistence_outputs)
if persistence_outputs not in settings.PERSISTENCE_OUTPUTS:
raise VolumeNotFoundError('Outputs volume with name `{}` was defined in specification, '
'but was not found'.format(persistence_outputs))
if 'mountPath' not in settings.PERSISTENCE_OUTPUTS[persistence_outputs]:
raise VolumeNotFoundError('Outputs volume with name `{}` '
'does not define a mountPath.'.format(persistence_outputs))
return settings.PERSISTENCE_OUTPUTS[persistence_outputs]['mountPath'] | en | 0.869212 | # If no persistence is defined we mount the first one as default | 2.241182 | 2 |
ffsas/models/sphere.py | stfc-sciml/ffsas | 2 | 6617710 | <filename>ffsas/models/sphere.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# sphere.py
# ffsas: free-form inversion for small-angle scattering
# Copyright © 2021 SciML, STFC, UK. All rights reserved.
""" sphere model class """
import math
import torch
from ffsas.models.base import SASModel
class Sphere(SASModel):
@classmethod
def compute_G(cls, q_list, par_dict, const_dict, V=None):
# get parameters
q = q_list[0]
r = par_dict['r']
drho = const_dict['drho']
# compute volume
if V is None:
V = cls.compute_V(par_dict)
#############
# Compute G #
#############
# step 1: qr
qr = torch.outer(q, r)
# step 2: shape factor
shape_factor = 3. * (torch.sin(qr) - qr * torch.cos(qr)) / qr ** 3
# limit at 0
shape_factor = torch.nan_to_num(shape_factor,
nan=1., posinf=1., neginf=1.)
# step 3: G
G = (drho * V[None, :] * shape_factor) ** 2
return G
@classmethod
def get_par_keys_G(cls):
return ['r']
@classmethod
def compute_V(cls, par_dict):
r = par_dict['r']
return 4. / 3. * math.pi * r ** 3
@classmethod
def get_par_keys_V(cls):
return ['r']
| <filename>ffsas/models/sphere.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# sphere.py
# ffsas: free-form inversion for small-angle scattering
# Copyright © 2021 SciML, STFC, UK. All rights reserved.
""" sphere model class """
import math
import torch
from ffsas.models.base import SASModel
class Sphere(SASModel):
@classmethod
def compute_G(cls, q_list, par_dict, const_dict, V=None):
# get parameters
q = q_list[0]
r = par_dict['r']
drho = const_dict['drho']
# compute volume
if V is None:
V = cls.compute_V(par_dict)
#############
# Compute G #
#############
# step 1: qr
qr = torch.outer(q, r)
# step 2: shape factor
shape_factor = 3. * (torch.sin(qr) - qr * torch.cos(qr)) / qr ** 3
# limit at 0
shape_factor = torch.nan_to_num(shape_factor,
nan=1., posinf=1., neginf=1.)
# step 3: G
G = (drho * V[None, :] * shape_factor) ** 2
return G
@classmethod
def get_par_keys_G(cls):
return ['r']
@classmethod
def compute_V(cls, par_dict):
r = par_dict['r']
return 4. / 3. * math.pi * r ** 3
@classmethod
def get_par_keys_V(cls):
return ['r']
| en | 0.441942 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # sphere.py # ffsas: free-form inversion for small-angle scattering # Copyright © 2021 SciML, STFC, UK. All rights reserved. sphere model class # get parameters # compute volume ############# # Compute G # ############# # step 1: qr # step 2: shape factor # limit at 0 # step 3: G | 2.363269 | 2 |
fisb/level1/TwgoMatcher.py | rand-projects/fisb-decode | 7 | 6617711 | import time, sys, os
import fisb.level1.level1Exceptions as ex
from fisb.level1.L1Base import L1Base
class TwgoMatcher(L1Base):
"""Handle matching NOTAMS text and graphic portions.
Takes TWGO objects that have text and graphic parts (all but G-AIRMET, SUA)
and will match them. The standard requires any text part comes
out immediately, but will also match and send out the text and graphics
when available.
This class handles one of the thorniest issues in all of FIS-B:
We want to match text and graphics. We are required to send any
text part out immediately. However, if the message has a text and
graphics part, we will send the text part first (if we get it
first), then the text with graphics. Now we get the text part again. If we
just send it out, the graphics part is gone until it comes
along again. That's not good. If we store and ignore it, we will
send it out next as a text/graphics message. That is fine, and that will
happen before any > 60 minutes expiration (standard requires these messages be
kept for > 60 minutes (unless they contain an explicit stop time)). But what if the text
changes? The test groups certainly check for that. Well, we can
check if the text changes and send it out as a new message. That's
good. But what if the message has only a text part, and it never
changes? *Oh, Oh*. Now we send the text part out once and never again.
So when the system sends it again, we will ignore it. It will
eventually expire in the system, never to be seen again.
Not good. What I've actually described is the case of the normal
text only TFR-NOTAM.
Approach Taken:
* We get a text part:
* If we have not seen it before, store in msgHx and it send out (with graphics
if we have any).
* If we have seen before:
* If the text has changed, remove any graphic notification and send out.
(we consider this to be a new fresh message whose current graphics
section may not agree with it. This could be debated).
* If the text hasn't changed:
* If we have never seen a graphics for this object, send out.
* If we have seen a graphic, just wait for the next graphic.
* We get a graphics part:
* If we have a text part, send out both.
* If we have no text part, just store away waiting for text part.
"""
def __init__(self, expungeTimeMins):
"""Initialize class
Args:
expungeTimeMins (int): Number of minutes
after which any messages still hanging around unmatched
will be removed.
"""
super().__init__(expungeTimeMins)
def processFrame(self, frame, currentTime):
"""Given a TWGO message, process or store for later.
Cancelations will always cause a message to be generated.
We do make changes to the frame. We rename the ``contents``
of any graphics part to ``contents_graphics`` and the
``contents`` of any text part to ``contents_text``. This way
we keep all the data, but keep it separated.
Args:
frame (dict): Current frame as a dictionary.
currentTime (int): Current system time (minutes since 1970)
Returns:
dict: ``None`` if we don't have anything to return. Otherwise
returns the modified frame to send out.
"""
productId = frame['product_id']
contents = frame['contents']
# Get whether textual or graphical
recordFormat = contents['record_format'] # 8 graph, 2 text
# We allow multiple graphic records, but only one text portion.
records = contents['records']
# Use the first record for recording the id (works
# for both graphics and text).
record = contents['records'][0]
# Allow multiple graphical records, but only one text record.
if (recordFormat == 2) and \
len(records) != 1:
raise ex.TwgoRecordsException('More than 1 text record in TWGO. Found {}'.format(len(records)))
# Create a unique name.
# Rules for uniqueness vary based on
# type. See standard B.3.3 for details. Location is especially
# needed for D-NOTAMS.
location = 'X'
month = 0
if 'location' in contents:
location = contents['location']
if 'month' in frame:
month = frame['month']
uniqueName = str(productId) + '-' + str(record['report_year']) + "-" + \
str(record['report_number']) + "-" + location + "-" + str(month)
# Get the msgHx object for this name, or create one
if uniqueName in self.msgHx:
msgHxRecord = self.msgHx[uniqueName]
else:
msgHxRecord = {'text_contents': None, \
'graphics_contents': None, \
'last_update_time': currentTime}
self.msgHx[uniqueName] = msgHxRecord
if recordFormat == 8:
# Graphical
msgHxRecord['graphics_contents'] = contents
# See if we have both parts
if msgHxRecord['text_contents'] is not None:
# yes, create and return the message
frame['contents_graphics'] = contents
frame['contents_text'] = msgHxRecord['text_contents']
del frame['contents']
return frame
# no, wait till we get text.
return None
elif recordFormat == 2:
# Textual
# If a cancellation, return it
if record['report_status'] == 0:
frame['contents_text'] = frame['contents']
del frame['contents']
return frame
# A lot of ACTIVE records have a text field of "". Ignore these unless
# they are of product type 8 which is an empty NOTAM-TFR-- in which case
# just send it out. NOTAM-TFRs get sent text only every other transmission.
# The ones with no text are just 'renewals'. This will result in a special
# level 2 message and special handling in Harvest.
if len(record['text']) == 0:
if productId != 8:
return None
else:
# NOTAM-TFRs with empty text are renewals.
frame['contents_text'] = frame['contents']
del frame['contents']
return frame
# If here, we don't have a text part yet. Send it out.
if msgHxRecord['text_contents'] is None:
# Brand new.
msgHxRecord['text_contents'] = contents
if msgHxRecord['graphics_contents'] is not None:
frame['contents_graphics'] = msgHxRecord['graphics_contents']
frame['contents_text'] = contents
del frame['contents']
return frame
# We have at least a text part. See if we have changed text.
if msgHxRecord['text_contents']['records'][0]['text'] != \
contents['records'][0]['text']:
# Text is changed. Reset any graphics portion and resend.
msgHxRecord['graphics_contents'] = None
msgHxRecord['text_contents'] = contents
frame['contents_text'] = contents
del frame['contents']
return frame
# Store text.
msgHxRecord['text_contents'] = contents
# See if we have both parts
if msgHxRecord['graphics_contents'] is not None:
# yes, create and return the message
frame['contents_graphics'] = msgHxRecord['graphics_contents']
frame['contents_text'] = contents
del frame['contents']
return frame
# If here, we don't have a graphics part. Send it
frame['contents_text'] = contents
del frame['contents']
return frame
else:
raise ex.TwgoRecordFormatException(\
'TWGO found record format not 2 or 8. Found: {}'.\
format(recordFormat))
| import time, sys, os
import fisb.level1.level1Exceptions as ex
from fisb.level1.L1Base import L1Base
class TwgoMatcher(L1Base):
"""Handle matching NOTAMS text and graphic portions.
Takes TWGO objects that have text and graphic parts (all but G-AIRMET, SUA)
and will match them. The standard requires any text part comes
out immediately, but will also match and send out the text and graphics
when available.
This class handles one of the thorniest issues in all of FIS-B:
We want to match text and graphics. We are required to send any
text part out immediately. However, if the message has a text and
graphics part, we will send the text part first (if we get it
first), then the text with graphics. Now we get the text part again. If we
just send it out, the graphics part is gone until it comes
along again. That's not good. If we store and ignore it, we will
send it out next as a text/graphics message. That is fine, and that will
happen before any > 60 minutes expiration (standard requires these messages be
kept for > 60 minutes (unless they contain an explicit stop time)). But what if the text
changes? The test groups certainly check for that. Well, we can
check if the text changes and send it out as a new message. That's
good. But what if the message has only a text part, and it never
changes? *Oh, Oh*. Now we send the text part out once and never again.
So when the system sends it again, we will ignore it. It will
eventually expire in the system, never to be seen again.
Not good. What I've actually described is the case of the normal
text only TFR-NOTAM.
Approach Taken:
* We get a text part:
* If we have not seen it before, store in msgHx and it send out (with graphics
if we have any).
* If we have seen before:
* If the text has changed, remove any graphic notification and send out.
(we consider this to be a new fresh message whose current graphics
section may not agree with it. This could be debated).
* If the text hasn't changed:
* If we have never seen a graphics for this object, send out.
* If we have seen a graphic, just wait for the next graphic.
* We get a graphics part:
* If we have a text part, send out both.
* If we have no text part, just store away waiting for text part.
"""
def __init__(self, expungeTimeMins):
"""Initialize class
Args:
expungeTimeMins (int): Number of minutes
after which any messages still hanging around unmatched
will be removed.
"""
super().__init__(expungeTimeMins)
def processFrame(self, frame, currentTime):
"""Given a TWGO message, process or store for later.
Cancelations will always cause a message to be generated.
We do make changes to the frame. We rename the ``contents``
of any graphics part to ``contents_graphics`` and the
``contents`` of any text part to ``contents_text``. This way
we keep all the data, but keep it separated.
Args:
frame (dict): Current frame as a dictionary.
currentTime (int): Current system time (minutes since 1970)
Returns:
dict: ``None`` if we don't have anything to return. Otherwise
returns the modified frame to send out.
"""
productId = frame['product_id']
contents = frame['contents']
# Get whether textual or graphical
recordFormat = contents['record_format'] # 8 graph, 2 text
# We allow multiple graphic records, but only one text portion.
records = contents['records']
# Use the first record for recording the id (works
# for both graphics and text).
record = contents['records'][0]
# Allow multiple graphical records, but only one text record.
if (recordFormat == 2) and \
len(records) != 1:
raise ex.TwgoRecordsException('More than 1 text record in TWGO. Found {}'.format(len(records)))
# Create a unique name.
# Rules for uniqueness vary based on
# type. See standard B.3.3 for details. Location is especially
# needed for D-NOTAMS.
location = 'X'
month = 0
if 'location' in contents:
location = contents['location']
if 'month' in frame:
month = frame['month']
uniqueName = str(productId) + '-' + str(record['report_year']) + "-" + \
str(record['report_number']) + "-" + location + "-" + str(month)
# Get the msgHx object for this name, or create one
if uniqueName in self.msgHx:
msgHxRecord = self.msgHx[uniqueName]
else:
msgHxRecord = {'text_contents': None, \
'graphics_contents': None, \
'last_update_time': currentTime}
self.msgHx[uniqueName] = msgHxRecord
if recordFormat == 8:
# Graphical
msgHxRecord['graphics_contents'] = contents
# See if we have both parts
if msgHxRecord['text_contents'] is not None:
# yes, create and return the message
frame['contents_graphics'] = contents
frame['contents_text'] = msgHxRecord['text_contents']
del frame['contents']
return frame
# no, wait till we get text.
return None
elif recordFormat == 2:
# Textual
# If a cancellation, return it
if record['report_status'] == 0:
frame['contents_text'] = frame['contents']
del frame['contents']
return frame
# A lot of ACTIVE records have a text field of "". Ignore these unless
# they are of product type 8 which is an empty NOTAM-TFR-- in which case
# just send it out. NOTAM-TFRs get sent text only every other transmission.
# The ones with no text are just 'renewals'. This will result in a special
# level 2 message and special handling in Harvest.
if len(record['text']) == 0:
if productId != 8:
return None
else:
# NOTAM-TFRs with empty text are renewals.
frame['contents_text'] = frame['contents']
del frame['contents']
return frame
# If here, we don't have a text part yet. Send it out.
if msgHxRecord['text_contents'] is None:
# Brand new.
msgHxRecord['text_contents'] = contents
if msgHxRecord['graphics_contents'] is not None:
frame['contents_graphics'] = msgHxRecord['graphics_contents']
frame['contents_text'] = contents
del frame['contents']
return frame
# We have at least a text part. See if we have changed text.
if msgHxRecord['text_contents']['records'][0]['text'] != \
contents['records'][0]['text']:
# Text is changed. Reset any graphics portion and resend.
msgHxRecord['graphics_contents'] = None
msgHxRecord['text_contents'] = contents
frame['contents_text'] = contents
del frame['contents']
return frame
# Store text.
msgHxRecord['text_contents'] = contents
# See if we have both parts
if msgHxRecord['graphics_contents'] is not None:
# yes, create and return the message
frame['contents_graphics'] = msgHxRecord['graphics_contents']
frame['contents_text'] = contents
del frame['contents']
return frame
# If here, we don't have a graphics part. Send it
frame['contents_text'] = contents
del frame['contents']
return frame
else:
raise ex.TwgoRecordFormatException(\
'TWGO found record format not 2 or 8. Found: {}'.\
format(recordFormat))
| en | 0.89216 | Handle matching NOTAMS text and graphic portions. Takes TWGO objects that have text and graphic parts (all but G-AIRMET, SUA) and will match them. The standard requires any text part comes out immediately, but will also match and send out the text and graphics when available. This class handles one of the thorniest issues in all of FIS-B: We want to match text and graphics. We are required to send any text part out immediately. However, if the message has a text and graphics part, we will send the text part first (if we get it first), then the text with graphics. Now we get the text part again. If we just send it out, the graphics part is gone until it comes along again. That's not good. If we store and ignore it, we will send it out next as a text/graphics message. That is fine, and that will happen before any > 60 minutes expiration (standard requires these messages be kept for > 60 minutes (unless they contain an explicit stop time)). But what if the text changes? The test groups certainly check for that. Well, we can check if the text changes and send it out as a new message. That's good. But what if the message has only a text part, and it never changes? *Oh, Oh*. Now we send the text part out once and never again. So when the system sends it again, we will ignore it. It will eventually expire in the system, never to be seen again. Not good. What I've actually described is the case of the normal text only TFR-NOTAM. Approach Taken: * We get a text part: * If we have not seen it before, store in msgHx and it send out (with graphics if we have any). * If we have seen before: * If the text has changed, remove any graphic notification and send out. (we consider this to be a new fresh message whose current graphics section may not agree with it. This could be debated). * If the text hasn't changed: * If we have never seen a graphics for this object, send out. * If we have seen a graphic, just wait for the next graphic. * We get a graphics part: * If we have a text part, send out both. * If we have no text part, just store away waiting for text part. Initialize class Args: expungeTimeMins (int): Number of minutes after which any messages still hanging around unmatched will be removed. Given a TWGO message, process or store for later. Cancelations will always cause a message to be generated. We do make changes to the frame. We rename the ``contents`` of any graphics part to ``contents_graphics`` and the ``contents`` of any text part to ``contents_text``. This way we keep all the data, but keep it separated. Args: frame (dict): Current frame as a dictionary. currentTime (int): Current system time (minutes since 1970) Returns: dict: ``None`` if we don't have anything to return. Otherwise returns the modified frame to send out. # Get whether textual or graphical # 8 graph, 2 text # We allow multiple graphic records, but only one text portion. # Use the first record for recording the id (works # for both graphics and text). # Allow multiple graphical records, but only one text record. # Create a unique name. # Rules for uniqueness vary based on # type. See standard B.3.3 for details. Location is especially # needed for D-NOTAMS. # Get the msgHx object for this name, or create one # Graphical # See if we have both parts # yes, create and return the message # no, wait till we get text. # Textual # If a cancellation, return it # A lot of ACTIVE records have a text field of "". Ignore these unless # they are of product type 8 which is an empty NOTAM-TFR-- in which case # just send it out. NOTAM-TFRs get sent text only every other transmission. # The ones with no text are just 'renewals'. This will result in a special # level 2 message and special handling in Harvest. # NOTAM-TFRs with empty text are renewals. # If here, we don't have a text part yet. Send it out. # Brand new. # We have at least a text part. See if we have changed text. # Text is changed. Reset any graphics portion and resend. # Store text. # See if we have both parts # yes, create and return the message # If here, we don't have a graphics part. Send it | 2.416553 | 2 |
LowCostSmartFarmHub/sensor.py | itumeleng96/LowCostSmartFarmHub | 1 | 6617712 | <reponame>itumeleng96/LowCostSmartFarmHub<filename>LowCostSmartFarmHub/sensor.py
from digi.xbee.devices import XBeeDevice
from digi.xbee.io import IOLine,IOMode
import time
import RPi.GPIO as GPIO
import dht11
class Sensor:
'''This class provides functionality for the Sensor'''
def __init__(self,sensorName,sensorID,sensorType,description,unit_of_measure,connection_pin,conversion,sensorValues=[]):
self.sensor_name=sensorName #Every Sensor on the network has a name
self.sensor_id=sensorID #Every Sensor on the network has a unique ID
self.sensor_type=sensorType #I2C,ADC,DIO
self.sensor_values=sensorValues #[recent sensor values]
self.description=description #More information about sensor ,humidity,Temperature
self.unit_of_measure=unit_of_measure #The unit of measure (percentage,degrees,grams of water per unit of air)
self.connection_pin=connection_pin
self.conversion=conversion
def read_analog_xbee_sensor(self,XbeeDevice:XBeeDevice):
"""
This provides functionality for getting the sensor value on a Xbee Node
Args:
analog_pin_index (Integer) : The analog pin that sensor is connected to on XBee module 0=>DIO0,1->DIO1
XbeeDevice (XBeeDevice) : The node device where the sensor is connected
Returns:
Sensor Value
"""
sensor_value=0
#Configure the pin to analog (Pin must support Analog signal Pin0-Pin3)
XbeeDevice.set_io_configuration(IOLine.get(int(self.connection_pin)),IOMode.ADC)
sensor_value=XbeeDevice.get_adc_value(IOLine.get(int(self.connection_pin)))
#Convert 10 Bit ADC value to relevant value
sensor_value=100-round(float(sensor_value/1023.0)*int(self.conversion),2)
#raise Exception('The selected pin does not support Analog');
self.sensor_values.append(sensor_value)
return str(sensor_value)
def read_digital_sensor_dht11(self):
"""
This function reads the values from the DHT11 sensor
Returns:
The sensor value
"""
time.sleep(20) #This ensures that sampling frequency is less than 1 Hz
GPIO.setmode(GPIO.BCM)
instance = dht11.DHT11(pin = int(self.connection_pin))
valid=True
while valid:
result = instance.read()
if(str(self.sensor_name)=='DHT11-temperature') and result.is_valid():
self.sensor_values.append(result.temperature)
valid=False
elif(str(self.sensor_name)=='DHT11-humidity') and result.is_valid():
self.sensor_values.append(result.humidity)
valid=False
return 0
def read_digital_xbee_sensor(self,xbee_device:XBeeDevice,io_digital_pin):
"""
This function provides functionality for interfacing with the DHT11 Humidity and Temperature sensor
connected to an XBee 3 module
Args:
xbee_device (XBee Device): The Xbee module object that represents the XBee module 3 in the network
io_digital_pin (Integer) : The digital IO pin that the sensor is connected to
"""
def get_sensor_value(self):
"""
Gets the most recent sensor value
Returns:
Sensor value
"""
return self.sensor_values[len(self.sensor_values)-1]
| from digi.xbee.devices import XBeeDevice
from digi.xbee.io import IOLine,IOMode
import time
import RPi.GPIO as GPIO
import dht11
class Sensor:
'''This class provides functionality for the Sensor'''
def __init__(self,sensorName,sensorID,sensorType,description,unit_of_measure,connection_pin,conversion,sensorValues=[]):
self.sensor_name=sensorName #Every Sensor on the network has a name
self.sensor_id=sensorID #Every Sensor on the network has a unique ID
self.sensor_type=sensorType #I2C,ADC,DIO
self.sensor_values=sensorValues #[recent sensor values]
self.description=description #More information about sensor ,humidity,Temperature
self.unit_of_measure=unit_of_measure #The unit of measure (percentage,degrees,grams of water per unit of air)
self.connection_pin=connection_pin
self.conversion=conversion
def read_analog_xbee_sensor(self,XbeeDevice:XBeeDevice):
"""
This provides functionality for getting the sensor value on a Xbee Node
Args:
analog_pin_index (Integer) : The analog pin that sensor is connected to on XBee module 0=>DIO0,1->DIO1
XbeeDevice (XBeeDevice) : The node device where the sensor is connected
Returns:
Sensor Value
"""
sensor_value=0
#Configure the pin to analog (Pin must support Analog signal Pin0-Pin3)
XbeeDevice.set_io_configuration(IOLine.get(int(self.connection_pin)),IOMode.ADC)
sensor_value=XbeeDevice.get_adc_value(IOLine.get(int(self.connection_pin)))
#Convert 10 Bit ADC value to relevant value
sensor_value=100-round(float(sensor_value/1023.0)*int(self.conversion),2)
#raise Exception('The selected pin does not support Analog');
self.sensor_values.append(sensor_value)
return str(sensor_value)
def read_digital_sensor_dht11(self):
"""
This function reads the values from the DHT11 sensor
Returns:
The sensor value
"""
time.sleep(20) #This ensures that sampling frequency is less than 1 Hz
GPIO.setmode(GPIO.BCM)
instance = dht11.DHT11(pin = int(self.connection_pin))
valid=True
while valid:
result = instance.read()
if(str(self.sensor_name)=='DHT11-temperature') and result.is_valid():
self.sensor_values.append(result.temperature)
valid=False
elif(str(self.sensor_name)=='DHT11-humidity') and result.is_valid():
self.sensor_values.append(result.humidity)
valid=False
return 0
def read_digital_xbee_sensor(self,xbee_device:XBeeDevice,io_digital_pin):
"""
This function provides functionality for interfacing with the DHT11 Humidity and Temperature sensor
connected to an XBee 3 module
Args:
xbee_device (XBee Device): The Xbee module object that represents the XBee module 3 in the network
io_digital_pin (Integer) : The digital IO pin that the sensor is connected to
"""
def get_sensor_value(self):
"""
Gets the most recent sensor value
Returns:
Sensor value
"""
return self.sensor_values[len(self.sensor_values)-1] | en | 0.684774 | This class provides functionality for the Sensor #Every Sensor on the network has a name #Every Sensor on the network has a unique ID #I2C,ADC,DIO #[recent sensor values] #More information about sensor ,humidity,Temperature #The unit of measure (percentage,degrees,grams of water per unit of air) This provides functionality for getting the sensor value on a Xbee Node Args: analog_pin_index (Integer) : The analog pin that sensor is connected to on XBee module 0=>DIO0,1->DIO1 XbeeDevice (XBeeDevice) : The node device where the sensor is connected Returns: Sensor Value #Configure the pin to analog (Pin must support Analog signal Pin0-Pin3) #Convert 10 Bit ADC value to relevant value #raise Exception('The selected pin does not support Analog'); This function reads the values from the DHT11 sensor Returns: The sensor value #This ensures that sampling frequency is less than 1 Hz This function provides functionality for interfacing with the DHT11 Humidity and Temperature sensor connected to an XBee 3 module Args: xbee_device (XBee Device): The Xbee module object that represents the XBee module 3 in the network io_digital_pin (Integer) : The digital IO pin that the sensor is connected to Gets the most recent sensor value Returns: Sensor value | 3.392194 | 3 |
LeetCode/Python/remove_element.py | tejeshreddy/competitive-programming | 0 | 6617713 | """
Title: 0027 - Remove Element
Tags: Array
Time: O(n)
Space: O(1)
Source: https://leetcode.com/problems/remove-element/
Difficulty: Easy
"""
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
for i in range(len(nums)):
i, last = 0, len(nums) - 1
while i <= last:
if nums[i] == val:
nums[i], nums[last] = nums[last], nums[i]
last -= 1
else:
i = i+1
return last + 1
| """
Title: 0027 - Remove Element
Tags: Array
Time: O(n)
Space: O(1)
Source: https://leetcode.com/problems/remove-element/
Difficulty: Easy
"""
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
for i in range(len(nums)):
i, last = 0, len(nums) - 1
while i <= last:
if nums[i] == val:
nums[i], nums[last] = nums[last], nums[i]
last -= 1
else:
i = i+1
return last + 1
| en | 0.733019 | Title: 0027 - Remove Element Tags: Array Time: O(n) Space: O(1) Source: https://leetcode.com/problems/remove-element/ Difficulty: Easy | 3.521783 | 4 |
Programming-Basics-with-Python-April-2019/07_conditional_statements_more_exercises/08_fuel_tank.py | marinakolova/Python-Courses | 0 | 6617714 | <filename>Programming-Basics-with-Python-April-2019/07_conditional_statements_more_exercises/08_fuel_tank.py
fuel = input()
liters = float(input())
if fuel not in ["Diesel", "Gasoline", "Gas"]:
print("Invalid fuel!")
exit()
if liters >= 25:
print(f"You have enough {fuel.lower()}.")
else:
print(f"Fill your tank with {fuel.lower()}!")
| <filename>Programming-Basics-with-Python-April-2019/07_conditional_statements_more_exercises/08_fuel_tank.py
fuel = input()
liters = float(input())
if fuel not in ["Diesel", "Gasoline", "Gas"]:
print("Invalid fuel!")
exit()
if liters >= 25:
print(f"You have enough {fuel.lower()}.")
else:
print(f"Fill your tank with {fuel.lower()}!")
| none | 1 | 4.15098 | 4 | |
auth/shared.py | WizBoom/Apate | 0 | 6617715 | from flask_sqlalchemy import SQLAlchemy
Database = SQLAlchemy()
SharedInfo = {
'alliance_id': 0,
'util': None,
'reddit': None,
}
EveAPI = {
'user_agent': "",
'default_user_preston': None,
'corp_preston': None,
'full_auth_preston': None
}
| from flask_sqlalchemy import SQLAlchemy
Database = SQLAlchemy()
SharedInfo = {
'alliance_id': 0,
'util': None,
'reddit': None,
}
EveAPI = {
'user_agent': "",
'default_user_preston': None,
'corp_preston': None,
'full_auth_preston': None
}
| none | 1 | 1.921612 | 2 | |
plan.py | aaronzguan/Sampling_based_Planning_for_Robot_Arm | 10 | 6617716 | <filename>plan.py<gh_stars>1-10
import argparse
import numpy as np
import rospy
from franka_robot import FrankaRobot
from collision_boxes_publisher import CollisionBoxesPublisher
from rrt import RRT
from rrt_connect import RRTConnect
from prm import PRM
from ob_prm import OBPRM
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--seed', '-s', type=int, default=0)
parser.add_argument('--rrt', '-rrt', type=str2bool, const=True, nargs='?', default=False, help="Use RRT?")
parser.add_argument('--rrtc', '-rrtc', type=str2bool, const=True, nargs='?', default=False, help="Use RRT-Connect?")
parser.add_argument('--prm', '-prm', type=str2bool, const=True, nargs='?', default=False, help="Use PRM?")
parser.add_argument('--obprm', '-obprm', type=str2bool, const=True, nargs='?', default=False, help="Use OBPRM?")
parser.add_argument('--map2', '-map2', type=str2bool, const=True, nargs='?', default=False, help="Use map 2?")
parser.add_argument('--map3', '-map3', type=str2bool, const=True, nargs='?', default=False, help="Use map 3?")
parser.add_argument('--reuse_graph', '-reuse_graph', type=str2bool, const=True, nargs='?', default=False, help="Reuse the graph for PRM?")
args = parser.parse_args()
np.random.seed(args.seed)
fr = FrankaRobot()
rospy.init_node('planner')
'''
TODO: Replace obstacle box w/ the box specs in your workspace:
[x, y, z, r, p, y, sx, sy, sz]
'''
if args.map3:
boxes = np.array([
# obstacle
# [0, 0, 0, 0, 0, 0, 0, 0, 0],
[0.45, -0.45, 0.7, 0, 0, 0.78, 0.6, 0.6, 0.05],
# sides
[-0.7, 0.7, 0.75, 0, 0, 0.78, 2, 0.01, 1.6],
[0.7, -0.7, 0.75, 0, 0, 0.78, 2, 0.01, 1.6],
# back
[-0.7, -0.7, 0.75, 0, 0, 0.78, 0.01, 2, 1.6],
# front
[0.7, 0.7, 0.75, 0, 0, 0.78, 0.01, 2, 1.6],
# top
[0, 0, 1.5, 0, 0, 0.78, 2, 2, 0.01],
# bottom
[0, 0, -0.05, 0, 0, 0.78, 2, 2, 0.01]
])
elif args.map2:
boxes = np.array([
# obstacle
[0.7, 0, 0.6, 0, 0, 0, 0.45, 0.3, 0.05],
# sides
[0.15, 0.66, 0.65, 0, 0, 0, 1.2, 0.01, 1.5],
[0.15, -0.66, 0.65, 0, 0, 0, 1.2, 0.01, 1.5],
# back
[-0.41, 0, 0.65, 0, 0, 0, 0.01, 1.4, 1.5],
# front
[0.75, 0, 0.65, 0, 0, 0, 0.01, 1.4, 1.5],
# top
[0.2, 0, 1.35, 0, 0, 0, 1.2, 1.4, 0.01],
# bottom
[0.2, 0, -0.05, 0, 0, 0, 1.2, 1.4, 0.01]
])
else:
boxes = np.array([
# obstacle
# [0, 0, 0, 0, 0, 0, 0, 0, 0],
[0.4, 0, 0.25, 0, 0, 0, 0.3, 0.05, 0.5],
# sides
[0.15, 0.46, 0.5, 0, 0, 0, 1.2, 0.01, 1.1],
[0.15, -0.46, 0.5, 0, 0, 0, 1.2, 0.01, 1.1],
# back
[-0.41, 0, 0.5, 0, 0, 0, 0.01, 1, 1.1],
# front
[0.75, 0, 0.5, 0, 0, 0, 0.01, 1, 1.1],
# top
[0.2, 0, 1, 0, 0, 0, 1.2, 1, 0.01],
# bottom
[0.2, 0, -0.05, 0, 0, 0, 1.2, 1, 0.01]
])
def is_in_collision(joints):
if fr.check_self_collision(joints):
return True
for box in boxes:
if fr.check_box_collision(joints, box):
return True
return False
desired_ee_rp = fr.ee(fr.home_joints)[3:5]
def ee_upright_constraint(q):
'''
TODO: Implement constraint function and its gradient.
This constraint should enforce the end-effector stays upright.
Hint: Use the roll and pitch angle in desired_ee_rp. The end-effector is upright in its home state.
Input:
q - a joint configuration
Output:
err - a non-negative scalar that is 0 when the constraint is satisfied
grad - a vector of length 6, where the ith element is the derivative of err w.r.t. the ith element of ee
'''
ee = fr.ee(q)
err = np.sum((np.asarray(desired_ee_rp) - np.asarray(ee[3:5])) ** 2)
grad = np.asarray([0, 0, 0, 2 * (ee[3] - desired_ee_rp[0]), 2 * (ee[4] - desired_ee_rp[1]), 0])
return err, grad
def get_plan_quality(plan):
dist = 0
for i in range(len(plan) - 1):
dist += np.linalg.norm(np.array(plan[i+1]) - np.array(plan[i]))
return dist
'''
TODO: Fill in start and target joint positions
'''
if args.map3:
joints_start = np.array([0, 3*np.pi/8, 0, -np.pi / 8, 0, np.pi / 2, np.pi / 4])
joints_start[0] = -np.deg2rad(45)
joints_target = np.array([0, 0, 0, -np.pi / 4, 0, np.pi / 4, np.pi / 4])
joints_target[0] = -np.deg2rad(45)
elif args.map2:
joints_start = np.array([0, np.pi/6, 0, -2*np.pi / 3, 0, 5*np.pi / 6, np.pi / 4])
joints_target = np.array([0, 0, 0, -np.pi / 4, 0, np.pi / 4, np.pi / 4])
else:
joints_start = fr.home_joints.copy()
joints_start[0] = -np.deg2rad(45)
joints_target = joints_start.copy()
joints_target[0] = np.deg2rad(45)
if args.rrt:
print("RRT: RRT planner is selected!")
planner = RRT(fr, is_in_collision)
elif args.rrtc:
print("RRTC: RRT Connect planner is selected!")
planner = RRTConnect(fr, is_in_collision)
elif args.prm:
print("PRM: PRM planner is selected!")
planner = PRM(fr, is_in_collision)
elif args.obprm:
print("OB_PRM: OB_PRM planner is selected!")
planner = OBPRM(fr, is_in_collision)
constraint = ee_upright_constraint
if args.prm or args.obprm:
plan = planner.plan(joints_start, joints_target, constraint, args)
else:
plan = planner.plan(joints_start, joints_target, constraint)
path_quality = get_plan_quality(plan)
print("Path quality: {}".format(path_quality))
collision_boxes_publisher = CollisionBoxesPublisher('collision_boxes')
rate = rospy.Rate(10)
i = 0
while not rospy.is_shutdown():
rate.sleep()
joints = plan[i % len(plan)]
fr.publish_joints(joints)
fr.publish_collision_boxes(joints)
collision_boxes_publisher.publish_boxes(boxes)
i += 1
| <filename>plan.py<gh_stars>1-10
import argparse
import numpy as np
import rospy
from franka_robot import FrankaRobot
from collision_boxes_publisher import CollisionBoxesPublisher
from rrt import RRT
from rrt_connect import RRTConnect
from prm import PRM
from ob_prm import OBPRM
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--seed', '-s', type=int, default=0)
parser.add_argument('--rrt', '-rrt', type=str2bool, const=True, nargs='?', default=False, help="Use RRT?")
parser.add_argument('--rrtc', '-rrtc', type=str2bool, const=True, nargs='?', default=False, help="Use RRT-Connect?")
parser.add_argument('--prm', '-prm', type=str2bool, const=True, nargs='?', default=False, help="Use PRM?")
parser.add_argument('--obprm', '-obprm', type=str2bool, const=True, nargs='?', default=False, help="Use OBPRM?")
parser.add_argument('--map2', '-map2', type=str2bool, const=True, nargs='?', default=False, help="Use map 2?")
parser.add_argument('--map3', '-map3', type=str2bool, const=True, nargs='?', default=False, help="Use map 3?")
parser.add_argument('--reuse_graph', '-reuse_graph', type=str2bool, const=True, nargs='?', default=False, help="Reuse the graph for PRM?")
args = parser.parse_args()
np.random.seed(args.seed)
fr = FrankaRobot()
rospy.init_node('planner')
'''
TODO: Replace obstacle box w/ the box specs in your workspace:
[x, y, z, r, p, y, sx, sy, sz]
'''
if args.map3:
boxes = np.array([
# obstacle
# [0, 0, 0, 0, 0, 0, 0, 0, 0],
[0.45, -0.45, 0.7, 0, 0, 0.78, 0.6, 0.6, 0.05],
# sides
[-0.7, 0.7, 0.75, 0, 0, 0.78, 2, 0.01, 1.6],
[0.7, -0.7, 0.75, 0, 0, 0.78, 2, 0.01, 1.6],
# back
[-0.7, -0.7, 0.75, 0, 0, 0.78, 0.01, 2, 1.6],
# front
[0.7, 0.7, 0.75, 0, 0, 0.78, 0.01, 2, 1.6],
# top
[0, 0, 1.5, 0, 0, 0.78, 2, 2, 0.01],
# bottom
[0, 0, -0.05, 0, 0, 0.78, 2, 2, 0.01]
])
elif args.map2:
boxes = np.array([
# obstacle
[0.7, 0, 0.6, 0, 0, 0, 0.45, 0.3, 0.05],
# sides
[0.15, 0.66, 0.65, 0, 0, 0, 1.2, 0.01, 1.5],
[0.15, -0.66, 0.65, 0, 0, 0, 1.2, 0.01, 1.5],
# back
[-0.41, 0, 0.65, 0, 0, 0, 0.01, 1.4, 1.5],
# front
[0.75, 0, 0.65, 0, 0, 0, 0.01, 1.4, 1.5],
# top
[0.2, 0, 1.35, 0, 0, 0, 1.2, 1.4, 0.01],
# bottom
[0.2, 0, -0.05, 0, 0, 0, 1.2, 1.4, 0.01]
])
else:
boxes = np.array([
# obstacle
# [0, 0, 0, 0, 0, 0, 0, 0, 0],
[0.4, 0, 0.25, 0, 0, 0, 0.3, 0.05, 0.5],
# sides
[0.15, 0.46, 0.5, 0, 0, 0, 1.2, 0.01, 1.1],
[0.15, -0.46, 0.5, 0, 0, 0, 1.2, 0.01, 1.1],
# back
[-0.41, 0, 0.5, 0, 0, 0, 0.01, 1, 1.1],
# front
[0.75, 0, 0.5, 0, 0, 0, 0.01, 1, 1.1],
# top
[0.2, 0, 1, 0, 0, 0, 1.2, 1, 0.01],
# bottom
[0.2, 0, -0.05, 0, 0, 0, 1.2, 1, 0.01]
])
def is_in_collision(joints):
if fr.check_self_collision(joints):
return True
for box in boxes:
if fr.check_box_collision(joints, box):
return True
return False
desired_ee_rp = fr.ee(fr.home_joints)[3:5]
def ee_upright_constraint(q):
'''
TODO: Implement constraint function and its gradient.
This constraint should enforce the end-effector stays upright.
Hint: Use the roll and pitch angle in desired_ee_rp. The end-effector is upright in its home state.
Input:
q - a joint configuration
Output:
err - a non-negative scalar that is 0 when the constraint is satisfied
grad - a vector of length 6, where the ith element is the derivative of err w.r.t. the ith element of ee
'''
ee = fr.ee(q)
err = np.sum((np.asarray(desired_ee_rp) - np.asarray(ee[3:5])) ** 2)
grad = np.asarray([0, 0, 0, 2 * (ee[3] - desired_ee_rp[0]), 2 * (ee[4] - desired_ee_rp[1]), 0])
return err, grad
def get_plan_quality(plan):
dist = 0
for i in range(len(plan) - 1):
dist += np.linalg.norm(np.array(plan[i+1]) - np.array(plan[i]))
return dist
'''
TODO: Fill in start and target joint positions
'''
if args.map3:
joints_start = np.array([0, 3*np.pi/8, 0, -np.pi / 8, 0, np.pi / 2, np.pi / 4])
joints_start[0] = -np.deg2rad(45)
joints_target = np.array([0, 0, 0, -np.pi / 4, 0, np.pi / 4, np.pi / 4])
joints_target[0] = -np.deg2rad(45)
elif args.map2:
joints_start = np.array([0, np.pi/6, 0, -2*np.pi / 3, 0, 5*np.pi / 6, np.pi / 4])
joints_target = np.array([0, 0, 0, -np.pi / 4, 0, np.pi / 4, np.pi / 4])
else:
joints_start = fr.home_joints.copy()
joints_start[0] = -np.deg2rad(45)
joints_target = joints_start.copy()
joints_target[0] = np.deg2rad(45)
if args.rrt:
print("RRT: RRT planner is selected!")
planner = RRT(fr, is_in_collision)
elif args.rrtc:
print("RRTC: RRT Connect planner is selected!")
planner = RRTConnect(fr, is_in_collision)
elif args.prm:
print("PRM: PRM planner is selected!")
planner = PRM(fr, is_in_collision)
elif args.obprm:
print("OB_PRM: OB_PRM planner is selected!")
planner = OBPRM(fr, is_in_collision)
constraint = ee_upright_constraint
if args.prm or args.obprm:
plan = planner.plan(joints_start, joints_target, constraint, args)
else:
plan = planner.plan(joints_start, joints_target, constraint)
path_quality = get_plan_quality(plan)
print("Path quality: {}".format(path_quality))
collision_boxes_publisher = CollisionBoxesPublisher('collision_boxes')
rate = rospy.Rate(10)
i = 0
while not rospy.is_shutdown():
rate.sleep()
joints = plan[i % len(plan)]
fr.publish_joints(joints)
fr.publish_collision_boxes(joints)
collision_boxes_publisher.publish_boxes(boxes)
i += 1
| en | 0.725248 | TODO: Replace obstacle box w/ the box specs in your workspace: [x, y, z, r, p, y, sx, sy, sz] # obstacle # [0, 0, 0, 0, 0, 0, 0, 0, 0], # sides # back # front # top # bottom # obstacle # sides # back # front # top # bottom # obstacle # [0, 0, 0, 0, 0, 0, 0, 0, 0], # sides # back # front # top # bottom TODO: Implement constraint function and its gradient. This constraint should enforce the end-effector stays upright. Hint: Use the roll and pitch angle in desired_ee_rp. The end-effector is upright in its home state. Input: q - a joint configuration Output: err - a non-negative scalar that is 0 when the constraint is satisfied grad - a vector of length 6, where the ith element is the derivative of err w.r.t. the ith element of ee TODO: Fill in start and target joint positions | 2.620747 | 3 |
queue_api/tasks.py | darki-D4C/queue_tasks | 0 | 6617717 | <gh_stars>0
import asyncio
from task import Task
from contextlib import suppress
class Tasks:
"""Class to represent tasks storage entity"""
def __init__(self):
self.all_tasks = {} # key: id, value: task
self.is_started = False
self.tasks_queue = asyncio.Queue(maxsize=-1)
"""
Add task to queue and return this task id
"""
async def add_task(self,data,type):
new_task = Task(data,type)
self.all_tasks[new_task.id] = new_task
await self.tasks_queue.put(new_task)
return new_task.id
"""
Start processing queue
"""
async def start(self):
if not self.is_started:
self.is_started = True
self._queue_process = asyncio.ensure_future(self._run())
"""
Stop processing queue
"""
async def stop(self):
if self.is_started:
self.is_started = False
self._queue_process.cancel()
with suppress(asyncio.CancelledError):
await self._queue_process
"""
Run queue until all tasks are processed and then stop process
"""
async def _run(self):
while not self.tasks_queue.empty():
task = await self.tasks_queue.get()
task.do_func()
task.status = "in_progress"
await asyncio.sleep(task.interval)
task.status = "done"
await self.stop()
"""
Get status of task by id from tasks data storage
"""
async def get_status_by_id(self,id):
try:
task = self.all_tasks[id]
except KeyError:
return "id_not_found"
return task.status
"""
Get result of task by id from tasks data storage
"""
async def get_result_by_id(self,id):
try:
task = self.all_tasks[id]
except KeyError:
return "id_not_found"
if(task.status != 'done'):
return "not_processed"
return task.data | import asyncio
from task import Task
from contextlib import suppress
class Tasks:
"""Class to represent tasks storage entity"""
def __init__(self):
self.all_tasks = {} # key: id, value: task
self.is_started = False
self.tasks_queue = asyncio.Queue(maxsize=-1)
"""
Add task to queue and return this task id
"""
async def add_task(self,data,type):
new_task = Task(data,type)
self.all_tasks[new_task.id] = new_task
await self.tasks_queue.put(new_task)
return new_task.id
"""
Start processing queue
"""
async def start(self):
if not self.is_started:
self.is_started = True
self._queue_process = asyncio.ensure_future(self._run())
"""
Stop processing queue
"""
async def stop(self):
if self.is_started:
self.is_started = False
self._queue_process.cancel()
with suppress(asyncio.CancelledError):
await self._queue_process
"""
Run queue until all tasks are processed and then stop process
"""
async def _run(self):
while not self.tasks_queue.empty():
task = await self.tasks_queue.get()
task.do_func()
task.status = "in_progress"
await asyncio.sleep(task.interval)
task.status = "done"
await self.stop()
"""
Get status of task by id from tasks data storage
"""
async def get_status_by_id(self,id):
try:
task = self.all_tasks[id]
except KeyError:
return "id_not_found"
return task.status
"""
Get result of task by id from tasks data storage
"""
async def get_result_by_id(self,id):
try:
task = self.all_tasks[id]
except KeyError:
return "id_not_found"
if(task.status != 'done'):
return "not_processed"
return task.data | en | 0.859283 | Class to represent tasks storage entity # key: id, value: task Add task to queue and return this task id Start processing queue Stop processing queue Run queue until all tasks are processed and then stop process Get status of task by id from tasks data storage Get result of task by id from tasks data storage | 3.068087 | 3 |
venv/lib/python3.8/site-packages/pip/_internal/utils/hashes.py | Retraces/UkraineBot | 2 | 6617718 | <reponame>Retraces/UkraineBot
/home/runner/.cache/pip/pool/a3/5a/90/124a9ed80aac466fc984ba0ce21931995b5ec07d1966943a10139b1ee5 | /home/runner/.cache/pip/pool/a3/5a/90/124a9ed80aac466fc984ba0ce21931995b5ec07d1966943a10139b1ee5 | none | 1 | 0.717155 | 1 | |
tests/test_modify_group.py | gerberolya/python_training1.0 | 0 | 6617719 | from model.group import Group
import random
import pytest
def test_modify_group_name(app, db, check_ui):
with pytest.allure.step('Given a non-empty group list'):
if len(db.get_group_list()) == 0:
app.group.create(Group(name="for modify"))
old_groups = db.get_group_list()
group = random.choice(old_groups)
with pytest.allure.step('When I modify random group %s from the list' % group):
old_groups.remove(group)
modify_group = Group(name="modify_name30")
modify_group.id = group.id
app.group.modify_group_by_id(group.id, modify_group)
with pytest.allure.step('Then the new group list is equal to the old list with modifyed group'):
assert len(old_groups) + 1 == app.group.count()
new_groups = db.get_group_list()
old_groups.append(modify_group)
if check_ui:
assert sorted(new_groups, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)
| from model.group import Group
import random
import pytest
def test_modify_group_name(app, db, check_ui):
with pytest.allure.step('Given a non-empty group list'):
if len(db.get_group_list()) == 0:
app.group.create(Group(name="for modify"))
old_groups = db.get_group_list()
group = random.choice(old_groups)
with pytest.allure.step('When I modify random group %s from the list' % group):
old_groups.remove(group)
modify_group = Group(name="modify_name30")
modify_group.id = group.id
app.group.modify_group_by_id(group.id, modify_group)
with pytest.allure.step('Then the new group list is equal to the old list with modifyed group'):
assert len(old_groups) + 1 == app.group.count()
new_groups = db.get_group_list()
old_groups.append(modify_group)
if check_ui:
assert sorted(new_groups, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)
| none | 1 | 2.58427 | 3 | |
app.py | yeukhon/take-your-medicine | 0 | 6617720 | import datetime
import sqlite3
import bottle
from twilio import twiml
db_conn = sqlite3.connect("app.db")
def record_yes():
"""Record user's confirmation to database, including
the date and the time the confirmation was received."""
# This context manager will automatically rollback/commit
with db_conn:
cursor = db_conn.cursor()
# Use UTC timestamp because SQLite timestamp type
# accepts UTC, and the best practice is to convert
# the stored timestamp to local time when "presenting".
data = (datetime.datetime.utcnow(),)
# The confirmed table has two columns:
# pk (int, auto), datetime
cursor.execute(
"INSERT INTO confirmed VALUES (?)", data)
# uWSGI will search for "application"
app = application = bottle.Bottle()
@app.route("/sms", method="POST")
def sms_views():
number = request.form['From']
message_body = request.form['Body']
if message_body.lower() in ("y", "yes"):
record_yes()
response = twiml.Response()
response.message("Acked!")
return str(response)
if __name__ == '__main__':
run(host='localhost', port=8000)
else:
application = default_app()
| import datetime
import sqlite3
import bottle
from twilio import twiml
db_conn = sqlite3.connect("app.db")
def record_yes():
"""Record user's confirmation to database, including
the date and the time the confirmation was received."""
# This context manager will automatically rollback/commit
with db_conn:
cursor = db_conn.cursor()
# Use UTC timestamp because SQLite timestamp type
# accepts UTC, and the best practice is to convert
# the stored timestamp to local time when "presenting".
data = (datetime.datetime.utcnow(),)
# The confirmed table has two columns:
# pk (int, auto), datetime
cursor.execute(
"INSERT INTO confirmed VALUES (?)", data)
# uWSGI will search for "application"
app = application = bottle.Bottle()
@app.route("/sms", method="POST")
def sms_views():
number = request.form['From']
message_body = request.form['Body']
if message_body.lower() in ("y", "yes"):
record_yes()
response = twiml.Response()
response.message("Acked!")
return str(response)
if __name__ == '__main__':
run(host='localhost', port=8000)
else:
application = default_app()
| en | 0.857527 | Record user's confirmation to database, including the date and the time the confirmation was received. # This context manager will automatically rollback/commit # Use UTC timestamp because SQLite timestamp type # accepts UTC, and the best practice is to convert # the stored timestamp to local time when "presenting". # The confirmed table has two columns: # pk (int, auto), datetime # uWSGI will search for "application" | 3.05917 | 3 |
api/controllers.py | WeNeedThePoh/euromillions-api | 2 | 6617721 | import os
from api.utils.db import Database
from flask import Blueprint, request, jsonify, request, send_from_directory
from api import service, db
bp = Blueprint('api', __name__)
db = Database()
@bp.post('/draws')
def parse_new_draws():
added = service.parse_new_draws()
db.close()
if added:
return "", 201
else:
return jsonify({"error": True}), 400
@bp.get('/draws')
def get_draws():
year = request.args.get('year')
dates = request.args.get('dates')
if dates != None:
dates = dates.split(',')
results = service.get_draws(year, dates)
db.close()
return jsonify(results), 200
@bp.get('/draws/<int:draw_id>')
def get_draw(draw_id):
contest = service.get_draw(draw_id)
db.close()
if contest != None:
return jsonify(contest), 200
return "", 404
@bp.get('/')
def index():
return "Hi there! Have a look at our documentation: https://euromillios-api.readme.io", 200
| import os
from api.utils.db import Database
from flask import Blueprint, request, jsonify, request, send_from_directory
from api import service, db
bp = Blueprint('api', __name__)
db = Database()
@bp.post('/draws')
def parse_new_draws():
added = service.parse_new_draws()
db.close()
if added:
return "", 201
else:
return jsonify({"error": True}), 400
@bp.get('/draws')
def get_draws():
year = request.args.get('year')
dates = request.args.get('dates')
if dates != None:
dates = dates.split(',')
results = service.get_draws(year, dates)
db.close()
return jsonify(results), 200
@bp.get('/draws/<int:draw_id>')
def get_draw(draw_id):
contest = service.get_draw(draw_id)
db.close()
if contest != None:
return jsonify(contest), 200
return "", 404
@bp.get('/')
def index():
return "Hi there! Have a look at our documentation: https://euromillios-api.readme.io", 200
| none | 1 | 2.768296 | 3 | |
trusd/trusd.py | mathiasbockwoldt/TruSD | 0 | 6617722 | <reponame>mathiasbockwoldt/TruSD
#!/usr/bin/env python3
import datetime
import json
import os
from functools import lru_cache
import numpy as np
from scipy.special import comb
@lru_cache(maxsize=None)
def wright_fisher_trans_matrix(selection_coefficient, num_generations, genepop):
'''
Calculates the Wrigth-Fisher transition matrix given the selection coefficient,
the number of generations and the genetic population. The calculation is
computatinally very expensive, so the result is cached.
@param selection_coefficient: The selection coefficient as float
@param num_generations: The generation number as integer
@param genepop: Gene population as integer
@returns: The Wright-Fisher transition matrix as numpy array with shape (genepop+1, genepop+1)
'''
matrix = np.full((genepop + 1, genepop + 1), np.nan, dtype=np.float64)
for n in range(genepop + 1):
for m in range(genepop + 1):
m_over_genepop = m / genepop
first_product = (m_over_genepop + selection_coefficient * \
m_over_genepop * (1 - m_over_genepop)) ** n
second_product = (1 - m_over_genepop - selection_coefficient * \
m_over_genepop * (1 - m_over_genepop)) ** (genepop - n)
matrix[n, m] = comb(genepop, n) * first_product * second_product
matrix = np.linalg.matrix_power(matrix, num_generations)
return matrix
def likelihood(selection_coefficient, proportion, time_points, trajectories, genepop):
'''
Calculates the likelihood at a given point.
@param selection_coefficient: The selection coefficient as float
@param proportion: The proportion as float
@param time_points: The time points to consider as list of integers
@param trajectories: The trajectories as numpy array with shape (???) TODO!!!################
@param genepop: Gene population as integer
@returns: The likelihood for the given point as float
'''
result = 0
for time_index in range(len(time_points) - 1):
timepoint = time_points[time_index + 1] - time_points[time_index]
transition_prob_sel = wright_fisher_trans_matrix(selection_coefficient, timepoint, genepop)
transition_prob_neut = wright_fisher_trans_matrix(0, timepoint, genepop)
for trajectory in range(len(trajectories)):
row = trajectories[trajectory, time_index + 1]
col = trajectories[trajectory, time_index]
a = transition_prob_sel[row, col]
b = transition_prob_neut[row, col]
result += np.log((proportion * a + (1 - proportion) * b))
return result
def likelihood_grid(trajectories, genepop, proportions, selections, time_points):
'''
Calculates the likelihood for each point of a grid of selection coefficients
and proportions.
@param trajectories: The trajectories as numpy array with shape (???) TODO!!!################
@param genepop: Gene population as integer
@param proportions: The proportions as list of floats
@param selections: The selection coefficients as list of floats
@param time_points: The time points to consider as list of integers
@returns: The likelihood for each given point as numpy array of floats
'''
plen = len(proportions)
slen = len(selections)
# calculates the log-likelihood for each point on the grid
mat = np.full((slen, plen), np.nan, dtype=np.float64)
for i in range(slen):
sel = selections[i]
for j in range(plen):
prop = proportions[j]
mat[i, j] = likelihood(sel, prop, time_points, trajectories, genepop)
return mat
def read_trajectory_file(fname, delimiter=',', skip_rows=1, skip_columns=0):
'''
Reads a trajectory file for use in TruSD
@param fname: The file name of the trajectory file
@param delimiter: Column delimiter
@param skip_rows: Number of rows to skip in the beginning (header line(s))
@param skip_columns: Number of columns to skip from left
@returns: The contents of the trajectory file as numpy array
'''
def __strip_n_cols(fname, delimiter, skip_columns):
'''
Generator for reading in a file while skipping the first column.
Modified from https://stackoverflow.com/a/20624201
'''
with open(fname, 'r') as infile:
for line in infile:
try:
yield line.split(delimiter, skip_columns)[skip_columns]
except IndexError:
continue
return np.loadtxt(
__strip_n_cols(fname, delimiter, skip_columns),
delimiter=delimiter,
skiprows=skip_rows,
dtype='uint16')
def write_info_file(input_file, output_file, command, pop_size, times, \
proportions, selection_coefficients, delimiter):
'''
Writes an info file in json format with all necessary information to
replicate and to plot the results.
The json filename will be the same as `output_file` with the file name
extension set to `.json`.
@param input_file: The file name of the trajectory file
@param output_file: The file name of the output table
@param command: The command used to run TruSD
@param pop_size: The population size
@param times: List of time stamps
@param proportions: List of proportions
@param selection_coefficients: List of selection coefficients
'''
info = {}
info['description'] = ('This file contains the information for the TruSD '
'file saved in output_file.')
info['link'] = 'https://github.com/mathiasbockwoldt/TruSD'
info['citation'] = ('<NAME>, <NAME>, <NAME>, '
'and <NAME>: TruSD: A python package to '
'co-estimate selection and drift from allele '
'trajectories. In preparation.')
info['input_file'] = input_file
info['output_file'] = output_file
info['datetime'] = datetime.datetime.now().replace(microsecond=0).isoformat()
info['command'] = command
info['population_size'] = pop_size
info['time_stamps'] = times
info['proportions'] = proportions
info['selection_coefficients'] = selection_coefficients
info['delimiter'] = delimiter
info_file = '{}.json'.format(os.path.splitext(output_file)[0])
with open(info_file, 'w') as out_stream:
json.dump(info, out_stream, indent=2)
| #!/usr/bin/env python3
import datetime
import json
import os
from functools import lru_cache
import numpy as np
from scipy.special import comb
@lru_cache(maxsize=None)
def wright_fisher_trans_matrix(selection_coefficient, num_generations, genepop):
'''
Calculates the Wrigth-Fisher transition matrix given the selection coefficient,
the number of generations and the genetic population. The calculation is
computatinally very expensive, so the result is cached.
@param selection_coefficient: The selection coefficient as float
@param num_generations: The generation number as integer
@param genepop: Gene population as integer
@returns: The Wright-Fisher transition matrix as numpy array with shape (genepop+1, genepop+1)
'''
matrix = np.full((genepop + 1, genepop + 1), np.nan, dtype=np.float64)
for n in range(genepop + 1):
for m in range(genepop + 1):
m_over_genepop = m / genepop
first_product = (m_over_genepop + selection_coefficient * \
m_over_genepop * (1 - m_over_genepop)) ** n
second_product = (1 - m_over_genepop - selection_coefficient * \
m_over_genepop * (1 - m_over_genepop)) ** (genepop - n)
matrix[n, m] = comb(genepop, n) * first_product * second_product
matrix = np.linalg.matrix_power(matrix, num_generations)
return matrix
def likelihood(selection_coefficient, proportion, time_points, trajectories, genepop):
'''
Calculates the likelihood at a given point.
@param selection_coefficient: The selection coefficient as float
@param proportion: The proportion as float
@param time_points: The time points to consider as list of integers
@param trajectories: The trajectories as numpy array with shape (???) TODO!!!################
@param genepop: Gene population as integer
@returns: The likelihood for the given point as float
'''
result = 0
for time_index in range(len(time_points) - 1):
timepoint = time_points[time_index + 1] - time_points[time_index]
transition_prob_sel = wright_fisher_trans_matrix(selection_coefficient, timepoint, genepop)
transition_prob_neut = wright_fisher_trans_matrix(0, timepoint, genepop)
for trajectory in range(len(trajectories)):
row = trajectories[trajectory, time_index + 1]
col = trajectories[trajectory, time_index]
a = transition_prob_sel[row, col]
b = transition_prob_neut[row, col]
result += np.log((proportion * a + (1 - proportion) * b))
return result
def likelihood_grid(trajectories, genepop, proportions, selections, time_points):
'''
Calculates the likelihood for each point of a grid of selection coefficients
and proportions.
@param trajectories: The trajectories as numpy array with shape (???) TODO!!!################
@param genepop: Gene population as integer
@param proportions: The proportions as list of floats
@param selections: The selection coefficients as list of floats
@param time_points: The time points to consider as list of integers
@returns: The likelihood for each given point as numpy array of floats
'''
plen = len(proportions)
slen = len(selections)
# calculates the log-likelihood for each point on the grid
mat = np.full((slen, plen), np.nan, dtype=np.float64)
for i in range(slen):
sel = selections[i]
for j in range(plen):
prop = proportions[j]
mat[i, j] = likelihood(sel, prop, time_points, trajectories, genepop)
return mat
def read_trajectory_file(fname, delimiter=',', skip_rows=1, skip_columns=0):
'''
Reads a trajectory file for use in TruSD
@param fname: The file name of the trajectory file
@param delimiter: Column delimiter
@param skip_rows: Number of rows to skip in the beginning (header line(s))
@param skip_columns: Number of columns to skip from left
@returns: The contents of the trajectory file as numpy array
'''
def __strip_n_cols(fname, delimiter, skip_columns):
'''
Generator for reading in a file while skipping the first column.
Modified from https://stackoverflow.com/a/20624201
'''
with open(fname, 'r') as infile:
for line in infile:
try:
yield line.split(delimiter, skip_columns)[skip_columns]
except IndexError:
continue
return np.loadtxt(
__strip_n_cols(fname, delimiter, skip_columns),
delimiter=delimiter,
skiprows=skip_rows,
dtype='uint16')
def write_info_file(input_file, output_file, command, pop_size, times, \
proportions, selection_coefficients, delimiter):
'''
Writes an info file in json format with all necessary information to
replicate and to plot the results.
The json filename will be the same as `output_file` with the file name
extension set to `.json`.
@param input_file: The file name of the trajectory file
@param output_file: The file name of the output table
@param command: The command used to run TruSD
@param pop_size: The population size
@param times: List of time stamps
@param proportions: List of proportions
@param selection_coefficients: List of selection coefficients
'''
info = {}
info['description'] = ('This file contains the information for the TruSD '
'file saved in output_file.')
info['link'] = 'https://github.com/mathiasbockwoldt/TruSD'
info['citation'] = ('<NAME>, <NAME>, <NAME>, '
'and <NAME>: TruSD: A python package to '
'co-estimate selection and drift from allele '
'trajectories. In preparation.')
info['input_file'] = input_file
info['output_file'] = output_file
info['datetime'] = datetime.datetime.now().replace(microsecond=0).isoformat()
info['command'] = command
info['population_size'] = pop_size
info['time_stamps'] = times
info['proportions'] = proportions
info['selection_coefficients'] = selection_coefficients
info['delimiter'] = delimiter
info_file = '{}.json'.format(os.path.splitext(output_file)[0])
with open(info_file, 'w') as out_stream:
json.dump(info, out_stream, indent=2) | en | 0.762879 | #!/usr/bin/env python3 Calculates the Wrigth-Fisher transition matrix given the selection coefficient, the number of generations and the genetic population. The calculation is computatinally very expensive, so the result is cached. @param selection_coefficient: The selection coefficient as float @param num_generations: The generation number as integer @param genepop: Gene population as integer @returns: The Wright-Fisher transition matrix as numpy array with shape (genepop+1, genepop+1) Calculates the likelihood at a given point. @param selection_coefficient: The selection coefficient as float @param proportion: The proportion as float @param time_points: The time points to consider as list of integers @param trajectories: The trajectories as numpy array with shape (???) TODO!!!################ @param genepop: Gene population as integer @returns: The likelihood for the given point as float Calculates the likelihood for each point of a grid of selection coefficients and proportions. @param trajectories: The trajectories as numpy array with shape (???) TODO!!!################ @param genepop: Gene population as integer @param proportions: The proportions as list of floats @param selections: The selection coefficients as list of floats @param time_points: The time points to consider as list of integers @returns: The likelihood for each given point as numpy array of floats # calculates the log-likelihood for each point on the grid Reads a trajectory file for use in TruSD @param fname: The file name of the trajectory file @param delimiter: Column delimiter @param skip_rows: Number of rows to skip in the beginning (header line(s)) @param skip_columns: Number of columns to skip from left @returns: The contents of the trajectory file as numpy array Generator for reading in a file while skipping the first column. Modified from https://stackoverflow.com/a/20624201 Writes an info file in json format with all necessary information to replicate and to plot the results. The json filename will be the same as `output_file` with the file name extension set to `.json`. @param input_file: The file name of the trajectory file @param output_file: The file name of the output table @param command: The command used to run TruSD @param pop_size: The population size @param times: List of time stamps @param proportions: List of proportions @param selection_coefficients: List of selection coefficients | 2.842021 | 3 |
tests/peptest_milestone.py | onakanob/Peptide_Graph_Autograd | 2 | 6617723 | <filename>tests/peptest_milestone.py
""" Testing peptide deep convnet
Based on regression example from https://github.com/HIPS/neural-fingerprint
<NAME>"""
import autograd.numpy as np
import autograd.numpy.random as npr
from matplotlib import pyplot as plt
from scipy.stats.stats import pearsonr
from pepgraph import load_data_csv
from pepgraph import build_conv_deep_net
from pepgraph import normalize_array, adam
from pepgraph import build_batched_grad
from pepgraph.util import rmse
from autograd import grad
task_params = {'input_name' : 'sequence',
'target_name' : 'Log_IC50',
'conditions' : {'mhc' : 'HLA-A*02:02'
# ,'peptide_length' : 9},
},
'data_file' : '../data/bdata.20130222.mhci.csv'}
#task_params = {'input_name' : 'smiles',
# 'target_name' : 'measured log solubility in mols per litre',
# 'conditions' : {},
# 'data_file' : 'delaney.csv'}
# MHC HLA-A*02:02 all lengths:
N_train = 2400
N_val = 830
N_test = 830
# MHC HLA-A*02:02 only 9:
#N_train = 1450 #2400
#N_val = 490 #830
#N_test = 490 #830
# Delayney:
#N_train = 800
#N_val = 80
#N_test = 80
# TODO switch to percentage slicing
Pct_train = 0.6
Pct_val = 0.2
Pct_test = 0.2
model_params = dict(fp_length=60,
fp_depth=7, # The depth of the network equals the fingerprint radius.
conv_width=20, # Only the neural fps need this parameter.
h1_size=200, # Size of hidden layer of network on top of fps.
L2_reg=np.exp(-2))
train_params = dict(num_iters=2,
batch_size=100,
init_scale=np.exp(-4),
step_size=np.exp(-6))
# Define the architecture of the network that sits on top of the fingerprints.
vanilla_net_params = dict(
layer_sizes = [model_params['fp_length'], model_params['h1_size']], # One hidden layer.
normalize=True, L2_reg = model_params['L2_reg'], nll_func = rmse)
def train_nn(pred_fun, loss_fun, num_weights, train_smiles, train_raw_targets, train_params, seed=0,
validation_aa=None, validation_raw_targets=None):
"""loss_fun has inputs (weights, smiles, targets)"""
print "Total number of weights in the network:", num_weights
init_weights = npr.RandomState(seed).randn(num_weights) * train_params['init_scale']
num_print_examples = 100
train_targets, undo_norm = normalize_array(train_raw_targets)
training_curve = [[], [], []] # Test error, Val error
def callback(weights, iter):
if iter % 1 == 0:
print "max of weights", np.max(np.abs(weights))
train_preds = undo_norm(pred_fun(weights, train_smiles[:num_print_examples]))
cur_loss = loss_fun(weights, train_smiles[:num_print_examples], train_targets[:num_print_examples])
training_curve[0].append(cur_loss)
train_RMSE = rmse(train_preds, train_raw_targets[:num_print_examples])
training_curve[1].append(train_RMSE)
print "Iteration", iter, "loss", cur_loss,\
"train RMSE", train_RMSE,
if validation_aa is not None:
validation_preds = undo_norm(pred_fun(weights, validation_aa))
val_RMSE = rmse(validation_preds, validation_raw_targets)
training_curve[2].append(val_RMSE)
print "Validation RMSE", iter, ":", val_RMSE,
# Build gradient using autograd.
grad_fun = grad(loss_fun)
grad_fun_with_data = build_batched_grad(grad_fun, train_params['batch_size'],
train_smiles, train_targets)
# Optimize weights.
trained_weights = adam(grad_fun_with_data, init_weights, callback=callback,
num_iters=train_params['num_iters'], step_size=train_params['step_size'])
def predict_func(new_aa):
"""Returns to the original units that the raw targets were in."""
return undo_norm(pred_fun(trained_weights, new_aa))
return predict_func, trained_weights, training_curve
def main():
print "Loading data..."
# Example Data:
traindata, valdata, testdata = load_data_csv(
task_params['data_file'], (N_train, N_val, N_test),
# task_params['data_file'], (Pct_train, Pct_val, Pct_test), # TODO switch to percents
input_name=task_params['input_name'], target_name=task_params['target_name'],
conditions=task_params['conditions'])
train_inputs, train_targets = traindata
val_inputs, val_targets = valdata
test_inputs, test_targets = testdata
def print_performance(pred_func):
train_preds = pred_func(train_inputs)
val_preds = pred_func(val_inputs)
print "\nPerformance (RMSE) on " + task_params['target_name'] + ":"
print "Train RMSE:", rmse(train_preds, train_targets)
print "Test RMSE: ", rmse(val_preds, val_targets)
print "Test Pearson: ", pearsonr(val_preds, val_targets)
print "-" * 80
return rmse(val_preds, val_targets)
def run_conv_experiment():
conv_layer_sizes = [model_params['conv_width']] * model_params['fp_depth']
conv_arch_params = {'num_hidden_features' : conv_layer_sizes,
'fp_length' : model_params['fp_length'],
'normalize' : 1}
loss_fun, pred_fun, conv_parser = \
build_conv_deep_net(conv_arch_params, vanilla_net_params, model_params['L2_reg'])
num_weights = len(conv_parser)
predict_func, trained_weights, conv_training_curve = \
train_nn(pred_fun, loss_fun, num_weights, train_inputs, train_targets,
train_params, validation_aa=val_inputs, validation_raw_targets=val_targets)
plt.plot(range(0, 10*(len(conv_training_curve[1])), 10),
conv_training_curve[1], label='training rmse')
plt.plot(range(0, 10*(len(conv_training_curve[2])), 10),
conv_training_curve[2], label='validation rmse')
plt.xlabel('iteration')
plt.ylabel('training loss')
plt.title(task_params['target_name'])
plt.legend()
plt.show()
print_performance(predict_func)
test_predictions = predict_func(test_inputs)
return rmse(test_predictions, test_targets)
print "Task params", task_params
print
print "Starting neural fingerprint experiment..."
test_loss = run_conv_experiment()
print "Neural test RMSE:", test_loss
if __name__ == '__main__':
main()
| <filename>tests/peptest_milestone.py
""" Testing peptide deep convnet
Based on regression example from https://github.com/HIPS/neural-fingerprint
<NAME>"""
import autograd.numpy as np
import autograd.numpy.random as npr
from matplotlib import pyplot as plt
from scipy.stats.stats import pearsonr
from pepgraph import load_data_csv
from pepgraph import build_conv_deep_net
from pepgraph import normalize_array, adam
from pepgraph import build_batched_grad
from pepgraph.util import rmse
from autograd import grad
task_params = {'input_name' : 'sequence',
'target_name' : 'Log_IC50',
'conditions' : {'mhc' : 'HLA-A*02:02'
# ,'peptide_length' : 9},
},
'data_file' : '../data/bdata.20130222.mhci.csv'}
#task_params = {'input_name' : 'smiles',
# 'target_name' : 'measured log solubility in mols per litre',
# 'conditions' : {},
# 'data_file' : 'delaney.csv'}
# MHC HLA-A*02:02 all lengths:
N_train = 2400
N_val = 830
N_test = 830
# MHC HLA-A*02:02 only 9:
#N_train = 1450 #2400
#N_val = 490 #830
#N_test = 490 #830
# Delayney:
#N_train = 800
#N_val = 80
#N_test = 80
# TODO switch to percentage slicing
Pct_train = 0.6
Pct_val = 0.2
Pct_test = 0.2
model_params = dict(fp_length=60,
fp_depth=7, # The depth of the network equals the fingerprint radius.
conv_width=20, # Only the neural fps need this parameter.
h1_size=200, # Size of hidden layer of network on top of fps.
L2_reg=np.exp(-2))
train_params = dict(num_iters=2,
batch_size=100,
init_scale=np.exp(-4),
step_size=np.exp(-6))
# Define the architecture of the network that sits on top of the fingerprints.
vanilla_net_params = dict(
layer_sizes = [model_params['fp_length'], model_params['h1_size']], # One hidden layer.
normalize=True, L2_reg = model_params['L2_reg'], nll_func = rmse)
def train_nn(pred_fun, loss_fun, num_weights, train_smiles, train_raw_targets, train_params, seed=0,
validation_aa=None, validation_raw_targets=None):
"""loss_fun has inputs (weights, smiles, targets)"""
print "Total number of weights in the network:", num_weights
init_weights = npr.RandomState(seed).randn(num_weights) * train_params['init_scale']
num_print_examples = 100
train_targets, undo_norm = normalize_array(train_raw_targets)
training_curve = [[], [], []] # Test error, Val error
def callback(weights, iter):
if iter % 1 == 0:
print "max of weights", np.max(np.abs(weights))
train_preds = undo_norm(pred_fun(weights, train_smiles[:num_print_examples]))
cur_loss = loss_fun(weights, train_smiles[:num_print_examples], train_targets[:num_print_examples])
training_curve[0].append(cur_loss)
train_RMSE = rmse(train_preds, train_raw_targets[:num_print_examples])
training_curve[1].append(train_RMSE)
print "Iteration", iter, "loss", cur_loss,\
"train RMSE", train_RMSE,
if validation_aa is not None:
validation_preds = undo_norm(pred_fun(weights, validation_aa))
val_RMSE = rmse(validation_preds, validation_raw_targets)
training_curve[2].append(val_RMSE)
print "Validation RMSE", iter, ":", val_RMSE,
# Build gradient using autograd.
grad_fun = grad(loss_fun)
grad_fun_with_data = build_batched_grad(grad_fun, train_params['batch_size'],
train_smiles, train_targets)
# Optimize weights.
trained_weights = adam(grad_fun_with_data, init_weights, callback=callback,
num_iters=train_params['num_iters'], step_size=train_params['step_size'])
def predict_func(new_aa):
"""Returns to the original units that the raw targets were in."""
return undo_norm(pred_fun(trained_weights, new_aa))
return predict_func, trained_weights, training_curve
def main():
print "Loading data..."
# Example Data:
traindata, valdata, testdata = load_data_csv(
task_params['data_file'], (N_train, N_val, N_test),
# task_params['data_file'], (Pct_train, Pct_val, Pct_test), # TODO switch to percents
input_name=task_params['input_name'], target_name=task_params['target_name'],
conditions=task_params['conditions'])
train_inputs, train_targets = traindata
val_inputs, val_targets = valdata
test_inputs, test_targets = testdata
def print_performance(pred_func):
train_preds = pred_func(train_inputs)
val_preds = pred_func(val_inputs)
print "\nPerformance (RMSE) on " + task_params['target_name'] + ":"
print "Train RMSE:", rmse(train_preds, train_targets)
print "Test RMSE: ", rmse(val_preds, val_targets)
print "Test Pearson: ", pearsonr(val_preds, val_targets)
print "-" * 80
return rmse(val_preds, val_targets)
def run_conv_experiment():
conv_layer_sizes = [model_params['conv_width']] * model_params['fp_depth']
conv_arch_params = {'num_hidden_features' : conv_layer_sizes,
'fp_length' : model_params['fp_length'],
'normalize' : 1}
loss_fun, pred_fun, conv_parser = \
build_conv_deep_net(conv_arch_params, vanilla_net_params, model_params['L2_reg'])
num_weights = len(conv_parser)
predict_func, trained_weights, conv_training_curve = \
train_nn(pred_fun, loss_fun, num_weights, train_inputs, train_targets,
train_params, validation_aa=val_inputs, validation_raw_targets=val_targets)
plt.plot(range(0, 10*(len(conv_training_curve[1])), 10),
conv_training_curve[1], label='training rmse')
plt.plot(range(0, 10*(len(conv_training_curve[2])), 10),
conv_training_curve[2], label='validation rmse')
plt.xlabel('iteration')
plt.ylabel('training loss')
plt.title(task_params['target_name'])
plt.legend()
plt.show()
print_performance(predict_func)
test_predictions = predict_func(test_inputs)
return rmse(test_predictions, test_targets)
print "Task params", task_params
print
print "Starting neural fingerprint experiment..."
test_loss = run_conv_experiment()
print "Neural test RMSE:", test_loss
if __name__ == '__main__':
main()
| en | 0.707263 | Testing peptide deep convnet Based on regression example from https://github.com/HIPS/neural-fingerprint <NAME> # ,'peptide_length' : 9}, #task_params = {'input_name' : 'smiles', # 'target_name' : 'measured log solubility in mols per litre', # 'conditions' : {}, # 'data_file' : 'delaney.csv'} # MHC HLA-A*02:02 all lengths: # MHC HLA-A*02:02 only 9: #N_train = 1450 #2400 #N_val = 490 #830 #N_test = 490 #830 # Delayney: #N_train = 800 #N_val = 80 #N_test = 80 # TODO switch to percentage slicing # The depth of the network equals the fingerprint radius. # Only the neural fps need this parameter. # Size of hidden layer of network on top of fps. # Define the architecture of the network that sits on top of the fingerprints. # One hidden layer. loss_fun has inputs (weights, smiles, targets) # Test error, Val error # Build gradient using autograd. # Optimize weights. Returns to the original units that the raw targets were in. # Example Data: # task_params['data_file'], (Pct_train, Pct_val, Pct_test), # TODO switch to percents | 2.624941 | 3 |
recipes/msgpack-cxx/all/conanfile.py | wouterz/conan-center-index | 1 | 6617724 | from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
import os
required_conan_version = ">=1.36.0"
class MsgpackCXXConan(ConanFile):
name = "msgpack-cxx"
description = "The official C++ library for MessagePack"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/msgpack/msgpack-c"
topics = ("msgpack", "message-pack", "serialization")
license = "BSL-1.0"
no_copy_source = True
@property
def _source_subfolder(self):
return "source_subfolder"
@property
def _build_subfolder(self):
return "build_subfolder"
def validate(self):
if self.options["boost"].header_only == True:
raise ConanInvalidConfiguration("{} requires boost with header_only = False".format(self.name))
if self.options["boost"].without_chrono == True or \
self.options["boost"].without_context == True or \
self.options["boost"].without_system == True or \
self.options["boost"].without_timer == True:
raise ConanInvalidConfiguration("{} requires boost with chrono, context, system, timer enabled".format(self.name))
def requirements(self):
self.requires("boost/1.77.0")
def package_id(self):
self.info.header_only()
def source(self):
tools.get(**self.conan_data["sources"][self.version],
destination=self._source_subfolder, strip_root=True)
def package(self):
self.copy("LICENSE_1_0.txt", dst="licenses", src=self._source_subfolder)
self.copy("*.h", dst="include", src=os.path.join(self._source_subfolder, "include"))
self.copy("*.hpp", dst="include", src=os.path.join(self._source_subfolder, "include"))
def package_info(self):
self.cpp_info.filenames["cmake_find_package"] = "msgpack-cxx"
self.cpp_info.filenames["cmake_find_package_multi"] = "msgpack-cxx"
self.cpp_info.set_property("cmake_file_name", "msgpack-cxx")
self.cpp_info.names["cmake_find_package"] = "msgpack"
self.cpp_info.names["cmake_find_package_multi"] = "msgpack"
self.cpp_info.set_property("cmake_target_name", "msgpack")
self.cpp_info.components["msgpack"].names["cmake_find_package"] = "msgpack-cxx"
self.cpp_info.components["msgpack"].names["cmake_find_package_multi"] = "msgpack-cxx"
self.cpp_info.components["msgpack"].set_property("cmake_target_name", "msgpack-cxx")
self.cpp_info.components["msgpack"].set_property("pkg_config_name", "msgpack-cxx")
self.cpp_info.components["msgpack"].defines = ["MSGPACK_USE_BOOST"]
self.cpp_info.components["msgpack"].requires = ["boost::boost"]
| from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
import os
required_conan_version = ">=1.36.0"
class MsgpackCXXConan(ConanFile):
name = "msgpack-cxx"
description = "The official C++ library for MessagePack"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/msgpack/msgpack-c"
topics = ("msgpack", "message-pack", "serialization")
license = "BSL-1.0"
no_copy_source = True
@property
def _source_subfolder(self):
return "source_subfolder"
@property
def _build_subfolder(self):
return "build_subfolder"
def validate(self):
if self.options["boost"].header_only == True:
raise ConanInvalidConfiguration("{} requires boost with header_only = False".format(self.name))
if self.options["boost"].without_chrono == True or \
self.options["boost"].without_context == True or \
self.options["boost"].without_system == True or \
self.options["boost"].without_timer == True:
raise ConanInvalidConfiguration("{} requires boost with chrono, context, system, timer enabled".format(self.name))
def requirements(self):
self.requires("boost/1.77.0")
def package_id(self):
self.info.header_only()
def source(self):
tools.get(**self.conan_data["sources"][self.version],
destination=self._source_subfolder, strip_root=True)
def package(self):
self.copy("LICENSE_1_0.txt", dst="licenses", src=self._source_subfolder)
self.copy("*.h", dst="include", src=os.path.join(self._source_subfolder, "include"))
self.copy("*.hpp", dst="include", src=os.path.join(self._source_subfolder, "include"))
def package_info(self):
self.cpp_info.filenames["cmake_find_package"] = "msgpack-cxx"
self.cpp_info.filenames["cmake_find_package_multi"] = "msgpack-cxx"
self.cpp_info.set_property("cmake_file_name", "msgpack-cxx")
self.cpp_info.names["cmake_find_package"] = "msgpack"
self.cpp_info.names["cmake_find_package_multi"] = "msgpack"
self.cpp_info.set_property("cmake_target_name", "msgpack")
self.cpp_info.components["msgpack"].names["cmake_find_package"] = "msgpack-cxx"
self.cpp_info.components["msgpack"].names["cmake_find_package_multi"] = "msgpack-cxx"
self.cpp_info.components["msgpack"].set_property("cmake_target_name", "msgpack-cxx")
self.cpp_info.components["msgpack"].set_property("pkg_config_name", "msgpack-cxx")
self.cpp_info.components["msgpack"].defines = ["MSGPACK_USE_BOOST"]
self.cpp_info.components["msgpack"].requires = ["boost::boost"]
| none | 1 | 2.105665 | 2 | |
examples/simple.py | timjstewart/parcsv | 0 | 6617725 | <gh_stars>0
import sys
from typing import Dict, Any
import parcsv
class MyMapper(parcsv.Mapper):
def _map(self, x: Dict[str, Any]) -> Dict[str, Any]:
print("stdout output")
sys.stderr.write("stderr output")
return dict(a=1, b=2)
if __name__ == "__main__":
parcsv.process_files(MyMapper(["a", "b"]), sys.argv[1:])
| import sys
from typing import Dict, Any
import parcsv
class MyMapper(parcsv.Mapper):
def _map(self, x: Dict[str, Any]) -> Dict[str, Any]:
print("stdout output")
sys.stderr.write("stderr output")
return dict(a=1, b=2)
if __name__ == "__main__":
parcsv.process_files(MyMapper(["a", "b"]), sys.argv[1:]) | none | 1 | 2.684711 | 3 | |
src/metarl/sampler/__init__.py | neurips2020submission11699/metarl | 2 | 6617726 | <filename>src/metarl/sampler/__init__.py
"""Samplers which run agents in environments."""
from metarl.sampler.batch_sampler import BatchSampler
from metarl.sampler.default_worker import DefaultWorker
from metarl.sampler.is_sampler import ISSampler
from metarl.sampler.local_sampler import LocalSampler
from metarl.sampler.multiprocessing_sampler import MultiprocessingSampler
from metarl.sampler.off_policy_vectorized_sampler import (
OffPolicyVectorizedSampler)
from metarl.sampler.on_policy_vectorized_sampler import (
OnPolicyVectorizedSampler)
from metarl.sampler.parallel_vec_env_executor import ParallelVecEnvExecutor
from metarl.sampler.ray_sampler import RaySampler
from metarl.sampler.sampler import Sampler
from metarl.sampler.stateful_pool import singleton_pool
from metarl.sampler.vec_env_executor import VecEnvExecutor
from metarl.sampler.vec_worker import VecWorker
from metarl.sampler.worker import Worker
from metarl.sampler.worker_factory import WorkerFactory
__all__ = [
'BatchSampler', 'ISSampler', 'Sampler', 'singleton_pool', 'LocalSampler',
'RaySampler', 'MultiprocessingSampler', 'ParallelVecEnvExecutor',
'VecEnvExecutor', 'VecWorker', 'OffPolicyVectorizedSampler',
'OnPolicyVectorizedSampler', 'WorkerFactory', 'Worker', 'DefaultWorker'
]
| <filename>src/metarl/sampler/__init__.py
"""Samplers which run agents in environments."""
from metarl.sampler.batch_sampler import BatchSampler
from metarl.sampler.default_worker import DefaultWorker
from metarl.sampler.is_sampler import ISSampler
from metarl.sampler.local_sampler import LocalSampler
from metarl.sampler.multiprocessing_sampler import MultiprocessingSampler
from metarl.sampler.off_policy_vectorized_sampler import (
OffPolicyVectorizedSampler)
from metarl.sampler.on_policy_vectorized_sampler import (
OnPolicyVectorizedSampler)
from metarl.sampler.parallel_vec_env_executor import ParallelVecEnvExecutor
from metarl.sampler.ray_sampler import RaySampler
from metarl.sampler.sampler import Sampler
from metarl.sampler.stateful_pool import singleton_pool
from metarl.sampler.vec_env_executor import VecEnvExecutor
from metarl.sampler.vec_worker import VecWorker
from metarl.sampler.worker import Worker
from metarl.sampler.worker_factory import WorkerFactory
__all__ = [
'BatchSampler', 'ISSampler', 'Sampler', 'singleton_pool', 'LocalSampler',
'RaySampler', 'MultiprocessingSampler', 'ParallelVecEnvExecutor',
'VecEnvExecutor', 'VecWorker', 'OffPolicyVectorizedSampler',
'OnPolicyVectorizedSampler', 'WorkerFactory', 'Worker', 'DefaultWorker'
]
| en | 0.955905 | Samplers which run agents in environments. | 1.511294 | 2 |
ip-tools.py | InTostor/py-tools | 2 | 6617727 | import struct #INOP
import math #for future
import re
#Converts hexadecimal ipv6 to address, that look like ipv4
# Example: fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:18:e716:fbff is 10752.4568.4609.0.38443.24.59158.64511
def ipv6to4like(ipv6):
ipv6_arr = ipv6.split(":")
ipv6to4 = []
for i in range(0,len(ipv6_arr)):
if (ipv6_arr[i] == ''):
ipv6to4.insert(i, "0")
else:
dec = int(str(ipv6_arr[i]),16)
ipv6to4.insert(i, dec)
if len(ipv6to4)<8:
zeros = ipv6to4.index('0')
for i in range (0,8):
ipv6to4.insert(zeros,"0")
if len(ipv6to4)==8: break
return str('.'.join(map(str, ipv6to4)))
#Converts decimal ipv6 (from function above) to standart ipv6
# Example: 10752.4568.4609.0.38443.24.59158.64511 is fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:18:e716:fbff
def ipv4liketo6(ipv6_4):
ipv6_arr = ipv6_4.split(".")
ipv6to4 = []
for i in range(0,len(ipv6_arr)):
if (ipv6_arr[i] == '' or ipv6_arr[i] == 0):
ipv6to4.insert(i, '0')
else:
dec = hex(int(ipv6_arr[i])).split('x')[-1]
ipv6to4.insert(i, dec)
return str(':'.join(map(str, ipv6to4)))
#Finds delta (addresses range) between two ipv4 addresses
def ip_delta4(ip1,ip2):
ipv4_arr1, ipv4_arr2 = ip1.split("."), ip2.split(".")
for i in range(0,len(ipv4_arr1)):
ipv4_arr1[i] = "0"*(3-len(ipv4_arr1[i]))+ipv4_arr1[i]
for i in range(0,len(ipv4_arr2)):
ipv4_arr2[i] = "0"*(3-len(ipv4_arr2[i]))+ipv4_arr2[i]
ipv41=int(''.join(map(str, ipv4_arr1)))
ipv42=int(''.join(map(str, ipv4_arr2)))
delta = abs(ipv41-ipv42)
return delta
#Finds delta (addresses range) between two ipv6 addresses
def ip_delta6(ip1,ip2):
ip1, ip2 = ipv6to4like(ip1), ipv6to4like(ip2)
ipv4_arr1, ipv4_arr2 = ip1.split("."), ip2.split(".")
for i in range(0,len(ipv4_arr1)):
ipv4_arr1[i] = "0"*(5-len(ipv4_arr1[i]))+ipv4_arr1[i]
for i in range(0,len(ipv4_arr2)):
ipv4_arr1[i] = "0"*(5-len(ipv4_arr1[i]))+ipv4_arr1[i]
ipv41=int(''.join(map(str, ipv4_arr1)))
ipv42=int(''.join(map(str, ipv4_arr2)))
delta = abs(ipv41-ipv42)
return delta
# returns version of address
def ipv(ip):
f = ip.find(".")
s = ip.find(":")
if not(f or s): return -1
if f: return 4
if s: return 6
print(ipv6to4like("2fc00:e968:6179::de52:7100"))
print(ipv4liketo6("65286.00..0000.0000.0000.195"))
print(ip_delta4("192.168.0.1","192.168.0.24"))
print(ip_delta6("fdf8:f53e:61e4::18","fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:18:e716:fbff"))
print(ipv("192.168.0.1")) | import struct #INOP
import math #for future
import re
#Converts hexadecimal ipv6 to address, that look like ipv4
# Example: fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:18:e716:fbff is 10752.4568.4609.0.38443.24.59158.64511
def ipv6to4like(ipv6):
ipv6_arr = ipv6.split(":")
ipv6to4 = []
for i in range(0,len(ipv6_arr)):
if (ipv6_arr[i] == ''):
ipv6to4.insert(i, "0")
else:
dec = int(str(ipv6_arr[i]),16)
ipv6to4.insert(i, dec)
if len(ipv6to4)<8:
zeros = ipv6to4.index('0')
for i in range (0,8):
ipv6to4.insert(zeros,"0")
if len(ipv6to4)==8: break
return str('.'.join(map(str, ipv6to4)))
#Converts decimal ipv6 (from function above) to standart ipv6
# Example: 10752.4568.4609.0.38443.24.59158.64511 is fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:18:e716:fbff
def ipv4liketo6(ipv6_4):
ipv6_arr = ipv6_4.split(".")
ipv6to4 = []
for i in range(0,len(ipv6_arr)):
if (ipv6_arr[i] == '' or ipv6_arr[i] == 0):
ipv6to4.insert(i, '0')
else:
dec = hex(int(ipv6_arr[i])).split('x')[-1]
ipv6to4.insert(i, dec)
return str(':'.join(map(str, ipv6to4)))
#Finds delta (addresses range) between two ipv4 addresses
def ip_delta4(ip1,ip2):
ipv4_arr1, ipv4_arr2 = ip1.split("."), ip2.split(".")
for i in range(0,len(ipv4_arr1)):
ipv4_arr1[i] = "0"*(3-len(ipv4_arr1[i]))+ipv4_arr1[i]
for i in range(0,len(ipv4_arr2)):
ipv4_arr2[i] = "0"*(3-len(ipv4_arr2[i]))+ipv4_arr2[i]
ipv41=int(''.join(map(str, ipv4_arr1)))
ipv42=int(''.join(map(str, ipv4_arr2)))
delta = abs(ipv41-ipv42)
return delta
#Finds delta (addresses range) between two ipv6 addresses
def ip_delta6(ip1,ip2):
ip1, ip2 = ipv6to4like(ip1), ipv6to4like(ip2)
ipv4_arr1, ipv4_arr2 = ip1.split("."), ip2.split(".")
for i in range(0,len(ipv4_arr1)):
ipv4_arr1[i] = "0"*(5-len(ipv4_arr1[i]))+ipv4_arr1[i]
for i in range(0,len(ipv4_arr2)):
ipv4_arr1[i] = "0"*(5-len(ipv4_arr1[i]))+ipv4_arr1[i]
ipv41=int(''.join(map(str, ipv4_arr1)))
ipv42=int(''.join(map(str, ipv4_arr2)))
delta = abs(ipv41-ipv42)
return delta
# returns version of address
def ipv(ip):
f = ip.find(".")
s = ip.find(":")
if not(f or s): return -1
if f: return 4
if s: return 6
print(ipv6to4like("2fc00:e968:6179::de52:7100"))
print(ipv4liketo6("65286.00..0000.0000.0000.195"))
print(ip_delta4("192.168.0.1","192.168.0.24"))
print(ip_delta6("fdf8:f53e:61e4::18","fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:18:e716:fbff"))
print(ipv("192.168.0.1")) | en | 0.721364 | #INOP #for future #Converts hexadecimal ipv6 to address, that look like ipv4 # Example: fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:18:e716:fbff is 10752.4568.4609.0.38443.24.59158.64511 #Converts decimal ipv6 (from function above) to standart ipv6 # Example: 10752.4568.4609.0.38443.24.59158.64511 is fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:18:e716:fbff #Finds delta (addresses range) between two ipv4 addresses #Finds delta (addresses range) between two ipv6 addresses # returns version of address | 3.318485 | 3 |
profiles/api/throttle.py | chandru-shane/django-forum-project | 0 | 6617728 | from rest_framework import throttling
class ChangePasswordThrottle(throttling.UserRateThrottle):
scope = 'change_password' | from rest_framework import throttling
class ChangePasswordThrottle(throttling.UserRateThrottle):
scope = 'change_password' | none | 1 | 1.325421 | 1 | |
symposion/proposals/migrations/0003_set_cached_tags.py | azkarmoulana/pycon | 154 | 6617729 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def no_op(apps, schema_editor):
pass
def set_cached_tags(apps, schema_editor):
TaggedItem = apps.get_model('taggit', 'TaggedItem')
ContentType = apps.get_model('contenttypes', 'ContentType')
to_migrate = [
('pycon', 'PyConTalkProposal'),
('pycon', 'PyConLightningTalkProposal'),
('pycon', 'PyConTutorialProposal'),
('pycon', 'PyConPosterProposal'),
('pycon', 'PyConSponsorTutorialProposal'),
('pycon', 'PyConOpenSpaceProposal'),
]
for app_label, model_name in to_migrate:
model = apps.get_model(app_label, model_name)
try:
ct = ContentType.objects.get(app_label=app_label, model__iexact=model_name)
except ContentType.DoesNotExist:
# If the content type for a proposal model doesn't exist, this
# must be the initial migration, with no data. So, nothing to
# cache tags for anyway.
pass
else:
for proposal in model.objects.all():
items = TaggedItem.objects.filter(
object_id=proposal.id,
content_type_id=ct.id,
)
names = items.values_list('tag__name', flat=True)
proposal.cached_tags = ', '.join(names)
proposal.save()
class Migration(migrations.Migration):
dependencies = [
('proposals', '0002_proposalbase_cached_tags'),
('taggit', '0001_initial'),
('contenttypes', '0001_initial'),
('pycon', '0001_initial'),
]
operations = [
migrations.RunPython(set_cached_tags, no_op),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def no_op(apps, schema_editor):
pass
def set_cached_tags(apps, schema_editor):
TaggedItem = apps.get_model('taggit', 'TaggedItem')
ContentType = apps.get_model('contenttypes', 'ContentType')
to_migrate = [
('pycon', 'PyConTalkProposal'),
('pycon', 'PyConLightningTalkProposal'),
('pycon', 'PyConTutorialProposal'),
('pycon', 'PyConPosterProposal'),
('pycon', 'PyConSponsorTutorialProposal'),
('pycon', 'PyConOpenSpaceProposal'),
]
for app_label, model_name in to_migrate:
model = apps.get_model(app_label, model_name)
try:
ct = ContentType.objects.get(app_label=app_label, model__iexact=model_name)
except ContentType.DoesNotExist:
# If the content type for a proposal model doesn't exist, this
# must be the initial migration, with no data. So, nothing to
# cache tags for anyway.
pass
else:
for proposal in model.objects.all():
items = TaggedItem.objects.filter(
object_id=proposal.id,
content_type_id=ct.id,
)
names = items.values_list('tag__name', flat=True)
proposal.cached_tags = ', '.join(names)
proposal.save()
class Migration(migrations.Migration):
dependencies = [
('proposals', '0002_proposalbase_cached_tags'),
('taggit', '0001_initial'),
('contenttypes', '0001_initial'),
('pycon', '0001_initial'),
]
operations = [
migrations.RunPython(set_cached_tags, no_op),
]
| en | 0.878159 | # -*- coding: utf-8 -*- # If the content type for a proposal model doesn't exist, this # must be the initial migration, with no data. So, nothing to # cache tags for anyway. | 1.960711 | 2 |
Desafios/Desafio013.py | julianascimentosantos/cursoemvideo-python3 | 0 | 6617730 | s = float(input('Qual é o salário do funcionário? R$ '))
a = s + (s*0.15)
print('O salário era R$ {:.2f} e com o aumento foi para R$ {:.2f}.'.format(s, a))
| s = float(input('Qual é o salário do funcionário? R$ '))
a = s + (s*0.15)
print('O salário era R$ {:.2f} e com o aumento foi para R$ {:.2f}.'.format(s, a))
| none | 1 | 3.784432 | 4 | |
pointnet/vanilla/model.py | carmelocs/pointnet.pytorch | 0 | 6617731 | <gh_stars>0
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import numpy as np
# Spatial Transform Net 3d
class STN3d(nn.Module):
def __init__(self):
super(STN3d, self).__init__()
self.conv1 = nn.Conv1d(3, 64, 1)
self.conv2 = nn.Conv1d(64, 128, 1)
self.conv3 = nn.Conv1d(128, 1024, 1)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 9)
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
self.bn4 = nn.BatchNorm1d(512)
self.bn5 = nn.BatchNorm1d(256)
def forward(self, x):
batchsize = x.size()[0]
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = torch.max(x, 2, keepdim=True)[0] # [0]只返回最大值的value
x = x.view(-1, 1024) # n*1024
x = F.relu(self.bn4(self.fc1(x)))
x = F.relu(self.bn5(self.fc2(x)))
x = self.fc3(x)
iden = Variable(torch.from_numpy(np.eye(3).flatten().astype(np.float32))).view(1,9).repeat(batchsize,1)
if x.is_cuda:
iden = iden.cuda()
x = x + iden
x = x.view(-1, 3, 3)
return x
# feature extraction net 64->128->1024
class FeatNet(nn.Module):
def __init__(self):
super(FeatNet, self).__init__()
self.stn = STN3d()
self.conv1 = nn.Conv1d(3, 64, 1)
self.conv2 = nn.Conv1d(64, 128, 1)
self.conv3 = nn.Conv1d(128, 1024, 1)
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
def forward(self, x):
n_pts = x.size()[2]
trans_matrix3d = self.stn(x)
x = x.transpose(2,1)
# Input transform, bmm performs a batch matrix-matrix product of matrices
x = torch.bmm(x, trans_matrix3d)
x = x.transpose(2,1)
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = self.bn3(self.conv3(x))
x = torch.max(x,2, keepdim=True)[0]
x = x.view(-1, 1024)
return x, trans_matrix3d
class PointNetCls(nn.Module):
def __init__(self, k=40):
super(PointNetCls, self).__init__()
self.feature = FeatNet()
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, k) # k = num_classes
self.dropout = nn.Dropout(p=0.3)
self.bn1 = nn.BatchNorm1d(512)
self.bn2 = nn.BatchNorm1d(256)
def forward(self, x):
x, trans_matrix3d = self.feature(x)
x = F.relu(self.bn1(self.fc1(x)))
x = F.relu(self.bn2(self.dropout(self.fc2(x))))
x = self.fc3(x)
return F.log_softmax(x, dim=1), trans_matrix3d
if __name__ == '__main__':
sim_data = torch.rand(32, 3, 2500)
trans_matrix3d = STN3d()
out = trans_matrix3d(sim_data)
print("input transform matrix size ", out.size())
pt_feat = FeatNet()
out, _ = pt_feat(sim_data)
print('global feature size: ', out.size())
cls = PointNetCls()
out, _ = cls(sim_data)
print('class matrix: ', out.size()) | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import numpy as np
# Spatial Transform Net 3d
class STN3d(nn.Module):
def __init__(self):
super(STN3d, self).__init__()
self.conv1 = nn.Conv1d(3, 64, 1)
self.conv2 = nn.Conv1d(64, 128, 1)
self.conv3 = nn.Conv1d(128, 1024, 1)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 9)
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
self.bn4 = nn.BatchNorm1d(512)
self.bn5 = nn.BatchNorm1d(256)
def forward(self, x):
batchsize = x.size()[0]
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = torch.max(x, 2, keepdim=True)[0] # [0]只返回最大值的value
x = x.view(-1, 1024) # n*1024
x = F.relu(self.bn4(self.fc1(x)))
x = F.relu(self.bn5(self.fc2(x)))
x = self.fc3(x)
iden = Variable(torch.from_numpy(np.eye(3).flatten().astype(np.float32))).view(1,9).repeat(batchsize,1)
if x.is_cuda:
iden = iden.cuda()
x = x + iden
x = x.view(-1, 3, 3)
return x
# feature extraction net 64->128->1024
class FeatNet(nn.Module):
def __init__(self):
super(FeatNet, self).__init__()
self.stn = STN3d()
self.conv1 = nn.Conv1d(3, 64, 1)
self.conv2 = nn.Conv1d(64, 128, 1)
self.conv3 = nn.Conv1d(128, 1024, 1)
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = nn.BatchNorm1d(128)
self.bn3 = nn.BatchNorm1d(1024)
def forward(self, x):
n_pts = x.size()[2]
trans_matrix3d = self.stn(x)
x = x.transpose(2,1)
# Input transform, bmm performs a batch matrix-matrix product of matrices
x = torch.bmm(x, trans_matrix3d)
x = x.transpose(2,1)
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = self.bn3(self.conv3(x))
x = torch.max(x,2, keepdim=True)[0]
x = x.view(-1, 1024)
return x, trans_matrix3d
class PointNetCls(nn.Module):
def __init__(self, k=40):
super(PointNetCls, self).__init__()
self.feature = FeatNet()
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, k) # k = num_classes
self.dropout = nn.Dropout(p=0.3)
self.bn1 = nn.BatchNorm1d(512)
self.bn2 = nn.BatchNorm1d(256)
def forward(self, x):
x, trans_matrix3d = self.feature(x)
x = F.relu(self.bn1(self.fc1(x)))
x = F.relu(self.bn2(self.dropout(self.fc2(x))))
x = self.fc3(x)
return F.log_softmax(x, dim=1), trans_matrix3d
if __name__ == '__main__':
sim_data = torch.rand(32, 3, 2500)
trans_matrix3d = STN3d()
out = trans_matrix3d(sim_data)
print("input transform matrix size ", out.size())
pt_feat = FeatNet()
out, _ = pt_feat(sim_data)
print('global feature size: ', out.size())
cls = PointNetCls()
out, _ = cls(sim_data)
print('class matrix: ', out.size()) | en | 0.606891 | # Spatial Transform Net 3d # [0]只返回最大值的value # n*1024 # feature extraction net 64->128->1024 # Input transform, bmm performs a batch matrix-matrix product of matrices # k = num_classes | 2.489892 | 2 |
Desenvolvimento Python para Redes e Sistemas Operacionais/Etapa9/etapa9-MultiplosProcessos-2.py | LC-ardovino/INFNET | 0 | 6617732 | <reponame>LC-ardovino/INFNET
import threading, time, random
def somaThread(lista,soma_parcial,id):
soma = 0
for i in lista:
soma = soma + i
soma_parcial[id] = soma
N = int(input("Entre com o tamanho do vetor:"))
# Gera lista com valores aleatórios
lista = []
for i in range(N):
lista.append(random.randint(-50,51))
Nthreads = 4 # Número de threads a ser criado
#Captura tempo inicial
t_inicio = float(time.time())
#Vetor para salvar a soma parcial de cada thread
soma_parcial =Nthreads * [0]
lista_threads = []
for i in range(Nthreads):
ini = i * int(N/Nthreads)
fim = (i + 1)*int(N/Nthreads)
t = threading.Thread(target=somaThread, args=(lista[ini:fim],soma_parcial,i))
t.start()
lista_threads.append(t)
for t in lista_threads:
t.join()
soma = 0
for i in soma_parcial:
soma = soma + i
t_fim = float(time.time())
print(f"Soma:{soma}")
print(f"Tempo total {t_fim - t_inicio}") | import threading, time, random
def somaThread(lista,soma_parcial,id):
soma = 0
for i in lista:
soma = soma + i
soma_parcial[id] = soma
N = int(input("Entre com o tamanho do vetor:"))
# Gera lista com valores aleatórios
lista = []
for i in range(N):
lista.append(random.randint(-50,51))
Nthreads = 4 # Número de threads a ser criado
#Captura tempo inicial
t_inicio = float(time.time())
#Vetor para salvar a soma parcial de cada thread
soma_parcial =Nthreads * [0]
lista_threads = []
for i in range(Nthreads):
ini = i * int(N/Nthreads)
fim = (i + 1)*int(N/Nthreads)
t = threading.Thread(target=somaThread, args=(lista[ini:fim],soma_parcial,i))
t.start()
lista_threads.append(t)
for t in lista_threads:
t.join()
soma = 0
for i in soma_parcial:
soma = soma + i
t_fim = float(time.time())
print(f"Soma:{soma}")
print(f"Tempo total {t_fim - t_inicio}") | pt | 0.741728 | # Gera lista com valores aleatórios # Número de threads a ser criado #Captura tempo inicial #Vetor para salvar a soma parcial de cada thread | 3.400765 | 3 |
Harmful/Bsod.py | Devtion/CrazyPy | 2 | 6617733 |
# Import modules
from ctypes import byref, c_bool, windll
from ctypes.wintypes import DWORD
__t1 = c_bool()
__t2 = DWORD()
""" Make blue screen of death """
def bsod():
windll.ntdll.RtlAdjustPrivilege(19, 1, 0, byref(__t1))
windll.ntdll.NtRaiseHardError(0xc0000022, 0, 0, 0, 6, byref(__t2)) |
# Import modules
from ctypes import byref, c_bool, windll
from ctypes.wintypes import DWORD
__t1 = c_bool()
__t2 = DWORD()
""" Make blue screen of death """
def bsod():
windll.ntdll.RtlAdjustPrivilege(19, 1, 0, byref(__t1))
windll.ntdll.NtRaiseHardError(0xc0000022, 0, 0, 0, 6, byref(__t2)) | en | 0.429325 | # Import modules Make blue screen of death | 2.212367 | 2 |
read_ckpt.py | llfl/pytorch-cifar | 0 | 6617734 | import torch
import os
print('{:^10s} | {:^9s} | {:^6s} | {:^9s}'.format('name', 'param', 'acc', 'epoch'))
print('-------------------------------------------')
for root, dirs, files in os.walk("./checkpoint", topdown=False):
for name in files:
surffix = os.path.splitext(name)[-1]
if surffix == '.pth':
ckpt = torch.load(os.path.join(root, name))
print('{:>10s} | {:>9d} | {:0<2.2f}% | epoch {}'.format(ckpt['name'], ckpt['total_param'], ckpt['acc'], ckpt['epoch'])) | import torch
import os
print('{:^10s} | {:^9s} | {:^6s} | {:^9s}'.format('name', 'param', 'acc', 'epoch'))
print('-------------------------------------------')
for root, dirs, files in os.walk("./checkpoint", topdown=False):
for name in files:
surffix = os.path.splitext(name)[-1]
if surffix == '.pth':
ckpt = torch.load(os.path.join(root, name))
print('{:>10s} | {:>9d} | {:0<2.2f}% | epoch {}'.format(ckpt['name'], ckpt['total_param'], ckpt['acc'], ckpt['epoch'])) | none | 1 | 2.234909 | 2 | |
job_search/repository/jobs/sqlite_job_repository.py | reaper47/job-search-aggregator | 1 | 6617735 | from sqlalchemy import create_engine, exc, desc
from sqlalchemy.orm import sessionmaker
from job_search.domain.jobs.job_repository import JobRepository
import job_search.repository.jobs.entities.job_entity as entities
from job_search.repository.jobs.job_assembler import JobAssembler
from job_search.repository.jobs.job_entity_factory import JobEntityFactory
from config import Config
class SQLiteJobRepository(JobRepository):
def __init__(self):
engine = create_engine(Config.SQLITE_DATABASE_URI, echo=Config.SQLALCHEMY_ECHO)
Session = sessionmaker(bind=engine)
self.session = Session()
self.entity_factory = JobEntityFactory(self)
self.assembler = JobAssembler()
def persist(self, job):
job_entity = self.entity_factory.create_job_entity(job)
try:
self.session.add(job_entity)
self.session.commit()
except exc.IntegrityError:
self.session.rollback()
print(f"Job '{job_entity.id}' already exists in the database.")
def load(self, job_id):
try:
job_found = (self.session.query(entities.JobEntity)
.filter_by(id=job_id)
.first())
return self.assembler.to_domain_object(job_found)
except AttributeError:
return None
def load_all_jobs(self):
all_jobs = (self.session.query(entities.JobEntity)
.order_by(desc(entities.JobEntity.id))
.all())
return [self.assembler.to_domain_object(x) for x in all_jobs]
def find_title(self, title):
return self.session.query(entities.TitleEntity).filter_by(name=title).first()
def find_company(self, company):
return self.session.query(entities.CompanyEntity).filter_by(name=company).first()
def find_location(self, location):
try:
city_entity = self.find_city(location.city)
state_entity = self.find_state(location.state)
country_entity = self.find_country(location.country)
location_entity = (self.session.query(entities.LocationEntity)
.filter_by(city_id=city_entity.id,
state_id=state_entity.id,
country_id=country_entity.id)
.first())
return location_entity
except AttributeError:
return None
def find_city(self, city):
return self.session.query(entities.CityEntity).filter_by(name=city).first()
def find_state(self, state):
return self.session.query(entities.StateEntity).filter_by(name=state).first()
def find_country(self, country):
return self.session.query(entities.CountryEntity).filter_by(name=country).first()
def find_contact_info(self, info):
try:
name_entity = self.find_contact_name(info.contact)
email_entity = self.find_contact_email(info.email)
website_entity = self.find_contact_website(info.website)
contact_info_entity = (self.session.query(entities.ContactInfoEntity)
.filter_by(contact_id=name_entity.id,
email_id=email_entity.id,
website_id=website_entity.id)
.first())
return contact_info_entity
except AttributeError:
return None
def find_contact_name(self, name):
return self.session.query(entities.ContactNameEntity).filter_by(name=name).first()
def find_contact_email(self, email):
return self.session.query(entities.ContactEmailEntity).filter_by(name=email).first()
def find_contact_website(self, website):
return self.session.query(entities.ContactWebsiteEntity).filter_by(name=website).first()
def find_restrictions(self, restrictions):
found, not_found = [], []
for name in restrictions:
name_entity = (self.session.query(entities.RestrictionNameEntity)
.filter_by(name=name)
.first())
if name_entity is None:
not_found.append(name)
else:
restriction_entity = (self.session.query(entities.RestrictionEntity)
.filter_by(name_id=name_entity.id)
.first())
found.append(restriction_entity)
return {'found': found, 'not_found': not_found}
def find_requirements(self, requirements):
found, not_found = [], []
for name in requirements:
name_entity = (self.session.query(entities.RequirementNameEntity)
.filter_by(name=name)
.first())
if name_entity is None:
not_found.append(name)
else:
requirement_entity = (self.session.query(entities.RequirementEntity)
.filter_by(name_id=name_entity.id)
.first())
found.append(requirement_entity)
return {'found': found, 'not_found': not_found}
def find_source(self, source):
return self.session.query(entities.SourceEntity).filter_by(name=source).first()
| from sqlalchemy import create_engine, exc, desc
from sqlalchemy.orm import sessionmaker
from job_search.domain.jobs.job_repository import JobRepository
import job_search.repository.jobs.entities.job_entity as entities
from job_search.repository.jobs.job_assembler import JobAssembler
from job_search.repository.jobs.job_entity_factory import JobEntityFactory
from config import Config
class SQLiteJobRepository(JobRepository):
def __init__(self):
engine = create_engine(Config.SQLITE_DATABASE_URI, echo=Config.SQLALCHEMY_ECHO)
Session = sessionmaker(bind=engine)
self.session = Session()
self.entity_factory = JobEntityFactory(self)
self.assembler = JobAssembler()
def persist(self, job):
job_entity = self.entity_factory.create_job_entity(job)
try:
self.session.add(job_entity)
self.session.commit()
except exc.IntegrityError:
self.session.rollback()
print(f"Job '{job_entity.id}' already exists in the database.")
def load(self, job_id):
try:
job_found = (self.session.query(entities.JobEntity)
.filter_by(id=job_id)
.first())
return self.assembler.to_domain_object(job_found)
except AttributeError:
return None
def load_all_jobs(self):
all_jobs = (self.session.query(entities.JobEntity)
.order_by(desc(entities.JobEntity.id))
.all())
return [self.assembler.to_domain_object(x) for x in all_jobs]
def find_title(self, title):
return self.session.query(entities.TitleEntity).filter_by(name=title).first()
def find_company(self, company):
return self.session.query(entities.CompanyEntity).filter_by(name=company).first()
def find_location(self, location):
try:
city_entity = self.find_city(location.city)
state_entity = self.find_state(location.state)
country_entity = self.find_country(location.country)
location_entity = (self.session.query(entities.LocationEntity)
.filter_by(city_id=city_entity.id,
state_id=state_entity.id,
country_id=country_entity.id)
.first())
return location_entity
except AttributeError:
return None
def find_city(self, city):
return self.session.query(entities.CityEntity).filter_by(name=city).first()
def find_state(self, state):
return self.session.query(entities.StateEntity).filter_by(name=state).first()
def find_country(self, country):
return self.session.query(entities.CountryEntity).filter_by(name=country).first()
def find_contact_info(self, info):
try:
name_entity = self.find_contact_name(info.contact)
email_entity = self.find_contact_email(info.email)
website_entity = self.find_contact_website(info.website)
contact_info_entity = (self.session.query(entities.ContactInfoEntity)
.filter_by(contact_id=name_entity.id,
email_id=email_entity.id,
website_id=website_entity.id)
.first())
return contact_info_entity
except AttributeError:
return None
def find_contact_name(self, name):
return self.session.query(entities.ContactNameEntity).filter_by(name=name).first()
def find_contact_email(self, email):
return self.session.query(entities.ContactEmailEntity).filter_by(name=email).first()
def find_contact_website(self, website):
return self.session.query(entities.ContactWebsiteEntity).filter_by(name=website).first()
def find_restrictions(self, restrictions):
found, not_found = [], []
for name in restrictions:
name_entity = (self.session.query(entities.RestrictionNameEntity)
.filter_by(name=name)
.first())
if name_entity is None:
not_found.append(name)
else:
restriction_entity = (self.session.query(entities.RestrictionEntity)
.filter_by(name_id=name_entity.id)
.first())
found.append(restriction_entity)
return {'found': found, 'not_found': not_found}
def find_requirements(self, requirements):
found, not_found = [], []
for name in requirements:
name_entity = (self.session.query(entities.RequirementNameEntity)
.filter_by(name=name)
.first())
if name_entity is None:
not_found.append(name)
else:
requirement_entity = (self.session.query(entities.RequirementEntity)
.filter_by(name_id=name_entity.id)
.first())
found.append(requirement_entity)
return {'found': found, 'not_found': not_found}
def find_source(self, source):
return self.session.query(entities.SourceEntity).filter_by(name=source).first()
| none | 1 | 2.61665 | 3 | |
src/main.py | fmudrunek/github-slack-pr-notifier | 0 | 6617736 | from pathlib import Path
from typing import Dict, List
from notifier.pull_request_fetcher import PullRequestFetcher
import notifier.properties as properties
from notifier.repository import RepositoryInfo
from notifier.slack_notifier import SlackNotifier
from notifier.summary_formatter import RepositorySummaryFormatter
# TODO rewrite to __main__.py
def main():
print("Reading config")
config_path = Path(__file__).resolve().parent / 'resources' / 'config.json'
slack_repositories_config = properties.read_config(config_path)
print(f"Fetching data from {properties.get_github_api_url()}")
fetcher = PullRequestFetcher(properties.get_github_api_url(),
properties.get_github_token())
slack_repositories = {channel: list(map(fetcher.get_repository_info, repository_names))
for (channel, repository_names) in slack_repositories_config.items()}
filtered = __filter_non_empty(slack_repositories)
slack_notifier = SlackNotifier("Open Pull Requests",
properties.get_slack_bearer_token(),
RepositorySummaryFormatter())
for (channel, repositories) in filtered.items():
slack_notifier.send_message(channel, repositories)
def __filter_non_empty(channel_to_repository: Dict[str, List[RepositoryInfo]]) -> Dict[str, List[RepositoryInfo]]:
return {
channel: [repo for repo in repositories if repo.pulls] # filter repositories with some PRs
for (channel, repositories) in channel_to_repository.items() if any(repo.pulls for repo in repositories)
# only add channel if it has at least one repo with PRs
}
if __name__ == "__main__":
main()
| from pathlib import Path
from typing import Dict, List
from notifier.pull_request_fetcher import PullRequestFetcher
import notifier.properties as properties
from notifier.repository import RepositoryInfo
from notifier.slack_notifier import SlackNotifier
from notifier.summary_formatter import RepositorySummaryFormatter
# TODO rewrite to __main__.py
def main():
print("Reading config")
config_path = Path(__file__).resolve().parent / 'resources' / 'config.json'
slack_repositories_config = properties.read_config(config_path)
print(f"Fetching data from {properties.get_github_api_url()}")
fetcher = PullRequestFetcher(properties.get_github_api_url(),
properties.get_github_token())
slack_repositories = {channel: list(map(fetcher.get_repository_info, repository_names))
for (channel, repository_names) in slack_repositories_config.items()}
filtered = __filter_non_empty(slack_repositories)
slack_notifier = SlackNotifier("Open Pull Requests",
properties.get_slack_bearer_token(),
RepositorySummaryFormatter())
for (channel, repositories) in filtered.items():
slack_notifier.send_message(channel, repositories)
def __filter_non_empty(channel_to_repository: Dict[str, List[RepositoryInfo]]) -> Dict[str, List[RepositoryInfo]]:
return {
channel: [repo for repo in repositories if repo.pulls] # filter repositories with some PRs
for (channel, repositories) in channel_to_repository.items() if any(repo.pulls for repo in repositories)
# only add channel if it has at least one repo with PRs
}
if __name__ == "__main__":
main()
| en | 0.933459 | # TODO rewrite to __main__.py # filter repositories with some PRs # only add channel if it has at least one repo with PRs | 2.478366 | 2 |
applications/app2/server.py | Markcial/microservices-ecosystem-sample | 0 | 6617737 | from flask import Flask, request, render_template, Response
import requests
import json
app = Flask(__name__)
allowed_objects = [
'user', 'note', 'phone'
]
def get(object, oid=None):
path = object
if oid is not None:
path += "/%s" % oid
resp = requests.get('http://www.api-ep.com/%s' % path)
return resp.json()
def post(object, oid=None):
path = object
if oid is not None:
path += "/%s" % oid
resp = requests.post('http://www.api-ep.com/%s' % path, request.form)
app.logger.debug(resp.text)
return resp.json()
def delete(object, oid):
pass
@app.route("/")
def main():
users = get('@user')
notes = get('@note')
phones = get('@phone')
return render_template('index.html', users=users, notes=notes, phones=phones)
@app.route("/<object>", methods=["GET", "POST", "DELETE"])
@app.route("/<object>/<int:oid>", methods=["GET", "POST", "DELETE"])
def rest_endpoint(object, oid=None):
if object not in allowed_objects:
return 'Not found', 404
if request.method == 'GET':
obj = get('@%s' % object, oid)
return Response(json.dumps(obj), mimetype='application/json')
elif request.method == 'POST':
obj = post('@%s' % object, oid)
return Response(json.dumps(obj), mimetype='application/json')
elif request.method == 'DELETE':
delete('@%s' % object, oid)
return '', 204
return '', 403 | from flask import Flask, request, render_template, Response
import requests
import json
app = Flask(__name__)
allowed_objects = [
'user', 'note', 'phone'
]
def get(object, oid=None):
path = object
if oid is not None:
path += "/%s" % oid
resp = requests.get('http://www.api-ep.com/%s' % path)
return resp.json()
def post(object, oid=None):
path = object
if oid is not None:
path += "/%s" % oid
resp = requests.post('http://www.api-ep.com/%s' % path, request.form)
app.logger.debug(resp.text)
return resp.json()
def delete(object, oid):
pass
@app.route("/")
def main():
users = get('@user')
notes = get('@note')
phones = get('@phone')
return render_template('index.html', users=users, notes=notes, phones=phones)
@app.route("/<object>", methods=["GET", "POST", "DELETE"])
@app.route("/<object>/<int:oid>", methods=["GET", "POST", "DELETE"])
def rest_endpoint(object, oid=None):
if object not in allowed_objects:
return 'Not found', 404
if request.method == 'GET':
obj = get('@%s' % object, oid)
return Response(json.dumps(obj), mimetype='application/json')
elif request.method == 'POST':
obj = post('@%s' % object, oid)
return Response(json.dumps(obj), mimetype='application/json')
elif request.method == 'DELETE':
delete('@%s' % object, oid)
return '', 204
return '', 403 | none | 1 | 2.721934 | 3 | |
namubufferiapp/migrations/0003_auto_20170117_1850.py | AS-kilta/namubufferi | 1 | 6617738 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-01-17 18:50
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('namubufferiapp', '0002_auto_20170115_1437'),
]
operations = [
migrations.AlterField(
model_name='account',
name='magic_token_ttl',
field=models.DateTimeField(default=datetime.datetime(2017, 1, 17, 19, 5, 20, 87978, tzinfo=utc)),
),
migrations.AlterField(
model_name='usertag',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-01-17 18:50
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('namubufferiapp', '0002_auto_20170115_1437'),
]
operations = [
migrations.AlterField(
model_name='account',
name='magic_token_ttl',
field=models.DateTimeField(default=datetime.datetime(2017, 1, 17, 19, 5, 20, 87978, tzinfo=utc)),
),
migrations.AlterField(
model_name='usertag',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
| en | 0.823794 | # -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-01-17 18:50 | 1.67115 | 2 |
apps/crawlable/middleware.py | jfterpstra/onepercentclub-site | 7 | 6617739 | import logging
from bluebottle.fundraisers.models import FundRaiser
from apps.projects.models import Project
from apps.tasks.models import Task
from django.http.response import HttpResponsePermanentRedirect
from django.template.response import SimpleTemplateResponse
import re
import time
import os
import urllib
import urlparse
import tempfile
from django.http import HttpResponse, HttpResponseServerError
from django.conf import settings
from django.utils import html as html_utils
from django.core import cache
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.common.utils import is_connectable
from selenium.webdriver.phantomjs.webdriver import WebDriver
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
logger = logging.getLogger(__name__)
HASHBANG = '#!'
ESCAPED_FRAGMENT = '_escaped_fragment_'
CACHE_PREFIX = '_share_'
class DedicatedWebDriver(RemoteWebDriver):
"""
Wrapper to communicate with a dedicated PhantomJS through Ghostdriver.
If you have a phantomjs instance running at all times, you can use this dedicated webdriver to communicate with it.
"""
def __init__(self, port=None, desired_capabilities=DesiredCapabilities.PHANTOMJS):
if port is None:
port = 8910
class DummyService():
"""Dummy service to accept the same calls as the PhantomJS webdriver."""
def __init__(self, port):
self.port = port
@property
def service_url(self):
return 'http://localhost:%d/wd/hub' % port
def stop(self, *args, **kwargs):
pass
self.service = DummyService(port)
# Start the remote web driver.
try:
RemoteWebDriver.__init__(self,
command_executor=self.service.service_url,
desired_capabilities=desired_capabilities)
except:
self.quit()
raise
self._is_remote = False
class WebCache(object):
"""
Class to make sure the web driver is lazily loaded. For regular requests, the driver should not be instantiated
because it significantly slows down the request/response cycle (it can easily take 10 seconds to start).
"""
_web_driver = None
def __init__(self):
if hasattr(settings, 'CRAWLABLE_PHANTOMJS_ARGS') and settings.CRAWLABLE_PHANTOMJS_ARGS:
service_args = settings.CRAWLABLE_PHANTOMJS_ARGS[:]
else:
service_args = [
'--load-images=false',
'--disk-cache=true',
'--local-storage-path=%s' % os.path.join(tempfile.gettempdir(), 'phantomjs')
]
self.service_args = service_args
def get_driver(self):
"""
Only creates the driver if not present and returns it.
:return: ``WebDriver`` instance.
"""
# Dedicated mode
if hasattr(settings, 'CRAWLABLE_PHANTOMJS_DEDICATED_MODE') and settings.CRAWLABLE_PHANTOMJS_DEDICATED_MODE:
if not self._web_driver:
self._web_driver = DedicatedWebDriver(
port=getattr(settings, 'CRAWLABLE_PHANTOMJS_DEDICATED_PORT', 8910)
)
elif not is_connectable(self._web_driver.service.port):
raise RuntimeError('Cannot connect to dedicated PhantomJS instance on: %s' %
self._web_driver.service.service_url)
# Instance based mode (more for testing purposes). When debugging, you can even replace the PhantomJS webdriver
# with firefox and remove the arguments to the web driver constructor below.
else:
if not self._web_driver:
self._web_driver = WebDriver(service_args=self.service_args)
elif not is_connectable(self._web_driver.service.port):
self._web_driver.service.stop()
self._web_driver = WebDriver(service_args=self.service_args)
# Make sure it doesn't time out.
self._web_driver.set_script_timeout(30)
return self._web_driver
# Create a single instance per process.
web_cache = WebCache()
class HashbangMiddleware(object):
"""
Middleware that catches requests with escaped fragments, like: http://example.com/?_escaped_fragment_=/projects
These special cases are most likely requested by search engines that detected hashbangs (#!) in the URL. If such a
request is made, the dynamic content is generated in the background, and the generated page source is served to the
search engine.
"""
def process_request(self, request):
if request.method == 'GET' and ESCAPED_FRAGMENT in request.GET:
original_url = request.build_absolute_uri()
parsed_url = urlparse.urlparse(original_url)
# Update URL with hashbang.
query = dict(urlparse.parse_qsl(parsed_url.query))
path = ''.join([parsed_url.path, HASHBANG, query.get(ESCAPED_FRAGMENT, '')])
# See if it's a page we now so that we can sent it back quickly.
route = parsed_url.query.replace('%2F', '/').split('/')
# Project page
if route[1] == 'projects' and len(route) > 2:
slug = route[2]
# strip query string
slug = slug.split('?')[0]
if slug != slug.lower():
return HttpResponsePermanentRedirect(original_url.lower())
try:
project = Project.objects.get(slug=slug)
return SimpleTemplateResponse(template='crawlable/project.html', context={'project': project})
except Project.DoesNotExist:
url = ''.join([parsed_url.path, '?', ESCAPED_FRAGMENT, '=', '/projects'])
return HttpResponsePermanentRedirect(url)
if route[1] == 'projects' and len(route) == 2:
projects = Project.objects.order_by('popularity').all()[:10]
url = ''.join([parsed_url.path, HASHBANG, '/projects'])
return SimpleTemplateResponse(template='crawlable/project_list.html',
context={'projects': projects, 'url': url})
# Task page
if route[1] == 'tasks' and len(route) > 2:
task_id = route[2].split('?')[0]
task = Task.objects.get(id=task_id)
return SimpleTemplateResponse(template='crawlable/task.html', context={'task': task})
# FundRaiser page
if route[1] == 'fundraisers' and len(route) > 2:
fundraiser_id = route[2].split('?')[0]
fundraiser = FundRaiser.objects.get(id=fundraiser_id)
return SimpleTemplateResponse(template='crawlable/fundraiser.html', context={'fundraiser': fundraiser})
# Update query string by removing the escaped fragment.
if ESCAPED_FRAGMENT in query:
del query[ESCAPED_FRAGMENT]
query = urllib.urlencode(query)
# Build new absolute URL.
# NOTE: Django behind a certain web/WSGI-server configuration cannot determine if a request was made using
# HTTPS or HTTP. We consult a special setting for that.
absolute_url = urlparse.urlunparse([
'https' if settings.CRAWLABLE_FORCE_HTTPS else parsed_url.scheme,
parsed_url.netloc,
path,
parsed_url.params,
query,
parsed_url.fragment
])
try:
driver = web_cache.get_driver()
logger.debug('Generating flat content from "%s" for "%s"%s.', absolute_url, original_url,
' (forced HTTPS)' if settings.CRAWLABLE_FORCE_HTTPS else '')
driver.get(absolute_url)
# TODO: This should be replaced with something smart that waits for a certain trigger that all JS
# is done.
time.sleep(3)
content = driver.page_source
# Remove all javascript, since its mostly useless now.
script_tags_template = re.compile(r'<script([^/]*/>|(\s+[^>]*><\/script>))', re.U)
content = script_tags_template.sub('', content)
cache.cache.set(CACHE_PREFIX+query,content)
except Exception, e:
if cache.cache.has_key(CACHE_PREFIX+query):
content = cache.cache.get(CACHE_PREFIX+query)
else:
logger.error('There was an error rendering "%s" for "%s" with the web driver: %s', absolute_url, original_url, e)
return HttpResponseServerError()
return HttpResponse(content=content)
return None
| import logging
from bluebottle.fundraisers.models import FundRaiser
from apps.projects.models import Project
from apps.tasks.models import Task
from django.http.response import HttpResponsePermanentRedirect
from django.template.response import SimpleTemplateResponse
import re
import time
import os
import urllib
import urlparse
import tempfile
from django.http import HttpResponse, HttpResponseServerError
from django.conf import settings
from django.utils import html as html_utils
from django.core import cache
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.common.utils import is_connectable
from selenium.webdriver.phantomjs.webdriver import WebDriver
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
logger = logging.getLogger(__name__)
HASHBANG = '#!'
ESCAPED_FRAGMENT = '_escaped_fragment_'
CACHE_PREFIX = '_share_'
class DedicatedWebDriver(RemoteWebDriver):
"""
Wrapper to communicate with a dedicated PhantomJS through Ghostdriver.
If you have a phantomjs instance running at all times, you can use this dedicated webdriver to communicate with it.
"""
def __init__(self, port=None, desired_capabilities=DesiredCapabilities.PHANTOMJS):
if port is None:
port = 8910
class DummyService():
"""Dummy service to accept the same calls as the PhantomJS webdriver."""
def __init__(self, port):
self.port = port
@property
def service_url(self):
return 'http://localhost:%d/wd/hub' % port
def stop(self, *args, **kwargs):
pass
self.service = DummyService(port)
# Start the remote web driver.
try:
RemoteWebDriver.__init__(self,
command_executor=self.service.service_url,
desired_capabilities=desired_capabilities)
except:
self.quit()
raise
self._is_remote = False
class WebCache(object):
"""
Class to make sure the web driver is lazily loaded. For regular requests, the driver should not be instantiated
because it significantly slows down the request/response cycle (it can easily take 10 seconds to start).
"""
_web_driver = None
def __init__(self):
if hasattr(settings, 'CRAWLABLE_PHANTOMJS_ARGS') and settings.CRAWLABLE_PHANTOMJS_ARGS:
service_args = settings.CRAWLABLE_PHANTOMJS_ARGS[:]
else:
service_args = [
'--load-images=false',
'--disk-cache=true',
'--local-storage-path=%s' % os.path.join(tempfile.gettempdir(), 'phantomjs')
]
self.service_args = service_args
def get_driver(self):
"""
Only creates the driver if not present and returns it.
:return: ``WebDriver`` instance.
"""
# Dedicated mode
if hasattr(settings, 'CRAWLABLE_PHANTOMJS_DEDICATED_MODE') and settings.CRAWLABLE_PHANTOMJS_DEDICATED_MODE:
if not self._web_driver:
self._web_driver = DedicatedWebDriver(
port=getattr(settings, 'CRAWLABLE_PHANTOMJS_DEDICATED_PORT', 8910)
)
elif not is_connectable(self._web_driver.service.port):
raise RuntimeError('Cannot connect to dedicated PhantomJS instance on: %s' %
self._web_driver.service.service_url)
# Instance based mode (more for testing purposes). When debugging, you can even replace the PhantomJS webdriver
# with firefox and remove the arguments to the web driver constructor below.
else:
if not self._web_driver:
self._web_driver = WebDriver(service_args=self.service_args)
elif not is_connectable(self._web_driver.service.port):
self._web_driver.service.stop()
self._web_driver = WebDriver(service_args=self.service_args)
# Make sure it doesn't time out.
self._web_driver.set_script_timeout(30)
return self._web_driver
# Create a single instance per process.
web_cache = WebCache()
class HashbangMiddleware(object):
"""
Middleware that catches requests with escaped fragments, like: http://example.com/?_escaped_fragment_=/projects
These special cases are most likely requested by search engines that detected hashbangs (#!) in the URL. If such a
request is made, the dynamic content is generated in the background, and the generated page source is served to the
search engine.
"""
def process_request(self, request):
if request.method == 'GET' and ESCAPED_FRAGMENT in request.GET:
original_url = request.build_absolute_uri()
parsed_url = urlparse.urlparse(original_url)
# Update URL with hashbang.
query = dict(urlparse.parse_qsl(parsed_url.query))
path = ''.join([parsed_url.path, HASHBANG, query.get(ESCAPED_FRAGMENT, '')])
# See if it's a page we now so that we can sent it back quickly.
route = parsed_url.query.replace('%2F', '/').split('/')
# Project page
if route[1] == 'projects' and len(route) > 2:
slug = route[2]
# strip query string
slug = slug.split('?')[0]
if slug != slug.lower():
return HttpResponsePermanentRedirect(original_url.lower())
try:
project = Project.objects.get(slug=slug)
return SimpleTemplateResponse(template='crawlable/project.html', context={'project': project})
except Project.DoesNotExist:
url = ''.join([parsed_url.path, '?', ESCAPED_FRAGMENT, '=', '/projects'])
return HttpResponsePermanentRedirect(url)
if route[1] == 'projects' and len(route) == 2:
projects = Project.objects.order_by('popularity').all()[:10]
url = ''.join([parsed_url.path, HASHBANG, '/projects'])
return SimpleTemplateResponse(template='crawlable/project_list.html',
context={'projects': projects, 'url': url})
# Task page
if route[1] == 'tasks' and len(route) > 2:
task_id = route[2].split('?')[0]
task = Task.objects.get(id=task_id)
return SimpleTemplateResponse(template='crawlable/task.html', context={'task': task})
# FundRaiser page
if route[1] == 'fundraisers' and len(route) > 2:
fundraiser_id = route[2].split('?')[0]
fundraiser = FundRaiser.objects.get(id=fundraiser_id)
return SimpleTemplateResponse(template='crawlable/fundraiser.html', context={'fundraiser': fundraiser})
# Update query string by removing the escaped fragment.
if ESCAPED_FRAGMENT in query:
del query[ESCAPED_FRAGMENT]
query = urllib.urlencode(query)
# Build new absolute URL.
# NOTE: Django behind a certain web/WSGI-server configuration cannot determine if a request was made using
# HTTPS or HTTP. We consult a special setting for that.
absolute_url = urlparse.urlunparse([
'https' if settings.CRAWLABLE_FORCE_HTTPS else parsed_url.scheme,
parsed_url.netloc,
path,
parsed_url.params,
query,
parsed_url.fragment
])
try:
driver = web_cache.get_driver()
logger.debug('Generating flat content from "%s" for "%s"%s.', absolute_url, original_url,
' (forced HTTPS)' if settings.CRAWLABLE_FORCE_HTTPS else '')
driver.get(absolute_url)
# TODO: This should be replaced with something smart that waits for a certain trigger that all JS
# is done.
time.sleep(3)
content = driver.page_source
# Remove all javascript, since its mostly useless now.
script_tags_template = re.compile(r'<script([^/]*/>|(\s+[^>]*><\/script>))', re.U)
content = script_tags_template.sub('', content)
cache.cache.set(CACHE_PREFIX+query,content)
except Exception, e:
if cache.cache.has_key(CACHE_PREFIX+query):
content = cache.cache.get(CACHE_PREFIX+query)
else:
logger.error('There was an error rendering "%s" for "%s" with the web driver: %s', absolute_url, original_url, e)
return HttpResponseServerError()
return HttpResponse(content=content)
return None
| en | 0.895747 | Wrapper to communicate with a dedicated PhantomJS through Ghostdriver. If you have a phantomjs instance running at all times, you can use this dedicated webdriver to communicate with it. Dummy service to accept the same calls as the PhantomJS webdriver. # Start the remote web driver. Class to make sure the web driver is lazily loaded. For regular requests, the driver should not be instantiated because it significantly slows down the request/response cycle (it can easily take 10 seconds to start). Only creates the driver if not present and returns it. :return: ``WebDriver`` instance. # Dedicated mode # Instance based mode (more for testing purposes). When debugging, you can even replace the PhantomJS webdriver # with firefox and remove the arguments to the web driver constructor below. # Make sure it doesn't time out. # Create a single instance per process. Middleware that catches requests with escaped fragments, like: http://example.com/?_escaped_fragment_=/projects These special cases are most likely requested by search engines that detected hashbangs (#!) in the URL. If such a request is made, the dynamic content is generated in the background, and the generated page source is served to the search engine. # Update URL with hashbang. # See if it's a page we now so that we can sent it back quickly. # Project page # strip query string # Task page # FundRaiser page # Update query string by removing the escaped fragment. # Build new absolute URL. # NOTE: Django behind a certain web/WSGI-server configuration cannot determine if a request was made using # HTTPS or HTTP. We consult a special setting for that. # TODO: This should be replaced with something smart that waits for a certain trigger that all JS # is done. # Remove all javascript, since its mostly useless now. | 2.133645 | 2 |
pyem410x/core.py | yrjyrj123/pyem410x | 2 | 6617740 | <gh_stars>1-10
# coding=utf-8
from bitstring import BitArray
import warnings
EM_TAG_ID_LEN = 5 # in byte
def encode(em_tag_id):
tag_bit_array = BitArray(em_tag_id)
if len(tag_bit_array.hex) > EM_TAG_ID_LEN * 2:
raise ValueError("Em410x tag ID must shorter than %s bytes" % EM_TAG_ID_LEN)
if len(tag_bit_array.hex) < EM_TAG_ID_LEN * 2:
warnings.warn("Em410x tag ID length usually equal %s bytes" % EM_TAG_ID_LEN)
tag_bit_array.prepend("0x" + "0" * (EM_TAG_ID_LEN * 2 - len(tag_bit_array.hex)))
bit_with_parity = ""
count_of_one = 0
for i in range(0, len(tag_bit_array.bin)):
bit_with_parity += tag_bit_array.bin[i]
if tag_bit_array.bin[i] == "1":
count_of_one += 1
if (i + 1) % 4 == 0:
if count_of_one % 2 == 0:
bit_with_parity += "0"
else:
bit_with_parity += "1"
count_of_one = 0
col_parity = ""
for i in range(0, 4):
pos = i
count_of_one = 0
while pos < len(bit_with_parity):
if bit_with_parity[pos] == "1":
count_of_one += 1
pos += 5
if count_of_one % 2 == 0:
col_parity += "0"
else:
col_parity += "1"
bit_with_parity = bit_with_parity + col_parity
return BitArray("0b" + "111111111" + bit_with_parity + "0")
def decode(data):
data_bit_array = BitArray(data)
if len(data_bit_array.bin) != 64 or data_bit_array.bin[0:9] != "111111111" or data_bit_array.bin[-1] != "0":
raise ValueError("Not a valid em410x encoded data")
bit_with_parity = data_bit_array.bin[9:-1]
pos = 0
tag_bit_string = "0b"
while pos < 50:
if (pos + 1) % 5 != 0:
tag_bit_string += bit_with_parity[pos]
pos += 1
if encode("0x" + BitArray(tag_bit_string).hex) == data_bit_array:
return BitArray(tag_bit_string)
else:
raise ValueError("Parity check error")
| # coding=utf-8
from bitstring import BitArray
import warnings
EM_TAG_ID_LEN = 5 # in byte
def encode(em_tag_id):
tag_bit_array = BitArray(em_tag_id)
if len(tag_bit_array.hex) > EM_TAG_ID_LEN * 2:
raise ValueError("Em410x tag ID must shorter than %s bytes" % EM_TAG_ID_LEN)
if len(tag_bit_array.hex) < EM_TAG_ID_LEN * 2:
warnings.warn("Em410x tag ID length usually equal %s bytes" % EM_TAG_ID_LEN)
tag_bit_array.prepend("0x" + "0" * (EM_TAG_ID_LEN * 2 - len(tag_bit_array.hex)))
bit_with_parity = ""
count_of_one = 0
for i in range(0, len(tag_bit_array.bin)):
bit_with_parity += tag_bit_array.bin[i]
if tag_bit_array.bin[i] == "1":
count_of_one += 1
if (i + 1) % 4 == 0:
if count_of_one % 2 == 0:
bit_with_parity += "0"
else:
bit_with_parity += "1"
count_of_one = 0
col_parity = ""
for i in range(0, 4):
pos = i
count_of_one = 0
while pos < len(bit_with_parity):
if bit_with_parity[pos] == "1":
count_of_one += 1
pos += 5
if count_of_one % 2 == 0:
col_parity += "0"
else:
col_parity += "1"
bit_with_parity = bit_with_parity + col_parity
return BitArray("0b" + "111111111" + bit_with_parity + "0")
def decode(data):
data_bit_array = BitArray(data)
if len(data_bit_array.bin) != 64 or data_bit_array.bin[0:9] != "111111111" or data_bit_array.bin[-1] != "0":
raise ValueError("Not a valid em410x encoded data")
bit_with_parity = data_bit_array.bin[9:-1]
pos = 0
tag_bit_string = "0b"
while pos < 50:
if (pos + 1) % 5 != 0:
tag_bit_string += bit_with_parity[pos]
pos += 1
if encode("0x" + BitArray(tag_bit_string).hex) == data_bit_array:
return BitArray(tag_bit_string)
else:
raise ValueError("Parity check error") | en | 0.506595 | # coding=utf-8 # in byte | 2.941834 | 3 |
visigoth/internal/svg/tspan.py | visigoths/visigoth | 0 | 6617741 | <gh_stars>0
# -*- coding: utf-8 -*-
# visigoth: A lightweight Python3 library for rendering data visualizations in SVG
# Copyright (C) 2020-2021 Visigoth Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from visigoth.internal.svg import svgstyled
# represent a section of text as an SVG tspan object
class tspan(svgstyled):
def __init__(self,txt,tooltip="",font_height=None,text_attributes={}):
svgstyled.__init__(self,"tspan",tooltip)
self.setContent(txt)
self.font_height = font_height
self.text_attributes = text_attributes
self.url = None
def setUrl(self,url):
self.url = url
def render(self,svgdoc,parent):
dattrs = svgdoc.getDiagram().getDefaultTextAttributes()
self.addAttrs(dattrs)
if self.text_attributes:
self.addAttrs(self.text_attributes)
if self.font_height:
self.addAttr("font-size",self.font_height)
font_family = self.text_attributes.get("font-family",dattrs.get("font-family",""))
font_weight = self.text_attributes.get("font-weight",dattrs.get("font-weight","normal"))
font_style = self.text_attributes.get("font-style",dattrs.get("font-style","normal"))
svgdoc.includeFont(font_family,font_weight,font_style)
if self.url:
doc = svgdoc.doc
self.addAttr("text-decoration","underline")
self.addAttr("stroke", "blue")
p = doc.createElement("a")
parent.appendChild(p)
p.setAttribute("href",self.url)
p.setAttribute("target","_new")
parent = p
return super().render(svgdoc, parent)
| # -*- coding: utf-8 -*-
# visigoth: A lightweight Python3 library for rendering data visualizations in SVG
# Copyright (C) 2020-2021 Visigoth Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from visigoth.internal.svg import svgstyled
# represent a section of text as an SVG tspan object
class tspan(svgstyled):
def __init__(self,txt,tooltip="",font_height=None,text_attributes={}):
svgstyled.__init__(self,"tspan",tooltip)
self.setContent(txt)
self.font_height = font_height
self.text_attributes = text_attributes
self.url = None
def setUrl(self,url):
self.url = url
def render(self,svgdoc,parent):
dattrs = svgdoc.getDiagram().getDefaultTextAttributes()
self.addAttrs(dattrs)
if self.text_attributes:
self.addAttrs(self.text_attributes)
if self.font_height:
self.addAttr("font-size",self.font_height)
font_family = self.text_attributes.get("font-family",dattrs.get("font-family",""))
font_weight = self.text_attributes.get("font-weight",dattrs.get("font-weight","normal"))
font_style = self.text_attributes.get("font-style",dattrs.get("font-style","normal"))
svgdoc.includeFont(font_family,font_weight,font_style)
if self.url:
doc = svgdoc.doc
self.addAttr("text-decoration","underline")
self.addAttr("stroke", "blue")
p = doc.createElement("a")
parent.appendChild(p)
p.setAttribute("href",self.url)
p.setAttribute("target","_new")
parent = p
return super().render(svgdoc, parent) | en | 0.76729 | # -*- coding: utf-8 -*- # visigoth: A lightweight Python3 library for rendering data visualizations in SVG # Copyright (C) 2020-2021 Visigoth Developers # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING # BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # represent a section of text as an SVG tspan object | 2.105538 | 2 |
qf_lib/common/utils/dateutils/relative_delta.py | webclinic017/qf-lib | 198 | 6617742 | # Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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 dateutil.relativedelta import relativedelta
class RelativeDelta(relativedelta):
def __eq__(self, other):
if other is self:
return True
if not isinstance(other, RelativeDelta):
return False
return (self.years, self.months, self.days, self.leapdays, self.hours, self.minutes, self.seconds,
self.microseconds, self.year, self.month, self.day, self.weekday, self.hour, self.minute,
self.second, self.microsecond) == \
(other.years, other.months, other.days, other.leapdays, other.hours, other.minutes, other.seconds,
other.microseconds, other.year, other.month, other.day, other.weekday, other.hour, other.minute,
other.second, other.microsecond)
def __hash__(self):
return hash((self.years, self.months, self.days, self.leapdays, self.hours, self.minutes, self.seconds,
self.microseconds, self.year, self.month, self.day, self.weekday, self.hour, self.minute,
self.second, self.microsecond))
| # Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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 dateutil.relativedelta import relativedelta
class RelativeDelta(relativedelta):
def __eq__(self, other):
if other is self:
return True
if not isinstance(other, RelativeDelta):
return False
return (self.years, self.months, self.days, self.leapdays, self.hours, self.minutes, self.seconds,
self.microseconds, self.year, self.month, self.day, self.weekday, self.hour, self.minute,
self.second, self.microsecond) == \
(other.years, other.months, other.days, other.leapdays, other.hours, other.minutes, other.seconds,
other.microseconds, other.year, other.month, other.day, other.weekday, other.hour, other.minute,
other.second, other.microsecond)
def __hash__(self):
return hash((self.years, self.months, self.days, self.leapdays, self.hours, self.minutes, self.seconds,
self.microseconds, self.year, self.month, self.day, self.weekday, self.hour, self.minute,
self.second, self.microsecond))
| en | 0.84273 | # Copyright 2016-present CERN – European Organization for Nuclear Research # # 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. | 2.103096 | 2 |
pyrobolearn/terminal_conditions/body_conditions.py | Pandinosaurus/pyrobolearn | 2 | 6617743 | <reponame>Pandinosaurus/pyrobolearn<filename>pyrobolearn/terminal_conditions/body_conditions.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Define some body terminal conditions for the environment.
"""
from abc import ABCMeta
import numpy as np
from pyrobolearn.robots.base import Body
from pyrobolearn.terminal_conditions.terminal_condition import TerminalCondition
from pyrobolearn.utils.transformation import get_rpy_from_quaternion, get_matrix_from_quaternion
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, PyRoboLearn"
__credits__ = ["<NAME>"]
__license__ = "GNU GPLv3"
__version__ = "1.0.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
class BodyCondition(TerminalCondition):
r"""Body Terminal Condition
This terminal condition describes 8 cases (4 failure and 4 success cases):
1. all the dimensions of the body state are:
1. in a certain bounds and must stay between these bounds. Once one gets out, the terminal condition is over,
and results in a failure. (all=True, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once they all get out, the terminal condition is over,
and results in a success. (all=True, out=False, stay=False)
3. outside a certain bounds and must get in. Once they all get in, the terminal condition is over, and results
in a success. (all=True, out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once one gets in, the terminal condition is over,
and results in a failure. (all=True, out=True, stay=True)
2. any of the dimension of the body state is:
1. in a certain bounds and must stay between these bounds. Once they all get out, the terminal condition is
over, and results in a failure. (all=False, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once one gets out, the terminal condition is over,
and results in a success. (all=False, out=False, stay=False)
3. outside a certain bounds and must get in. Once one gets in, the terminal condition is over, and results in
a success. (all=False ,out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once they all get in, the terminal condition is
over, and results in a failure. (all=False, out=True, stay=True)
Body state includes the position and orientation for instance.
"""
__metaclass__ = ABCMeta
def __init__(self, body, bounds, dim=None, all=False, stay=False, out=False):
"""
Initialize the body terminal condition.
Args:
body (Body): body instance
dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will
consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If
a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1]
means to consider the bounds along the x and z axes.
all (bool): this is only used if they are multiple dimensions. if True, all the dimensions of the state
are checked if they are inside or outside the bounds depending on the other parameters. if False, any
dimensions will be checked.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the state
leave the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the state leaves the bounds, it results in a success.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
"""
super(BodyCondition, self).__init__()
self.body = body
self.dim = dim
self.bounds = bounds
self._out = bool(out)
self._stay = bool(stay)
self._all = bool(all)
##############
# Properties #
##############
@property
def body(self):
"""Return the body instance."""
return self._body
@body.setter
def body(self, body):
"""Set the body instance."""
if not isinstance(body, Body):
raise TypeError("Expecting the given 'body' to be an instance of `Body`, instead got: "
"{}".format(type(body)))
self._body = body
@property
def dim(self):
"""Return the dimension(s)."""
return self._dim
@dim.setter
def dim(self, dim):
"""Set the dimensions."""
if dim is not None:
if not isinstance(dim, (int, np.ndarray)):
if isinstance(dim, (list, tuple)):
dim = np.asarray(dim)
else:
raise TypeError("Expecting the given 'dim' to be an int or an np.array of 3 int, but got instead: "
"{}".format(type(dim)))
if isinstance(dim, np.ndarray):
if dim.size != 3:
raise ValueError("Expecting the given 'dim' np.array to be of size 3, but got instead a size of: "
"{}".format(dim.size))
dim = np.array([bool(d) for d in dim])
self._dim = dim
@property
def simulator(self):
"""Return the simulator instance."""
return self.body.simulator
###########
# Methods #
###########
def _check_bounds(self, bounds):
"""Check the given bounds."""
# check the type of the bounds
if not isinstance(bounds, (tuple, list, np.ndarray)):
raise TypeError("Expecting the given bounds to be a tuple/list/np.ndarray of float, instead got: "
"{}".format(type(bounds)))
# check that the bounds have a length of 2 (i.e. lower and upper bounds)
if len(bounds) != 2:
raise ValueError("Expecting the bounds to be of length 2 (i.e. lower and upper bounds), instead got a "
"length of {}".format(len(bounds)))
# if one of the bounds is None, raise error
if bounds[0] is None or bounds[1] is None:
raise ValueError("Expecting the bounds to not have None, but got: {}".format(bounds))
# reshape bounds if necessary
bounds = np.asarray(bounds).reshape(2, -1)
if self.dim is None:
if bounds.shape[1] != 3:
raise ValueError("Expecting the bounds to be of shape (2,3) but got instead a shape of: "
"{}".format(bounds.shape))
else:
if isinstance(self.dim, int) and bounds.shape[1] != 1:
raise ValueError("If you specified one dimension, we expect the shape of the bounds to be (2,1), but "
"got instead a shape of: {}".format(bounds.shape))
elif isinstance(self.dim, np.ndarray):
if bounds.shape[1] != len(self.dim[self.dim]):
raise ValueError("Expecting each bound to have the same number of elements than the elements that "
"are not zero in the given 'dim' attribute")
return bounds
def check(self):
"""
Check if the terminating condition has been fulfilled, and return True or False accordingly
"""
states = self._get_states()
if self._all: # all the dimension states
if self._out: # are outside a certain bounds
if self._stay: # and must stay outside these ones.
if np.any((self.bounds[0] <= states) & (states <= self.bounds[1])): # one dimension went inside
self._btype = False # failure
self._over = True # it is over
else: # they are still all outside
self._btype = True # success
self._over = False # it is not over
else: # and must go inside these ones
if np.all((self.bounds[0] <= states) & (states <= self.bounds[1])): # they all went inside
self._btype = True # success
self._over = True # it is over
else: # they are some still left outside
self._btype = False # failure
self._over = False # it is not over
else: # are inside a certain bounds
if self._stay: # and must stay inside these ones.
if not np.all((self.bounds[0] <= states) &
(states <= self.bounds[1])): # one dimension went outside
self._btype = False # failure
self._over = True # it is over
else: # they are still all inside
self._btype = True # success
self._over = False # it is not over
else: # and must go outside these ones.
if np.any((self.bounds[0] <= states) & (states <= self.bounds[1])): # they are still some inside
self._btype = False # failure
self._over = False # it is not over
else: # they are all outside
self._btype = True # success
self._over = True # it is over
else: # any of the dimension states
if self._out: # is outside a certain bounds
if self._stay: # and still stays outside these ones.
if not np.all((self.bounds[0] <= states) &
(states <= self.bounds[1])): # at least one dim. is still outside
self._btype = True # success
self._over = False # it is not over
else: # they are all inside
self._btype = False # failure
self._over = True # it is over
else: # and one must at least go inside these ones
if np.any((self.bounds[0] <= states) & (states <= self.bounds[1])): # at least one state is inside
self._btype = True # success
self._over = True # it is over
else: # they are still all outside
self._btype = False # failure
self._over = False # it is not over
else: # is inside a certain bounds
if self._stay: # and must stay inside these ones.
if np.any((self.bounds[0] <= states) &
(states <= self.bounds[1])): # at least one state is still inside
self._btype = True # success
self._over = False # it is not over
else: # they are all outside
self._btype = False # failure
self._over = True # it is over
else: # and must go outside these ones.
if np.all((self.bounds[0] <= states) & (states <= self.bounds[1])): # they are all inside
self._btype = False # failure
self._over = False # it is not over
else: # at least one went outside
self._btype = True # success
self._over = True # it is over
return self._over
def _get_states(self):
"""Get the base states. Has to be implemented in the child class."""
raise NotImplementedError
class PositionCondition(BodyCondition):
r"""World position terminal condition
This terminal condition describes 8 cases (4 failure and 4 success cases):
1. all the dimensions of the body position state are:
1. in a certain bounds and must stay between these bounds. Once one gets out, the terminal condition is over,
and results in a failure. (all=True, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once they all get out, the terminal condition is over,
and results in a success. (all=True, out=False, stay=False)
3. outside a certain bounds and must get in. Once they all get in, the terminal condition is over, and results
in a success. (all=True, out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once one gets in, the terminal condition is over,
and results in a failure. (all=True, out=True, stay=True)
2. any of the dimension of the body position state is:
1. in a certain bounds and must stay between these bounds. Once they all get out, the terminal condition is
over, and results in a failure. (all=False, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once one gets out, the terminal condition is over,
and results in a success. (all=False, out=False, stay=False)
3. outside a certain bounds and must get in. Once one gets in, the terminal condition is over, and results in
a success. (all=False ,out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once they all get in, the terminal condition is
over, and results in a failure. (all=False, out=True, stay=True)
"""
def __init__(self, body, bounds=(None, None), dim=None, out=False, stay=False, all=False):
"""
Initialize the world position terminal condition.
Args:
body (Body): body instance.
bounds (tuple of 2 float / np.array[3]): bounds on the body position.
dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will
consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If
a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1]
means to consider the bounds along the x and z axes.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the position
leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the position leaves the bounds, it results in a success.
all (bool): this is only used if they are multiple dimensions. if True, all the dimensions of the state
are checked if they are inside or outside the bounds depending on the other parameters. if False, any
dimensions will be checked.
"""
super(PositionCondition, self).__init__(body, bounds=bounds, dim=dim, out=out, stay=stay, all=all)
# check the bounds
self.bounds = self._check_bounds(bounds=bounds)
def _get_states(self):
"""Return the state."""
position = self.body.position
if self.dim is None:
print(position)
return position
print(position[self.dim])
return position[self.dim]
class OrientationCondition(BodyCondition):
r"""World orientation terminal condition
This terminal condition describes 8 cases (4 failure and 4 success cases):
1. all the dimensions of the body orientation (expressed as roll-pitch-yaw angles) state are:
1. in a certain bounds and must stay between these bounds. Once one gets out, the terminal condition is over,
and results in a failure. (all=True, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once they all get out, the terminal condition is over,
and results in a success. (all=True, out=False, stay=False)
3. outside a certain bounds and must get in. Once they all get in, the terminal condition is over, and results
in a success. (all=True, out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once one gets in, the terminal condition is over,
and results in a failure. (all=True, out=True, stay=True)
2. any of the dimension of the body orientation (expressed as roll-pitch-yaw angles) state is:
1. in a certain bounds and must stay between these bounds. Once they all get out, the terminal condition is
over, and results in a failure. (all=False, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once one gets out, the terminal condition is over,
and results in a success. (all=False, out=False, stay=False)
3. outside a certain bounds and must get in. Once one gets in, the terminal condition is over, and results in
a success. (all=False ,out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once they all get in, the terminal condition is
over, and results in a failure. (all=False, out=True, stay=True)
"""
def __init__(self, body, bounds=(None, None), dim=None, out=False, stay=False, all=False):
"""
Initialize the world orientation terminal condition.
Args:
body (Body): body instance.
bounds (tuple of 2 float / np.array[3]): bounds on the body orientation expressed as roll-pitch-yaw angles
or axis-angle if the :attr:`axis` is provided.
dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will
consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If
a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1]
means to consider the bounds along the x (roll) and z (yaw) axes.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the orientation
leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the orientation leaves the bounds, it results in a success.
all (bool): this is only used if they are multiple dimensions. if True, all the dimensions of the state
are checked if they are inside or outside the bounds depending on the other parameters. if False, any
dimensions will be checked.
"""
super(OrientationCondition, self).__init__(body, bounds=bounds, dim=dim, out=out, stay=stay, all=all)
# check the bounds
self.bounds = self._check_bounds(bounds=bounds)
def _get_states(self):
"""Return the state."""
orientation = get_rpy_from_quaternion(self.body.orientation)
if self.dim is None:
return orientation
return orientation[self.dim]
class BaseOrientationAxisCondition(BodyCondition):
r"""Base orientation axis terminal condition
This uses the cosine similarity function by computing the angle between the given axis and one of the axis
of the base orientation (i.e. one of the columns of the rotation matrix).
This terminal condition describes 4 cases (2 failure and 2 success cases); the angle is in:
1. in a certain bounds and must stay between these bounds. Once it gets out, the terminal condition is over,
and results in a failure. (stay=True, out=False --> must stay in)
2. in a certain bounds and must get out of these bounds. Once it gets out, the terminal condition is over,
and results in a success. (stay=False, out=False --> must not stay in)
3. outside a certain bounds and must get in. Once it gets in, the terminal condition is over, and results
in a success. (stay=False, out=True --> must not stay out)
4. outside a certain bounds and must stay outside these ones. Once it gets in, the terminal condition is over,
and results in a failure. (stay=True, out=True --> must stay out)
"""
def __init__(self, body, angle=0.85, axis=(0., 0., 1.), dim=2, stay=False, out=False):
"""
Initialize the base orientation axis terminal condition.
Args:
body (Body): body instance.
angle (float): angle bound.
axis (tuple/list[float[3]], np.array[float[3]]): axis.
dim (int): column that we should consider for the rotation matrix.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the orientation
leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the orientation leaves the bounds, it results in a success.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
"""
bounds = np.array([[angle], [1.1]]) # 1.1 is just to be sure
super(BaseOrientationAxisCondition, self).__init__(body, bounds=bounds, dim=dim, stay=stay, out=out)
self.axis = np.asarray(axis)
def _get_states(self):
"""Return the state."""
axis = get_matrix_from_quaternion(self.body.orientation)[self.dim]
return np.dot(axis, self.axis)
class BaseHeightCondition(BodyCondition):
r"""Base Height terminal condition
This terminal condition describes 4 cases (2 failure and 2 success cases); the base height (i.e. z-position) state
is:
1. in a certain bounds and must stay between these bounds. Once it gets out, the terminal condition is over,
and results in a failure. (stay=True, out=False --> must stay in)
2. in a certain bounds and must get out of these bounds. Once it gets out, the terminal condition is over,
and results in a success. (stay=False, out=False --> must not stay in)
3. outside a certain bounds and must get in. Once it gets in, the terminal condition is over, and results
in a success. (stay=False, out=True --> must not stay out)
4. outside a certain bounds and must stay outside these ones. Once it gets in, the terminal condition is over,
and results in a failure. (stay=True, out=True --> must stay out)
"""
def __init__(self, body, height, stay=False, out=False):
"""
Initialize the base height terminal condition.
Args:
body (Body): body instance.
height (float): max height which defines the bound; the bounds will be defined to be between 0 and height.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the position
leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the position leaves the bounds, it results in a success.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
"""
bounds = np.array([[0.], [height]])
super(BaseHeightCondition, self).__init__(body, bounds=bounds, stay=stay, out=out)
def _get_states(self):
"""Return the state."""
return self.body.position[2]
class DistanceCondition(BodyCondition):
r"""Distance terminal condition
This is a bit similar than the ``PositionCondition``. The difference is that this class describes a nd-sphere,
while the ``PositionCondition`` describes a nd-rectangle.
This terminal condition describes 4 cases (2 failure and 2 success cases); the body distance with respect to the
provided center must be:
1. in a certain bounds and must stay between these bounds. Once it gets out, the terminal condition is over,
and results in a failure. (stay=True, out=False --> must stay in)
2. in a certain bounds and must get out of these bounds. Once it gets out, the terminal condition is over,
and results in a success. (stay=False, out=False --> must not stay in)
3. outside a certain bounds and must get in. Once it gets in, the terminal condition is over, and results
in a success. (stay=False, out=True --> must not stay out)
4. outside a certain bounds and must stay outside these ones. Once it gets in, the terminal condition is over,
and results in a failure. (stay=True, out=True --> must stay out)
"""
def __init__(self, body, distance=float("inf"), center=(0., 0., 0.), dim=None, stay=False, out=False):
"""
Initialize the distance terminal condition.
Args:
body (Body): body instance.
distance (float): max distance with respect to the specified :attr:`center`.
center (np.array(float[3]), list[float[3]], tuple[float[3]]): center from which take the distance.
dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will
consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If
a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1]
means to consider the distance along the x and z axes.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the position
leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the position leaves the bounds, it results in a success.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
"""
bounds = np.array([[0.], [distance]])
super(DistanceCondition, self).__init__(body, bounds=bounds, dim=dim, stay=stay, out=out)
self.center = np.asarray(center)
def _get_states(self):
"""Return the state."""
position = self.body.position - self.center
if self.dim is None:
return np.linalg.norm(position)
return np.linalg.norm(position[self.dim])
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Define some body terminal conditions for the environment.
"""
from abc import ABCMeta
import numpy as np
from pyrobolearn.robots.base import Body
from pyrobolearn.terminal_conditions.terminal_condition import TerminalCondition
from pyrobolearn.utils.transformation import get_rpy_from_quaternion, get_matrix_from_quaternion
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, PyRoboLearn"
__credits__ = ["<NAME>"]
__license__ = "GNU GPLv3"
__version__ = "1.0.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
class BodyCondition(TerminalCondition):
r"""Body Terminal Condition
This terminal condition describes 8 cases (4 failure and 4 success cases):
1. all the dimensions of the body state are:
1. in a certain bounds and must stay between these bounds. Once one gets out, the terminal condition is over,
and results in a failure. (all=True, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once they all get out, the terminal condition is over,
and results in a success. (all=True, out=False, stay=False)
3. outside a certain bounds and must get in. Once they all get in, the terminal condition is over, and results
in a success. (all=True, out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once one gets in, the terminal condition is over,
and results in a failure. (all=True, out=True, stay=True)
2. any of the dimension of the body state is:
1. in a certain bounds and must stay between these bounds. Once they all get out, the terminal condition is
over, and results in a failure. (all=False, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once one gets out, the terminal condition is over,
and results in a success. (all=False, out=False, stay=False)
3. outside a certain bounds and must get in. Once one gets in, the terminal condition is over, and results in
a success. (all=False ,out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once they all get in, the terminal condition is
over, and results in a failure. (all=False, out=True, stay=True)
Body state includes the position and orientation for instance.
"""
__metaclass__ = ABCMeta
def __init__(self, body, bounds, dim=None, all=False, stay=False, out=False):
"""
Initialize the body terminal condition.
Args:
body (Body): body instance
dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will
consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If
a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1]
means to consider the bounds along the x and z axes.
all (bool): this is only used if they are multiple dimensions. if True, all the dimensions of the state
are checked if they are inside or outside the bounds depending on the other parameters. if False, any
dimensions will be checked.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the state
leave the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the state leaves the bounds, it results in a success.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
"""
super(BodyCondition, self).__init__()
self.body = body
self.dim = dim
self.bounds = bounds
self._out = bool(out)
self._stay = bool(stay)
self._all = bool(all)
##############
# Properties #
##############
@property
def body(self):
"""Return the body instance."""
return self._body
@body.setter
def body(self, body):
"""Set the body instance."""
if not isinstance(body, Body):
raise TypeError("Expecting the given 'body' to be an instance of `Body`, instead got: "
"{}".format(type(body)))
self._body = body
@property
def dim(self):
"""Return the dimension(s)."""
return self._dim
@dim.setter
def dim(self, dim):
"""Set the dimensions."""
if dim is not None:
if not isinstance(dim, (int, np.ndarray)):
if isinstance(dim, (list, tuple)):
dim = np.asarray(dim)
else:
raise TypeError("Expecting the given 'dim' to be an int or an np.array of 3 int, but got instead: "
"{}".format(type(dim)))
if isinstance(dim, np.ndarray):
if dim.size != 3:
raise ValueError("Expecting the given 'dim' np.array to be of size 3, but got instead a size of: "
"{}".format(dim.size))
dim = np.array([bool(d) for d in dim])
self._dim = dim
@property
def simulator(self):
"""Return the simulator instance."""
return self.body.simulator
###########
# Methods #
###########
def _check_bounds(self, bounds):
"""Check the given bounds."""
# check the type of the bounds
if not isinstance(bounds, (tuple, list, np.ndarray)):
raise TypeError("Expecting the given bounds to be a tuple/list/np.ndarray of float, instead got: "
"{}".format(type(bounds)))
# check that the bounds have a length of 2 (i.e. lower and upper bounds)
if len(bounds) != 2:
raise ValueError("Expecting the bounds to be of length 2 (i.e. lower and upper bounds), instead got a "
"length of {}".format(len(bounds)))
# if one of the bounds is None, raise error
if bounds[0] is None or bounds[1] is None:
raise ValueError("Expecting the bounds to not have None, but got: {}".format(bounds))
# reshape bounds if necessary
bounds = np.asarray(bounds).reshape(2, -1)
if self.dim is None:
if bounds.shape[1] != 3:
raise ValueError("Expecting the bounds to be of shape (2,3) but got instead a shape of: "
"{}".format(bounds.shape))
else:
if isinstance(self.dim, int) and bounds.shape[1] != 1:
raise ValueError("If you specified one dimension, we expect the shape of the bounds to be (2,1), but "
"got instead a shape of: {}".format(bounds.shape))
elif isinstance(self.dim, np.ndarray):
if bounds.shape[1] != len(self.dim[self.dim]):
raise ValueError("Expecting each bound to have the same number of elements than the elements that "
"are not zero in the given 'dim' attribute")
return bounds
def check(self):
"""
Check if the terminating condition has been fulfilled, and return True or False accordingly
"""
states = self._get_states()
if self._all: # all the dimension states
if self._out: # are outside a certain bounds
if self._stay: # and must stay outside these ones.
if np.any((self.bounds[0] <= states) & (states <= self.bounds[1])): # one dimension went inside
self._btype = False # failure
self._over = True # it is over
else: # they are still all outside
self._btype = True # success
self._over = False # it is not over
else: # and must go inside these ones
if np.all((self.bounds[0] <= states) & (states <= self.bounds[1])): # they all went inside
self._btype = True # success
self._over = True # it is over
else: # they are some still left outside
self._btype = False # failure
self._over = False # it is not over
else: # are inside a certain bounds
if self._stay: # and must stay inside these ones.
if not np.all((self.bounds[0] <= states) &
(states <= self.bounds[1])): # one dimension went outside
self._btype = False # failure
self._over = True # it is over
else: # they are still all inside
self._btype = True # success
self._over = False # it is not over
else: # and must go outside these ones.
if np.any((self.bounds[0] <= states) & (states <= self.bounds[1])): # they are still some inside
self._btype = False # failure
self._over = False # it is not over
else: # they are all outside
self._btype = True # success
self._over = True # it is over
else: # any of the dimension states
if self._out: # is outside a certain bounds
if self._stay: # and still stays outside these ones.
if not np.all((self.bounds[0] <= states) &
(states <= self.bounds[1])): # at least one dim. is still outside
self._btype = True # success
self._over = False # it is not over
else: # they are all inside
self._btype = False # failure
self._over = True # it is over
else: # and one must at least go inside these ones
if np.any((self.bounds[0] <= states) & (states <= self.bounds[1])): # at least one state is inside
self._btype = True # success
self._over = True # it is over
else: # they are still all outside
self._btype = False # failure
self._over = False # it is not over
else: # is inside a certain bounds
if self._stay: # and must stay inside these ones.
if np.any((self.bounds[0] <= states) &
(states <= self.bounds[1])): # at least one state is still inside
self._btype = True # success
self._over = False # it is not over
else: # they are all outside
self._btype = False # failure
self._over = True # it is over
else: # and must go outside these ones.
if np.all((self.bounds[0] <= states) & (states <= self.bounds[1])): # they are all inside
self._btype = False # failure
self._over = False # it is not over
else: # at least one went outside
self._btype = True # success
self._over = True # it is over
return self._over
def _get_states(self):
"""Get the base states. Has to be implemented in the child class."""
raise NotImplementedError
class PositionCondition(BodyCondition):
r"""World position terminal condition
This terminal condition describes 8 cases (4 failure and 4 success cases):
1. all the dimensions of the body position state are:
1. in a certain bounds and must stay between these bounds. Once one gets out, the terminal condition is over,
and results in a failure. (all=True, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once they all get out, the terminal condition is over,
and results in a success. (all=True, out=False, stay=False)
3. outside a certain bounds and must get in. Once they all get in, the terminal condition is over, and results
in a success. (all=True, out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once one gets in, the terminal condition is over,
and results in a failure. (all=True, out=True, stay=True)
2. any of the dimension of the body position state is:
1. in a certain bounds and must stay between these bounds. Once they all get out, the terminal condition is
over, and results in a failure. (all=False, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once one gets out, the terminal condition is over,
and results in a success. (all=False, out=False, stay=False)
3. outside a certain bounds and must get in. Once one gets in, the terminal condition is over, and results in
a success. (all=False ,out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once they all get in, the terminal condition is
over, and results in a failure. (all=False, out=True, stay=True)
"""
def __init__(self, body, bounds=(None, None), dim=None, out=False, stay=False, all=False):
"""
Initialize the world position terminal condition.
Args:
body (Body): body instance.
bounds (tuple of 2 float / np.array[3]): bounds on the body position.
dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will
consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If
a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1]
means to consider the bounds along the x and z axes.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the position
leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the position leaves the bounds, it results in a success.
all (bool): this is only used if they are multiple dimensions. if True, all the dimensions of the state
are checked if they are inside or outside the bounds depending on the other parameters. if False, any
dimensions will be checked.
"""
super(PositionCondition, self).__init__(body, bounds=bounds, dim=dim, out=out, stay=stay, all=all)
# check the bounds
self.bounds = self._check_bounds(bounds=bounds)
def _get_states(self):
"""Return the state."""
position = self.body.position
if self.dim is None:
print(position)
return position
print(position[self.dim])
return position[self.dim]
class OrientationCondition(BodyCondition):
r"""World orientation terminal condition
This terminal condition describes 8 cases (4 failure and 4 success cases):
1. all the dimensions of the body orientation (expressed as roll-pitch-yaw angles) state are:
1. in a certain bounds and must stay between these bounds. Once one gets out, the terminal condition is over,
and results in a failure. (all=True, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once they all get out, the terminal condition is over,
and results in a success. (all=True, out=False, stay=False)
3. outside a certain bounds and must get in. Once they all get in, the terminal condition is over, and results
in a success. (all=True, out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once one gets in, the terminal condition is over,
and results in a failure. (all=True, out=True, stay=True)
2. any of the dimension of the body orientation (expressed as roll-pitch-yaw angles) state is:
1. in a certain bounds and must stay between these bounds. Once they all get out, the terminal condition is
over, and results in a failure. (all=False, out=False, stay=True)
2. in a certain bounds and must get out of these bounds. Once one gets out, the terminal condition is over,
and results in a success. (all=False, out=False, stay=False)
3. outside a certain bounds and must get in. Once one gets in, the terminal condition is over, and results in
a success. (all=False ,out=True, stay=False)
4. outside a certain bounds and must stay outside these ones. Once they all get in, the terminal condition is
over, and results in a failure. (all=False, out=True, stay=True)
"""
def __init__(self, body, bounds=(None, None), dim=None, out=False, stay=False, all=False):
"""
Initialize the world orientation terminal condition.
Args:
body (Body): body instance.
bounds (tuple of 2 float / np.array[3]): bounds on the body orientation expressed as roll-pitch-yaw angles
or axis-angle if the :attr:`axis` is provided.
dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will
consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If
a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1]
means to consider the bounds along the x (roll) and z (yaw) axes.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the orientation
leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the orientation leaves the bounds, it results in a success.
all (bool): this is only used if they are multiple dimensions. if True, all the dimensions of the state
are checked if they are inside or outside the bounds depending on the other parameters. if False, any
dimensions will be checked.
"""
super(OrientationCondition, self).__init__(body, bounds=bounds, dim=dim, out=out, stay=stay, all=all)
# check the bounds
self.bounds = self._check_bounds(bounds=bounds)
def _get_states(self):
"""Return the state."""
orientation = get_rpy_from_quaternion(self.body.orientation)
if self.dim is None:
return orientation
return orientation[self.dim]
class BaseOrientationAxisCondition(BodyCondition):
r"""Base orientation axis terminal condition
This uses the cosine similarity function by computing the angle between the given axis and one of the axis
of the base orientation (i.e. one of the columns of the rotation matrix).
This terminal condition describes 4 cases (2 failure and 2 success cases); the angle is in:
1. in a certain bounds and must stay between these bounds. Once it gets out, the terminal condition is over,
and results in a failure. (stay=True, out=False --> must stay in)
2. in a certain bounds and must get out of these bounds. Once it gets out, the terminal condition is over,
and results in a success. (stay=False, out=False --> must not stay in)
3. outside a certain bounds and must get in. Once it gets in, the terminal condition is over, and results
in a success. (stay=False, out=True --> must not stay out)
4. outside a certain bounds and must stay outside these ones. Once it gets in, the terminal condition is over,
and results in a failure. (stay=True, out=True --> must stay out)
"""
def __init__(self, body, angle=0.85, axis=(0., 0., 1.), dim=2, stay=False, out=False):
"""
Initialize the base orientation axis terminal condition.
Args:
body (Body): body instance.
angle (float): angle bound.
axis (tuple/list[float[3]], np.array[float[3]]): axis.
dim (int): column that we should consider for the rotation matrix.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the orientation
leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the orientation leaves the bounds, it results in a success.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
"""
bounds = np.array([[angle], [1.1]]) # 1.1 is just to be sure
super(BaseOrientationAxisCondition, self).__init__(body, bounds=bounds, dim=dim, stay=stay, out=out)
self.axis = np.asarray(axis)
def _get_states(self):
"""Return the state."""
axis = get_matrix_from_quaternion(self.body.orientation)[self.dim]
return np.dot(axis, self.axis)
class BaseHeightCondition(BodyCondition):
r"""Base Height terminal condition
This terminal condition describes 4 cases (2 failure and 2 success cases); the base height (i.e. z-position) state
is:
1. in a certain bounds and must stay between these bounds. Once it gets out, the terminal condition is over,
and results in a failure. (stay=True, out=False --> must stay in)
2. in a certain bounds and must get out of these bounds. Once it gets out, the terminal condition is over,
and results in a success. (stay=False, out=False --> must not stay in)
3. outside a certain bounds and must get in. Once it gets in, the terminal condition is over, and results
in a success. (stay=False, out=True --> must not stay out)
4. outside a certain bounds and must stay outside these ones. Once it gets in, the terminal condition is over,
and results in a failure. (stay=True, out=True --> must stay out)
"""
def __init__(self, body, height, stay=False, out=False):
"""
Initialize the base height terminal condition.
Args:
body (Body): body instance.
height (float): max height which defines the bound; the bounds will be defined to be between 0 and height.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the position
leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the position leaves the bounds, it results in a success.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
"""
bounds = np.array([[0.], [height]])
super(BaseHeightCondition, self).__init__(body, bounds=bounds, stay=stay, out=out)
def _get_states(self):
"""Return the state."""
return self.body.position[2]
class DistanceCondition(BodyCondition):
r"""Distance terminal condition
This is a bit similar than the ``PositionCondition``. The difference is that this class describes a nd-sphere,
while the ``PositionCondition`` describes a nd-rectangle.
This terminal condition describes 4 cases (2 failure and 2 success cases); the body distance with respect to the
provided center must be:
1. in a certain bounds and must stay between these bounds. Once it gets out, the terminal condition is over,
and results in a failure. (stay=True, out=False --> must stay in)
2. in a certain bounds and must get out of these bounds. Once it gets out, the terminal condition is over,
and results in a success. (stay=False, out=False --> must not stay in)
3. outside a certain bounds and must get in. Once it gets in, the terminal condition is over, and results
in a success. (stay=False, out=True --> must not stay out)
4. outside a certain bounds and must stay outside these ones. Once it gets in, the terminal condition is over,
and results in a failure. (stay=True, out=True --> must stay out)
"""
def __init__(self, body, distance=float("inf"), center=(0., 0., 0.), dim=None, stay=False, out=False):
"""
Initialize the distance terminal condition.
Args:
body (Body): body instance.
distance (float): max distance with respect to the specified :attr:`center`.
center (np.array(float[3]), list[float[3]], tuple[float[3]]): center from which take the distance.
dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will
consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If
a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1]
means to consider the distance along the x and z axes.
stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the position
leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds;
if the position leaves the bounds, it results in a success.
out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds.
"""
bounds = np.array([[0.], [distance]])
super(DistanceCondition, self).__init__(body, bounds=bounds, dim=dim, stay=stay, out=out)
self.center = np.asarray(center)
def _get_states(self):
"""Return the state."""
position = self.body.position - self.center
if self.dim is None:
return np.linalg.norm(position)
return np.linalg.norm(position[self.dim]) | en | 0.917716 | #!/usr/bin/env python # -*- coding: utf-8 -*- Define some body terminal conditions for the environment. Body Terminal Condition This terminal condition describes 8 cases (4 failure and 4 success cases): 1. all the dimensions of the body state are: 1. in a certain bounds and must stay between these bounds. Once one gets out, the terminal condition is over, and results in a failure. (all=True, out=False, stay=True) 2. in a certain bounds and must get out of these bounds. Once they all get out, the terminal condition is over, and results in a success. (all=True, out=False, stay=False) 3. outside a certain bounds and must get in. Once they all get in, the terminal condition is over, and results in a success. (all=True, out=True, stay=False) 4. outside a certain bounds and must stay outside these ones. Once one gets in, the terminal condition is over, and results in a failure. (all=True, out=True, stay=True) 2. any of the dimension of the body state is: 1. in a certain bounds and must stay between these bounds. Once they all get out, the terminal condition is over, and results in a failure. (all=False, out=False, stay=True) 2. in a certain bounds and must get out of these bounds. Once one gets out, the terminal condition is over, and results in a success. (all=False, out=False, stay=False) 3. outside a certain bounds and must get in. Once one gets in, the terminal condition is over, and results in a success. (all=False ,out=True, stay=False) 4. outside a certain bounds and must stay outside these ones. Once they all get in, the terminal condition is over, and results in a failure. (all=False, out=True, stay=True) Body state includes the position and orientation for instance. Initialize the body terminal condition. Args: body (Body): body instance dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1] means to consider the bounds along the x and z axes. all (bool): this is only used if they are multiple dimensions. if True, all the dimensions of the state are checked if they are inside or outside the bounds depending on the other parameters. if False, any dimensions will be checked. stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the state leave the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds; if the state leaves the bounds, it results in a success. out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds. ############## # Properties # ############## Return the body instance. Set the body instance. Return the dimension(s). Set the dimensions. Return the simulator instance. ########### # Methods # ########### Check the given bounds. # check the type of the bounds # check that the bounds have a length of 2 (i.e. lower and upper bounds) # if one of the bounds is None, raise error # reshape bounds if necessary Check if the terminating condition has been fulfilled, and return True or False accordingly # all the dimension states # are outside a certain bounds # and must stay outside these ones. # one dimension went inside # failure # it is over # they are still all outside # success # it is not over # and must go inside these ones # they all went inside # success # it is over # they are some still left outside # failure # it is not over # are inside a certain bounds # and must stay inside these ones. # one dimension went outside # failure # it is over # they are still all inside # success # it is not over # and must go outside these ones. # they are still some inside # failure # it is not over # they are all outside # success # it is over # any of the dimension states # is outside a certain bounds # and still stays outside these ones. # at least one dim. is still outside # success # it is not over # they are all inside # failure # it is over # and one must at least go inside these ones # at least one state is inside # success # it is over # they are still all outside # failure # it is not over # is inside a certain bounds # and must stay inside these ones. # at least one state is still inside # success # it is not over # they are all outside # failure # it is over # and must go outside these ones. # they are all inside # failure # it is not over # at least one went outside # success # it is over Get the base states. Has to be implemented in the child class. World position terminal condition This terminal condition describes 8 cases (4 failure and 4 success cases): 1. all the dimensions of the body position state are: 1. in a certain bounds and must stay between these bounds. Once one gets out, the terminal condition is over, and results in a failure. (all=True, out=False, stay=True) 2. in a certain bounds and must get out of these bounds. Once they all get out, the terminal condition is over, and results in a success. (all=True, out=False, stay=False) 3. outside a certain bounds and must get in. Once they all get in, the terminal condition is over, and results in a success. (all=True, out=True, stay=False) 4. outside a certain bounds and must stay outside these ones. Once one gets in, the terminal condition is over, and results in a failure. (all=True, out=True, stay=True) 2. any of the dimension of the body position state is: 1. in a certain bounds and must stay between these bounds. Once they all get out, the terminal condition is over, and results in a failure. (all=False, out=False, stay=True) 2. in a certain bounds and must get out of these bounds. Once one gets out, the terminal condition is over, and results in a success. (all=False, out=False, stay=False) 3. outside a certain bounds and must get in. Once one gets in, the terminal condition is over, and results in a success. (all=False ,out=True, stay=False) 4. outside a certain bounds and must stay outside these ones. Once they all get in, the terminal condition is over, and results in a failure. (all=False, out=True, stay=True) Initialize the world position terminal condition. Args: body (Body): body instance. bounds (tuple of 2 float / np.array[3]): bounds on the body position. dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1] means to consider the bounds along the x and z axes. out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds. stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the position leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds; if the position leaves the bounds, it results in a success. all (bool): this is only used if they are multiple dimensions. if True, all the dimensions of the state are checked if they are inside or outside the bounds depending on the other parameters. if False, any dimensions will be checked. # check the bounds Return the state. World orientation terminal condition This terminal condition describes 8 cases (4 failure and 4 success cases): 1. all the dimensions of the body orientation (expressed as roll-pitch-yaw angles) state are: 1. in a certain bounds and must stay between these bounds. Once one gets out, the terminal condition is over, and results in a failure. (all=True, out=False, stay=True) 2. in a certain bounds and must get out of these bounds. Once they all get out, the terminal condition is over, and results in a success. (all=True, out=False, stay=False) 3. outside a certain bounds and must get in. Once they all get in, the terminal condition is over, and results in a success. (all=True, out=True, stay=False) 4. outside a certain bounds and must stay outside these ones. Once one gets in, the terminal condition is over, and results in a failure. (all=True, out=True, stay=True) 2. any of the dimension of the body orientation (expressed as roll-pitch-yaw angles) state is: 1. in a certain bounds and must stay between these bounds. Once they all get out, the terminal condition is over, and results in a failure. (all=False, out=False, stay=True) 2. in a certain bounds and must get out of these bounds. Once one gets out, the terminal condition is over, and results in a success. (all=False, out=False, stay=False) 3. outside a certain bounds and must get in. Once one gets in, the terminal condition is over, and results in a success. (all=False ,out=True, stay=False) 4. outside a certain bounds and must stay outside these ones. Once they all get in, the terminal condition is over, and results in a failure. (all=False, out=True, stay=True) Initialize the world orientation terminal condition. Args: body (Body): body instance. bounds (tuple of 2 float / np.array[3]): bounds on the body orientation expressed as roll-pitch-yaw angles or axis-angle if the :attr:`axis` is provided. dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1] means to consider the bounds along the x (roll) and z (yaw) axes. out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds. stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the orientation leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds; if the orientation leaves the bounds, it results in a success. all (bool): this is only used if they are multiple dimensions. if True, all the dimensions of the state are checked if they are inside or outside the bounds depending on the other parameters. if False, any dimensions will be checked. # check the bounds Return the state. Base orientation axis terminal condition This uses the cosine similarity function by computing the angle between the given axis and one of the axis of the base orientation (i.e. one of the columns of the rotation matrix). This terminal condition describes 4 cases (2 failure and 2 success cases); the angle is in: 1. in a certain bounds and must stay between these bounds. Once it gets out, the terminal condition is over, and results in a failure. (stay=True, out=False --> must stay in) 2. in a certain bounds and must get out of these bounds. Once it gets out, the terminal condition is over, and results in a success. (stay=False, out=False --> must not stay in) 3. outside a certain bounds and must get in. Once it gets in, the terminal condition is over, and results in a success. (stay=False, out=True --> must not stay out) 4. outside a certain bounds and must stay outside these ones. Once it gets in, the terminal condition is over, and results in a failure. (stay=True, out=True --> must stay out) Initialize the base orientation axis terminal condition. Args: body (Body): body instance. angle (float): angle bound. axis (tuple/list[float[3]], np.array[float[3]]): axis. dim (int): column that we should consider for the rotation matrix. stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the orientation leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds; if the orientation leaves the bounds, it results in a success. out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds. # 1.1 is just to be sure Return the state. Base Height terminal condition This terminal condition describes 4 cases (2 failure and 2 success cases); the base height (i.e. z-position) state is: 1. in a certain bounds and must stay between these bounds. Once it gets out, the terminal condition is over, and results in a failure. (stay=True, out=False --> must stay in) 2. in a certain bounds and must get out of these bounds. Once it gets out, the terminal condition is over, and results in a success. (stay=False, out=False --> must not stay in) 3. outside a certain bounds and must get in. Once it gets in, the terminal condition is over, and results in a success. (stay=False, out=True --> must not stay out) 4. outside a certain bounds and must stay outside these ones. Once it gets in, the terminal condition is over, and results in a failure. (stay=True, out=True --> must stay out) Initialize the base height terminal condition. Args: body (Body): body instance. height (float): max height which defines the bound; the bounds will be defined to be between 0 and height. stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the position leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds; if the position leaves the bounds, it results in a success. out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds. Return the state. Distance terminal condition This is a bit similar than the ``PositionCondition``. The difference is that this class describes a nd-sphere, while the ``PositionCondition`` describes a nd-rectangle. This terminal condition describes 4 cases (2 failure and 2 success cases); the body distance with respect to the provided center must be: 1. in a certain bounds and must stay between these bounds. Once it gets out, the terminal condition is over, and results in a failure. (stay=True, out=False --> must stay in) 2. in a certain bounds and must get out of these bounds. Once it gets out, the terminal condition is over, and results in a success. (stay=False, out=False --> must not stay in) 3. outside a certain bounds and must get in. Once it gets in, the terminal condition is over, and results in a success. (stay=False, out=True --> must not stay out) 4. outside a certain bounds and must stay outside these ones. Once it gets in, the terminal condition is over, and results in a failure. (stay=True, out=True --> must stay out) Initialize the distance terminal condition. Args: body (Body): body instance. distance (float): max distance with respect to the specified :attr:`center`. center (np.array(float[3]), list[float[3]], tuple[float[3]]): center from which take the distance. dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1] means to consider the distance along the x and z axes. stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the position leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds; if the position leaves the bounds, it results in a success. out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds. Return the state. | 2.559832 | 3 |
LintCode/chapter 20/17. Subsets/.ipynb_checkpoints/solution_4-checkpoint.py | vincent507cpu/Comprehensive-Algorithm-Solution | 4 | 6617744 | <gh_stars>1-10
# DFS 2
class Solution:
"""
@param nums: A set of numbers
@return: A list of lists
"""
def subsets(self, nums):
# write your code here
if not nums:
return [[]]
results = []
nums.sort()
self.dfs(nums, 0, [], results)
return results
def dfs(self, nums, start_index, path, results):
# if start_index == len(nums):
results.append(path[:])
for i in range(start_index, len(nums)):
path.append(nums[i])
self.dfs(nums, i + 1, path, results)
path.pop() | # DFS 2
class Solution:
"""
@param nums: A set of numbers
@return: A list of lists
"""
def subsets(self, nums):
# write your code here
if not nums:
return [[]]
results = []
nums.sort()
self.dfs(nums, 0, [], results)
return results
def dfs(self, nums, start_index, path, results):
# if start_index == len(nums):
results.append(path[:])
for i in range(start_index, len(nums)):
path.append(nums[i])
self.dfs(nums, i + 1, path, results)
path.pop() | en | 0.492455 | # DFS 2 @param nums: A set of numbers @return: A list of lists # write your code here # if start_index == len(nums): | 3.635705 | 4 |
test_config.py | SkuldNorniern/upbit_trader | 0 | 6617745 | <gh_stars>0
from modules import datasetmod as dsm
def test_answer():
assert dsm.check() == "pass"
| from modules import datasetmod as dsm
def test_answer():
assert dsm.check() == "pass" | none | 1 | 1.349941 | 1 | |
yosim/settings/apps.py | thoongnv/yosim | 2 | 6617746 | <reponame>thoongnv/yosim
# -*- coding: utf-8 -*-
from django.apps import AppConfig
class SettingsConfig(AppConfig):
name = 'yosim.settings'
verbose_name = "Settings"
def ready(self):
pass
| # -*- coding: utf-8 -*-
from django.apps import AppConfig
class SettingsConfig(AppConfig):
name = 'yosim.settings'
verbose_name = "Settings"
def ready(self):
pass | en | 0.769321 | # -*- coding: utf-8 -*- | 1.289593 | 1 |
melissa/actions/sleep.py | blacksparrow6/Melissa-Core | 554 | 6617747 | <reponame>blacksparrow6/Melissa-Core
import random
# Melissa
from melissa import profile
from melissa.tts import tts
WORDS = {'go_to_sleep': {'groups': ['sleep', 'bye', 'deactivate', 'stop',
'suspend', 'quit', ['power', 'off'], ['stand', 'down'],
['good', 'bye']]}}
def go_to_sleep(text):
replies = ['See you later!', 'Just call my name and I\'ll be there!']
tts(random.choice(replies))
if profile.data['hotword_detection'] == 'on':
print('\nListening for Keyword...')
print('Press Ctrl+C to exit')
quit()
| import random
# Melissa
from melissa import profile
from melissa.tts import tts
WORDS = {'go_to_sleep': {'groups': ['sleep', 'bye', 'deactivate', 'stop',
'suspend', 'quit', ['power', 'off'], ['stand', 'down'],
['good', 'bye']]}}
def go_to_sleep(text):
replies = ['See you later!', 'Just call my name and I\'ll be there!']
tts(random.choice(replies))
if profile.data['hotword_detection'] == 'on':
print('\nListening for Keyword...')
print('Press Ctrl+C to exit')
quit() | none | 1 | 2.828441 | 3 | |
tools/test_apps/build_system/ldalign_test/check_alignment.py | lovyan03/esp-idf | 8,747 | 6617748 | <filename>tools/test_apps/build_system/ldalign_test/check_alignment.py
#!/usr/bin/env python
#
# Copyright 2020 Espressif Systems (Shanghai) PTE LTD
#
# 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 argparse
import re
import subprocess
from typing import Tuple
argparser = argparse.ArgumentParser()
argparser.add_argument('readelf')
argparser.add_argument('elf')
args = argparser.parse_args()
# Get the content of the readelf command
contents = subprocess.check_output([args.readelf, '-S', args.elf]).decode()
# Define a class for readelf parsing error
class ParsingError(Exception):
pass
# Look for the start address and size of any section
def find_partition_info(sectionname): # type: (str) -> Tuple[int, int, int]
match = re.search(sectionname + r'\s+PROGBITS\s+([a-f0-9]+) [a-f0-9]+ ([a-f0-9]+) \d+\s+[A-Z]+ 0 0 (\d+)',
contents)
if not match:
raise ParsingError('ELF header parsing error')
# Return the address of the section, the size and the alignment
address = match.group(1)
size = match.group(2)
alignment = match.group(3)
return (int(address, 16), int(size, 16), int(alignment, 10))
# Get address and size for .flash.appdesc section
app_address, app_size, app_align = find_partition_info('.flash.appdesc')
# Same goes for .flash.rodata section
rodata_address, _, rodata_align = find_partition_info('.flash.rodata')
# Assert than everything is as expected:
# appdesc is aligned on 16
# rodata is aligned on 64
# appdesc ends where rodata starts
assert app_align == 16, '.flash.appdesc section should have been aligned on 16!'
assert rodata_align == 64, '.flash.rodata section should have been aligned on 64!'
assert app_address + app_size == rodata_address, ".flash.appdesc's end address and .flash.rodata's begin start must have no gap in between!"
| <filename>tools/test_apps/build_system/ldalign_test/check_alignment.py
#!/usr/bin/env python
#
# Copyright 2020 Espressif Systems (Shanghai) PTE LTD
#
# 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 argparse
import re
import subprocess
from typing import Tuple
argparser = argparse.ArgumentParser()
argparser.add_argument('readelf')
argparser.add_argument('elf')
args = argparser.parse_args()
# Get the content of the readelf command
contents = subprocess.check_output([args.readelf, '-S', args.elf]).decode()
# Define a class for readelf parsing error
class ParsingError(Exception):
pass
# Look for the start address and size of any section
def find_partition_info(sectionname): # type: (str) -> Tuple[int, int, int]
match = re.search(sectionname + r'\s+PROGBITS\s+([a-f0-9]+) [a-f0-9]+ ([a-f0-9]+) \d+\s+[A-Z]+ 0 0 (\d+)',
contents)
if not match:
raise ParsingError('ELF header parsing error')
# Return the address of the section, the size and the alignment
address = match.group(1)
size = match.group(2)
alignment = match.group(3)
return (int(address, 16), int(size, 16), int(alignment, 10))
# Get address and size for .flash.appdesc section
app_address, app_size, app_align = find_partition_info('.flash.appdesc')
# Same goes for .flash.rodata section
rodata_address, _, rodata_align = find_partition_info('.flash.rodata')
# Assert than everything is as expected:
# appdesc is aligned on 16
# rodata is aligned on 64
# appdesc ends where rodata starts
assert app_align == 16, '.flash.appdesc section should have been aligned on 16!'
assert rodata_align == 64, '.flash.rodata section should have been aligned on 64!'
assert app_address + app_size == rodata_address, ".flash.appdesc's end address and .flash.rodata's begin start must have no gap in between!"
| en | 0.813286 | #!/usr/bin/env python # # Copyright 2020 Espressif Systems (Shanghai) PTE LTD # # 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. # # Get the content of the readelf command # Define a class for readelf parsing error # Look for the start address and size of any section # type: (str) -> Tuple[int, int, int] # Return the address of the section, the size and the alignment # Get address and size for .flash.appdesc section # Same goes for .flash.rodata section # Assert than everything is as expected: # appdesc is aligned on 16 # rodata is aligned on 64 # appdesc ends where rodata starts | 2.284391 | 2 |
barry/data/desi_mock_challenge_0/pickle.py | nam8/Barry | 13 | 6617749 | import pickle
import pandas as pd
import numpy as np
def getdf(loc):
df = pd.read_csv(loc, comment="#", delim_whitespace=True, names=["k", "pk0", "pk2"])
return df.astype(np.float32)
def getwin(ks):
res = {"w_ks_input": ks.copy(), "w_k0_scale": np.zeros(ks.size), "w_transform": np.eye(2 * ks.size), "w_ks_output": ks.copy()}
return {1: res} # Step size is one
def getcomp(ks):
matrix = np.eye(2 * ks.size)
return matrix
if __name__ == "__main__":
pk_filename = "Pk_multipoles_BAO_fitting_DC.v0.dat"
cov_filename = "Pk_multipoles_cov_BAO_fitting_DC.v0.dat"
data = getdf(pk_filename)
ks = data["k"].to_numpy()
cov = pd.read_csv(cov_filename, delim_whitespace=True, header=None).to_numpy()
split = {
"pre-recon data": [data],
"pre-recon cov": cov.astype(np.float32),
"post-recon data": None,
"post-recon cov": None,
"pre-recon mocks": None,
"post-recon mocks": None,
"cosmology": {"om": 0.31, "h0": 0.676, "z": 0.61, "ob": 0.04814, "ns": 0.97, "reconsmoothscale": 15},
"name": f"DESI Mock BAO Challenge 0, z= Pk",
"winfit": getwin(ks),
"winpk": None, # We can set this to None; Barry will set it to zeroes given the length of the data vector.
"m_mat": getcomp(ks),
}
with open(f"../desi_mock_challenge_0.pkl", "wb") as f:
pickle.dump(split, f)
| import pickle
import pandas as pd
import numpy as np
def getdf(loc):
df = pd.read_csv(loc, comment="#", delim_whitespace=True, names=["k", "pk0", "pk2"])
return df.astype(np.float32)
def getwin(ks):
res = {"w_ks_input": ks.copy(), "w_k0_scale": np.zeros(ks.size), "w_transform": np.eye(2 * ks.size), "w_ks_output": ks.copy()}
return {1: res} # Step size is one
def getcomp(ks):
matrix = np.eye(2 * ks.size)
return matrix
if __name__ == "__main__":
pk_filename = "Pk_multipoles_BAO_fitting_DC.v0.dat"
cov_filename = "Pk_multipoles_cov_BAO_fitting_DC.v0.dat"
data = getdf(pk_filename)
ks = data["k"].to_numpy()
cov = pd.read_csv(cov_filename, delim_whitespace=True, header=None).to_numpy()
split = {
"pre-recon data": [data],
"pre-recon cov": cov.astype(np.float32),
"post-recon data": None,
"post-recon cov": None,
"pre-recon mocks": None,
"post-recon mocks": None,
"cosmology": {"om": 0.31, "h0": 0.676, "z": 0.61, "ob": 0.04814, "ns": 0.97, "reconsmoothscale": 15},
"name": f"DESI Mock BAO Challenge 0, z= Pk",
"winfit": getwin(ks),
"winpk": None, # We can set this to None; Barry will set it to zeroes given the length of the data vector.
"m_mat": getcomp(ks),
}
with open(f"../desi_mock_challenge_0.pkl", "wb") as f:
pickle.dump(split, f)
| en | 0.871378 | # Step size is one # We can set this to None; Barry will set it to zeroes given the length of the data vector. | 2.413499 | 2 |
setup.py | mikhaildruzhinin/flask-blog | 0 | 6617750 | <reponame>mikhaildruzhinin/flask-blog<filename>setup.py
from setuptools import (
find_packages,
setup,
)
setup(
name='blog',
version='1.0.0',
packages=find_packages(),
include_package_data=True,
zip_file=False,
install_requires=[
'flask',
],
)
| from setuptools import (
find_packages,
setup,
)
setup(
name='blog',
version='1.0.0',
packages=find_packages(),
include_package_data=True,
zip_file=False,
install_requires=[
'flask',
],
) | none | 1 | 1.120749 | 1 |