hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 10 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 248 | max_stars_repo_name stringlengths 5 125 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 248 | max_issues_repo_name stringlengths 5 125 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 248 | max_forks_repo_name stringlengths 5 125 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 2.06M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.03M | alphanum_fraction float64 0 1 | count_classes int64 0 1.6M | score_classes float64 0 1 | count_generators int64 0 651k | score_generators float64 0 1 | count_decorators int64 0 990k | score_decorators float64 0 1 | count_async_functions int64 0 235k | score_async_functions float64 0 1 | count_documentation int64 0 1.04M | score_documentation float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8933611dccd35f84e21b95c6ea6cb9c0aef59e5b | 633 | py | Python | Codefights/arcade/intro/level-6/25.Array-Replace/Python/test.py | RevansChen/online-judge | ad1b07fee7bd3c49418becccda904e17505f3018 | [
"MIT"
] | 7 | 2017-09-20T16:40:39.000Z | 2021-08-31T18:15:08.000Z | Codefights/arcade/intro/level-6/25.Array-Replace/Python/test.py | RevansChen/online-judge | ad1b07fee7bd3c49418becccda904e17505f3018 | [
"MIT"
] | null | null | null | Codefights/arcade/intro/level-6/25.Array-Replace/Python/test.py | RevansChen/online-judge | ad1b07fee7bd3c49418becccda904e17505f3018 | [
"MIT"
] | null | null | null | # Python3
from solution1 import arrayReplace as f
qa = [
([1, 2, 1], 1, 3,
[3, 2, 3]),
([1, 2, 3, 4, 5], 3, 0,
[1, 2, 0, 4, 5]),
([1, 1, 1], 1, 10,
[10, 10, 10]),
([1, 2, 1, 2, 1], 2, 1,
[1, 1, 1, 1, 1]),
([1, 2, 1, 2, 1], 2, 2,
[1, 2, 1, 2, 1]),
([3, 1], 3, 9,
[9, 1])
]
for *q, a in qa:
for i, e in enumerate(q):
print('input{0}: {1}'.format(i + 1, e))
ans = f(*q)
if ans != a:
print(' [failed]')
print(' output:', ans)
print(' expected:', a)
else:
print(' [ok]')
print(' output:', ans)
print()
| 19.78125 | 47 | 0.366509 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 85 | 0.134281 |
8934d1367807f17b7ccddc78c329f89fdb3334b2 | 8,563 | py | Python | tests/inception/test_inception_hardware_perf.py | ispras/avatar2 | 5bab7239c368cc69d4f63d5fbb724808a6aa87b6 | [
"Apache-2.0"
] | 415 | 2017-06-14T07:49:50.000Z | 2022-03-31T12:32:58.000Z | tests/inception/test_inception_hardware_perf.py | HexHive/avatar2 | b406c3512f6bcf6f7635c6bd70a5951bde9ae0a2 | [
"Apache-2.0"
] | 58 | 2017-06-16T14:51:12.000Z | 2022-03-25T14:13:32.000Z | tests/inception/test_inception_hardware_perf.py | HexHive/avatar2 | b406c3512f6bcf6f7635c6bd70a5951bde9ae0a2 | [
"Apache-2.0"
] | 101 | 2017-06-16T09:05:12.000Z | 2022-03-23T12:23:19.000Z | from avatar2 import *
import sys
import os
import logging
import serial
import time
import argparse
import pyudev
import struct
import ctypes
from random import randint
# For profiling
import pstats
logging.basicConfig(filename='/tmp/inception-tests.log', level=logging.INFO)
# ****************************************************************************
def single_step(target, nb_test):
print("[*] Single step target %d times" % nb_test)
for i in range(nb_test):
pc = target.protocols.execution.read_pc()
print(pc)
target.step()
print('stepped')
next_pc = target.protocols.execution.read_pc()
print(next_pc)
# ****************************************************************************
def read_full_mem(target, nb_test, raw=True, summary=True):
print(" - Read the full memory")
nb_test = 1
average_read = 0
for i in range(nb_test):
t0 = time.time()
target.read_memory(ram.address, 1, ram.size, raw=raw)
t1 = time.time()
average_read += t1 - t0
if summary:
average_read = average_read / nb_test
speed_read = ram.size / average_read / 1024
print(" -> On average raw read of %s bytes takes %.2f sec, speed: %.2f KB/sec" % (ram.size, average_read, speed_read))
# ****************************************************************************
def write_full_mem(target, nb_test, raw=True, summary=True):
print(" - Write the full memory")
nb_test = 1
average_write = 0
buf = ctypes.create_string_buffer(ram.size)
for i in range(int(ram.size / 4)):
struct.pack_into(">I", buf, i * 4, randint(0, 0xffffffff))
for i in range(nb_test):
t0 = time.time()
target.write_memory(ram.address, 1, buf, raw=raw)
t1 = time.time()
average_write += t1 - t0
if summary:
average_write = average_write / nb_test
speed_write = ram.size / average_write / 1024
print(" -> On average raw write of %s bytes takes %.2f sec, speed: %.2f KB/sec" % (ram.size, average_write, speed_write))
# ****************************************************************************
def read_write_full_mem(target, nb_test, raw=True, summary=True):
print(" - Read and write the full memory")
reads = []
average_read_write = 0
for i in range(nb_test):
if raw:
t0 = time.time()
reads.append(target.read_memory(ram.address, 1, ram.size, raw=raw))
target.write_memory(ram.address, 1, reads[i], raw=raw)
t1 = time.time()
else:
t0 = time.time()
reads.append(target.read_memory(ram.address, 1, ram.size, raw=raw))
target.write_memory(ram.address, 1, reads[i], len(reads[i]), raw=raw)
t1 = time.time()
average_read_write += t1 - t0
if summary:
average_read_write = average_read_write / nb_test
speed_read_write = ram.size / average_read_write / 1024
print(" -> On average raw read&write of %s bytes takes %.2f sec, speed: %.2f KB/sec" % (ram.size, average_read_write, speed_read_write))
# Verify all reads are identical
for i in range(len(reads) - 1):
assert(reads[i] == reads[i+1])
#print("[!] Multiple reads produce different values !")
# ****************************************************************************
def random_read_write(target, nb_test, raw=True):
print(" - Random read / writes of random size in the ram")
for i in range(0, nb_test):
size = randint(0, int(ram.size / 8)) * 8
#size = 2**4
# Reset the board and wait to reach the breakpoint
target.reset()
target.wait()
if raw:
m1 = ctypes.create_string_buffer(size)
for j in range(int(size / 4)):
struct.pack_into(">I", m1, j * 4, randint(0, 0xFFFFFFFF))
target.write_memory(ram.address, 1, m1, raw=True)
m2 = target.read_memory(ram.address, 1, size, raw=True)
n1, n2 = ([] for i in range(2))
for j in range(int(size / 4)):
n1.append(struct.unpack_from(">I", m1, j)[0])
n2.append(struct.unpack_from(">I", m2, j)[0])
assert(n1 == n2)
#print("i=%s m1: %s m2: %s" % (i, m1.raw, m2))
#print("[!] Multiple random reads produce different values !")
else:
m1 = []
for j in range(int(size / 4)):
m1.append(randint(0, 0xFFFFFFFF))
target.write_memory(ram.address, 1, m1, size, raw=False)
m2 = target.read_memory(ram.address, 1, size, raw=False)
for j in range(int(size / 4)):
assert(m1[j] == m2[j])
#print("[!] Multiple random reads produce different values !")
#print("i=%s j=%s m1[j]: %s m2[j]: %s" % (i, j, m1[j], m2[j]))
# ****************************************************************************
def random_4bytes_read_write(target, nb_test):
print(" - Random read / writes of 4 bytes in the ram")
for i in range(nb_test):
written_word = randint(0, 0xFFFFFFFF)
address = randint(ram.address, ram.address + ram.size - 4)
target.write_memory(address, 4, written_word, 1, raw=False)
read_word = target.read_memory(address, 4, 1, raw=False)
assert(written_word == read_word)
# ****************************************************************************
def read_write_registers(target, nb_test):
print(" - Read / write registers")
regs = ['R0', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'R10',
'R11', 'R12', 'SP', 'LR', 'PC', 'CPSR']
for i in range(nb_test):
for j in range(17):
written_reg = randint(0, 0xFFFFFFFF)
saved_reg = target.read_register(regs[j])
target.write_register(regs[j], written_reg)
read_reg = target.read_register(regs[j])
'''
if read_reg != written_reg:
print(i)
print(j)
print(hex(read_reg))
print(hex(written_reg))
'''
target.write_register(regs[j], saved_reg)
# ****************************************************************************
def transfer_state(av, target_from, target_to, nb_test, summary=True):
print(" - Transfer state")
average = 0
for i in range(nb_test):
t0 = time.time()
av.transfer_state(target_from, target_to, synced_ranges=[ram])
t1 = time.time()
average += t1 - t0
if summary:
average = average / nb_test
speed = ram.size / average / 1024
print(" -> On average transfer state from %s to %s of %s bytes takes %.2f sec, speed: %.2f KB/sec" % (target_from.name, target_to.name, ram.size, average, speed))
if __name__ == '__main__':
# Number each test is repeated
n = 2
avatar = Avatar(arch=ARMV7M, output_directory='/tmp/inception-tests')
nucleo = avatar.add_target(InceptionTarget, name='nucleo')
dum = avatar.add_target(DummyTarget, name='dum')
#qemu = avatar.add_target(QemuTarget, gdb_port=1236)
# Memory mapping of NUCLEO-L152RE
rom = avatar.add_memory_range(0x08000000, 0x1000000, 'rom',
file=firmware)
ram = avatar.add_memory_range(0x20000000, 0x14000, 'ram')
mmio = avatar.add_memory_range(0x40000000, 0x1000000,
forwarded=True, forwarded_to=nucleo)
ram = avatar.get_memory_range(0x20000000)
avatar.init_targets()
print("Targets initialized")
nucleo.reset()
nucleo.cont()
nucleo.stop()
print("Targets stopped, start tests for n = %s" % n)
print("[*] Raw read / writes tests")
read_full_mem(nucleo, n)
write_full_mem(nucleo, n)
read_write_full_mem(nucleo, n)
random_read_write(nucleo, n)
print("[*] !raw read / writes tests")
read_full_mem(nucleo, n, raw=False, summary=False)
write_full_mem(nucleo, n, raw=False, summary=False)
read_write_full_mem(nucleo, n, raw=False, summary=False)
random_read_write(nucleo, n, raw=False)
random_4bytes_read_write(nucleo, 100 * n)
print("[*] Read / Write registers")
read_write_registers(nucleo, n)
print("[*] Transfer state to dummy target")
transfer_state(avatar, nucleo, dum, n)
#Stop all threads for the profiler
print("[*] Test completed")
avatar.stop()
| 33.84585 | 172 | 0.552727 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,333 | 0.272451 |
893500b28f3f57e96f65fa9b86818c48a291c5c0 | 1,164 | py | Python | tianshou/env/worker/dummy.py | Leeqh666/tianshou | f71db624bee67b6170caaa06b0d3f68901b87985 | [
"MIT"
] | null | null | null | tianshou/env/worker/dummy.py | Leeqh666/tianshou | f71db624bee67b6170caaa06b0d3f68901b87985 | [
"MIT"
] | null | null | null | tianshou/env/worker/dummy.py | Leeqh666/tianshou | f71db624bee67b6170caaa06b0d3f68901b87985 | [
"MIT"
] | null | null | null | import gym
import numpy as np
from typing import List, Callable, Optional, Any
from tianshou.env.worker import EnvWorker
class DummyEnvWorker(EnvWorker):
"""Dummy worker used in sequential vector environments."""
def __init__(self, env_fn: Callable[[], gym.Env]) -> None:
super().__init__(env_fn)
self.env = env_fn()
def __getattr__(self, key: str) -> Any:
return getattr(self.env, key)
def reset(self) -> Any:
return self.env.reset()
@staticmethod
def wait(workers: List['DummyEnvWorker'],
wait_num: int,
timeout: Optional[float] = None) -> List['DummyEnvWorker']:
# SequentialEnvWorker objects are always ready
return workers
def send_action(self, action: np.ndarray) -> None:
self.result = self.env.step(action)
def seed(self, seed: Optional[int] = None) -> List[int]:
return self.env.seed(seed) if hasattr(self.env, 'seed') else None
def render(self, **kwargs) -> Any:
return self.env.render(**kwargs) \
if hasattr(self.env, 'render') else None
def close_env(self) -> None:
self.env.close()
| 29.1 | 73 | 0.631443 | 1,039 | 0.892612 | 0 | 0 | 238 | 0.204467 | 0 | 0 | 150 | 0.128866 |
89352fbdd1b631cd689cfa66c662c5a6306871c6 | 6,687 | py | Python | beartype/_decor/conf.py | posita/beartype | e56399686e1f2ffd5128a4030b19314504e32450 | [
"MIT"
] | null | null | null | beartype/_decor/conf.py | posita/beartype | e56399686e1f2ffd5128a4030b19314504e32450 | [
"MIT"
] | null | null | null | beartype/_decor/conf.py | posita/beartype | e56399686e1f2ffd5128a4030b19314504e32450 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2021 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype decorator configuration API** (i.e., enumerations, classes,
singletons, and other attributes enabling external callers to selectively
configure the :func:`beartype` decorator on a fine-grained per-decoration call
basis).
Most of the public attributes defined by this private submodule are explicitly
exported to external callers in our top-level :mod:`beartype.__init__`
submodule. This private submodule is *not* intended for direct importation by
downstream callers.
'''
# ....................{ IMPORTS }....................
from enum import (
Enum,
auto as next_enum_member_value,
unique as die_unless_enum_member_values_unique,
)
# ....................{ ENUMERATIONS }....................
#FIXME: Unit test us up, please.
@die_unless_enum_member_values_unique
class BeartypeStrategy(Enum):
'''
Enumeration of all kinds of **container type-checking strategies** (i.e.,
competing procedures for type-checking items of containers passed to or
returned from :func:`beartype.beartype`-decorated callables, each with
concomitant benefits and disadvantages with respect to runtime complexity
and quality assurance).
Strategies are intentionally named according to `conventional Big O
notation <Big O_>`__ (e.g., :attr:`BeartypeStrategy.On` enables the
``O(n)`` strategy). Strategies are established per-decoration at the
fine-grained level of callables decorated by the :func: `beartype.beartype`
decorator by either:
* Calling a high-level convenience decorator establishing that strategy
(e.g., :func:`beartype.conf.beartype_On`, enabling the ``O(n)`` strategy
for all callables decorated by that decorator).
* Setting the :attr:`BeartypeConfiguration.strategy` variable of the
:attr:`BeartypeConfiguration` object passed as the optional ``conf``
parameter to the lower-level core :func: `beartype.beartype` decorator.
Strategies enforce and guarantee their corresponding runtime complexities
(e.g., ``O(n)``) across all type checks performed for all callables
enabling those strategies. For example, a callable decorated with the
:attr:`BeartypeStrategy.On` strategy will exhibit linear runtime complexity
as its type-checking overhead.
.. _Big O:
https://en.wikipedia.org/wiki/Big_O_notation
Attributes
----------
O0 : EnumMemberType
**No-time strategy** (i.e, disabling type-checking for a callable by
reducing :func:`beartype.beartype` to the identity decorator for that
callable). Although currently useless, this strategy will usefully
allow end users to selectively prevent callables from being
type-checked by our as-yet-unimplemented import hook. When implemented,
that hook will type-check *all* callables in a given package by
default. Some means is needed to prevent that from happening for select
callables. This is that means.
O1 : EnumMemberType
**Constant-time strategy** (i.e., our default ``O(1)`` strategy
type-checking a single randomly selected item of a container that you
currently enjoy). Since this is the default, this strategy need *not*
be explicitly configured.
Ologn : EnumMemberType
**Logarithmic-time strategy** (i.e., an ``O(lgn)` strategy
type-checking a randomly selected number of items ``j`` of a container
``obj`` such that ``j = len(obj)``. This strategy is **currently
unimplemented.** (*To be implemented by a future beartype release.*)
On : EnumMemberType
**Linear-time strategy** (i.e., an ``O(n)`` strategy type-checking
*all* items of a container. This strategy is **currently
unimplemented.** (*To be implemented by a future beartype release.*)
'''
O0 = next_enum_member_value()
O1 = next_enum_member_value()
Ologn = next_enum_member_value()
On = next_enum_member_value()
# ....................{ CLASSES }....................
#FIXME: *INSUFFICIENT.* Critically, we also *MUST* declare a __new__() method
#to enforce memoization. A new "BeartypeConfiguration" instance is instantiated
#*ONLY* if no existing instance with the same settings has been previously
#instantiated; else, an existing cached instance is reused. This is essential,
#as the @beartype decorator itself memoizes on the basis of this instance. See
#the following StackOverflow post for the standard design pattern:
# https://stackoverflow.com/a/13054570/2809027
#
#Note, however, that there's an intriguing gotcha:
# "When you define __new__, you usually do all the initialization work in
# __new__; just don't define __init__ at all."
#
#Why? Because if you define both __new__() and __init__() then Python
#implicitly invokes *BOTH*, even if the object returned by __new__() has
#already been previously initialized with __init__(). This is a facepalm
#moment, although the rationale does indeed make sense. Ergo, we *ONLY* want to
#define __new__(); the existing __init__() should simply be renamed __new__()
#and generalized from there to support caching.
#FIXME: Unit test us up, please.
#FIXME: Document us up, please.
class BeartypeConfiguration(object):
'''
* An `is_debug` boolean instance variable. When enabled, `@beartype`
emits debugging information for the decorated callable – including
the code for the wrapper function dynamically generated by
`@beartype` that type-checks that callable.
* A `strategy` instance variable whose value must be a
`BeartypeStrategy` enumeration member. This is how you notify
`@beartype` of which strategy to apply to each callable.
'''
is_debug: bool
strategy: BeartypeStrategy
def __init__(
self,
is_debug: bool = False,
strategy: BeartypeStrategy = BeartypeStrategy.O1,
) -> None:
#FIXME: Implement actual validation, please.
if not isinstance(is_debug, bool):
raise ValueError()
if not isinstance(strategy, BeartypeStrategy):
raise ValueError()
self.is_debug = is_debug
self.strategy = strategy
# ....................{ SINGLETONS }....................
#FIXME: Unit test us up, please.
#FIXME: Document us up, please. Note this attribute is intentionally *NOT*
#exported from "beartype.__init__".
BEAR_CONF_DEFAULT = BeartypeConfiguration()
| 46.117241 | 79 | 0.686257 | 4,133 | 0.61788 | 0 | 0 | 3,199 | 0.478248 | 0 | 0 | 5,810 | 0.86859 |
89386b743e51694854f66d61583124c986f918df | 349 | py | Python | 001-099/38/38.py | lunixbochs/project-euler | aa974c5ae68547309f33adbb4e633fe040964855 | [
"MIT"
] | 6 | 2015-07-21T20:45:08.000Z | 2021-03-13T14:07:48.000Z | 001-099/38/38.py | lunixbochs/project-euler | aa974c5ae68547309f33adbb4e633fe040964855 | [
"MIT"
] | null | null | null | 001-099/38/38.py | lunixbochs/project-euler | aa974c5ae68547309f33adbb4e633fe040964855 | [
"MIT"
] | 2 | 2017-10-28T09:52:08.000Z | 2019-04-11T00:55:36.000Z | ref = set('123456789')
def pans(n):
r = str(n)
i = 1
while True:
i += 1
r += str(i * n)
if len(r) > 9:
break
if len(r) == 9 and set(r) == ref:
yield i, r
m = 0
for i in xrange(2, 1000000000):
for z, n in pans(i):
if n > m:
m = n
print z, i, n
| 17.45 | 41 | 0.383954 | 0 | 0 | 198 | 0.567335 | 0 | 0 | 0 | 0 | 11 | 0.031519 |
89390457453d455098d6d865b97a3debbac7c065 | 43 | py | Python | sugaroid/version.py | blackxspade/sugaroid | 64e2031c1b432e6647b15f59120879c7e1b9f8f8 | [
"MIT"
] | null | null | null | sugaroid/version.py | blackxspade/sugaroid | 64e2031c1b432e6647b15f59120879c7e1b9f8f8 | [
"MIT"
] | null | null | null | sugaroid/version.py | blackxspade/sugaroid | 64e2031c1b432e6647b15f59120879c7e1b9f8f8 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
VERSION = "v0.22.0"
| 14.333333 | 22 | 0.651163 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 31 | 0.72093 |
893a18910761a8b9355e949965665e778b901cd2 | 187 | py | Python | nixnet/_session/__init__.py | ni-ldp/nixnet-python | 83f30c5b44098de0dc4828838e263b7be0866228 | [
"MIT"
] | 16 | 2017-06-14T19:44:45.000Z | 2022-02-06T15:14:52.000Z | nixnet/_session/__init__.py | ni-ldp/nixnet-python | 83f30c5b44098de0dc4828838e263b7be0866228 | [
"MIT"
] | 216 | 2017-06-15T16:41:10.000Z | 2021-09-23T23:00:50.000Z | nixnet/_session/__init__.py | ni-ldp/nixnet-python | 83f30c5b44098de0dc4828838e263b7be0866228 | [
"MIT"
] | 23 | 2017-06-14T22:51:08.000Z | 2022-03-03T03:04:40.000Z | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import typing # NOQA: F401
__all__ = [] # type: typing.List[typing.Text]
| 23.375 | 46 | 0.791444 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 44 | 0.232804 |
893b8dc20ad6ef7ad20e4051cafdb423c6e82129 | 11,196 | py | Python | hedweb/services.py | hed-standard/hed-web | 8603526266dff78cf07e49e6c0f0c715a9225289 | [
"MIT"
] | null | null | null | hedweb/services.py | hed-standard/hed-web | 8603526266dff78cf07e49e6c0f0c715a9225289 | [
"MIT"
] | null | null | null | hedweb/services.py | hed-standard/hed-web | 8603526266dff78cf07e49e6c0f0c715a9225289 | [
"MIT"
] | 2 | 2022-02-04T19:55:40.000Z | 2022-02-04T21:36:04.000Z | import os
import io
import json
from flask import current_app
from hed import models
from hed.errors import HedFileError
from hed import schema as hedschema
from hedweb.constants import base_constants
from hedweb import events, spreadsheet, sidecar, strings
app_config = current_app.config
def get_input_from_request(request):
""" Get a dictionary of input from a service request.
Args:
request (Request): A Request object containing user data for the service request.
Returns:
dict: A dictionary containing input arguments for calling the service request.
"""
form_data = request.data
form_string = form_data.decode()
service_request = json.loads(form_string)
arguments = get_service_info(service_request)
arguments[base_constants.SCHEMA] = get_input_schema(service_request)
get_columns_selected(arguments, service_request)
get_sidecars(arguments, service_request)
get_input_objects(arguments, service_request)
arguments[base_constants.QUERY] = service_request.get('query', None)
return arguments
def get_columns_selected(arguments, params):
""" Update arguments with the columns that are categorical or value where appropriate.
Args:
arguments (dict): A dictionary with the extracted parameters that are to be processed.
params (dict): The service request dictionary extracted from the Request object.
Updates the arguments dictionary with the column information in service_request.
"""
if 'columns_categorical' not in params and 'columns_value' not in params:
return
columns_selected = {}
for column in params['columns_categorical']:
columns_selected[column] = True
for column in params['columns_value']:
columns_selected[column] = False
arguments[base_constants.COLUMNS_SELECTED] = columns_selected
def get_sidecars(arguments, params):
""" Update arguments with the sidecars if there are any.
Args:
arguments (dict): A dictionary with the extracted parameters that are to be processed.
params (dict): The service request dictionary extracted from the Request object.
Updates the arguments dictionary with the sidecars.
"""
sidecar_list = []
if base_constants.JSON_STRING in params and params[base_constants.JSON_STRING]:
sidecar_list = [models.Sidecar(file=io.StringIO(params[base_constants.JSON_STRING]), name='JSON_Sidecar')]
elif base_constants.JSON_LIST in params and params[base_constants.JSON_LIST]:
for index, sidecar_string in params[base_constants.JSON_LIST].items():
if not sidecar_string:
continue
sidecar_list.append(models.Sidecar(file=io.StringIO(params[base_constants.JSON_STRING]),
name=f"JSON_Sidecar {index}"))
arguments[base_constants.JSON_SIDECARS] = sidecar_list
def get_input_objects(arguments, params):
""" Update arguments with the information in the params dictionary.
Args:
arguments (dict): A dictionary with the extracted parameters that are to be processed.
params (dict): A dictionary of the service request values.
Updates the arguments dictionary with the input objects including events, spreadsheets, schemas or strings.
"""
if base_constants.EVENTS_STRING in params and params[base_constants.EVENTS_STRING]:
arguments[base_constants.EVENTS] = \
models.EventsInput(file=io.StringIO(params[base_constants.EVENTS_STRING]),
sidecars=arguments.get(base_constants.JSON_SIDECARS, None), name='Events')
if base_constants.SPREADSHEET_STRING in params and params[base_constants.SPREADSHEET_STRING]:
tag_columns, prefix_dict = spreadsheet.get_prefix_dict(params)
has_column_names = arguments.get(base_constants.HAS_COLUMN_NAMES, None)
arguments[base_constants.SPREADSHEET] = \
models.HedInput(file=io.StringIO(params[base_constants.SPREADSHEET_STRING]), file_type=".tsv",
tag_columns=tag_columns,
has_column_names=has_column_names,
column_prefix_dictionary=prefix_dict, name='spreadsheet.tsv')
if base_constants.STRING_LIST in params and params[base_constants.STRING_LIST]:
s_list = []
for s in params[base_constants.STRING_LIST]:
s_list.append(models.HedString(s))
arguments[base_constants.STRING_LIST] = s_list
def get_service_info(params):
""" Get a dictionary with the service request command information filled in..
Args:
params (dict): A dictionary of the service request values.
Returns:
dict: A dictionary with the command, command target and options resolved from the service request.
"""
service = params.get(base_constants.SERVICE, '')
command = service
command_target = ''
pieces = service.split('_', 1)
if command != "get_services" and len(pieces) == 2:
command = pieces[1]
command_target = pieces[0]
has_column_names = params.get(base_constants.HAS_COLUMN_NAMES, '') == 'on'
expand_defs = params.get(base_constants.EXPAND_DEFS, '') == 'on'
check_for_warnings = params.get(base_constants.CHECK_FOR_WARNINGS, '') == 'on'
include_description_tags = params.get(base_constants.INCLUDE_DESCRIPTION_TAGS, '') == 'on'
return {base_constants.SERVICE: service,
base_constants.COMMAND: command,
base_constants.COMMAND_TARGET: command_target,
base_constants.HAS_COLUMN_NAMES: has_column_names,
base_constants.CHECK_FOR_WARNINGS: check_for_warnings,
base_constants.EXPAND_DEFS: expand_defs,
base_constants.INCLUDE_DESCRIPTION_TAGS: include_description_tags
# base_constants.TAG_COLUMNS: tag_columns,
# base_constants.COLUMN_PREFIX_DICTIONARY: prefix_dict
}
def get_input_schema(parameters):
the_schema = None
try:
if base_constants.SCHEMA_STRING in parameters and parameters[base_constants.SCHEMA_STRING]:
the_schema = hedschema.from_string(parameters[base_constants.SCHEMA_STRING])
elif base_constants.SCHEMA_URL in parameters and parameters[base_constants.SCHEMA_URL]:
schema_url = parameters[base_constants.SCHEMA_URL]
the_schema = hedschema.load_schema(schema_url)
elif base_constants.SCHEMA_VERSION in parameters and parameters[base_constants.SCHEMA_VERSION]:
hed_file_path = hedschema.get_path_from_hed_version(parameters[base_constants.SCHEMA_VERSION])
the_schema = hedschema.load_schema(hed_file_path)
except HedFileError:
the_schema = None
return the_schema
def process(arguments):
""" Call the desired service processing function and return the results in a standard format.
Args:
arguments (dict): A dictionary of arguments for the processing resolved from the request.
Returns:
dict: A dictionary of results in standard response format to be jsonified.
"""
command = arguments.get(base_constants.COMMAND, '')
target = arguments.get(base_constants.COMMAND_TARGET, '')
response = {base_constants.SERVICE: arguments.get(base_constants.SERVICE, ''),
'results': '', 'error_type': '', 'error_msg': ''}
if not arguments.get(base_constants.SERVICE, ''):
response["error_type"] = 'HEDServiceMissing'
response["error_msg"] = "Must specify a valid service"
elif command == 'get_services':
response["results"] = services_list()
elif target == "events":
response["results"] = events.process(arguments)
elif target == "sidecar":
response["results"] = sidecar.process(arguments)
elif target == "spreadsheet":
results = spreadsheet.process(arguments)
response["results"] = package_spreadsheet(results)
elif target == "strings":
response["results"] = strings.process(arguments)
else:
response["error_type"] = 'HEDServiceNotSupported'
response["error_msg"] = f"{command} for {target} not supported"
return response
def package_spreadsheet(results):
""" Get the transformed results dictionary where spreadsheets are converted to strings.
Args:
results (dict): The dictionary of results in standardized form returned from processing.
Returns:
dict: The results transformed so that all entries are strings.
"""
if results['msg_category'] == 'success' and base_constants.SPREADSHEET in results:
results[base_constants.SPREADSHEET] = results[base_constants.SPREADSHEET].to_csv(file=None)
elif base_constants.SPREADSHEET in results:
del results[base_constants.SPREADSHEET]
return results
def services_list():
""" Get a formatted string describing services using the resources/services.json file
Returns:
str: A formatted string listing available services.
"""
dir_path = os.path.dirname(os.path.realpath(__file__))
the_path = os.path.join(dir_path, 'static/resources/services.json')
with open(the_path) as f:
service_info = json.load(f)
services = service_info['services']
meanings = service_info['parameter_meanings']
returns = service_info['returns']
results = service_info['results']
services_string = '\nServices:\n'
for service, info in services.items():
description = info['Description']
parameters = get_parameter_string(info['Parameters'])
return_string = info['Returns']
next_string = \
f'\n{service}:\n\tDescription: {description}\n{parameters}\n\tReturns: {return_string}\n'
services_string += next_string
meanings_string = '\nParameter meanings:\n'
for string, meaning in meanings.items():
meanings_string += f'\t{string}: {meaning}\n'
returns_string = '\nReturn values:\n'
for return_val, meaning in returns.items():
returns_string += f'\t{return_val}: {meaning}\n'
results_string = '\nResults field meanings:\n'
for result_val, meaning in results.items():
results_string += f'\t{result_val}: {meaning}\n'
data = services_string + meanings_string + returns_string + results_string
return {base_constants.COMMAND: 'get_services', base_constants.COMMAND_TARGET: '',
'data': data, 'output_display_name': '',
base_constants.SCHEMA_VERSION: '', 'msg_category': 'success',
'msg': "List of available services and their meanings"}
def get_parameter_string(params):
if not params:
return "\tParameters: []"
param_list = []
for p in params:
if isinstance(p, list):
param_list.append( " or ".join(p))
else:
param_list.append(p)
return "\tParameters:\n\t\t" + "\n\t\t".join(param_list)
| 41.620818 | 115 | 0.681761 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,610 | 0.322437 |
893d5a4482f292937557682d8715ef74cab055df | 563 | py | Python | Python/easy/e395.py | tlgs/dailyprogrammer | 6e7d3352616fa54a8e9caf8564a9cfb951eb0af9 | [
"Unlicense"
] | 4 | 2017-10-18T02:17:02.000Z | 2022-02-02T01:19:02.000Z | Python/easy/e395.py | tlseabra/dailyprogrammer | 6e7d3352616fa54a8e9caf8564a9cfb951eb0af9 | [
"Unlicense"
] | 4 | 2016-01-24T20:30:02.000Z | 2017-01-18T16:01:23.000Z | Python/easy/e395.py | tlgs/dailyprogrammer | 6e7d3352616fa54a8e9caf8564a9cfb951eb0af9 | [
"Unlicense"
] | null | null | null | # 22/06/2021
import itertools
def nonogramrow(seq):
return [sum(g) for k, g in itertools.groupby(seq) if k]
assert nonogramrow([]) == []
assert nonogramrow([0, 0, 0, 0, 0]) == []
assert nonogramrow([1, 1, 1, 1, 1]) == [5]
assert nonogramrow([0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1]) == [5, 4]
assert nonogramrow([1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0]) == [2, 1, 3]
assert nonogramrow([0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1]) == [2, 1, 3]
assert nonogramrow([1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]) == [
1,
1,
1,
1,
1,
1,
1,
1,
]
| 22.52 | 72 | 0.488455 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 0.021314 |
893f8bb01e7634c61b028bca09870c81605af91c | 2,191 | py | Python | paura_lite.py | 777AVY777/Clone_paura | 415bb323e31040154d331ba582617841ef909f64 | [
"MIT"
] | 191 | 2016-09-04T23:27:58.000Z | 2022-03-01T07:08:02.000Z | paura_lite.py | 777AVY777/Clone_paura | 415bb323e31040154d331ba582617841ef909f64 | [
"MIT"
] | 9 | 2017-07-06T14:13:55.000Z | 2021-06-06T12:55:07.000Z | paura_lite.py | 777AVY777/Clone_paura | 415bb323e31040154d331ba582617841ef909f64 | [
"MIT"
] | 42 | 2016-11-15T06:16:13.000Z | 2021-08-11T03:46:45.000Z | # paura_lite:
# An ultra-simple command-line audio recorder with real-time
# spectrogram visualization
import numpy as np
import pyaudio
import struct
import scipy.fftpack as scp
import termplotlib as tpl
import os
# get window's dimensions
rows, columns = os.popen('stty size', 'r').read().split()
buff_size = 0.2 # window size in seconds
wanted_num_of_bins = 40 # number of frequency bins to display
# initialize soundcard for recording:
fs = 8000
pa = pyaudio.PyAudio()
stream = pa.open(format=pyaudio.paInt16, channels=1, rate=fs,
input=True, frames_per_buffer=int(fs * buff_size))
while 1: # for each recorded window (until ctr+c) is pressed
# get current block and convert to list of short ints,
block = stream.read(int(fs * buff_size))
format = "%dh" % (len(block) / 2)
shorts = struct.unpack(format, block)
# then normalize and convert to numpy array:
x = np.double(list(shorts)) / (2**15)
seg_len = len(x)
# get total energy of the current window and compute a normalization
# factor (to be used for visualizing the maximum spectrogram value)
energy = np.mean(x ** 2)
max_energy = 0.01 # energy for which the bars are set to max
max_width_from_energy = int((energy / max_energy) * int(columns)) + 1
if max_width_from_energy > int(columns) - 10:
max_width_from_energy = int(columns) - 10
# get the magnitude of the FFT and the corresponding frequencies
X = np.abs(scp.fft(x))[0:int(seg_len/2)]
freqs = (np.arange(0, 1 + 1.0/len(X), 1.0 / len(X)) * fs / 2)
# ... and resample to a fix number of frequency bins (to visualize)
wanted_step = (int(freqs.shape[0] / wanted_num_of_bins))
freqs2 = freqs[0::wanted_step].astype('int')
X2 = np.mean(X.reshape(-1, wanted_step), axis=1)
# plot (freqs, fft) as horizontal histogram:
fig = tpl.figure()
fig.barh(X2, labels=[str(int(f)) + " Hz" for f in freqs2[0:-1]],
show_vals=False, max_width=max_width_from_energy)
fig.show()
# add exactly as many new lines as they are needed to
# fill clear the screen in the next iteration:
print("\n" * (int(rows) - freqs2.shape[0] - 1))
| 37.135593 | 73 | 0.671839 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 857 | 0.391146 |
8940f390419a60889fc99a07fdf4b127ea3f0da6 | 3,398 | py | Python | dataviva/apps/map/views.py | joelvisroman/dataviva-site | b4219558457746fd5c6b8f4b65b04c738c656fbd | [
"MIT"
] | 126 | 2015-03-24T12:30:43.000Z | 2022-01-06T03:29:54.000Z | dataviva/apps/map/views.py | joelvisroman/dataviva-site | b4219558457746fd5c6b8f4b65b04c738c656fbd | [
"MIT"
] | 694 | 2015-01-14T11:55:28.000Z | 2021-02-08T20:23:11.000Z | dataviva/apps/map/views.py | joelvisroman/dataviva-site | b4219558457746fd5c6b8f4b65b04c738c656fbd | [
"MIT"
] | 52 | 2015-06-19T01:54:56.000Z | 2019-09-23T13:10:46.000Z | # -*- coding: utf-8 -*-
from flask import Blueprint, render_template, g, request, make_response
from dataviva.apps.general.views import get_locale
from dataviva.translations.dictionary import dictionary
from dataviva import datavivadir
from config import GZIP_DATA
from dataviva.utils.cached_query import cached_query
from dataviva.utils.graphs_services import location_service
from dataviva.apps.title.views import get_title
from dataviva.utils.graphs_services import *
import urllib
import json
mod = Blueprint('map', __name__,
template_folder='templates',
url_prefix='/<lang_code>/map',
static_folder='static')
@mod.url_value_preprocessor
def pull_lang_code(endpoint, values):
g.locale = values.pop('lang_code')
@mod.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', get_locale())
@mod.before_request
def before_request():
g.page_type = mod.name
@mod.route('/<dataset>/<value>/', defaults={'id_ibge': ''})
@mod.route('/<dataset>/<value>/<id_ibge>')
def index(dataset, value, id_ibge):
filters = []
title_attrs = {}
services = {
'product': product_service,
'id_ibge': location_service,
'wld': wld_service,
'occupation': occupation_service,
'industry': industry_service,
'basic_course': sc_service,
}
for k, v in request.args.items():
if k not in ['values', 'filters', 'count', 'year']:
if v and k in services:
filters.append(services[k](v))
title_attrs[services[k](v)[0]] = services[k](v)[1]
else:
if k != 'colors':
filters.append((k, v))
title_attrs[k] = v
if id_ibge:
location = location_service(id_ibge)[0]
filters.append((location, id_ibge))
state = '' if location == 'region' else id_ibge[:2]
title_attrs[location] = id_ibge
else:
state = id_ibge
location = 'municipality'
filters = urllib.urlencode(filters)
title, subtitle = get_title(dataset, value, 'map', title_attrs)
return render_template('map/index.html',
dataset=dataset,
value=value,
state=state,
filters=filters,
title=title or '',
subtitle=subtitle or '',
dictionary=json.dumps(dictionary()))
@mod.route('/coords/', defaults={'id': 'all'})
@mod.route('/coords/<id>')
def coords(id):
if GZIP_DATA:
fileext = ".gz"
filetype = "gzip"
else:
fileext = ""
filetype = "json"
if id == "all":
file_name = "bra_all_states.json" + fileext
else:
file_name = ("coords-{0}.json" + fileext).format(id)
cached_q = cached_query(file_name)
if cached_q:
ret = make_response(cached_q)
else:
path = datavivadir + "/static/json/map/{0}".format(file_name)
gzip_file = open(path).read()
cached_query(file_name, gzip_file)
ret = make_response(gzip_file)
ret.headers['Content-Encoding'] = filetype
ret.headers['Content-Length'] = str(len(ret.data))
return ret
| 31.174312 | 72 | 0.58093 | 0 | 0 | 0 | 0 | 2,686 | 0.790465 | 0 | 0 | 447 | 0.131548 |
89414998e5a7ff84331d610b6b9cc51dadd75709 | 6,364 | py | Python | TransfertFichier.py | Fabien034/TimeLaps | a9fcbdfd6551cf8c12961adeef15dfdfaad8fb3c | [
"CC0-1.0"
] | null | null | null | TransfertFichier.py | Fabien034/TimeLaps | a9fcbdfd6551cf8c12961adeef15dfdfaad8fb3c | [
"CC0-1.0"
] | null | null | null | TransfertFichier.py | Fabien034/TimeLaps | a9fcbdfd6551cf8c12961adeef15dfdfaad8fb3c | [
"CC0-1.0"
] | null | null | null | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright: Fabien Rosso
# Version 0.1.1 - 19 Avril 2016
# Version 0.1.2 - 29 Avril 2016
## Debug VisualStudio
# import ptvsd
# ptvsd.enable_attach(None)
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
import subprocess
import pickle
import socket
import threading
from datetime import datetime
from time import sleep
from wrappers import *
from fonctions import *
import logging
from logging.handlers import RotatingFileHandler
os.system("clear")
class ThreadReception(threading.Thread):
"""objet thread gerant la reception des messages"""
def __init__(self, conn):
threading.Thread.__init__(self)
self.connexion = conn # ref. du socket de connexion
def run(self):
while True:
try:
# en attente de reception
message_recu = self.connexion.recv(4096)
message_recu = message_recu.encode(encoding='UTF-8')
print(message_recu)
except:
# fin du thread
break
print("ThreadReception arrete. Connexion interrompue.")
self.connexion.close()
def main():
# création de l'objet logger qui va nous servir à écrire dans les logs
logger = logging.getLogger()
# on met le niveau du logger à DEBUG, comme ça il écrit tout
logger.setLevel(logging.DEBUG)
# création d'un formateur qui va ajouter le temps, le niveau
# de chaque message quand on écrira un message dans le log
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
# création d'un handler qui va rediriger une écriture du log vers
# un fichier en mode 'append', avec 1 backup et une taille max de 1Mo
file_handler = RotatingFileHandler('activity_transfert_fichier.log', 'a', 1000000, 1)
# on lui met le niveau sur DEBUG, on lui dit qu'il doit utiliser le formateur
# créé précédement et on ajoute ce handler au logger
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# création d'un second handler qui va rediriger chaque écriture de log
# sur la console
steam_handler = logging.StreamHandler()
steam_handler.setLevel(logging.DEBUG)
logger.addHandler(steam_handler)
raw_input("Appuyer sur une touche pour demarrer l'envoi des photos")
os.system("clear")
#Lecture et recuperation des variables dans le fichier configServer
with open("configServer", "rb") as fichierConfig:
configRead = pickle.Unpickler(fichierConfig)
HOST = configRead.load()
PORT = int(configRead.load())
USER = configRead.load()
PORTSSH = int(configRead.load())
HOMESERVER = os.path.join("/home",USER,"Images")
# Création du dossier attente de tranfert
WAITPATH = os.path.join(os.path.expanduser("~"),"Pictures","Attente")
if not os.path.exists(WAITPATH):
os.makedirs(WAITPATH, mode=0o777)
# Etablissement de la connexion avec le serveur
# protocoles IPv4 et TCP
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
logger.info(" >> Connexion en cours avec " + HOST + "...")
try:
mySocket.connect((HOST, PORT))
except socket.error:
logger.warning(" >> le serveur '" + host + "' est introuvable.")
sys.exit()
# Dialogue avec le serveur : threads pour gerer la reception des messages
th_Reception = ThreadReception(mySocket)
th_Reception.start()
while True:
listFile = ListDirectory(WAITPATH)
if len(listFile) > 0:
file = Photo(listFile[0]) # Création de la class photo
octets = os.path.getsize(file.pathFile) / 1024 # Nombre d'octets de la photo
logger.info(" >> Transfert : '" + file.nameFile + "' [" + str(octets) + " Ko]")
# on crée le chemin du fichier pour le serveur suivant la date de création
datePath = time.strftime("%Y/%y.%m.%d/",file.createDate)
pathDestination = os.path.join(HOMESERVER,datePath)
fileDestination = os.path.join(pathDestination,file.nameFile)
# on demande au serveur de créer le chemin si il n'eiste pas
message_emis = b"makedirs {0}".format(pathDestination)
try:
# emission
mySocket.send(message_emis.decode(encoding='UTF-8'))
time.sleep(0.1)
except:
break
# on indique au serveur que l'on va lui enoyer un fichier de x octets
message_emis = b"EnvoiPhoto {0} {1}".format(file.nameFile,octets)
try:
# emission
mySocket.send(message_emis.decode(encoding='UTF-8'))
time.sleep(0.1)
except:
break
logger.info(" >> Envoi de la photo '{0}'".format(file.nameFile))
# subprocess SCP pour l'envoie de la photo
subprocess.call(["scp", "-P", bytes(PORTSSH), "-p", file.pathFile ,"{0}@{1}:{2}".format(USER, bytes(HOST), fileDestination)])
time.sleep(0.01)
logger.info(" >> Envoi OK")
# on crée le chemin du fichier pour le rangement sur le RPi suivant la date de création
# si il n'existe pas on crée le dossier
sourcePath = os.path.join(os.path.expanduser("~"),"Pictures",datePath)
if not os.path.exists(sourcePath):
os.makedirs(sourcePath, mode=0o777)
# Creation du nouveau nom
newPathFile = os.path.join(sourcePath,file.nameFile)
# Deplace/rennome la photo
file = file.move(newPathFile)
logger.info(" >> Fichier '{0}' déplacé vers '{1}'".format(file.nameFile, file.parenPathFile))
print("")
mySocket.close()
logger.info(" >> envoi des photos termine")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
logger.warning("Programme interrompu par l'utilisateur")
sys.exit(0)
| 36.574713 | 138 | 0.61675 | 677 | 0.105914 | 0 | 0 | 0 | 0 | 0 | 0 | 2,357 | 0.368742 |
89418edd3c2fb8634084937401da418c6baab778 | 388 | py | Python | posts/urls.py | xXcoronaXx/Dblog | 56ee1b8f6f74fabbe0e081921e6cff092661e8df | [
"MIT"
] | null | null | null | posts/urls.py | xXcoronaXx/Dblog | 56ee1b8f6f74fabbe0e081921e6cff092661e8df | [
"MIT"
] | null | null | null | posts/urls.py | xXcoronaXx/Dblog | 56ee1b8f6f74fabbe0e081921e6cff092661e8df | [
"MIT"
] | null | null | null | from django.conf.urls import include, url
urlpatterns = [
url(r'^admin/(?P<slug>[\w\-]+)/', 'posts.views.post_preview', name='post_preview'),
url(r'^tag/(?P<slug>[\w\-]+)/', 'posts.views.posts_view_tag', name='posts_tag'),
url(r'^popular/', 'posts.views.posts_view_popular', name='posts_popular'),
url(r'^(?P<slug>[\w\-]+)/', 'posts.views.post_view', name='post_view'),
] | 48.5 | 87 | 0.634021 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 248 | 0.639175 |
8941caffd99fa97347e96be2cc0144b6388f9d9c | 14,320 | py | Python | Basic_if_then/movement.py | BH4/Halite3-bots | 97eb4dcab6bccbfd1649bbac74ef06f0e22035de | [
"MIT"
] | null | null | null | Basic_if_then/movement.py | BH4/Halite3-bots | 97eb4dcab6bccbfd1649bbac74ef06f0e22035de | [
"MIT"
] | null | null | null | Basic_if_then/movement.py | BH4/Halite3-bots | 97eb4dcab6bccbfd1649bbac74ef06f0e22035de | [
"MIT"
] | null | null | null | from hlt.positionals import Position, Direction
from hlt import constants
import random
import logging
# Import my stuff
import helpers
def navigate_old(ship, destination, game_map):
curr_pos = ship.position
move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO
if ship.halite_amount >= move_cost:
move = game_map.naive_navigate(ship, destination)
new_pos = curr_pos+Position(move[0], move[1])
game_map[curr_pos].ship = None
game_map[new_pos].mark_unsafe(ship)
return move
return (0, 0)
def navigate(game_map, ship, destination):
destination = game_map.normalize(destination)
logging.info("destination normalized")
w = game_map.width
h = game_map.height
curr_pos = ship.position
move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO
if ship.halite_amount < move_cost:
# If the ship doesn't have enough halite on board to move
# Then it MUST stay still. No other action is possible.
logging.info("navigate: Ship {} decided there isn't enough halite to move.".format(ship.id))
return [(0, 0)]
logging.info("navigate: Ship {} decided there is enough halite to move.".format(ship.id))
possible_moves = []
dy = destination.y - curr_pos.y
if dy > w//2:
dy -= w
elif dy < -w//2:
dy += w
dx = destination.x - curr_pos.x
if dx > w//2:
dx -= w
elif dx < -w//2:
dx += w
logging.info("navigate: Ship {} says dx={} and dy={}.".format(ship.id, dx, dy))
h_amount = {x: game_map[curr_pos+Position(*x)].halite_amount
for x in Direction.get_all_cardinals()}
logging.info("navigate: Ship {} got halite amount at adjacent positions.".format(ship.id))
# Possible moves sorted by preference only taking into account distance
if abs(dy) > abs(dx):
logging.info("navigate: Ship {} wants vertical move.".format(ship.id))
y_sign = dy//abs(dy)
possible_moves.append((0, y_sign)) # dy>0
if dx == 0:
logging.info("test1")
possible_moves.append((0, 0))
if h_amount[(1, 0)] <= h_amount[(-1, 0)]:
logging.info("test2")
possible_moves.append((1, 0))
possible_moves.append((-1, 0))
else:
logging.info("test3")
possible_moves.append((-1, 0))
possible_moves.append((1, 0))
possible_moves.append((0, -1*y_sign))
else:
logging.info("test4")
x_sign = dx//abs(dx)
possible_moves.append((x_sign, 0))
possible_moves.append((0, 0))
possible_moves.append((-1*x_sign, 0))
possible_moves.append((0, -1*y_sign))
# Take halite amount into consideration for preference
# (weather or not to flip the first two and same but independent of the last two)
# currently ignored
elif abs(dy) < abs(dx) or (abs(dy) == abs(dx) and dy != 0):
logging.info("navigate: Ship {} wants horizontal move.".format(ship.id))
x_sign = dx//abs(dx)
possible_moves.append((x_sign, 0)) # dx>0
if dy == 0:
logging.info("test1")
possible_moves.append((0, 0))
if h_amount[(0, 1)] <= h_amount[(0, -1)]:
logging.info("test2")
possible_moves.append((0, 1))
possible_moves.append((0, -1))
else:
logging.info("test3")
possible_moves.append((0, -1))
possible_moves.append((0, 1))
possible_moves.append((-1*x_sign, 0))
else:
logging.info("test4")
y_sign = dy//abs(dy)
possible_moves.append((0, y_sign))
possible_moves.append((0, 0))
possible_moves.append((0, -1*y_sign))
possible_moves.append((-1*x_sign, 0))
# Take halite amount into consideration for preference
# (weather or not to flip the first two and same but independent of the last two)
# currently ignored
else:
# This ship doesn't want to move
logging.info("navigate: Ship {} doesn't want to move.".format(ship.id))
a = [(-1, 0), (1, 0), (0, -1), (0, 1)]
random.shuffle(a)
possible_moves = [(0, 0)] + a
logging.info("navigate: Ship {} got possible_moves.".format(ship.id))
return possible_moves
def group_navigate(game, ship_status, ship_destination, crash=False):
me = game.me
game_map = game.game_map
# Can't navigate with no ships.
if len(me.get_ships()) == 0:
return {}
logging.info("group_navigate: There is more than zero ships.")
# List all moves for each ship
move_list = {ship.id: navigate(game_map, ship, ship_destination[ship.id]) for ship in me.get_ships()}
logging.info("group_navigate: Got moves.")
priority_list = {}
# Ship priorities will follow distances from current destination.
# Ships making a dropoff have highest priority.
sorted_ship_list = []
dist_list = []
for ship in me.get_ships():
sorted_ship_list.append(ship)
if ship.id in ship_destination and ship_status[ship.id] != "returning":
dist_list.append(game_map.calculate_distance(ship.position, ship_destination[ship.id]))
elif ship_status[ship.id] == "dropoff":
dist_list.append(-1)
else:
dist_list.append(0)
z = zip(dist_list, sorted_ship_list)
sz = sorted(z, key=lambda x: x[0])
dist_list, sorted_ship_list = list(zip(*sz))
for i in range(len(sorted_ship_list)):
priority_list[sorted_ship_list[i].id] = i
logging.info("group_navigate: Made priority_list.")
solution = group_navigate_main(me.get_ships(), game, priority_list, move_list, crash)
if solution is None:
logging.info("group_navigate: No solution")
return solution
def group_navigate_main(ship_list, game, priority_list, move_list, crash):
me = game.me
game_map = game.game_map
logging.info("group_navigate_main: "+str(move_list))
conflicting_positions = set()
move_test = {x: move_list[x][0] for x in move_list.keys()}
position_test = {}
for ship in ship_list:
s = str(game_map.normalize(ship.position + Position(*move_test[ship.id])))
if s in position_test:
conflicting_positions.add(s)
position_test[s].append(ship.id)
else:
position_test[s] = [ship.id]
if crash:
drop_s = str(me.shipyard.position)
if drop_s in conflicting_positions:
conflicting_positions.remove(drop_s)
for drop in me.get_dropoffs():
drop_s = str(drop.position)
if drop_s in conflicting_positions:
conflicting_positions.remove(drop_s)
# Solution is acceptable
if len(conflicting_positions) == 0:
return move_test
# Conflict resolution
# Attempt resolution to one conflict at a time when all are solved a
# solution will be returned.
logging.info("group_navigate_main: "+str(conflicting_positions))
for s in conflicting_positions:
logging.info("group_navigate_main: "+s)
crashing_ships = position_test[s]
logging.info("group_navigate_main: "+str(crashing_ships))
priorities = [priority_list[x] for x in crashing_ships]
logging.info("group_navigate_main: "+str(priorities))
# Allow one ship to move to this position but no more.
# If there are any that don't have the ability to move at all
# (not enough halite) then they must be the one to remain in
# this position and all other ships that want to move here will
# have to go somewhere else. If there is more than one that can't
# move then there is no solution.
only_one_move = [i for i, x in enumerate(crashing_ships) if len(move_list[x]) == 1]
logging.info("group_navigate_main: "+str(only_one_move))
if len(only_one_move) == 1:
sorted_inds = [only_one_move[0]]
elif len(only_one_move) > 1:
return None # There are no solutions
else:
_, sorted_inds = list(zip(*sorted(zip(priorities, range(len(priorities))))))
logging.info("group_navigate_main: "+str(sorted_inds))
for ind in sorted_inds:
new_move_list = {x: [y for y in move_list[x]] for x in move_list}
# Keep the other crashing ships from moving here.
# Keep ship at ind the same.
for i in range(len(crashing_ships)):
if i != ind:
shipid = crashing_ships[i]
new_move_list[shipid] = new_move_list[shipid][1:]
solution = group_navigate_main(ship_list, game, priority_list, new_move_list, crash)
if solution is not None:
return solution
return None # failed to find any solutions
def random_move(ship, game_map, params):
curr_pos = ship.position
# Don't move if there is enough halite here
if game_map[curr_pos].halite_amount < params.minimum_useful_halite:
move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO
# Don't move if I can't pay for it
if ship.halite_amount >= move_cost:
spaces = curr_pos.get_surrounding_cardinals()
# Don't move if nowhere else is safe
if len(spaces) > 0:
new_pos = random.choice(spaces)
return new_pos
return curr_pos
def returning_move(ship, me, game_map):
closest, dist = helpers.closest_drop(ship.position, me, game_map)
curr_pos = ship.position
move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO
if ship.halite_amount >= move_cost:
return closest
return curr_pos
def smart_explore(ship, game_map, params):
curr_pos = ship.position
# Don't move if there is enough halite here
if game_map[curr_pos].halite_amount < params.minimum_useful_halite:
logging.info("Ship {} decided there isn't enough halite here.".format(ship.id))
move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO
# Don't move if I can't pay for it
if ship.halite_amount >= move_cost:
logging.info("Ship {} is able to pay for movement.".format(ship.id))
spaces = helpers.get_spaces_in_region(ship, search_region=params.search_region)
# spaces = curr_pos.get_surrounding_cardinals()
# Don't set destination to be on top of another ship
# unless it is necessary.
new_spaces = []
for p in spaces:
if not game_map[p].is_occupied:
new_spaces.append(p)
if len(new_spaces) > 0:
spaces = new_spaces
# Don't move if nowhere else is safe
if len(spaces) > 0:
h_amount = [game_map[x].halite_amount for x in spaces]
# If none of the spaces have enough halite then move to a
# better area
if max(h_amount) < params.minimum_useful_halite:
logging.info("Moving to better area")
pos, dist = helpers.closest_dense_spot(ship, game_map, params)
if dist == 0:
logging.info("Moving to same location :/")
if pos is None: # default to other method if none found over threshold
# pos, dist = helpers.closest_most_dense_spot(ship, game_map, params, n=params.number_of_dense_spots_to_check)
pos = vacuum_explore(ship, game_map, params)
return pos
h_amount, spaces = list(zip(*sorted(zip(h_amount, spaces), key=lambda x: x[0], reverse=True)))
destination = spaces[0]
return destination
else:
logging.info("Ship {} is NOT able to pay for movement.".format(ship.id))
else:
logging.info("Ship {} decided there is plenty of halite here.".format(ship.id))
return curr_pos
def vacuum_explore(ship, game_map, params):
curr_pos = ship.position
minimum_useful_halite = constants.EXTRACT_RATIO*2
explore_density = minimum_useful_halite*params.density_kernal_side_length**2
# Don't move if there is enough halite here
if game_map[curr_pos].halite_amount < minimum_useful_halite:
logging.info("Ship {} decided there isn't enough halite here.".format(ship.id))
# Movement cost should always be zero.
logging.info("Ship {} is able to pay for movement.".format(ship.id))
spaces = helpers.get_spaces_in_region(ship, search_region=params.search_region)
# spaces = curr_pos.get_surrounding_cardinals()
# Don't set destination to be on top of another ship
# unless it is necessary.
new_spaces = []
for p in spaces:
if not game_map[p].is_occupied:
new_spaces.append(p)
if len(new_spaces) > 0:
spaces = new_spaces
# Don't move if nowhere else is safe
if len(spaces) > 0:
h_amount = [game_map[x].halite_amount for x in spaces]
# If none of the spaces have enough halite then move to a
# better area
if max(h_amount) < minimum_useful_halite:
logging.info("Moving to better area")
pos, dist = helpers.closest_dense_spot(ship, game_map, params, density_req=explore_density)
if dist == 0:
logging.info("Moving to same location :/")
if pos is None: # default to other method if none found over threshold
pos, dist = helpers.closest_most_dense_spot(ship, game_map, params, n=params.number_of_dense_spots_to_check)
return pos
h_amount, spaces = list(zip(*sorted(zip(h_amount, spaces), key=lambda x: x[0], reverse=True)))
destination = spaces[0]
return destination
else:
logging.info("Ship {} decided there is plenty of halite here.".format(ship.id))
return curr_pos
| 37.098446 | 134 | 0.615573 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,485 | 0.243366 |
8942b3f4142fb4752d39c8c79839362babc520e3 | 2,569 | py | Python | Bert/regressor.py | RohithYogi/Funniness-in-News-Headlines | db6755b4fa66f3aa827b235751cd49f707c321bc | [
"MIT"
] | null | null | null | Bert/regressor.py | RohithYogi/Funniness-in-News-Headlines | db6755b4fa66f3aa827b235751cd49f707c321bc | [
"MIT"
] | null | null | null | Bert/regressor.py | RohithYogi/Funniness-in-News-Headlines | db6755b4fa66f3aa827b235751cd49f707c321bc | [
"MIT"
] | null | null | null | from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import HuberRegressor
import numpy as np
import pickle
from dataloader import HeadlineDataset
from csv import writer
import os, subprocess
import math
from collections import Counter
def get_weights(ys, countings):
total = sum(countings.values())
weights = []
for y in ys:
bin_num = int(y * 5)
weights.append(total / countings[bin_num])
print(ys[:10])
print(weights[:10])
return weights
def load_data(ds):
with open(f'data/{ds}_features.pkl', 'rb') as f:
train_features = pickle.load(f)
with open(f'data/{ds}-lstm.csv') as f:
lines = f.readlines()[1:]
for i, line in enumerate(lines):
lstm_prediction = float(line.split(',')[1])
train_features[i][0]['lstm-output'] = lstm_prediction
Xs = []
Ys = []
for features, y in train_features:
Ys.append(y)
x = []
for k in ["orig_score", "edit_score", "bert_sim", "glove_sim", "score_diff", "lstm-output"]:
x.append(features[k])
x = np.array(x)
Xs.append(x)
return Xs, Ys
# grouping bins
countings = Counter()
for i in range(30):
countings[i] += 1
dev_dataset = HeadlineDataset('dev')
train_dataset = HeadlineDataset('training')
for sample in dev_dataset:
bin_num = int(sample['label'] * 5)
countings[bin_num] += 1
for sample in train_dataset:
bin_num = int(sample['label'] * 5)
countings[bin_num] += 1
print('load data')
Xs, Ys = load_data('train')
train_weights = get_weights(Ys, countings)
dev_Xs, dev_Ys = load_data('dev')
dev_weights = get_weights(dev_Ys, countings)
model = GradientBoostingRegressor(
learning_rate=0.05, n_estimators=50,
subsample=0.5,
min_samples_split=2,
max_depth=3
)
print('train')
model.fit(Xs, Ys, train_weights)
print('trained')
print(model.feature_importances_)
pred_Ys = model.predict(dev_Xs)
dev_rmse = math.sqrt(mean_squared_error(dev_Ys, pred_Ys))
print(dev_rmse)
test_Xs, _ = load_data('test')
pred_Ys = model.predict(test_Xs)
test_dataset = HeadlineDataset('test')
with open('data/task-1-output.csv', 'w') as f:
output_writer = writer(f)
output_writer.writerow(('id', 'pred'))
for row, pred in zip(test_dataset, pred_Ys):
output_writer.writerow((row['id'], pred.item()))
os.chdir('data')
subprocess.run(['zip', 'task-1-output.zip', 'task-1-output.csv'])
os.chdir('..') | 26.760417 | 100 | 0.673803 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 325 | 0.126508 |
8942f14789d57a93ee819d488c307294d017124c | 108 | py | Python | examples/blogprj/urls.py | pimentech/django-mongoforms | 6220e91e05d73a26e495460f98667e23dc16c5f6 | [
"BSD-3-Clause"
] | 1 | 2017-07-27T05:44:47.000Z | 2017-07-27T05:44:47.000Z | examples/blogprj/urls.py | pimentech/django-mongoforms | 6220e91e05d73a26e495460f98667e23dc16c5f6 | [
"BSD-3-Clause"
] | null | null | null | examples/blogprj/urls.py | pimentech/django-mongoforms | 6220e91e05d73a26e495460f98667e23dc16c5f6 | [
"BSD-3-Clause"
] | null | null | null | from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^', include('apps.blog.urls')),
) | 21.6 | 39 | 0.657407 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 22 | 0.203704 |
894431402e6b83e572b12cd14d0e6138af1aab09 | 2,285 | py | Python | recursive_categories.py | singulart/wikiwalks | 674f4f8ada699619ed52a95eb0a8bd8b8eb093c7 | [
"MIT"
] | null | null | null | recursive_categories.py | singulart/wikiwalks | 674f4f8ada699619ed52a95eb0a8bd8b8eb093c7 | [
"MIT"
] | null | null | null | recursive_categories.py | singulart/wikiwalks | 674f4f8ada699619ed52a95eb0a8bd8b8eb093c7 | [
"MIT"
] | null | null | null | import wikipediaapi
import os
import json
import progressbar
CATEGORY = 'Category:Feminist artists'
#CATEGORY = 'Category:Contemporary artists'
def traverse_categories_tree(categorymembers, level=0, max_level=100):
for c in categorymembers.values():
#print("%s: %s (ns: %d)" % ("*" * (level + 1), c.title, c.ns))
if c.ns == wikipediaapi.Namespace.CATEGORY and level < max_level and interesting_category in c.title and c.title not in processed_categories:
print("%s: %s (ns: %d)" % ("*" * (level + 1), c.title, c.ns))
processed_categories.add(c.title)
traverse_categories_tree(c.categorymembers, level=level + 1, max_level=max_level)
elif c.ns == wikipediaapi.Namespace.MAIN and c.title not in unique_artists:
unique_artists.add(c.title)
print(c.title)
d['pages'].append({
'name': c.title,
'pagetext': c.text
})
def store_categories(ctg):
d = {'categories': list(ctg)}
with open('categories.json', 'w') as json_file:
json.dump(d, json_file)
json_file.close()
def load_categories():
if os.path.exists('categories.json'):
with open('categories.json', 'r') as json_file:
try:
return json.load(json_file)['categories']
except:
return []
return []
unique_artists = set()
processed_categories = load_categories()
if processed_categories:
print('Loaded %d processed categories' % (len(list(processed_categories))))
else:
print('No categories found, starting from scratch')
processed_categories = set()
wiki_wiki = wikipediaapi.Wikipedia('en')
interesting_category = 'artists'
filename = 'output.json'
d = {}
with open('output.json', 'r') as existing_artists:
d = json.load(existing_artists)
if 'pages' in d.keys():
unique_artists = set([x['name'] for x in d['pages']])
else:
d['pages'] = []
unique_artists = set()
print('Loaded %s processed artists' % (len(list(unique_artists))))
cat = wiki_wiki.page(CATEGORY)
traverse_categories_tree(cat.categorymembers)
store_categories(processed_categories)
work_result_filename = 'output.json'
with open(work_result_filename, 'w') as json_file:
json.dump(d, json_file)
| 33.115942 | 149 | 0.653392 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 446 | 0.195186 |
894560d68f6fed0a38a05e50cb3d569b69bc6ff3 | 730 | py | Python | tests/test_handlers/test_yamlHandler/test_yamlHandler.py | UCHIC/ODMStreamingDataLoader | 711886167a068754efff6dfbd604e3e19e545253 | [
"BSD-3-Clause"
] | null | null | null | tests/test_handlers/test_yamlHandler/test_yamlHandler.py | UCHIC/ODMStreamingDataLoader | 711886167a068754efff6dfbd604e3e19e545253 | [
"BSD-3-Clause"
] | null | null | null | tests/test_handlers/test_yamlHandler/test_yamlHandler.py | UCHIC/ODMStreamingDataLoader | 711886167a068754efff6dfbd604e3e19e545253 | [
"BSD-3-Clause"
] | null | null | null | from os import getcwd
from os.path import join
from src.handlers.yamlHandler import YAMLHandler
from tests.test_utils import returnFiles
__author__ = 'jmeline'
class TestYAMLHandler:
def setup(self):
self.path = join(getcwd(), 'test_handlers', 'test_yamlHandler', 'yamlFiles')
assert self.path
self.yaml = YAMLHandler()
assert self.yaml
self.files = returnFiles(self.path)
assert self.files
def test_read_yaml(self):
load = self.yaml.read_yaml(self.files[0])
assert load
def test_write_yaml(self):
load = self.yaml.read_yaml(self.files[0])
assert load
result = self.yaml.write_yaml(load, 'test.yaml')
print(result)
| 25.172414 | 84 | 0.663014 | 565 | 0.773973 | 0 | 0 | 0 | 0 | 0 | 0 | 64 | 0.087671 |
89497af5999c47772bcb8017e9ebdd35c45a92b6 | 1,031 | py | Python | samples/donut.py | stoneskin/python-minecraft | 29051b8626620245ff54fc4d8ab1278d60d3a1ca | [
"MIT"
] | 7 | 2020-05-26T04:20:15.000Z | 2022-03-09T06:33:20.000Z | samples/donut.py | stoneskin/python-minecraft | 29051b8626620245ff54fc4d8ab1278d60d3a1ca | [
"MIT"
] | 1 | 2020-05-17T18:15:59.000Z | 2020-05-17T21:22:03.000Z | samples/donut.py | stoneskin/python-minecraft | 29051b8626620245ff54fc4d8ab1278d60d3a1ca | [
"MIT"
] | 1 | 2021-12-14T00:14:11.000Z | 2021-12-14T00:14:11.000Z | from mcpi_e.minecraft import Minecraft
from mcpi_e import block
from time import sleep
from random import *
from math import *
def draw_donut(mcx,mcy,mcz,R,r,mcblock):
for x in range(-R-r,R+r):
for y in range(-R-r,R+r):
xy_dist = sqrt(x**2 + y**2)
if (xy_dist > 0):
ringx = x / xy_dist * R # nearest point on major ring
ringy = y / xy_dist * R
ring_dist_sq = (x-ringx)**2 + (y-ringy)**2
for z in range(-R-r,R+r):
if (ring_dist_sq + z**2 <= r**2):
mc.setBlock(mcx+x, mcy+z, mcz+y, mcblock)
serverAddress="server" # change to your minecraft server
playerName ="stoneskin"
pythonApiPort=4712
mc=Minecraft.create(serverAddress,pythonApiPort,playerName)
playerPos=mc.player.getTilePos()
draw_donut(playerPos.x, playerPos.y + 9, playerPos.z, 18, 9, block.GLASS)
mc.postToChat("Glass donut done")
draw_donut(playerPos.x, playerPos.y + 9, playerPos.z, 18, 6, block.WATER_STATIONARY)
mc.postToChat("Water donut done") | 34.366667 | 84 | 0.642095 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 117 | 0.113482 |
894a5fed9ddf654ea364f9de215cbb93bd3168ae | 582 | py | Python | britecoreproject/orm.py | alis0nc/britecore-project | aa31eb1f87c1c250f8bca9d9aa109eeae1232b9b | [
"MIT"
] | null | null | null | britecoreproject/orm.py | alis0nc/britecore-project | aa31eb1f87c1c250f8bca9d9aa109eeae1232b9b | [
"MIT"
] | 1 | 2018-02-13T00:34:22.000Z | 2018-02-13T00:34:22.000Z | britecoreproject/orm.py | alis0nc/britecore-project | aa31eb1f87c1c250f8bca9d9aa109eeae1232b9b | [
"MIT"
] | null | null | null | """
Define ORM classes.
"""
from sqlobject import *
class RiskType(SQLObject):
"""Define RiskType ORM class."""
riskTypeName = StringCol()
fields = RelatedJoin('Field')
class Field(SQLObject):
"""Define Field ORM class."""
fieldName = StringCol()
fieldType = ForeignKey('FieldType')
risks = RelatedJoin('RiskType')
class FieldType(SQLObject):
"""Define FieldType ORM class."""
fieldTypeName = StringCol()
def create_tables():
"""Create tables in database."""
RiskType.createTable()
Field.createTable()
FieldType.createTable()
| 22.384615 | 39 | 0.671821 | 386 | 0.66323 | 0 | 0 | 0 | 0 | 0 | 0 | 181 | 0.310997 |
894b00993b1f21de2137b7f78408f37441e40edc | 16,178 | py | Python | plumbum.py | maxnasonov/cloudwatch-to-graphite | c7eecda02cb3476616b397e4d1699de39e2728dd | [
"Apache-2.0"
] | null | null | null | plumbum.py | maxnasonov/cloudwatch-to-graphite | c7eecda02cb3476616b397e4d1699de39e2728dd | [
"Apache-2.0"
] | null | null | null | plumbum.py | maxnasonov/cloudwatch-to-graphite | c7eecda02cb3476616b397e4d1699de39e2728dd | [
"Apache-2.0"
] | null | null | null | # -*- coding: UTF-8 -*-
"""
Usage:
plumbum <template> <namespace> [region] [options]...
Options:
template path to the jinja2 template
namespace AWS namespace. Currently supports: elasticache, elb, ec2, rds, asg, sqs
region AWS region [default: us-east-1]
options key value combinations, they can be tags or any other property
Examples:
plumbum elb.yaml.j2 elb
plumbum elb.yaml.j2 elb us-west-2
plumbum ec2.yaml.j2 ec2 environment=production
plumbum ec2.yaml.j2 ec2 us-west-2 environment=production
Outputs to stdout.
About Templates:
Templates are used to generate config.yml files based on running resources.
They're written in jinja2, and have these variables available:
filters A dictionary of the filters that were passed in
region The region the resource is located in
resources A list of the resources as boto objects
"""
from __future__ import unicode_literals
import argparse
import sys
import boto
import boto.dynamodb
import boto.ec2
import boto.emr
import boto.ec2.elb
import boto.ec2.cloudwatch
import boto.rds
import boto.elasticache
import boto.ec2.autoscale
import boto.kinesis
import boto.redshift
import boto.sqs
import boto3
import jinja2
import os.path
from leadbutt import __version__
# DEFAULT_NAMESPACE = 'ec2' # TODO
DEFAULT_REGION = 'us-east-1'
class CliArgsException(Exception):
pass
def get_property_func(key):
"""
Get the accessor function for an instance to look for `key`.
Look for it as an attribute, and if that does not work, look to see if it
is a tag.
"""
def get_it(obj):
try:
return getattr(obj, key)
except AttributeError:
return obj.tags.get(key)
return get_it
def filter_key(filter_args):
def filter_instance(instance):
return all([value == get_property_func(key)(instance)
for key, value in filter_args.items()])
return filter_instance
def lookup(instances, filter_by=None):
if filter_by is not None:
return list(filter(filter_key(filter_by), instances))
return instances
def interpret_options(args=sys.argv[1:]):
parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version', version=__version__)
parser.add_argument("-r", "--region", help="AWS region", default=DEFAULT_REGION)
parser.add_argument("-f", "--filter", action='append', default=[],
help="filter to apply to AWS objects in key=value form, can be used multiple times")
parser.add_argument('--token', action='append', help='a key=value pair to use when populating templates')
parser.add_argument("template", type=str, help="the template to interpret")
parser.add_argument("namespace", type=str, help="AWS namespace")
args = parser.parse_args(args=args)
# filters are passed in as list of key=values pairs, we need a dictionary to pass to lookup()
filters = dict([x.split('=', 1) for x in args.filter])
# Support 'ec2' (human friendly) and 'AWS/EC2' (how CloudWatch natively calls these things)
if args.namespace is not None: # Just making test pass, argparse will catch this missing.
namespace = args.namespace.rsplit('/', 2)[-1].lower()
else:
namespace = None
return args.template, namespace, args.region, filters, args.token
def list_billing(region, filter_by_kwargs):
"""List available billing metrics"""
conn = boto.ec2.cloudwatch.connect_to_region(region)
metrics = conn.list_metrics(metric_name='EstimatedCharges')
# Filtering is based on metric Dimensions. Only really valuable one is
# ServiceName.
if filter_by_kwargs:
filter_key = filter_by_kwargs.keys()[0]
filter_value = filter_by_kwargs.values()[0]
if filter_value:
filtered_metrics = [x for x in metrics if x.dimensions.get(filter_key) and x.dimensions.get(filter_key)[0] == filter_value]
else:
# ServiceName=''
filtered_metrics = [x for x in metrics if not x.dimensions.get(filter_key)]
else:
filtered_metrics = metrics
return filtered_metrics
def list_cloudfront(region, filter_by_kwargs):
"""List running ec2 instances."""
conn = boto.connect_cloudfront()
instances = conn.get_all_distributions()
return lookup(instances, filter_by=filter_by_kwargs)
def list_ec2(region, filter_by_kwargs):
"""List running ec2 instances."""
conn = boto.ec2.connect_to_region(region)
instances = conn.get_only_instances()
return lookup(instances, filter_by=filter_by_kwargs)
def list_ebs(region, filter_by_kwargs):
"""List running ebs volumes."""
conn = boto.ec2.connect_to_region(region)
instances = conn.get_all_volumes()
return lookup(instances, filter_by=filter_by_kwargs)
def list_elb(region, filter_by_kwargs):
"""List all load balancers."""
conn = boto.ec2.elb.connect_to_region(region)
instances = conn.get_all_load_balancers()
return lookup(instances, filter_by=filter_by_kwargs)
def list_alb(region, filter_by_kwargs):
boto3.setup_default_session(region_name=region)
alb = boto3.client('elbv2')
resp = alb.describe_load_balancers()
albs = [{'name': lb['LoadBalancerName'], 'arn': lb['LoadBalancerArn']} for lb in resp['LoadBalancers']]
return albs
def list_es(region, filter_by_kwargs):
boto3.setup_default_session(region_name=region)
es = boto3.client('es')
resp = es.list_domain_names()
domain_names = [domain_name['DomainName'] for domain_name in resp['DomainNames']]
return domain_names
def list_rds(region, filter_by_kwargs):
"""List all RDS thingys."""
conn = boto.rds.connect_to_region(region)
instances = conn.get_all_dbinstances()
return lookup(instances, filter_by=filter_by_kwargs)
def list_elasticache(region, filter_by_kwargs):
"""List all ElastiCache Clusters."""
conn = boto.elasticache.connect_to_region(region)
req = conn.describe_cache_clusters()
data = req["DescribeCacheClustersResponse"]["DescribeCacheClustersResult"]["CacheClusters"]
if filter_by_kwargs:
clusters = [x['CacheClusterId'] for x in data if x[filter_by_kwargs.keys()[0]] == filter_by_kwargs.values()[0]]
else:
clusters = [x['CacheClusterId'] for x in data]
return clusters
def list_autoscaling_group(region, filter_by_kwargs):
"""List all Auto Scaling Groups."""
conn = boto.ec2.autoscale.connect_to_region(region)
groups = conn.get_all_groups()
return lookup(groups, filter_by=filter_by_kwargs)
def list_sqs(region, filter_by_kwargs):
"""List all SQS Queues."""
conn = boto.sqs.connect_to_region(region)
queues = conn.get_all_queues()
return lookup(queues, filter_by=filter_by_kwargs)
def list_kinesis_applications(region, filter_by_kwargs):
"""List all the kinesis applications along with the shards for each stream"""
conn = boto.kinesis.connect_to_region(region)
streams = conn.list_streams()['StreamNames']
kinesis_streams = {}
for stream_name in streams:
shard_ids = []
shards = conn.describe_stream(stream_name)['StreamDescription']['Shards']
for shard in shards:
shard_ids.append(shard['ShardId'])
kinesis_streams[stream_name] = shard_ids
return kinesis_streams
def list_dynamodb(region, filter_by_kwargs):
"""List all DynamoDB tables."""
conn = boto.dynamodb.connect_to_region(region)
tables = conn.list_tables()
return lookup(tables, filter_by=filter_by_kwargs)
def list_emr(region, filter_by_kwargs):
conn = boto.emr.connect_to_region(region)
q_list = conn.list_clusters(cluster_states=['WAITING', 'RUNNING'])
queues = q_list.clusters
return lookup(queues, filter_by=filter_by_kwargs)
def none(region, filter_by_kwargs):
return []
list_resources = {
'cloudfront': list_cloudfront,
'ec2': list_ec2,
'ebs': list_ebs,
'elb': list_elb,
'applicationelb': list_alb,
'es': list_es,
'rds': list_rds,
'elasticache': list_elasticache,
'asg': list_autoscaling_group,
'sqs': list_sqs,
'kinesis': none,
'kinesisapp': list_kinesis_applications,
'dynamodb': list_dynamodb,
'billing': list_billing,
'elasticmapreduce': list_emr,
'redshift': none,
'firehose': none,
's3': none,
}
def list_dynamodb_indices(region, table_name):
boto3.setup_default_session(region_name=region)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(table_name)
indices = table.global_secondary_indexes or []
return list(map(lambda idx: idx['IndexName'], indices))
def get_account_id(region):
boto3.setup_default_session(region_name=region)
sts = boto3.client("sts")
return sts.get_caller_identity()["Account"]
def get_tag(tags, rm_key, dp_key=None):
if dp_key is None:
dp_key = rm_key
value = [tag['Value'] for tag in tags['TagList'] if tag['Key'] == 'dp:' + dp_key]
if len(value) == 0:
value = [tag['Value'] for tag in tags['TagList'] if tag['Key'] == 'rm:' + rm_key]
if len(value) == 0:
value = ''
else:
value = value[0]
return value
def rds_name_tag_metric_path(region, rds_id, resource_type='db'):
boto3.setup_default_session(region_name=region)
sts = boto3.client("sts")
account_id = sts.get_caller_identity()["Account"]
rds_arn = "arn:aws:rds:%s:%s:%s:%s" % (region, account_id, resource_type, rds_id)
rds = boto3.client('rds')
tags = rds.list_tags_for_resource(ResourceName=rds_arn)
name_tag = [tag['Value'] for tag in tags['TagList'] if tag['Key'] == 'Name']
mod_env = get_tag(tags, 'env')
mod_type = get_tag(tags, 'type', 'stack-id')
mod_name = get_tag(tags, 'module', 'module-type')
mod_service = get_tag(tags, 'service', 'resource')
mod_id = [tag_value for tag_value in [mod_env, mod_type, mod_name, mod_service] if tag_value != '']
name_tag_metric_path = '.'.join(mod_id) + '.' if len(mod_id) > 0 else ''
return name_tag_metric_path
def elb_name_tag_metric_path(region, elb_name):
boto3.setup_default_session(region_name=region)
elb = boto3.client('elb')
tags = elb.describe_tags(LoadBalancerNames=[elb_name])
name_tag = [tag['Value'] for tag in tags['TagDescriptions'][0]['Tags'] if tag['Key'] == 'Name']
name_tag_metric_path = '.'.join(name_tag[0].split('-')) + '.' if len(name_tag) > 0 else ''
return name_tag_metric_path
def alb_name_tag_metric_path(region, alb_name):
boto3.setup_default_session(region_name=region)
alb = boto3.client('elbv2')
tags = alb.describe_tags(ResourceArns=[alb_name])
name_tag = [tag['Value'] for tag in tags['TagDescriptions'][0]['Tags'] if tag['Key'] == 'Name']
name_tag_metric_path = '.'.join(name_tag[0].split('-')) + '.' if len(name_tag) > 0 else ''
return name_tag_metric_path
def list_alb_target_groups(region, alb_arn):
boto3.setup_default_session(region_name=region)
alb = boto3.client('elbv2')
resp = alb.describe_target_groups(LoadBalancerArn=alb_arn)
tgs = [{'name': tg['TargetGroupName'], 'arn': tg['TargetGroupArn']} for tg in resp['TargetGroups']]
return tgs
def list_rds_clusters(region):
boto3.setup_default_session(region_name=region)
rds = boto3.client('rds')
rds_clusters = []
marker = ''
while marker != None:
resp = rds.describe_db_clusters(Marker=marker)
marker = resp['Marker'] if 'Marker' in resp else None
rds_clusters += resp['DBClusters']
return rds_clusters
def list_rds_instances(region):
boto3.setup_default_session(region_name=region)
rds = boto3.client('rds')
rds_instances = []
marker = ''
while marker != None:
resp = rds.describe_db_instances(Marker=marker)
marker = resp['Marker'] if 'Marker' in resp else None
rds_instances += resp['DBInstances']
return rds_instances
def list_elasticache_clusters(region):
"""List all ElastiCache Clusters."""
conn = boto.elasticache.connect_to_region(region)
clusters = []
marker = ''
while marker != None:
resp = conn.describe_cache_clusters(marker=marker, show_cache_node_info=True)
marker = resp['Marker'] if 'Marker' in resp else None
clusters += resp["DescribeCacheClustersResponse"]["DescribeCacheClustersResult"]["CacheClusters"]
return clusters
def list_redshift_clusters(region):
"""List all Redshift Clusters."""
conn = boto.redshift.connect_to_region(region)
clusters = []
marker = ''
while marker != None:
resp = conn.describe_clusters(marker=marker)
marker = resp['Marker'] if 'Marker' in resp else None
clusters += resp['DescribeClustersResponse']['DescribeClustersResult']["Clusters"]
return clusters
def list_firehose_delivery_streams(region):
boto3.setup_default_session(region_name=region)
firehose = boto3.client('firehose')
delivery_streams = []
hasMoreDeliveryStreams = True
while hasMoreDeliveryStreams == True:
resp = firehose.list_delivery_streams(Limit=100)
hasMoreDeliveryStreams = resp['HasMoreDeliveryStreams']
delivery_streams += resp["DeliveryStreamNames"]
return delivery_streams
def list_s3_buckets(region):
boto3.setup_default_session(region_name=region)
s3 = boto3.client('s3')
resp = s3.list_buckets()
buckets = [bucket['Name'] for bucket in resp['Buckets']]
return buckets
def list_kinesis_streams(region):
boto3.setup_default_session(region_name=region)
kinesis = boto3.client('kinesis')
streams = []
hasMore = True
while hasMore == True:
resp = kinesis.list_streams(Limit=100)
hasMore = resp['HasMoreStreams']
streams += resp["StreamNames"]
return streams
def main():
template, namespace, region, filters, tokens = interpret_options()
# get the template first so this can fail before making a network request
fs_path = os.path.abspath(os.path.dirname(template))
loader = jinja2.FileSystemLoader(fs_path)
jinja2_env = jinja2.Environment(loader=loader, extensions=["jinja2.ext.do"])
jinja2_env.globals['list_dynamodb_indices'] = list_dynamodb_indices
jinja2_env.globals['list_rds_instances'] = list_rds_instances
jinja2_env.globals['list_rds_clusters'] = list_rds_clusters
jinja2_env.globals['list_redshift_clusters'] = list_redshift_clusters
jinja2_env.globals['list_s3_buckets'] = list_s3_buckets
jinja2_env.globals['list_elasticache_clusters'] = list_elasticache_clusters
jinja2_env.globals['list_firehose_delivery_streams'] = list_firehose_delivery_streams
jinja2_env.globals['list_kinesis_streams'] = list_kinesis_streams
jinja2_env.globals['rds_name_tag_metric_path'] = rds_name_tag_metric_path
jinja2_env.globals['elb_name_tag_metric_path'] = elb_name_tag_metric_path
jinja2_env.globals['alb_name_tag_metric_path'] = alb_name_tag_metric_path
jinja2_env.globals['list_alb_target_groups'] = list_alb_target_groups
jinja2_env.globals['get_account_id'] = get_account_id
template = jinja2_env.get_template(os.path.basename(template))
# insure a valid region is set
if region not in [r.name for r in boto.ec2.regions()]:
raise ValueError("Invalid region:{0}".format(region))
# should I be using ARNs?
try:
resources = list_resources[namespace](region, filters)
except KeyError:
print('ERROR: AWS namespace "{}" not supported or does not exist'
.format(namespace))
sys.exit(1)
# base tokens
template_tokens = {
'filters': filters,
'region': region, # Use for Auth config section if needed
'resources': resources,
}
# add tokens passed as cli args:
if tokens is not None:
for token_pair in tokens:
if token_pair.count('=') != 1:
raise CliArgsException("token pair '{0}' invalid, must contain exactly one '=' character.".format(token_pair))
(key, value) = token_pair.split('=')
template_tokens[key] = value
print(template.render(template_tokens))
if __name__ == '__main__':
main()
| 36.111607 | 135 | 0.701261 | 43 | 0.002658 | 0 | 0 | 0 | 0 | 0 | 0 | 4,115 | 0.254358 |
894dd8d8e0b0dd429807b917fe2e70454c198af1 | 10,440 | py | Python | fixtures/aerl/fabfile.py | bbengfort/honu | 3bfbf6a1959ec60a1e120a287f84996fa333757c | [
"MIT"
] | 2 | 2018-05-28T18:27:35.000Z | 2020-10-07T10:12:38.000Z | fixtures/aerl/fabfile.py | bbengfort/honu | 3bfbf6a1959ec60a1e120a287f84996fa333757c | [
"MIT"
] | 3 | 2021-10-05T00:37:26.000Z | 2021-10-05T01:53:00.000Z | fixtures/aerl/fabfile.py | bbengfort/honu | 3bfbf6a1959ec60a1e120a287f84996fa333757c | [
"MIT"
] | null | null | null | # fabfile
# Fabric command definitions for running anti-entropy reinforcement learning.
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Tue Jun 13 22:26:00 2017 -0400
#
# Copyright (C) 2017 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: fabfile.py [] benjamin@bengfort.com $
"""
Fabric command definitions for running anti-entropy reinforcement learning.
"""
##########################################################################
## Imports
##########################################################################
import os
import re
import json
import pytz
from datetime import datetime
from StringIO import StringIO
from tabulate import tabulate
from operator import itemgetter
from collections import defaultdict
from dotenv import load_dotenv, find_dotenv
from dateutil.parser import parse as date_parse
from fabric.contrib import files
from fabric.api import env, run, cd, get
from fabric.colors import red, green, cyan
from fabric.api import parallel, task, runs_once, execute
##########################################################################
## Environment Helpers
##########################################################################
# Load the host information
def load_hosts(path):
with open(path, 'r') as f:
return json.load(f)
def load_host_regions(hosts):
locations = defaultdict(list)
for host in hosts:
loc = " ".join(host.split("-")[1:-1])
locations[loc].append(host)
return locations
def parse_bool(val):
if isinstance(val, basestring):
val = val.lower().strip()
if val in {'yes', 'y', 'true', 't', '1'}:
return True
if val in {'no', 'n', 'false', 'f', '0'}:
return False
return bool(val)
##########################################################################
## Environment
##########################################################################
## Load the environment
load_dotenv(find_dotenv())
## Local paths
fixtures = os.path.dirname(__file__)
hostinfo = os.path.join(fixtures, "hosts.json")
## Remote Paths
workspace = "/data/honu"
repo = "~/workspace/go/src/github.com/bbengfort/honu"
## Load Hosts
hosts = load_hosts(hostinfo)
regions = load_host_regions(hosts)
addrs = {info['hostname']: host for host, info in hosts.items()}
env.hosts = sorted(list(hosts.keys()))
## Fabric Env
env.user = "ubuntu"
env.colorize_errors = True
env.use_ssh_config = True
env.forward_agent = True
##########################################################################
## Task Helper Functions
##########################################################################
def pproc_command(commands):
"""
Creates a pproc command from a list of command strings.
"""
commands = " ".join([
"\"{}\"".format(command) for command in commands
])
return "pproc {}".format(commands)
def round_robin(n, host, hosts=env.hosts):
"""
Returns a number n (of clients) for the specified host, by allocating the
n clients evenly in a round robin fashion. For example, if hosts = 3 and
n = 5; then this function returns 2 for host[0], 2 for host[1] and 1 for
host[2].
"""
num = n / len(hosts)
idx = hosts.index(host)
if n % len(hosts) > 0 and idx < (n % len(hosts)):
num += 1
return num
def add_suffix(path, suffix=None):
if suffix:
base, ext = os.path.splitext(path)
path = "{}-{}{}".format(base, suffix, ext)
return path
def unique_name(path, start=0, maxtries=1000):
for idx in range(start+1, start+maxtries):
ipath = add_suffix(path, idx)
if not os.path.exists(ipath):
return ipath
raise ValueError(
"could not get a unique path after {} tries".format(maxtries)
)
def make_replica_args(config, host):
name = addrs[host]
info = hosts[name]
if name not in config["replicas"]["hosts"]:
return None
args = config['replicas']['config'].copy()
args['pid'] = int(name.split("-")[-1])
args['peers'] = ",".join([
hosts[peer]['hostname'] + ":3264"
for peer in config["replicas"]["hosts"]
if peer != name
])
return " ".join(["--{} {}".format(k,v).strip() for k,v in args.items()])
def make_client_args(config, host):
cmds = []
name = addrs[host]
if name not in config["clients"]["hosts"]:
return cmds
for conf in config['clients']['configs']:
args = conf.copy()
args['prefix'] = config["clients"]["hosts"][name]
cmds.append(
" ".join(["--{} {}".format(k,v).strip() for k,v in args.items()])
)
return cmds
##########################################################################
## Honu Commands
##########################################################################
@task
@parallel
def install():
"""
Install epaxos for the first time on each machine
"""
with cd(os.path.dirname(repo)):
run("git clone git@github.com:bbengfort/honu.git")
with cd(repo):
run("godep restore")
run("go install ./...")
run("mkdir -p {}".format(workspace))
@task
@parallel
def uninstall():
"""
Uninstall ePaxos on every machine
"""
run("rm -rf {}".format(repo))
run("rm -rf {}".format(workspace))
@task
@parallel
def update():
"""
Update honu by pulling the repository and installing the command.
"""
with cd(repo):
run("git pull")
run("godep restore")
run("go install ./...")
@task
@parallel
def version():
"""
Get the current honu version number
"""
with cd(repo):
run("honu --version")
@task
@parallel
def cleanup():
"""
Cleans up results files so that the experiment can be run again.
"""
names = (
"metrics.json", "visibile_versions.log",
)
for name in names:
path = os.path.join(workspace, name)
run("rm -f {}".format(path))
@task
@parallel
def bench(config="config.json"):
"""
Run all servers on the host as well as benchmarks for the number of
clients specified.
"""
command = []
# load the configuration
with open(config, 'r') as f:
config = json.load(f)
# Create the serve command
args = make_replica_args(config, env.host)
if args:
command.append("honu serve {}".format(args))
# Create the bench command
args = make_client_args(config, env.host)
for arg in args:
command.append("honu bench {}".format(arg))
with cd(workspace):
run(pproc_command(command))
@task
@parallel
def getmerge(name="metrics.json", path="data", suffix=None):
"""
Get the results.json and the metrics.json files and save them with the
specified suffix to the localpath.
"""
remote = os.path.join(workspace, name)
hostname = addrs[env.host]
local = os.path.join(path, hostname, add_suffix(name, suffix))
local = unique_name(local)
if files.exists(remote):
get(remote, local)
@task
@parallel
def putkey(key="foo", value=None, visibility=True, geo="virginia", n_replicas=1):
n_replicas = int(n_replicas)
hostname = addrs[env.host]
region = " ".join(hostname.split("-")[1:-1])
# Perform geography filtering
geo = geo.split(";")
if region not in geo: return "ignoring {}".format(geo)
if hostname not in regions[region][:n_replicas]: return
if value is None:
now = pytz.timezone('America/New_York').localize(datetime.now())
now = now.strftime("%Y-%m-%d %H:%M:%S %z")
value = '"created on {} at {}"'.format(hostname, now)
cmd = "honu put -k {} -v {}".format(key, value)
if visibility:
cmd += " --visibility"
run(cmd)
@parallel
def _getkey(key):
return run("honu get -k {}".format(key), quiet=True)
@task
@runs_once
def getkey(key="foo"):
"""
Returns the latest version of the key on the hosts specified
"""
row = re.compile(r'version ([\d\.]+), value: (.*)', re.I)
data = execute(_getkey, key)
table = []
for host, line in data.items():
match = row.match(line)
if match is None:
version = 0.0
value = red(line.split("\n")[-1])
else:
version, value = match.groups()
table.append([host, float(version), value])
table = [["Host", "Version", "Value"]] + table
print(tabulate(table, tablefmt='simple', headers='firstrow', floatfmt=".2f"))
@parallel
def fetch_visibility():
"""
Fetch and parse the visibility data
"""
fd = StringIO()
remote = os.path.join(workspace, "visibile_versions.log")
get(remote, fd)
rows = fd.getvalue().split("\n")
return list(map(json.loads, filter(None, rows)))
@task
@runs_once
def visibility():
"""
Print a table of the current key visibility listed
"""
def loc_count(replicas):
locs = defaultdict(int)
for replica in replicas:
loc = " ".join(replica.split("-")[1:-1])
locs[loc] += 1
output = [
"{}-{}".format(l, c) for l, c in
sorted(locs.items(), key=itemgetter(1), reverse=True)
]
for idx in range(0, len(output), 2):
output[idx] = cyan(output[idx])
return " ".join(output)
data = execute(fetch_visibility)
n_hosts = len(data)
versions = defaultdict(list)
for host, vals in data.items():
for val in vals:
vers = "{Key} {Version}".format(**val)
versions[vers].append((host, val['Timestamp']))
table = [['Version', 'R', '%', 'L (secs)', 'Created', 'Updated', 'Regions']]
for vers, timestamps in sorted(versions.items(), key=itemgetter(0)):
replicas = [h[0] for h in timestamps]
timestamps = [date_parse(h[1]) for h in timestamps]
replicated = len(set(replicas))
visibility = (float(replicated) / float(n_hosts)) * 100.0
created = min(timestamps)
updated = max(timestamps)
latency = (updated - created).total_seconds()
table.append([
vers,
replicated,
"{:0.2f}".format(visibility),
"{:0.2f}".format(latency),
created.strftime("%Y-%m-%d %H:%M:%S"),
updated.strftime("%Y-%m-%d %H:%M:%S"),
loc_count(replicas)
])
print(tabulate(table, tablefmt='simple', headers='firstrow'))
| 26.034913 | 81 | 0.561782 | 0 | 0 | 0 | 0 | 5,562 | 0.532759 | 0 | 0 | 3,600 | 0.344828 |
894e84bd7eebee8f3642ef1949280cffa18756ab | 2,275 | py | Python | python/657.robot-return-to-origin.py | Zhenye-Na/leetcode | 95196a45f5709ccf7b970ee5ac84a4bf8fe2301e | [
"MIT"
] | 10 | 2019-09-15T00:23:57.000Z | 2022-01-05T12:53:42.000Z | python/657.robot-return-to-origin.py | Zhenye-Na/leetcode | 95196a45f5709ccf7b970ee5ac84a4bf8fe2301e | [
"MIT"
] | 3 | 2021-06-30T00:39:26.000Z | 2021-08-01T07:13:59.000Z | python/657.robot-return-to-origin.py | Zhenye-Na/leetcode | 95196a45f5709ccf7b970ee5ac84a4bf8fe2301e | [
"MIT"
] | 6 | 2020-02-08T02:55:22.000Z | 2022-01-02T22:48:18.000Z | #
# @lc app=leetcode id=657 lang=python3
#
# [657] Robot Return to Origin
#
# https://leetcode.com/problems/robot-return-to-origin/description/
#
# algorithms
# Easy (73.67%)
# Likes: 1228
# Dislikes: 692
# Total Accepted: 274.1K
# Total Submissions: 371K
# Testcase Example: '"UD"'
#
# There is a robot starting at position (0, 0), the origin, on a 2D plane.
# Given a sequence of its moves, judge if this robot ends up at (0, 0) after it
# completes its moves.
#
# The move sequence is represented by a string, and the character moves[i]
# represents its ith move. Valid moves are R (right), L (left), U (up), and D
# (down). If the robot returns to the origin after it finishes all of its
# moves, return true. Otherwise, return false.
#
# Note: The way that the robot is "facing" is irrelevant. "R" will always make
# the robot move to the right once, "L" will always make it move left, etc.
# Also, assume that the magnitude of the robot's movement is the same for each
# move.
#
#
# Example 1:
#
#
# Input: moves = "UD"
# Output: true
# Explanation: The robot moves up once, and then down once. All moves have the
# same magnitude, so it ended up at the origin where it started. Therefore, we
# return true.
#
#
# Example 2:
#
#
# Input: moves = "LL"
# Output: false
# Explanation: The robot moves left twice. It ends up two "moves" to the left
# of the origin. We return false because it is not at the origin at the end of
# its moves.
#
#
# Example 3:
#
#
# Input: moves = "RRDD"
# Output: false
#
#
# Example 4:
#
#
# Input: moves = "LDRRLRUULR"
# Output: false
#
#
#
# Constraints:
#
#
# 1 <= moves.length <= 2 * 10^4
# moves only contains the characters 'U', 'D', 'L' and 'R'.
#
#
#
# @lc code=start
class Solution:
def judgeCircle(self, moves: str) -> bool:
start = [0, 0]
for move in moves:
if move == "U":
start[0], start[1] = start[0] + 0, start[1] + 1
elif move == "R":
start[0], start[1] = start[0] + 1, start[1] + 0
elif move == "D":
start[0], start[1] = start[0] + 0, start[1] + (-1)
else:
start[0], start[1] = start[0] + (-1), start[1] + 0
return start == [0, 0]
# @lc code=end
| 24.202128 | 79 | 0.607033 | 513 | 0.225495 | 0 | 0 | 0 | 0 | 0 | 0 | 1,692 | 0.743736 |
894f30ac75460bc645b7f7aa2b1775bd8ac09220 | 2,171 | py | Python | src/python/pants/backend/swift/goals/tailor.py | danxmoran/pants | 7fafd7d789747c9e6a266847a0ccce92c3fa0754 | [
"Apache-2.0"
] | null | null | null | src/python/pants/backend/swift/goals/tailor.py | danxmoran/pants | 7fafd7d789747c9e6a266847a0ccce92c3fa0754 | [
"Apache-2.0"
] | null | null | null | src/python/pants/backend/swift/goals/tailor.py | danxmoran/pants | 7fafd7d789747c9e6a266847a0ccce92c3fa0754 | [
"Apache-2.0"
] | null | null | null | # Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
from pants.backend.swift.target_types import SWIFT_FILE_EXTENSIONS, SwiftSourcesGeneratorTarget
from pants.core.goals.tailor import (
AllOwnedSources,
PutativeTarget,
PutativeTargets,
PutativeTargetsRequest,
group_by_dir,
)
from pants.engine.fs import PathGlobs, Paths
from pants.engine.internals.selectors import Get
from pants.engine.rules import Rule, collect_rules, rule
from pants.engine.target import Target
from pants.engine.unions import UnionRule
from pants.util.logging import LogLevel
@dataclass(frozen=True)
class PutativeSwiftTargetsRequest(PutativeTargetsRequest):
pass
def classify_source_files(paths: Iterable[str]) -> dict[type[Target], set[str]]:
"""Returns a dict of target type -> files that belong to targets of that type."""
sources_files = set(paths)
return {SwiftSourcesGeneratorTarget: sources_files}
@rule(level=LogLevel.DEBUG, desc="Determine candidate Swift targets to create")
async def find_putative_targets(
req: PutativeSwiftTargetsRequest,
all_owned_sources: AllOwnedSources,
) -> PutativeTargets:
all_swift_files = await Get(
Paths, PathGlobs, req.path_globs(*(f"*{ext}" for ext in SWIFT_FILE_EXTENSIONS))
)
unowned_swift_files = set(all_swift_files.files) - set(all_owned_sources)
classified_unowned_swift_files = classify_source_files(unowned_swift_files)
putative_targets = []
for tgt_type, paths in classified_unowned_swift_files.items():
for dirname, filenames in group_by_dir(paths).items():
putative_targets.append(
PutativeTarget.for_target_type(
tgt_type, path=dirname, name=None, triggering_sources=sorted(filenames)
)
)
return PutativeTargets(putative_targets)
def rules() -> Iterable[Rule | UnionRule]:
return (
*collect_rules(),
UnionRule(PutativeTargetsRequest, PutativeSwiftTargetsRequest),
)
| 33.921875 | 95 | 0.748042 | 67 | 0.030861 | 0 | 0 | 1,000 | 0.460617 | 829 | 0.381852 | 264 | 0.121603 |
894fdf877d94231d589d47daadc64f279fa8f303 | 1,059 | py | Python | WP5/KU/SharedResources/get_incrementer.py | MONICA-Project/sfn | 40509e520e83441068b5a2d151864fe3a5814d5e | [
"Apache-2.0"
] | 1 | 2021-10-05T08:00:42.000Z | 2021-10-05T08:00:42.000Z | WP5/KU/SharedResources/get_incrementer.py | MONICA-Project/sfn | 40509e520e83441068b5a2d151864fe3a5814d5e | [
"Apache-2.0"
] | 10 | 2020-03-31T07:49:14.000Z | 2022-03-12T00:17:51.000Z | WP5/KU/SharedResources/get_incrementer.py | MONICA-Project/sfn | 40509e520e83441068b5a2d151864fe3a5814d5e | [
"Apache-2.0"
] | 1 | 2021-10-05T07:59:18.000Z | 2021-10-05T07:59:18.000Z | # get_incrementer.py
"""Helper function to create counter strings with a set length throughout."""
__version__ = '0.2'
__author__ = 'Rob Dupre (KU)'
def get_incrementer(num, num_digits):
if num >= 10**num_digits:
print('NUMBER IS LARGER THAN THE MAX POSSIBLE BASED ON num_digits')
return -1
else:
if num > 9999999:
number_length = 8
elif num > 999999:
number_length = 7
elif num > 99999:
number_length = 6
elif num > 9999:
number_length = 5
elif num > 999:
number_length = 4
elif num > 99:
number_length = 3
elif num > 9:
number_length = 2
else:
number_length = 1
char = ''
for i in range(num_digits - number_length):
char = char + '0'
return char + str(num)
def get_num_length(num):
if type(num) == int:
return len(str(num))
else:
print('Number is not an Int. Length will include the decimal')
return len(str(num))
| 24.627907 | 77 | 0.558074 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 238 | 0.22474 |
89506cba8d48107a96bebd4fb53108e48e413e52 | 179 | py | Python | Curso_Coursera/Ex1_ParImpar.py | shirleyguimaraes/Linguagem_Python | cb8b871ee4fe85f803c35bfe55ce533cab8150fb | [
"MIT"
] | null | null | null | Curso_Coursera/Ex1_ParImpar.py | shirleyguimaraes/Linguagem_Python | cb8b871ee4fe85f803c35bfe55ce533cab8150fb | [
"MIT"
] | null | null | null | Curso_Coursera/Ex1_ParImpar.py | shirleyguimaraes/Linguagem_Python | cb8b871ee4fe85f803c35bfe55ce533cab8150fb | [
"MIT"
] | null | null | null |
def main():
n = int(input("Digite um número inteiro: "))
resto = n % 2
if resto == 0:
print("Par")
else:
print("Impar")
main()
| 11.933333 | 49 | 0.435754 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 41 | 0.227778 |
89528b5ef79fc793c901837f37deed12889d7c14 | 536 | py | Python | pyro/contrib/oed/__init__.py | cweniger/pyro | ba104f07ca17865d2600e8765d920d549fcb3fbc | [
"MIT"
] | 10 | 2020-03-18T14:41:25.000Z | 2021-07-04T08:49:57.000Z | pyro/contrib/oed/__init__.py | cweniger/pyro | ba104f07ca17865d2600e8765d920d549fcb3fbc | [
"MIT"
] | 19 | 2018-10-30T13:45:31.000Z | 2019-09-27T14:16:57.000Z | pyro/contrib/oed/__init__.py | cweniger/pyro | ba104f07ca17865d2600e8765d920d549fcb3fbc | [
"MIT"
] | 5 | 2020-06-21T23:40:35.000Z | 2021-11-09T16:18:42.000Z | """
The :mod:`pyro.contrib.oed` module provides tools to create optimal experiment
designs for pyro models. In particular, it provides estimators for the
expected information gain (EIG) criterion.
To estimate the EIG for a particular design, use::
def model(design):
...
# Select an appropriate EIG estimator, such as
eig = vnmc_eig(model, design, ...)
EIG can then be maximised using existing optimisers in :mod:`pyro.optim`.
"""
from pyro.contrib.oed import search, eig
__all__ = [
"search",
"eig"
]
| 23.304348 | 78 | 0.701493 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 467 | 0.871269 |
8953849e85ab59dfe4d9f0bc0daf7168cfaa9806 | 311 | py | Python | tests/serve/test_metadata.py | outerbounds/tempo | 0878ae32ed6163a1c5115f20167d991a28535364 | [
"Apache-2.0"
] | 75 | 2021-02-15T09:49:02.000Z | 2022-03-31T02:06:38.000Z | tests/serve/test_metadata.py | outerbounds/tempo | 0878ae32ed6163a1c5115f20167d991a28535364 | [
"Apache-2.0"
] | 106 | 2021-02-13T09:25:19.000Z | 2022-03-25T16:18:00.000Z | tests/serve/test_metadata.py | outerbounds/tempo | 0878ae32ed6163a1c5115f20167d991a28535364 | [
"Apache-2.0"
] | 21 | 2021-02-12T17:12:50.000Z | 2022-03-04T02:09:26.000Z | import pytest
from tempo.serve.metadata import KubernetesRuntimeOptions
@pytest.mark.parametrize(
"runtime, replicas",
[
({"replicas": 2}, 2),
({}, 1),
],
)
def test_runtime_options(runtime, replicas):
r = KubernetesRuntimeOptions(**runtime)
assert r.replicas == replicas
| 19.4375 | 57 | 0.655949 | 0 | 0 | 0 | 0 | 235 | 0.755627 | 0 | 0 | 29 | 0.093248 |
895431e6e79bcf654061cac0d31efed8ab34ab25 | 323 | py | Python | referral/faker_factories.py | exolever/django-earlyparrot | 031b7f2d67e1e78d525f85ae10e82d4cc0c198f3 | [
"MIT"
] | null | null | null | referral/faker_factories.py | exolever/django-earlyparrot | 031b7f2d67e1e78d525f85ae10e82d4cc0c198f3 | [
"MIT"
] | 7 | 2019-09-04T10:59:39.000Z | 2019-12-12T22:16:25.000Z | referral/faker_factories.py | exolever/django-earlyparrot | 031b7f2d67e1e78d525f85ae10e82d4cc0c198f3 | [
"MIT"
] | null | null | null | import factory
from faker import Faker
from referral.models import Campaign
faker = Faker()
class FakeCampaignFactory(factory.django.DjangoModelFactory):
class Meta:
model = Campaign
campaign_id = factory.LazyAttribute(lambda x: faker.sha1())
name = factory.LazyAttribute(lambda x: faker.word())
| 19 | 63 | 0.739938 | 225 | 0.696594 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
89543e9c996717e15aa0e3c4f48041c92613b895 | 3,703 | py | Python | main.py | djlafferty7/itlookslikedanlaffertyoutside | fc98a4c42911d364c72317abdb9fc96abd70b8b2 | [
"Apache-2.0"
] | null | null | null | main.py | djlafferty7/itlookslikedanlaffertyoutside | fc98a4c42911d364c72317abdb9fc96abd70b8b2 | [
"Apache-2.0"
] | null | null | null | main.py | djlafferty7/itlookslikedanlaffertyoutside | fc98a4c42911d364c72317abdb9fc96abd70b8b2 | [
"Apache-2.0"
] | null | null | null | import json
import requests
import time
from flask import Flask, render_template, request
app = Flask(__name__)
API_KEY='<insert_api_key_here>'
@app.route('/')
def index():
background, style, message = setParams()
return render_template('index.html', background=background, style=style, message=message)
#funstion to set parameters
def setParams():
weather = getWeather()
background, style = getBackground(weather)
condition = weather['weather'][0]['description']
message = "Looks like it's " + condition + " outside"
return background, style, message
#get users city from IP address and return weather
def getWeather():
try:
ip_address = request.headers['x-appengine-user-ip']
url = f'http://ip-api.com/json/{ip_address}'
location = requests.get(url, verify=False).json()
city = location['city']
except Exception as e:
print(e)
city='london'
url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}'
weather = requests.get(url, verify=False).json()
return weather
#get current time in seconds
def getCurrentTime():
now = round(time.time())
return now
#return background image based on time of day
def getBackground(weather):
sunrise = weather['sys']['sunrise']
sunset = weather['sys']['sunset']
startSunset = sunset - 3600
endSunset = sunset + 3600
now = getCurrentTime()
condition = weather['weather'][0]['main']
if (now < sunrise):
background = 'https://storage.googleapis.com/apportunity.appspot.com/night_spain.jpeg'
day = False
elif (now > sunrise and now < startSunset):
background = weatherPic(condition)
day = True
elif (now > startSunset and now < endSunset):
background = sunsetPic(condition)
day = True
elif (now > endSunset):
background = 'https://storage.googleapis.com/apportunity.appspot.com/night_spain.jpeg'
day = False
style = setStyle(day)
return background, style
#retrin sunset image based on weather
def sunsetPic(condition):
if (condition == 'Clear'):
background = 'https://storage.googleapis.com/apportunity.appspot.com/sunset_burma.jpg'
elif (condition == 'Clouds'):
background = 'https://storage.googleapis.com/apportunity.appspot.com/sunset_england.jpg'
else:
background = 'https://storage.googleapis.com/apportunity.appspot.com/sunset_burma.jpg'
return background
#return daytime image based on weather
def weatherPic(condition):
if (condition == 'Clear'):
background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'
elif (condition == 'Clouds'):
background = 'https://storage.googleapis.com/apportunity.appspot.com/clouds_london.jpg'
elif (condition == 'Rain'):
background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'
elif (condition == 'Drizzle'):
background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'
elif (condition == 'Snow'):
background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'
elif (condition == 'Thunderstorm'):
background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'
else:
background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'
return background
#fucntion to get style
def setStyle(day):
if (day == True):
style = ['grey lighten-5','grey lighten-3']
else:
style = ['grey darken-4','black']
return style
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
| 35.266667 | 96 | 0.676479 | 0 | 0 | 0 | 0 | 167 | 0.045099 | 0 | 0 | 1,524 | 0.411558 |
8955852e7532c9fcb8b74321bae9283af152725a | 2,587 | py | Python | meta/dice.py | dkkim93/meta-mapg | 98d4d1be3f5fd628b42e451bed99004f02f553d0 | [
"MIT"
] | 15 | 2021-06-09T09:56:37.000Z | 2022-02-27T18:56:33.000Z | meta/dice.py | dkkim93/meta-mapg | 98d4d1be3f5fd628b42e451bed99004f02f553d0 | [
"MIT"
] | 1 | 2021-11-17T07:38:30.000Z | 2021-11-29T15:27:46.000Z | meta/dice.py | dkkim93/meta-mapg | 98d4d1be3f5fd628b42e451bed99004f02f553d0 | [
"MIT"
] | 2 | 2021-09-14T07:26:25.000Z | 2021-10-03T04:09:24.000Z | import torch
def magic_box(x):
"""DiCE operation that saves computation graph inside tensor
See ``Implementation of DiCE'' section in the DiCE Paper for details
Args:
x (tensor): Input tensor
Returns:
1 (tensor): Tensor that has computation graph saved
References:
https://github.com/alshedivat/lola/blob/master/lola_dice/rpg.py
https://github.com/alexis-jacq/LOLA_DiCE/blob/master/ipd_DiCE.py
"""
return torch.exp(x - x.detach())
def get_dice_loss(logprobs, reward, value, args, i_agent, is_train):
"""Compute DiCE loss
In our code, we use DiCE in the inner loop to be able to keep the dependency in the
adapted parameters. This is required in order to compute the opponent shaping term.
Args:
logprobs (list): Contains log probability of all agents
reward (list): Contains rewards across trajectories for specific agent
value (tensor): Contains value for advantage computed via linear baseline
args (argparse): Python argparse that contains arguments
i_agent (int): Agent to compute DiCE loss for
is_train (bool): Flag to identify whether in meta-train or not
Returns:
dice loss (tensor): DiCE loss with baseline reduction
References:
https://github.com/alshedivat/lola/blob/master/lola_dice/rpg.py
https://github.com/alexis-jacq/LOLA_DiCE/blob/master/ipd_DiCE.py
"""
# Get discounted_reward
reward = torch.stack(reward, dim=1)
cum_discount = torch.cumprod(args.discount * torch.ones(*reward.size()), dim=1) / args.discount
discounted_reward = reward * cum_discount
# Compute stochastic nodes involved in reward dependencies
if args.opponent_shaping and is_train:
logprob_sum, stochastic_nodes = 0., 0.
for logprob in logprobs:
logprob = torch.stack(logprob, dim=1)
logprob_sum += logprob
stochastic_nodes += logprob
dependencies = torch.cumsum(logprob_sum, dim=1)
else:
logprob = torch.stack(logprobs[i_agent], dim=1)
dependencies = torch.cumsum(logprob, dim=1)
stochastic_nodes = logprob
# Get DiCE loss
dice_loss = torch.mean(torch.sum(magic_box(dependencies) * discounted_reward, dim=1))
# Apply variance_reduction if value is provided
baseline_term = 0.
if value is not None:
discounted_value = value.detach() * cum_discount
baseline_term = torch.mean(torch.sum((1 - magic_box(stochastic_nodes)) * discounted_value, dim=1))
return -(dice_loss + baseline_term)
| 41.063492 | 106 | 0.688829 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,426 | 0.551218 |
8956a32ea669342323a0da4e15ade20f0c7f1b66 | 91 | py | Python | src/coreapis/apps.py | salemzii/ChopFast | 95ea88387ecfdb56bd643970b69425b1a1c6f388 | [
"MIT"
] | null | null | null | src/coreapis/apps.py | salemzii/ChopFast | 95ea88387ecfdb56bd643970b69425b1a1c6f388 | [
"MIT"
] | null | null | null | src/coreapis/apps.py | salemzii/ChopFast | 95ea88387ecfdb56bd643970b69425b1a1c6f388 | [
"MIT"
] | null | null | null | from django.apps import AppConfig
class CoreapisConfig(AppConfig):
name = 'coreapis'
| 15.166667 | 33 | 0.758242 | 54 | 0.593407 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 0.10989 |
895976c032c7db9f729336aff5e0279c9a266299 | 274 | py | Python | project/opendata/parse.py | FelippeJC/besa | 083e62457c9c9beccc869beb89675720be0d248a | [
"MIT"
] | null | null | null | project/opendata/parse.py | FelippeJC/besa | 083e62457c9c9beccc869beb89675720be0d248a | [
"MIT"
] | 2 | 2021-05-10T16:40:12.000Z | 2021-09-05T09:26:07.000Z | project/opendata/parse.py | FelippeJC/besa | 083e62457c9c9beccc869beb89675720be0d248a | [
"MIT"
] | null | null | null | from .request import datastore_search
def get_data_from_datastore(expression):
"""Returns a list of records found in a datastore search"""
response = datastore_search(expression)
result = response.get("result", dict())
return result.get("records", dict())
| 30.444444 | 63 | 0.729927 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 76 | 0.277372 |
8959f2b49b675b763760dbc29357913d9e63369d | 1,486 | py | Python | dynamicserialize/dstypes/gov/noaa/nws/ncep/common/dataplugin/gempak/request/Station.py | mjames-upc/python-awips | e2b05f5587b02761df3b6dd5c6ee1f196bd5f11c | [
"BSD-3-Clause"
] | null | null | null | dynamicserialize/dstypes/gov/noaa/nws/ncep/common/dataplugin/gempak/request/Station.py | mjames-upc/python-awips | e2b05f5587b02761df3b6dd5c6ee1f196bd5f11c | [
"BSD-3-Clause"
] | null | null | null | dynamicserialize/dstypes/gov/noaa/nws/ncep/common/dataplugin/gempak/request/Station.py | mjames-upc/python-awips | e2b05f5587b02761df3b6dd5c6ee1f196bd5f11c | [
"BSD-3-Clause"
] | null | null | null |
# File auto-generated against equivalent DynamicSerialize Java class
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# Sep 16, 2016 pmoyer Generated
import numpy
class Station(object):
def __init__(self):
self.elevation = None
self.state = None
self.stationId = None
self.longitude = None
self.latitude = None
self.wmoIndex = None
self.country = None
def getElevation(self):
return self.elevation
def setElevation(self, elevation):
self.elevation = elevation
def getState(self):
return self.state
def setState(self, state):
self.state = state
def getStationId(self):
return self.stationId
def setStationId(self, stationId):
self.stationId = stationId
def getLongitude(self):
return self.longitude
def setLongitude(self, longitude):
self.longitude = numpy.float64(longitude)
def getLatitude(self):
return self.latitude
def setLatitude(self, latitude):
self.latitude = numpy.float64(latitude)
def getWmoIndex(self):
return self.wmoIndex
def setWmoIndex(self, wmoIndex):
self.wmoIndex = wmoIndex
def getCountry(self):
return self.country
def setCountry(self, country):
self.country = country
| 22.861538 | 77 | 0.588156 | 1,169 | 0.786676 | 0 | 0 | 0 | 0 | 0 | 0 | 292 | 0.196501 |
895aafff76fa0567fe017a820fa38e5c27392a87 | 4,051 | py | Python | gghc/dbcluster.py | opengauss-mirror/openGauss-housekeeper | 6f741efe182ebd5da792faac16534823beb45d20 | [
"MulanPSL-1.0"
] | null | null | null | gghc/dbcluster.py | opengauss-mirror/openGauss-housekeeper | 6f741efe182ebd5da792faac16534823beb45d20 | [
"MulanPSL-1.0"
] | null | null | null | gghc/dbcluster.py | opengauss-mirror/openGauss-housekeeper | 6f741efe182ebd5da792faac16534823beb45d20 | [
"MulanPSL-1.0"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# dbcluster.py
# GGHC cluster class
# Copyright (c) 2021 Chinasoft International Co., Ltd.
#
# gghc is licensed under Mulan PSL v2.
# You can use this software according to the terms
# and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
# http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
#
# IDENTIFICATION
# gghc/dbcluster.py
# ----------------------------------------------------------------------------
import re
import time
from dbnode import DbNode
import copy
class DbCluster():
"""
classdocs
"""
def __init__(self):
"""
Constructor
"""
self.state = ""
self.nodes = []
self.timeStamp = None
def clear(self):
self.state = ""
self.nodes = []
self.timeStamp = None
def buildByQuery(self, clusterInfo):
self.clear()
flag1 = False
dbClusterFormatter = None
for info in clusterInfo.split("\n"):
info = info.strip()
if len(info) == 0:
continue
if (self.state == ""):
if "cluster_state" in info:
self.state = info.split(":")[-1].strip()
flag1 = True
continue
# 判定节点状态是否竖线分割。等于1是为竖线分割,等于2分行显示
if dbClusterFormatter is None:
if re.search(r"(node\s+node_ip\s+instance\s+state\s+\|)+", info) is not None:
dbClusterFormatter = "v1"
elif re.search(r"(node\s+node_ip\s+port\s+instance\s+state)", info) is not None:
dbClusterFormatter = "v2"
continue
# 所有datanode的状态竖线分割
if dbClusterFormatter == 'v1':
if re.search(r"(([0-9]{1,3}\.){3}[0-9]{1,3}.*\|)+", info) is not None:
for nodeInfo in info.split("|"):
dbNode = DbNode()
dbNode.buildByQuery(nodeInfo, dbClusterFormatter)
self.nodes.append(dbNode)
# 每个datanode的状态分行显示
elif dbClusterFormatter == 'v2':
dbNode = DbNode()
dbNode.buildByQuery(info, dbClusterFormatter)
self.nodes.append(dbNode)
self.timeStamp = time.localtime()
return flag1 and len(self.nodes) > 0
def getPrimaryNodeIds(self):
nodeIds = []
for nodeId in range(len(self.nodes)):
node = self.nodes[nodeId]
if((node.state).lower() == "primary"):
nodeIds.append(nodeId)
return nodeIds
def getStandbyNodeIds(self):
nodeIds = []
for nodeId in range(len(self.nodes)):
node = self.nodes[nodeId]
if(node.state.lower() == "standby"):
nodeIds.append(nodeId)
return nodeIds
def getNodeState(self, nodeId):
if(nodeId >= len(self.nodes)):
return None
node = self.nodes[nodeId]
return node.state
def existsPendingNode(self):
for node in self.nodes:
if node.isPendingNode():
return True
return False
def getClusterStateStr(self):
return "%s[%s]" % (self.state, time.strftime("%Y-%m-%d %H:%M:%S", self.timeStamp))
def __str__(self):
nodeStr = ""
for node in self.nodes:
nodeStr += "%s;" % str(node)
return "%s;%s" % (self.state, nodeStr[:-1])
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, copy.deepcopy(v, memo))
super(DbCluster, result).__init__()
return result
| 28.328671 | 96 | 0.534189 | 3,330 | 0.803765 | 0 | 0 | 0 | 0 | 0 | 0 | 1,176 | 0.283852 |
895af3a6b4f4978f67e07a5374ce2c7a074ba071 | 36,892 | py | Python | ProjectFiles/bin/Release/2.80/scripts/addons_contrib/io_directx_bel/import_x.py | BlazesRus/Bforartists | 126bdd9e47cc984fd97ba5299bfb92ec5278e754 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2019-07-08T15:51:14.000Z | 2019-07-08T15:51:14.000Z | ProjectFiles/bin/Release/2.80/scripts/addons_contrib/io_directx_bel/import_x.py | BlazesRus/Bforartists | 126bdd9e47cc984fd97ba5299bfb92ec5278e754 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | ProjectFiles/bin/Release/2.80/scripts/addons_contrib/io_directx_bel/import_x.py | BlazesRus/Bforartists | 126bdd9e47cc984fd97ba5299bfb92ec5278e754 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | # Blender directX importer
# version baby
# litterature explaining the parser directions :
# I don't want to load the whole file as it can be huge : go chunks
# also I want random access to 3d datas to import pieces, not always everything
# so step1 is a whole file fast parsing, retrieving tokens name and building en empty internal dict
# with only pointers and no 3d datas.
# step 2 is to call any token by their names and retrieve the 3d datas thanks to pointers stored in dicts
# between step 1 and step 2 a script ui should be provided to select, transform etc before import.
# > I need to know the pointer position of tokens but data.tell() is slow
# a += pointer computed from line length is way faster. so I need eol -> rb mode
# and readline() is ok in binary mode 'rb' with \r\n (win) \n (unix) but not \r mac..
# 2chrs for windows, 1 for mac and lunix > win eol \r\n becomes \n\n (add a line)
# mac eol \r becomes \n so win lines info are wrong
# this also allows support for wrong files format (mixed \r and \r\n)
# for now it only works for text format, but the used methods will be independant of the container type.
# TEST FILES
# http://assimp.svn.sourceforge.net/viewvc/assimp/trunk/test/models/X/
import os
import re
import struct, binascii
import time
import bpy
import mathutils as bmat
from mathutils import Vector, Matrix
try :
import bel
import bel.mesh
import bel.image
import bel.uv
import bel.material
import bel.ob
import bel.fs
except :
import io_directx_bel.bel as bel
from .bel import mesh,image,uv,material,ob,fs
from .templates_x import *
'''
# just a temp hack to reload bel everytime
import imp
imp.reload(bel)
imp.reload(bel.fs)
imp.reload(bel.image)
imp.reload(bel.material)
imp.reload(bel.mesh)
imp.reload(bel.ob)
imp.reload(bel.uv)
'''
###################################################
def load(operator, context, filepath,
global_clamp_size=0.0,
show_tree=False,
show_templates=False,
show_geninfo=False,
quickmode=False,
parented=False,
bone_maxlength=1.0,
chunksize=False,
naming_method=0,
use_ngons=True,
use_edges=True,
use_smooth_groups=True,
use_split_objects=True,
use_split_groups=True,
use_groups_as_vgroups=False,
use_image_search=True,
global_matrix=None,
):
if quickmode :
parented = False
bone_minlength = bone_maxlength / 100.0
#global templates, tokens
rootTokens = []
namelookup = {}
imgnamelookup = {}
chunksize = int(chunksize)
reserved_type = (
'dword',
'float',
'string'
)
'''
'array',
'Matrix4x4',
'Vector',
'''
'''
with * : defined in dXdata
WORD 16 bits
* DWORD 32 bits
* FLOAT IEEE float
DOUBLE 64 bits
CHAR 8 bits
UCHAR 8 bits
BYTE 8 bits
* STRING NULL-terminated string
CSTRING Formatted C-string (currently unsupported)
UNICODE UNICODE string (currently unsupported)
BINARY FORMAT
# TOKENS in little-endian WORDs
#define TOKEN_NAME 1
#define TOKEN_STRING 2
#define TOKEN_INTEGER 3
#define TOKEN_GUID 5
#define TOKEN_INTEGER_LIST 6
#define TOKEN_FLOAT_LIST 7
#define TOKEN_OBRACE 10
#define TOKEN_CBRACE 11
#define TOKEN_OPAREN 12
#define TOKEN_CPAREN 13
#define TOKEN_OBRACKET 14
#define TOKEN_CBRACKET 15
#define TOKEN_OANGLE 16
#define TOKEN_CANGLE 17
#define TOKEN_DOT 18
#define TOKEN_COMMA 19
#define TOKEN_SEMICOLON 20
#define TOKEN_TEMPLATE 31
#define TOKEN_WORD 40
#define TOKEN_DWORD 41
#define TOKEN_FLOAT 42
#define TOKEN_DOUBLE 43
#define TOKEN_CHAR 44
#define TOKEN_UCHAR 45
#define TOKEN_SWORD 46
#define TOKEN_SDWORD 47
#define TOKEN_VOID 48
#define TOKEN_LPSTR 49
#define TOKEN_UNICODE 50
#define TOKEN_CSTRING 51
#define TOKEN_ARRAY 52
'''
# COMMON REGEX
space = '[\ \t]{1,}' # at least one space / tab
space0 = '[\ \t]{0,}' # zero or more space / tab
# DIRECTX REGEX TOKENS
r_template = r'template' + space + '[\w]*' + space0 + '\{'
if quickmode :
r_sectionname = r'Mesh' + space + '[\W-]*'
else :
r_sectionname = r'[\w]*' + space + '[\w-]*' + space0 + '\{'
r_refsectionname = r'\{' + space0 + '[\w-]*' + space0 + '\}'
r_endsection = r'\{|\}'
# dX comments
r_ignore = r'#|//'
#r_frame = r'Frame' + space + '[\w]*'
#r_matrix = r'FrameTransformMatrix' + space + '\{[\s\d.,-]*'
#r_mesh = r'Mesh' + space + '[\W]*'
###################
## STEP 1 FUNCTIONS
###################
## HEADER
# returns header values or False if directx reco tag is missing
# assuming there's never comment header and that xof if the 1st
# string of the file
'''
they look like xof 0303txt 0032
4 Magic Number (required) "xof "
2 Minor Version 03
2 Major Version 02
4 Format Type (required)
"txt " Text File
"bin " Binary File
"tzip" MSZip Compressed Text File
"bzip" MSZip Compressed Binary File
4 Float Accuracy "0032" 32 bit or "0064" 64 bit
'''
def dXheader(data) :
l = data.read(4)
if l != b'xof ' :
print ('no header found !')
data.seek(0)
return False
minor = data.read(2).decode()
major = data.read(2).decode()
format = data.read(4).decode().strip()
accuracy = int(data.read(4).decode())
data.seek(0)
return ( minor, major, format, accuracy )
##
def dXtree(data,quickmode = False) :
tokens = {}
templates = {}
tokentypes = {}
c = 0
lvl = 0
tree = ['']
ptr = 0
eol = 0
trunkated = False
previouslvl = False
while True :
#for l in data.readlines() :
lines, trunkated = nextFileChunk(data,trunkated)
if lines == None : break
for l in lines :
# compute pointer position
ptr += eol
c += 1
eol = len(l) + 1
#print(c,data.tell(),ptr+eol)
#if l != '' : print('***',l)
#if l == '' : break
l = l.strip()
# remove blank and comment lines
if l == '' or re.match(r_ignore,l) :
continue
# one line token cases level switch
if previouslvl :
lvl -= 1
previouslvl = False
#print('%s lines in %.2f\''%(c,time.clock()-t),end='\r')
#print(c,len(l)+1,ptr,data.tell())
if '{' in l :
lvl += 1
if '}' in l : previouslvl = True #; print('got one line token : \n%s'%l)
elif '}' in l :
lvl -= 1
#print(c,lvl,tree)
if quickmode == False :
## look for templates
if re.match(r_template,l) :
tname = l.split(' ')[1]
templates[tname] = {'pointer' : ptr, 'line' : c}
continue
## look for {references}
if re.match(r_refsectionname,l) :
refname = namelookup[ l[1:-1].strip() ]
#print('FOUND reference to %s in %s at line %s (level %s)'%(refname,tree[lvl-1],c,lvl))
#tree = tree[0:lvl]
parent = tree[lvl-1]
# tag it as a reference, since it's not exactly a child.
# put it in childs since order can matter in sub tokens declaration
tokens[parent]['childs'].append('*'+refname)
if refname not in tokens :
print('reference to %s done before its declaration (line %s)\ncreated dummy'%(refname,c))
tokens[refname] = {}
if 'user' not in tokens[refname] : tokens[refname]['users'] = [parent]
else : tokens[refname]['users'].append(parent)
continue
## look for any token or only Mesh token in quickmode
if re.match(r_sectionname,l) :
tokenname = getName(l,tokens)
#print('FOUND %s %s %s %s'%(tokenname,c,lvl,tree))
#print('pointer %s %s'%(data.tell(),ptr))
if lvl == 1 : rootTokens.append(tokenname)
typ = l.split(' ')[0].strip().lower()
tree = tree[0:lvl]
if typ not in tokentypes : tokentypes[typ] = [tokenname]
else : tokentypes[typ].append(tokenname)
parent = tree[-1]
if tokenname in tokens :
tokens[tokenname]['pointer'] = ptr
tokens[tokenname]['line'] = c
tokens[tokenname]['parent'] = parent
tokens[tokenname]['childs'] = []
tokens[tokenname]['type'] = typ
else : tokens[tokenname] = {'pointer': ptr,
'line' : c,
'parent' : parent,
'childs' : [],
'users' : [],
'type' : typ
}
tree.append(tokenname)
if lvl > 1 and quickmode == False :
tokens[parent]['childs'].append(tokenname)
return tokens, templates, tokentypes
## returns file binary chunks
def nextFileChunk(data,trunkated=False,chunksize=1024) :
if chunksize == 0 : chunk = data.read()
else : chunk = data.read(chunksize)
if format == 'txt' :
lines = chunk.decode('utf-8', errors='ignore')
#if stream : return lines.replace('\r','').replace('\n','')
lines = lines.replace('\r','\n').split('\n')
if trunkated : lines[0] = trunkated + lines[0]
if len(lines) == 1 :
if lines[0] == '' : return None, None
return lines, False
return lines, lines.pop()
# wip, todo for binaries
else :
print(chunk)
for word in range(0,len(chunk)) :
w = chunk[word:word+4]
print(word,w,struct.unpack("<l", w),binascii.unhexlify(w))
# name unnamed tokens, watchout for x duplicate
# for blender, referenced token in x should be named and unique..
def getName(l,tokens) :
xnam = l.split(' ')[1].strip()
#if xnam[0] == '{' : xnam = ''
if xnam and xnam[-1] == '{' : xnam = xnam[:-1]
name = xnam
if len(name) == 0 : name = l.split(' ')[0].strip()
namelookup[xnam] = bel.bpyname(name,tokens,4)
return namelookup[xnam]
###################
## STEP 2 FUNCTIONS
###################
# once the internal dict is populated the functions below can be used
## from a list of tokens, displays every child, users and references
'''
walk_dxtree( [ 'Mesh01', 'Mesh02' ] ) # for particular pieces
walk_dxtree(tokens.keys()) for the whole tree
'''
def walk_dXtree(field,lvl=0,tab='') :
for fi, tokenname in enumerate(field) :
if lvl > 0 or tokens[tokenname]['parent'] == '' :
if tokenname not in tokens :
tokenname = tokenname[1:]
ref = 'ref: '
else : ref = False
frame_type = tokens[tokenname]['type']
line = ('{:7}'.format(tokens[tokenname]['line']))
log = ' %s%s (%s)'%( ref if ref else '', tokenname, frame_type )
print('%s.%s%s'%(line, tab, log))
if fi == len(field) - 1 : tab = tab[:-3] + ' '
if ref == False :
for user in tokens[tokenname]['users'] :
print('%s.%s |__ user: %s'%(line, tab.replace('_',' '), user))
walk_dXtree(tokens[tokenname]['childs'],lvl+1,tab.replace('_',' ')+' |__')
if fi == len(field) - 1 and len(tokens[tokenname]['childs']) == 0 :
print('%s.%s'%(line,tab))
## remove eol, comments, spaces from a raw block of datas
def cleanBlock(block) :
while '//' in block :
s = block.index('//')
e = block.index('\n',s+1)
block = block[0:s] + block[e:]
while '#' in block :
s = block.index('#')
e = block.index('\n',s+1)
block = block[0:s] + block[e:]
block = block.replace('\n','').replace(' ','').replace('\t ','')
return block
def readToken(tokenname) :
token = tokens[tokenname]
datatype = token['type'].lower()
if datatype in templates : tpl = templates[datatype]
elif datatype in defaultTemplates : tpl = defaultTemplates[datatype]
else :
print("can't find any template to read %s (type : %s)"%(tokenname,datatype))
return False
#print('> use template %s'%datatype)
block = readBlock(data,token)
ptr = 0
#return dXtemplateData(tpl,block)
fields, ptr = dXtemplateData(tpl,block)
if datatype in templatesConvert :
fields = eval( templatesConvert[datatype] )
return fields
def dXtemplateData(tpl,block,ptr=0) :
#print('dxTPL',block[ptr])
pack = []
for member in tpl['members'] :
#print(member)
dataname = member[-1]
datatype = member[0].lower()
if datatype == 'array' :
datatype = member[1].lower()
s = dataname.index('[') + 1
e = dataname.index(']')
#print(dataname[s:e])
length = eval(dataname[s:e])
#print("array %s type %s length defined by '%s' : %s"%(dataname[:s-1],datatype,dataname[s:e],length))
dataname = dataname[:s-1]
datavalue, ptr = dXarray(block, datatype, length, ptr)
#print('back to %s'%(dataname))
else :
length = 1
datavalue, ptr = dXdata(block, datatype, length, ptr)
#if len(str(datavalue)) > 50 : dispvalue = str(datavalue[0:25]) + ' [...] ' + str(datavalue[-25:])
#else : dispvalue = str(datavalue)
#print('%s : %s %s'%(dataname,dispvalue,type(datavalue)))
exec('%s = datavalue'%(dataname))
pack.append( datavalue )
return pack, ptr + 1
def dXdata(block,datatype,length,s=0,eof=';') :
#print('dxDTA',block[s])
# at last, the data we need
# should be a ';' but one meet ',' often, like in meshface
if datatype == 'dword' :
e = block.index(';',s+1)
try : field = int(block[s:e])
except :
e = block.index(',',s+1)
field = int(block[s:e])
return field, e+1
elif datatype == 'float' :
e = block.index(eof,s+1)
return float(block[s:e]), e+1
elif datatype == 'string' :
e = block.index(eof,s+1)
return str(block[s+1:e-1]) , e+1
else :
if datatype in templates : tpl = templates[datatype]
elif datatype in defaultTemplates : tpl = defaultTemplates[datatype]
else :
print("can't find any template for type : %s"%(datatype))
return False
#print('> use template %s'%datatype)
fields, ptr = dXtemplateData(tpl,block,s)
if datatype in templatesConvert :
fields = eval( templatesConvert[datatype] )
return fields, ptr
def dXarray(block, datatype, length, s=0) :
#print('dxARR',block[s])
lst = []
if datatype in reserved_type :
eoi=','
for i in range(length) :
if i+1 == length : eoi = ';'
datavalue, s = dXdata(block,datatype,1,s,eoi)
lst.append( datavalue )
else :
eoi = ';,'
for i in range(length) :
if i+1 == length : eoi = ';;'
#print(eoi)
e = block.index(eoi,s)
#except : print(block,s) ; popo()
datavalue, na = dXdata(block[s:e+1],datatype,1)
lst.append( datavalue )
s = e + 2
return lst, s
###################################################
## populate a template with its datas
# this make them available in the internal dict. should be used in step 2 for unknown data type at least
def readTemplate(data,tpl_name,display=False) :
ptr = templates[tpl_name]['pointer']
line = templates[tpl_name]['line']
#print('> %s at line %s (chr %s)'%(tpl_name,line,ptr))
data.seek(ptr)
block = ''
trunkated = False
go = True
while go :
lines, trunkated = nextFileChunk(data,trunkated,chunksize) # stream ?
if lines == None :
break
for l in lines :
#l = data.readline().decode().strip()
block += l.strip()
if '}' in l :
go = False
break
uuid = re.search(r'<.+>',block).group()
templates[tpl_name]['uuid'] = uuid.lower()
templates[tpl_name]['members'] = []
templates[tpl_name]['restriction'] = 'closed'
members = re.search(r'>.+',block).group()[1:-1].split(';')
for member in members :
if member == '' : continue
if member[0] == '[' :
templates[tpl_name]['restriction'] = member
continue
templates[tpl_name]['members'].append( member.split(' ') )
if display :
print('\ntemplate %s :'%tpl_name)
for k,v in templates[tpl_name].items() :
if k != 'members' :
print(' %s : %s'%(k,v))
else :
for member in v :
print(' %s'%str(member)[1:-1].replace(',',' ').replace("'",''))
if tpl_name in defaultTemplates :
defaultTemplates[tpl_name]['line'] = templates[tpl_name]['line']
defaultTemplates[tpl_name]['pointer'] = templates[tpl_name]['pointer']
if defaultTemplates[tpl_name] != templates[tpl_name] :
print('! DIFFERS FROM BUILTIN TEMPLATE :')
print('raw template %s :'%tpl_name)
print(templates[tpl_name])
print('raw default template %s :'%tpl_name)
print(defaultTemplates[tpl_name])
#for k,v in defaultTemplates[tpl_name].items() :
# if k != 'members' :
# print(' %s : %s'%(k,v))
# else :
# for member in v :
# print(' %s'%str(member)[1:-1].replace(',',' ').replace("'",''))
else :
print('MATCHES BUILTIN TEMPLATE')
## read any kind of token data block
# by default the block is cleaned from inline comment space etc to allow data parsing
# useclean = False (retrieve all bytes) if you need to compute a file byte pointer
# to mimic the file.tell() function and use it with file.seek()
def readBlock(data,token, clean=True) :
ptr = token['pointer']
data.seek(ptr)
block = ''
#lvl = 0
trunkated = False
go = True
while go :
lines, trunkated = nextFileChunk(data,trunkated,chunksize)
if lines == None : break
for l in lines :
#eol = len(l) + 1
l = l.strip()
#c += 1
block += l+'\n'
if re.match(r_endsection,l) :
go = False
break
s = block.index('{') + 1
e = block.index('}')
block = block[s:e]
if clean : block = cleanBlock(block)
return block
def getChilds(tokenname) :
childs = []
# '*' in childname means it's a reference. always perform this test
# when using the childs field
for childname in tokens[tokenname]['childs'] :
if childname[0] == '*' : childname = childname[1:]
childs.append( childname )
return childs
# the input nested list of [bonename, matrix, [child0,child1..]] is given by import_dXtree()
def buildArm(armdata, child,lvl=0,parent_matrix=False) :
bonename, bonemat, bonechilds = child
if lvl == 0 :
armname = armdata
armdata = bpy.data.armatures.new(name=armname)
arm = bpy.data.objects.new(armname,armdata)
bpy.context.scene.objects.link(arm)
arm.select = True
bpy.context.scene.objects.active = arm
bpy.ops.object.mode_set(mode='EDIT')
parent_matrix = Matrix()
bone = armdata.edit_bones.new(name=bonename)
bonematW = parent_matrix * bonemat
bone.head = bonematW.to_translation()
#bone.roll.. ?
bone_length = bone_maxlength
for bonechild in bonechilds :
bonechild = buildArm(armdata,bonechild,lvl+1,bonematW)
bonechild.parent = bone
bone_length = min((bonechild.head - bone.head).length, bone_length)
bone.tail = bonematW * Vector((0,bone_length,0))
if lvl == 0 :
bpy.ops.object.mode_set(mode='OBJECT')
return arm
return bone
def import_dXtree(field,lvl=0) :
tab = ' '*lvl*2
if field == [] :
if show_geninfo : print('%s>> no childs, return False'%(tab))
return False
ob = False
mat = False
is_root = False
frames = []
obs = []
parentname = tokens[field[0]]['parent']
if show_geninfo : print('%s>>childs in frame %s :'%(tab,parentname))
for tokenname in field :
tokentype = tokens[tokenname]['type']
# frames can contain more than one mesh
if tokentype == 'mesh' :
# object and mesh naming :
# if parent frame has several meshes : obname = meshname = mesh token name,
# if parent frame has only one mesh : obname = parent frame name, meshname = mesh token name.
if parentname :
meshcount = 0
for child in getChilds(parentname) :
if tokens[child]['type'] == 'mesh' :
meshcount += 1
if meshcount == 2 :
parentname = tokenname
break
else : parentname = tokenname
ob = getMesh(parentname,tokenname)
obs.append(ob)
if show_geninfo : print('%smesh : %s'%(tab,tokenname))
# frames contain one matrix (empty or bone)
elif tokentype == 'frametransformmatrix' :
[mat] = readToken(tokenname)
if show_geninfo : print('%smatrix : %s'%(tab,tokenname))
# frames can contain 0 or more frames
elif tokentype == 'frame' :
frames.append(tokenname)
if show_geninfo : print('%sframe : %s'%(tab,tokenname))
# matrix is used for mesh transform if some mesh(es) exist(s)
if ob :
is_root = True
if mat == False :
mat = Matrix()
if show_geninfo : print('%smesh token without matrix, set it to default\n%splease report in bug tracker if you read this !'%(tab,tab))
if parentname == '' :
mat = mat * global_matrix
if len(obs) == 1 :
ob.matrix_world = mat
else :
ob = bel.ob.new(parentname, None, naming_method)
ob.matrix_world = mat
for child in obs :
child.parent = ob
# matrix only, store it as a list as we don't know if
# it's a bone or an empty yet
elif mat :
ob = [parentname, mat,[]]
# nothing case ?
else :
ob = [parentname, Matrix() * global_matrix,[]]
if show_geninfo : print('%snothing here'%(tab))
childs = []
for tokenname in frames :
if show_geninfo : print('%s<Begin %s :'%(tab,tokenname))
# child is either False, empty, object, or a list or undefined name matrices hierarchy
child = import_dXtree(getChilds(tokenname),lvl+1)
if child and type(child) != list :
is_root = True
childs.append( [tokenname, child] )
if show_geninfo : print('%sEnd %s>'%(tab,tokenname))
if is_root and parentname != '' :
if show_geninfo : print('%send of tree a this point'%(tab))
if type(ob) == list :
mat = ob[1]
ob = bel.ob.new(parentname, None, naming_method)
ob.matrix_world = mat
for tokenname, child in childs :
if show_geninfo : print('%sbegin2 %s>'%(tab,tokenname))
# returned a list of object(s) or matrice(s)
if child :
# current frame is an object or an empty, we parent this frame to it
#if eot or (ob and ( type(ob.data) == type(None) or type(ob.data) == bpy.types.Mesh ) ) :
if is_root :
# this branch is an armature, convert it
if type(child) == list :
if show_geninfo : print('%sconvert to armature %s'%(tab,tokenname))
child = buildArm(tokenname, child)
# parent the obj/empty/arm to current
# or apply the global user defined matrix to the object root
if parentname != '' :
child.parent = ob
else :
child.matrix_world = global_matrix
# returned a list of parented matrices. append it in childs list
elif type(child[0]) == str :
ob[2].append(child)
# child is an empty or a mesh, so current frame is an empty, not an armature
elif ob and ( type(child.data) == type(None) or type(child.data) == bpy.types.Mesh ) :
#print(' child data type: %s'%type(child.data))
child.parent = ob
#print('%s parented to %s'%(child.name,ob.name))
# returned False
else :
if show_geninfo : print('%sreturned %s, nothing'%(tab,child))
#print('>> %s return %s'%(field,ob))
return ob# if ob else False
# build from mesh token type
def getMesh(obname,tokenname,debug = False):
if debug : print('\nmesh name : %s'%tokenname)
verts = []
edges = []
faces = []
matslots = []
facemats = []
uvs = []
groupnames = []
groupindices = []
groupweights = []
nVerts, verts, nFaces, faces = readToken(tokenname)
if debug :
print('verts : %s %s\nfaces : %s %s'%(nVerts, len(verts),nFaces, len(faces)))
#for childname in token['childs'] :
for childname in getChilds(tokenname) :
tokentype = tokens[childname]['type']
# UV
if tokentype == 'meshtexturecoords' :
uv = readToken(childname)
#uv = bel.uv.asVertsLocation(uv, faces)
uv = bel.uv.asFlatList(uv, faces)
uvs.append(uv)
if debug : print('uv : %s'%(len(uv)))
# MATERIALS
elif tokentype == 'meshmateriallist' :
nbslots, facemats = readToken(childname)
if debug : print('facemats : %s'%(len(facemats)))
# mat can exist but with no datas so we prepare the mat slot
# with dummy ones
for slot in range(nbslots) :
matslots.append('dXnoname%s'%slot )
# length does not match (could be tuned more, need more cases)
if len(facemats) != len(faces) :
facemats = [ facemats[0] for i in faces ]
# seek for materials then textures if any mapped in this mesh.
# no type test, only one option type in token meshmateriallist : 'Material'
for slotid, matname in enumerate(getChilds(childname)) :
# rename dummy mats with the right name
matslots[slotid] = matname
# blender material creation (need tuning)
mat = bel.material.new(matname,naming_method)
matslots[slotid] = mat.name
if naming_method != 1 :
#print('matname : %s'%matname)
(diffuse_color,alpha), power, specCol, emitCol = readToken(matname)
#if debug : print(diffuse_color,alpha, power, specCol, emitCol)
mat.diffuse_color = diffuse_color
mat.diffuse_intensity = power
mat.specular_color = specCol
# dX emit don't use diffuse color but is a color itself
# convert it to a kind of intensity
mat.emit = (emitCol[0] + emitCol[1] + emitCol[2] ) / 3
if alpha != 1.0 :
mat.use_transparency = True
mat.transparency_method = 'Z_TRANSPARENCY'
mat.alpha = alpha
mat.specular_alpha = 0
transp = True
else : transp = False
# texture
# only 'TextureFilename' can be here, no type test
# textures have no name in .x so we build
# image and texture names from the image file name
# bdata texture slot name = bdata image name
btexnames = []
for texname in getChilds(matname) :
# create/rename/reuse etc corresponding data image
# (returns False if not found)
[filename] = readToken(texname)
img = bel.image.new(path+'/'+filename)
if img == False :
imgname = 'not_found'
else :
imgname = img.name
#print('texname : %s'%texname)
#print('filename : %s'%filename)
#print('btex/img name : %s'%imgname)
# associated texture (no naming check.. maybe tune more)
# tex and texslot are created even if img not found
if imgname in bpy.data.textures and ( img == False or bpy.data.textures[imgname].image == img ) :
tex = bpy.data.textures[imgname]
else :
tex = bpy.data.textures.new(name=imgname,type='IMAGE')
if img : tex.image = img
tex.use_alpha = transp
tex.use_preview_alpha = transp
# then create texture slot
texslot = mat.texture_slots.create(index=0)
texslot.texture = tex
texslot.texture_coords = 'UV'
texslot.uv_layer = 'UV0'
texslot.use_map_alpha = transp
texslot.alpha_factor = alpha
# create remaining dummy mat
for slotid, matname in enumerate(matslots) :
if matname not in bpy.data.materials :
mat = bel.material.new(matname,naming_method)
matslots[slotid] = mat.name
if debug : print('matslots : %s'%matslots)
# VERTICES GROUPS/WEIGHTS
elif tokentype == 'skinweights' :
groupname, nverts, vindices, vweights, mat = readToken(childname)
groupname = namelookup[groupname]
if debug :
print('vgroup : %s (%s/%s verts) %s'%(groupname,len(vindices),len(vweights),'bone' if groupname in tokens else ''))
#if debug : print('matrix : %s\n%s'%(type(mat),mat))
groupnames.append(groupname)
groupindices.append(vindices)
groupweights.append(vweights)
ob = bel.mesh.write(obname,tokenname,
verts, edges, faces,
matslots, facemats, uvs,
groupnames, groupindices, groupweights,
use_smooth_groups,
naming_method)
return ob
## here we go
file = os.path.basename(filepath)
print('\nimporting %s...'%file)
start = time.clock()
path = os.path.dirname(filepath)
filepath = os.fsencode(filepath)
data = open(filepath,'rb')
header = dXheader(data)
if global_matrix is None:
global_matrix = mathutils.Matrix()
if header :
minor, major, format, accuracy = header
if show_geninfo :
print('\n%s directX header'%file)
print(' minor : %s'%(minor))
print(' major : %s'%(major))
print(' format : %s'%(format))
print(' floats are %s bits'%(accuracy))
if format in [ 'txt' ] : #, 'bin' ] :
## FILE READ : STEP 1 : STRUCTURE
if show_geninfo : print('\nBuilding internal .x tree')
t = time.clock()
tokens, templates, tokentypes = dXtree(data,quickmode)
readstruct_time = time.clock()-t
if show_geninfo : print('builded tree in %.2f\''%(readstruct_time)) # ,end='\r')
## populate templates with datas
for tplname in templates :
readTemplate(data,tplname,show_templates)
## DATA TREE CHECK
if show_tree :
print('\nDirectX Data Tree :\n')
walk_dXtree(tokens.keys())
## DATA IMPORTATION
if show_geninfo :
#print(tokens)
print('Root frames :\n %s'%rootTokens)
if parented :
import_dXtree(rootTokens)
else :
for tokenname in tokentypes['mesh'] :
obname = tokens[tokenname]['parent']
# object and mesh naming :
# if parent frame has several meshes : obname = meshname = mesh token name,
# if parent frame has only one mesh : obname = parent frame name, meshname = mesh token name.
if obname :
meshcount = 0
for child in getChilds(obname) :
if tokens[child]['type'] == 'mesh' :
meshcount += 1
if meshcount == 2 :
obname = tokenname
break
else : obname = tokenname
ob = getMesh(obname,tokenname,show_geninfo)
ob.matrix_world = global_matrix
print('done in %.2f\''%(time.clock()-start)) # ,end='\r')
else :
print('only .x files in text format are currently supported')
print('please share your file to make the importer evolve')
return {'FINISHED'}
| 37.993821 | 150 | 0.497235 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 11,730 | 0.317955 |
895c1ad530c40f1c5d1fb2b8ed674dd74150a4b7 | 49 | py | Python | urduhack/utils/tests/test_text.py | fahdrazavi/urduhack | a2370b0d8c1ee3f260ff90ca5056f45ed9b73ee8 | [
"MIT"
] | null | null | null | urduhack/utils/tests/test_text.py | fahdrazavi/urduhack | a2370b0d8c1ee3f260ff90ca5056f45ed9b73ee8 | [
"MIT"
] | null | null | null | urduhack/utils/tests/test_text.py | fahdrazavi/urduhack | a2370b0d8c1ee3f260ff90ca5056f45ed9b73ee8 | [
"MIT"
] | null | null | null | # coding: utf8
"""Test cases for text.py file"""
| 16.333333 | 33 | 0.653061 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 47 | 0.959184 |
895c60b9edfa055022804d7ee382f90d6f53e6ab | 1,987 | py | Python | tag_generation/preprocesing.py | krispingal/improved-happiness | 1113e19065fee08a2530bf1fb1d4b2f888155f77 | [
"BSD-3-Clause"
] | null | null | null | tag_generation/preprocesing.py | krispingal/improved-happiness | 1113e19065fee08a2530bf1fb1d4b2f888155f77 | [
"BSD-3-Clause"
] | null | null | null | tag_generation/preprocesing.py | krispingal/improved-happiness | 1113e19065fee08a2530bf1fb1d4b2f888155f77 | [
"BSD-3-Clause"
] | null | null | null | """Preprocessing for tag generation"""
from tag_generation.util import utils
import jsonlines
import csv
# For test
FILE_LOC = '/home/krispin/data/improved-happiness/'
# For dev
#FILE_LOC = '/home/krispin/data/improved-happiness/proto/'
skipped, wrote = 0, 0
def get_recipe_tags(file_name: str,
common_tags: list):
"""Get a dict with preparation steps and tags"""
global skipped, wrote
with jsonlines.open(file_name) as reader:
for recipe in reader:
if 'preparation_steps' not in recipe or (not recipe['preparation_steps'][0].strip()) \
or recipe['preparation_steps'][0].strip() == 'N/A':
skipped += 1
continue
target = {'preparation_steps': ''.join(recipe['preparation_steps'][0])}
target['name'] = recipe['name'][0]
wrote += 1
if 'tags' not in recipe:
target.update({tag: 0 for tag in common_tags})
else:
for tag in common_tags:
target[tag] = 1 if tag in recipe['tags'][0] else 0
yield target
def create_tag_gen_file(file_name: str,
common_tags: list,
target_file):
with open(target_file, 'w') as csvfile:
fieldnames = ['name', 'preparation_steps'] + common_tags
recipewriter = csv.DictWriter(csvfile, fieldnames=fieldnames, quoting=csv.QUOTE_NONNUMERIC)
recipewriter.writeheader()
recipe_tags = get_recipe_tags(file_name, common_tags)
for row in recipe_tags:
recipewriter.writerow(row)
def main(k: int = 6):
_file_name = FILE_LOC + 'recipes.jl'
_tags = utils.get_k_most_common_tags(k, _file_name)
_tags = [x for (x, c) in _tags]
trg_filename = FILE_LOC + 'recipe_tags.csv'
create_tag_gen_file(_file_name, _tags, trg_filename)
print(f'Wrote {wrote} records; skipped {skipped}')
if __name__ == '__main__':
main(k=10) | 34.859649 | 99 | 0.613488 | 0 | 0 | 863 | 0.434323 | 0 | 0 | 0 | 0 | 439 | 0.220936 |
895c87f9120184e4c7af4de57a702b500aeade12 | 8,263 | py | Python | CDS_GRF/env/wrapper_grf_3vs3.py | ltzheng/CDS | 397282147498647a9f26577adfa451e8478de76d | [
"Apache-2.0"
] | 1 | 2021-06-19T23:57:55.000Z | 2021-06-19T23:57:55.000Z | CDS_GRF/env/wrapper_grf_3vs3.py | ltzheng/CDS | 397282147498647a9f26577adfa451e8478de76d | [
"Apache-2.0"
] | null | null | null | CDS_GRF/env/wrapper_grf_3vs3.py | ltzheng/CDS | 397282147498647a9f26577adfa451e8478de76d | [
"Apache-2.0"
] | null | null | null | import gfootball.env as football_env
from gfootball.env import observation_preprocessing
import gym
import numpy as np
import matplotlib.pyplot as plt
class GoogleFootballMultiAgentEnv(object):
"""An wrapper for GFootball to make it compatible with our codebase."""
def __init__(self, dense_reward, dump_freq, render=False):
self.nagents = 2
self.time_limit = 500
self.time_step = 0
self.obs_dim = 28 # for 3 vs 3
self.dense_reward = dense_reward # select whether to use dense reward
# Instantiate environment
self.env = football_env.create_environment(
env_name='3_vs_3',
stacked=False,
representation="simple115",
rewards='scoring',
logdir='football_dumps',
render=render,
write_video=False,
dump_frequency=dump_freq,
number_of_left_players_agent_controls=self.nagents,
number_of_right_players_agent_controls=0,
channel_dimensions=(observation_preprocessing.SMM_WIDTH, observation_preprocessing.SMM_HEIGHT))
obs_space_low = self.env.observation_space.low[0][:self.obs_dim]
obs_space_high = self.env.observation_space.high[0][:self.obs_dim]
self.action_space = [gym.spaces.Discrete(
self.env.action_space.nvec[1]) for _ in range(self.nagents)]
self.observation_space = [
gym.spaces.Box(low=obs_space_low, high=obs_space_high, dtype=self.env.observation_space.dtype) for _ in range(self.nagents)
]
self.reward_record = [0, 0]
self.game_mode = 0
self.old_game_mode = 0
self.goal_owned_team = -1
def get_obs(self, index=-1):
full_obs = self.env.unwrapped.observation()[0]
simple_obs = []
# Add some features to discribe offside
'''pos_1st_ours = full_obs['left_team'][np.argmax(
full_obs['left_team'][1:, 0])]
_, col = np.unravel_index(
np.argsort(full_obs['right_team'][:, 0].reshape(1, -1).ravel()), full_obs['right_team'][:, 0].reshape(1, -1).shape)
pos_2nd_opponent = full_obs['right_team'][col[-2]]
pos_1st_opponent = full_obs['right_team'][np.argmin(
full_obs['right_team'][1:, 0])]
_, col = np.unravel_index(
np.argsort(full_obs['left_team'][:, 0].reshape(1, -1).ravel()), full_obs['left_team'][:, 0].reshape(1, -1).shape)
pos_2nd_ours = full_obs['left_team'][col[2]]
offside_ours = max(pos_2nd_opponent[0], 0) - pos_1st_ours[0]
offside_opponent = pos_1st_opponent[0] - min(pos_2nd_ours[0], 0)'''
self.old_game_mode = self.game_mode
self.game_mode = full_obs['game_mode']
if full_obs['ball_owned_team'] != -1:
self.goal_owned_team = full_obs['ball_owned_team']
if index == -1:
# global state, absolute position
# cannot control our goal keeper
simple_obs.append(full_obs['left_team']
[-self.nagents:].reshape(-1))
simple_obs.append(
full_obs['left_team_direction'][-self.nagents:].reshape(-1))
simple_obs.append(full_obs['right_team'].reshape(-1))
simple_obs.append(full_obs['right_team_direction'].reshape(-1))
simple_obs.append(full_obs['ball'])
simple_obs.append(full_obs['ball_direction'])
'''simple_obs.append(pos_1st_ours)
simple_obs.append(pos_1st_opponent)
simple_obs.append(pos_2nd_ours)
simple_obs.append(pos_2nd_opponent)
simple_obs.append(np.array([offside_ours]))
simple_obs.append(np.array([offside_opponent]))'''
simple_obs.append(np.array([self.game_mode]))
simple_obs.append(np.array([full_obs['ball_owned_team']]))
else:
# local state, relative position
ego_position = full_obs['left_team'][-self.nagents +
index].reshape(-1)
simple_obs.append(ego_position)
simple_obs.append((np.delete(
full_obs['left_team'][-self.nagents:], index, axis=0) - ego_position).reshape(-1))
simple_obs.append(
full_obs['left_team_direction'][-self.nagents + index].reshape(-1))
simple_obs.append(np.delete(
full_obs['left_team_direction'][-self.nagents:], index, axis=0).reshape(-1))
simple_obs.append(
(full_obs['right_team'] - ego_position).reshape(-1))
simple_obs.append(full_obs['right_team_direction'].reshape(-1))
simple_obs.append(full_obs['ball'][:2] - ego_position)
simple_obs.append(full_obs['ball'][-1].reshape(-1))
simple_obs.append(full_obs['ball_direction'])
'''offside_ego = max(
pos_2nd_opponent[0], 0) - ego_position[0]
simple_obs.append(pos_1st_ours - ego_position)
simple_obs.append(pos_1st_opponent - ego_position)
simple_obs.append(pos_2nd_ours - ego_position)
simple_obs.append(pos_2nd_opponent - ego_position)
simple_obs.append(np.array([offside_ours]))
simple_obs.append(np.array([offside_ego]))
simple_obs.append(np.array([offside_opponent]))'''
simple_obs.append(np.array([self.game_mode]))
simple_obs.append(np.array([full_obs['ball_owned_team']]))
simple_obs = np.concatenate(simple_obs)
return simple_obs
def get_global_state(self):
return self.get_obs(-1)
def check_if_our_out(self):
if self.old_game_mode != self.game_mode and self.game_mode != 0:
# -1 = ball not owned, 0 = left team, 1 = right team.
if self.goal_owned_team == 0:
return -1
elif self.goal_owned_team == 1:
return 1
return 0
def reset(self):
self.time_step = 0
self.env.reset()
obs = np.array([self.get_obs(i) for i in range(self.nagents)])
self.reward_record = [0, 0]
self.game_mode = 0
self.old_game_mode = 0
self.goal_owned_team = -1
return obs, self.get_global_state()
def step(self, actions):
self.time_step += 1
_, original_rewards, done, infos = self.env.step(
actions + 1) # cancel not move action
obs = np.array([self.get_obs(i) for i in range(self.nagents)])
if self.time_step >= self.time_limit:
done = True
if sum(original_rewards) < 0:
self.reward_record[1] += 1
if sum(original_rewards) > 0:
self.reward_record[0] += 1
infos['reward_record'] = self.reward_record
if sum(original_rewards) == 0:
return obs, self.get_global_state(), self.check_if_our_out(), done, infos
if sum(original_rewards) < 0:
return obs, self.get_global_state(), -100, done, infos
return obs, self.get_global_state(), 100, done, infos
def seed(self, seed):
self.env.seed(seed)
def close(self):
self.env.close()
def get_env_info(self):
output_dict = {}
output_dict['n_actions'] = self.action_space[0].n - 1
output_dict['obs_shape'] = self.obs_dim
output_dict['n_agents'] = 2
output_dict['state_shape'] = self.obs_dim - 1
output_dict['episode_limit'] = self.time_limit
return output_dict
# def make_football_env(seed_dir, dump_freq=1000, representation='extracted', render=False):
def make_football_env_3vs3(dense_reward=False, dump_freq=1000):
'''
Creates a env object. This can be used similar to a gym
environment by calling env.reset() and env.step().
Some useful env properties:
.observation_space : Returns the observation space for each agent
.action_space : Returns the action space for each agent
.nagents : Returns the number of Agents
'''
return GoogleFootballMultiAgentEnv(dense_reward, dump_freq)
if __name__ == "__main__":
env = make_football_env_3vs3()
a, b = env.reset()
print(a.shape, b.shape)
| 37.38914 | 135 | 0.61491 | 7,397 | 0.895195 | 0 | 0 | 0 | 0 | 0 | 0 | 2,819 | 0.341159 |
895ceb1226f1223073e975c0eb48dfda8072b8fb | 2,136 | py | Python | performance_test/testcase.py | DeqingQu/CacheControlHelper | d9425ff08253f10ef1028b724418c705f8d58bf5 | [
"MIT"
] | null | null | null | performance_test/testcase.py | DeqingQu/CacheControlHelper | d9425ff08253f10ef1028b724418c705f8d58bf5 | [
"MIT"
] | null | null | null | performance_test/testcase.py | DeqingQu/CacheControlHelper | d9425ff08253f10ef1028b724418c705f8d58bf5 | [
"MIT"
] | null | null | null | from cache_control_helper import CacheControlHelper
import time
import sys
import requests
import requests_cache
requests_cache.install_cache('performance_test')
def get_request(url):
requests = CacheControlHelper()
try:
res = requests.get(url, timeout=120)
except requests.exceptions.Timeout:
print(url, file=sys.stderr)
print('Timeout for URL: ' + url, file=sys.stderr)
return None
except KeyboardInterrupt:
sys.exit(0)
except BaseException as e:
print(url, file=sys.stderr)
print('%s received for URL: %s' % (e, url), file=sys.stderr)
return None
status_code = res.status_code
if status_code != 200:
print(url, file=sys.stderr)
print('Status code ' + str(status_code) + ' for url: ' + url, file=sys.stderr)
return None
return res.json()
def get_request_cache(url):
try:
res = requests.get(url, timeout=120)
except requests.exceptions.Timeout:
print(url, file=sys.stderr)
print('Timeout for URL: ' + url, file=sys.stderr)
return None
except KeyboardInterrupt:
sys.exit(0)
except BaseException as e:
print(url, file=sys.stderr)
print('%s received for URL: %s' % (e, url), file=sys.stderr)
return None
status_code = res.status_code
if status_code != 200:
print(url, file=sys.stderr)
print('Status code ' + str(status_code) + ' for url: ' + url, file=sys.stderr)
return None
return res.json()
if __name__ == '__main__':
# using CacheControl
# base_url = 'http://localhost:3000/test/'
# t = time.time()
# for i in range(100000):
# r = get_request(base_url + str(i))
# if i % 1000 == 0:
# print(r)
# # print(time.time() - t)
# print(time.time() - t)
# using requests-cache
base_url = 'http://localhost:3000/test/'
t = time.time()
for i in range(10000):
r = get_request_cache(base_url + str(i))
if i % 1000 == 0:
print(r)
# print(time.time() - t)
print(time.time() - t)
| 28.48 | 86 | 0.598315 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 490 | 0.229401 |
895d00024c1c457aa98a15e9b661a4e74c3e68a2 | 1,731 | py | Python | main.py | nimom38/Bangla-letter-frequency-statistics | 7121f7fe36f9e8f5c310d4cc3b49083977dc8ce6 | [
"MIT"
] | null | null | null | main.py | nimom38/Bangla-letter-frequency-statistics | 7121f7fe36f9e8f5c310d4cc3b49083977dc8ce6 | [
"MIT"
] | null | null | null | main.py | nimom38/Bangla-letter-frequency-statistics | 7121f7fe36f9e8f5c310d4cc3b49083977dc8ce6 | [
"MIT"
] | null | null | null | import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import numpy as np
freq = {}
def read_file(filename='corpora.txt'):
f = open(filename, "r", encoding="utf-8")
for character in f.read():
if (character in freq):
freq[character] += 1
else:
freq[character] = 1
def main():
read_file()
bangla_alphabets = 'অআ াই িঈ ীউ ুঊ ূঋ ৃএ েঐ ৈও োঔ ৌকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহড়ঢ়য়ৎংঃ'
bangla_alphabets = "".join(bangla_alphabets.split())
sorted_counts = []
for character in bangla_alphabets:
if character in freq:
sorted_counts.append(freq[character])
else:
sorted_counts.append(0)
total_count = 0
for value in sorted_counts:
total_count += value
sorted_counts = [100 * value / total_count for value in sorted_counts]
fig, ax = plt.subplots(figsize=(40, 20))
prop = fm.FontProperties(fname='kalpurush.ttf')
ax.legend(prop=prop)
font_dirs = ['./', ]
font_files = fm.findSystemFonts(fontpaths=font_dirs)
font_list = fm.createFontList(font_files)
fm.fontManager.ttflist.extend(font_list)
plt.tick_params(labelsize=20)
plt.bar(range(len(bangla_alphabets)), sorted_counts, align='center')
plt.xticks(np.arange(len(bangla_alphabets)),
list(bangla_alphabets), fontfamily='Kalpurush')
plt.xlabel('বর্ণ-সমূহ', fontsize=24, fontfamily='Kalpurush')
plt.ylabel('শতকরা-হার (%)', fontsize=24, fontfamily='Kalpurush')
fig.suptitle(
'Relative Frequencies of letters in Bengali text\nCreated by Gazi Mohaimin Iqbal', fontsize=18)
plt.show()
if __name__ == "__main__":
main()
| 27.47619 | 103 | 0.658579 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 423 | 0.22488 |
895d842bfc897627a79eb5fa98161a381e6ef77f | 3,925 | py | Python | venv/Lib/site-packages/caffe2/python/serialized_test/coverage.py | Westlanderz/AI-Plat1 | 1187c22819e5135e8e8189c99b86a93a0d66b8d8 | [
"MIT"
] | 1 | 2022-01-08T12:30:44.000Z | 2022-01-08T12:30:44.000Z | venv/Lib/site-packages/caffe2/python/serialized_test/coverage.py | Westlanderz/AI-Plat1 | 1187c22819e5135e8e8189c99b86a93a0d66b8d8 | [
"MIT"
] | null | null | null | venv/Lib/site-packages/caffe2/python/serialized_test/coverage.py | Westlanderz/AI-Plat1 | 1187c22819e5135e8e8189c99b86a93a0d66b8d8 | [
"MIT"
] | null | null | null |
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import os
import tempfile
from zipfile import ZipFile
'''
Generates a document in markdown format summrizing the coverage of serialized
testing. The document lives in
`caffe2/python/serialized_test/SerializedTestCoverage.md`
'''
OpSchema = workspace.C.OpSchema
def gen_serialized_test_coverage(source_dir, output_dir):
(covered, not_covered, schemaless) = gen_coverage_sets(source_dir)
num_covered = len(covered)
num_not_covered = len(not_covered)
num_schemaless = len(schemaless)
total_ops = num_covered + num_not_covered
with open(os.path.join(output_dir, 'SerializedTestCoverage.md'), 'w+') as f:
f.write('# Serialized Test Coverage Report\n')
f.write("This is an automatically generated file. Please see "
"`caffe2/python/serialized_test/README.md` for details. "
"In the case of merge conflicts, please rebase and regenerate.\n")
f.write('## Summary\n')
f.write(
'Serialized tests have covered {}/{} ({}%) operators\n\n'.format(
num_covered, total_ops,
(int)(num_covered / total_ops * 1000) / 10))
f.write('## Not covered operators\n')
f.write('<details>\n')
f.write(
'<summary>There are {} not covered operators</summary>\n\n'.format(
num_not_covered))
for n in sorted(not_covered):
f.write('* ' + n + '\n')
f.write('</details>\n\n')
f.write('## Covered operators\n')
f.write('<details>\n')
f.write(
'<summary>There are {} covered operators</summary>\n\n'.format(
num_covered))
for n in sorted(covered):
f.write('* ' + n + '\n')
f.write('</details>\n\n')
f.write('## Excluded from coverage statistics\n')
f.write('### Schemaless operators\n')
f.write('<details>\n')
f.write(
'<summary>There are {} schemaless operators</summary>\n\n'.format(
num_schemaless))
for n in sorted(schemaless):
f.write('* ' + n + '\n')
f.write('</details>\n\n')
def gen_coverage_sets(source_dir):
covered_ops = gen_covered_ops(source_dir)
not_covered_ops = set()
schemaless_ops = []
for op_name in core._GetRegisteredOperators():
s = OpSchema.get(op_name)
if s is not None and s.private:
continue
if s:
if op_name not in covered_ops:
not_covered_ops.add(op_name)
else:
if op_name.find("_ENGINE_") == -1:
schemaless_ops.append(op_name)
return (covered_ops, not_covered_ops, schemaless_ops)
def gen_covered_ops(source_dir):
def parse_proto(x):
proto = caffe2_pb2.OperatorDef()
proto.ParseFromString(x)
return proto
covered = set()
for f in os.listdir(source_dir):
zipfile = os.path.join(source_dir, f)
if not os.path.isfile(zipfile):
continue
temp_dir = tempfile.mkdtemp()
with ZipFile(zipfile) as z:
z.extractall(temp_dir)
op_path = os.path.join(temp_dir, 'op.pb')
with open(op_path, 'rb') as f:
loaded_op = f.read()
op_proto = parse_proto(loaded_op)
covered.add(op_proto.type)
index = 0
grad_path = os.path.join(temp_dir, 'grad_{}.pb'.format(index))
while os.path.isfile(grad_path):
with open(grad_path, 'rb') as f:
loaded_grad = f.read()
grad_proto = parse_proto(loaded_grad)
covered.add(grad_proto.type)
index += 1
grad_path = os.path.join(temp_dir, 'grad_{}.pb'.format(index))
return covered
| 33.547009 | 81 | 0.581401 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 945 | 0.240764 |
895d85c3848fdf650e4c05e01cd969f8ec991a9c | 3,081 | py | Python | phylib/electrode/tests/test_mea.py | kushbanga/phylib | a4c7262b4ebcd6edb29409e2c08c5870fc9444eb | [
"BSD-3-Clause"
] | 6 | 2019-05-06T19:05:59.000Z | 2020-11-20T03:21:01.000Z | phylib/electrode/tests/test_mea.py | kushbanga/phylib | a4c7262b4ebcd6edb29409e2c08c5870fc9444eb | [
"BSD-3-Clause"
] | 31 | 2019-05-13T14:14:57.000Z | 2021-08-08T15:52:55.000Z | phylib/electrode/tests/test_mea.py | kushbanga/phylib | a4c7262b4ebcd6edb29409e2c08c5870fc9444eb | [
"BSD-3-Clause"
] | 14 | 2019-05-09T12:09:37.000Z | 2021-06-17T12:42:47.000Z | # -*- coding: utf-8 -*-
"""Test MEA."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
from pathlib import Path
from pytest import raises
import numpy as np
from numpy.testing import assert_array_equal as ae
from ..mea import (_probe_channels, _remap_adjacency, _adjacency_subset,
_probe_positions, _probe_adjacency_list,
MEA, load_probe, list_probes
)
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
def test_remap():
adjacency = {1: [2, 3, 7], 3: [5, 11]}
mapping = {1: 3, 2: 20, 3: 30, 5: 50, 7: 70, 11: 1}
remapped = _remap_adjacency(adjacency, mapping)
assert sorted(remapped.keys()) == [3, 30]
assert remapped[3] == [20, 30, 70]
assert remapped[30] == [50, 1]
def test_adjacency_subset():
adjacency = {1: [2, 3, 7], 3: [5, 11], 5: [1, 2, 11]}
subset = [1, 5, 32]
adjsub = _adjacency_subset(adjacency, subset)
assert sorted(adjsub.keys()) == [1, 5]
assert adjsub[1] == []
assert adjsub[5] == [1]
def test_probe():
probe = {'channel_groups': {
0: {'channels': [0, 3, 1],
'graph': [[0, 3], [1, 0]],
'geometry': {0: (10, 10), 1: (10, 20), 3: (20, 30)},
},
1: {'channels': [7],
'graph': [],
},
}}
adjacency = {0: set([1, 3]),
1: set([0]),
3: set([0]),
}
assert _probe_channels(probe, 0) == [0, 3, 1]
ae(_probe_positions(probe, 0), [(10, 10), (20, 30), (10, 20)])
assert _probe_adjacency_list(probe) == adjacency
mea = MEA(probe=probe)
assert mea.adjacency == adjacency
assert mea.channels_per_group == {0: [0, 3, 1], 1: [7]}
assert mea.channels == [0, 3, 1]
assert mea.n_channels == 3
ae(mea.positions, [(10, 10), (20, 30), (10, 20)])
def test_mea():
n_channels = 10
channels = np.arange(n_channels)
positions = np.random.randn(n_channels, 2)
mea = MEA(channels, positions=positions)
ae(mea.positions, positions)
assert mea.adjacency is None
mea = MEA(channels, positions=positions)
assert mea.n_channels == n_channels
mea = MEA(channels, positions=positions)
assert mea.n_channels == n_channels
with raises(ValueError):
MEA(channels=np.arange(n_channels + 1), positions=positions)
with raises(ValueError):
MEA(channels=channels, positions=positions[:-1, :])
def test_library(tempdir):
assert '1x32_buzsaki' in list_probes()
probe = load_probe('1x32_buzsaki')
assert probe
assert probe.channels == list(range(32))
path = Path(tempdir) / 'test.prb'
with raises(IOError):
load_probe(path)
with open(path, 'w') as f:
f.write('')
with raises(KeyError):
load_probe(path)
| 28.527778 | 79 | 0.506654 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 473 | 0.153522 |
895e4c63f5ae467a6f1d90d9268cfad2b249e278 | 4,233 | py | Python | brownies/legacy/endl/endlmath.py | brown170/fudge | 4f818b0e0b0de52bc127dd77285b20ce3568c97a | [
"BSD-3-Clause"
] | 14 | 2019-08-29T23:46:24.000Z | 2022-03-21T10:16:25.000Z | brownies/legacy/endl/endlmath.py | brown170/fudge | 4f818b0e0b0de52bc127dd77285b20ce3568c97a | [
"BSD-3-Clause"
] | 1 | 2020-08-04T16:14:45.000Z | 2021-12-01T01:54:34.000Z | brownies/legacy/endl/endlmath.py | brown170/fudge | 4f818b0e0b0de52bc127dd77285b20ce3568c97a | [
"BSD-3-Clause"
] | 2 | 2022-03-03T22:41:41.000Z | 2022-03-03T22:54:43.000Z | # <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
This module contains useful fudge math routines that do not fit into any other module.
"""
from pqu import PQU
from fudge.core.utilities import brb
try :
import numpy
numpyFloat64 = numpy.float64( 1. )
except :
numpyFloat64 = 1.
__metaclass__ = type
def runningZSum( data, xLabel = None, yLabel = None, zLabel = None, normalize = False ) :
"""Returns the running sum of dy * z (normalized to 1 of normalize is True) for each x as an endl3dmath object.
Data must be list of ( x, list of ( y, z ) )."""
d3 = []
for x_yz in data : d3.append( [ x_yz[0], runningYSum( x_yz[1], normalize = normalize ).data ] )
from brownies.legacy.endl import endl3dmathClasses
return endl3dmathClasses.endl3dmath(d3, xLabel = xLabel, yLabel = yLabel, zLabel = zLabel, checkDataType = 0)
def runningYSum( data, normalize = False ) :
"""Returns the running sum of dx * y (normalized to 1 of normalize is True) as an endl2dmath object.
Data must be list of ( x, y )."""
x1 = None
runningSum = []
for xy in data :
x2 = xy[0]
y2 = xy[1]
if ( x1 is None ) :
Sum = 0.
else :
Sum += 0.5 * ( y2 + y1 ) * ( x2 - x1 )
runningSum.append( [ x2, Sum ] )
x1 = x2
y1 = y2
if( normalize and ( Sum != 0. ) ) :
for xy in runningSum : xy[1] /= Sum
from brownies.legacy.endl import endl2dmathClasses
return endl2dmathClasses.endl2dmath(runningSum, checkDataType = 0)
def ZSum( data ) :
"""Returns the area under the curve z(y) for each x as an endl2dmath object. Data must be list of
( x, list of ( y, z ) )."""
d2 = []
for x_yz in data : d2.append( [ x_yz[0], YSum( x_yz[1] ) ] )
from brownies.legacy.endl import endl2dmathClasses
return endl2dmathClasses.endl2dmath(d2, checkDataType = 0)
def YSum( data ) :
"""Returns the area under the curve y(x). Data must be list of list( x, y )."""
x1 = None
for x2, y2 in data :
if ( x1 is None ) :
Sum = 0.
else :
Sum += ( y2 + y1 ) * ( x2 - x1 )
x1 = x2
y1 = y2
return 0.5 * Sum
class fastSumOfManyAddends :
"""This class in designed to sum a lot of endl2dmath or fudge2dmath object together efficiently. For example,
consider the list f2d of 100,000 fudge2dmath objects that are to be summed. One way to do this is as
s = fudge2dmath( )
for f in f2d : s = s + f
In general, this is very inefficient and will take a long time. Using, this class as
fs = fastSumOfManyAddends( )
for f in f2d : fs.appendAddend( f )
s = fs.returnSum( )
is, in general, much more efficient (i.e., runs a lot faster) and it should never be less efficient.
While this class was designed for endl2dmath and fudge2dmath objects, it should work for any object
for which the '+' operation is defined."""
def __init__( self ) :
"""Constructor for fastSumOfManyAddends."""
self.clear( )
def appendAddend( self, addend ) :
"""Adds addend to current sum efficiently."""
n = len( self.list )
for i in range( n ) :
if( self.list[i] is None ) :
self.list[i] = addend
addend = None
break
else :
addend = addend + self.list[i]
self.list[i] = None
if( addend is not None ) : self.list.append( addend )
def clear( self ) :
"""Clears currently summed data."""
self.list = []
def returnSum( self ) :
"""Returns the current sum of all addends appended."""
s = None
for l in self.list :
if( l is not None ) :
if( s is None ) :
s = l
else :
s = s + l
return( s )
def getValue( n ) :
if( isNumber( n ) ) : return( n )
if( isinstance( n, PQU.PQU ) ) : return( n.getValue( ) )
raise Exception( 'Invalue number object = %s' % brb.getType( n ) )
| 32.068182 | 115 | 0.584692 | 1,696 | 0.400661 | 0 | 0 | 0 | 0 | 0 | 0 | 1,710 | 0.403969 |
896328ad1b36a8f2472f83b37ee24bfcae36a1c4 | 14 | py | Python | object-oriented-design/python/jigsaw.py | DatGreekChick/ctci | b165bd529fe3ca32cc5c95ea274080bd5689501d | [
"MIT"
] | null | null | null | object-oriented-design/python/jigsaw.py | DatGreekChick/ctci | b165bd529fe3ca32cc5c95ea274080bd5689501d | [
"MIT"
] | null | null | null | object-oriented-design/python/jigsaw.py | DatGreekChick/ctci | b165bd529fe3ca32cc5c95ea274080bd5689501d | [
"MIT"
] | null | null | null | # 7.6: Jigsaw
| 7 | 13 | 0.571429 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 0.928571 |
89633e1d922672b9a497cfb56951f732f39ebba2 | 9,502 | py | Python | kyk/kyk.py | atrautsch/kyk | 9f843bf9503a3da3669fa5d18e43cfdf5c4207ba | [
"MIT"
] | null | null | null | kyk/kyk.py | atrautsch/kyk | 9f843bf9503a3da3669fa5d18e43cfdf5c4207ba | [
"MIT"
] | 1 | 2021-03-25T22:02:54.000Z | 2021-03-25T22:02:54.000Z | kyk/kyk.py | atrautsch/kyk | 9f843bf9503a3da3669fa5d18e43cfdf5c4207ba | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import os
import time
import shutil
import signal
import yaml
import sass
import pyinotify
from colorama import init, Fore, Style
from jsmin import jsmin
from csscompressor import compress
VERSION = '1.4.7'
class Kyk(object):
"""Kyk
Build JS
- if min: minify in place, append _minifed
- concat to destfile
Build SASS:
- compile SASS file
- concat to destfile
Build partial js not yet implemented completely
"""
def __init__(self, folder, debug):
self._folder = folder
self._debug = debug
init()
self._load_config()
signal.signal(signal.SIGINT, self.teardown)
def teardown(self, signal, frame):
if type(self.notifier) == pyinotify.ThreadedNotifier:
print('stopping watching')
self.notifier.stop()
def _load_config(self, reloading=False):
cfgfile = os.path.normpath(os.path.join(self._folder, 'kyk.yaml'))
if not os.path.isfile(cfgfile) and reloading:
time.sleep(1) # wait for it to appear (ftp program maybe?)
if not os.path.isfile(cfgfile):
raise Exception('no config file "{}" found!'.format(cfgfile))
with open(cfgfile, 'r', encoding='utf-8') as f:
dat = f.read()
self._cfg = yaml.load(dat)
self._js = {}
self._css = {}
self._jswatchlist = []
self._listen_events = []
self._timestamp_file = None
if 'watch_path' in self._cfg.keys():
self._folder = self._cfg['watch_path']
# no overwriting of command line debug, if config file does not hold debug: True we do not want to disable --debug
if not self._debug:
self._debug = 'debug' in self._cfg.keys() and self._cfg['debug']
self._version = self._cfg['version']
self._listen_events = self._cfg['events']
if 'timestamp_file' in self._cfg.keys():
self._timestamp_file = self._cfg['timestamp_file']
for minfile in self._cfg.keys():
if minfile.endswith('.js'):
jsfile = self._cfg[minfile]
minify = False
for jsfile in self._cfg[minfile]:
if jsfile.startswith('min:'):
minify = True
jsfile = jsfile.split('min:')[1].strip()
if minfile not in self._js.keys():
self._js[minfile] = []
self._js[minfile].append({'file': os.path.abspath(jsfile), 'minify': minify})
self._jswatchlist.append(os.path.abspath(jsfile))
elif minfile.endswith('.css'):
self._css[minfile] = self._cfg[minfile]
print('Kyk version: {}'.format(VERSION))
print('config version: {}'.format(self._version))
def oneshot(self):
print('oneshot')
self.build_js()
self.build_sass()
def watch_forever(self):
print('listening on:')
print(self._listen_events)
# first run, build everything
self.build_js()
self.build_sass()
# now only changed files
self.wm = pyinotify.WatchManager()
self.notifier = pyinotify.ThreadedNotifier(self.wm, default_proc_fun=self.handler)
self.wm.add_watch(self._folder, pyinotify.ALL_EVENTS, rec=True, auto_add=True)
# self.notifier.loop()
self.notifier.start()
signal.pause()
def reload(self):
self.notifier.stop()
self._load_config(True)
self.watch_forever()
def handler(self, event):
# catch every scss file change, we can do this here because we are limited by the watchpath
if getattr(event, 'pathname'):
if event.pathname.endswith('.scss'):
if event.maskname in self._listen_events:
print('{} changed!'.format(event.pathname))
self.build_sass()
# catch only changes to our configured jsfiles
elif event.pathname in self._jswatchlist:
if event.maskname in self._listen_events:
print('{} changed!'.format(event.pathname))
self.build_js()
elif event.pathname.endswith('kyk.yaml'):
print('kyk config changed, reloading')
self.reload()
def build_js(self):
"""minify everything, then concat everything
"""
print('building js...')
for minfile in self._js.keys():
with open(minfile, 'w', encoding='utf-8') as f:
for jsfile in self._js[minfile]:
if jsfile['minify'] and not self._debug:
self.minify_js(jsfile['file'])
out = self._load_js(jsfile['file'], load_minified=jsfile['minify'])
f.write(out + "\n")
print('finished')
self._update_timestamp()
def concat_js(self, destfile):
print('building {}...'.format(destfile))
with open(destfile, 'w', encoding='utf-8') as f:
for jsfile in self._js[destfile]:
if self._debug:
f.write('{}\n'.format(self._load_js(jsfile['file'])))
f.write(self._load_js(jsfile['file']) + ';')
print('finished')
def minify_js(self, jsfile=None):
"""Minify JS in place, append _minified
"""
out = jsmin(self._load_js(jsfile, load_minified=False))
with open('{}_minified'.format(jsfile), 'w', encoding='utf-8') as f:
f.write(out)
def build_partial_js(self, changed):
print('building partial js...')
for minfile in self._js:
for jsfile in self._js[minfile]:
if changed == jsfile['file']:
if jsfile['minify'] and not self._debug:
self.minify_js(jsfile['file'])
self.concat_js(minfile)
print('finished')
def _load_js(self, jsfile, load_minified=True):
"""Load js from file, load _minifed if exists and we want to have it (we do not want it if we minify anew)
"""
if load_minified and os.path.isfile('{}_minified'.format(jsfile)):
jsfile = '{}_minified'.format(jsfile)
if not os.path.isfile(jsfile):
print(Fore.RED + 'File {} not found!'.format(jsfile))
print(Style.RESET_ALL)
return ''
else:
with open(jsfile, 'r', encoding='utf-8') as f:
out = f.read()
return out
def _update_timestamp(self):
try:
if self._timestamp_file:
with open(self._timestamp_file, 'w') as f:
f.write('{}'.format(int(time.time())))
print('timestamp file updated')
except Exception as e:
print(Fore.RED + 'Error updating timestamp file: {}'.format(e))
print(Style.RESET_ALL)
def build_sass(self):
print('building sass...')
for minfile in self._css.keys():
try:
# tmp minfile name for writing
minfile_name = os.path.basename(minfile)
tmp_minfile_name = 'kyk_{}'.format(minfile_name)
tmp_minfile = minfile.replace(minfile_name, tmp_minfile_name)
# only scss source map file
mapfile = tmp_minfile.replace('.css', '.css.map')
smapfile = tmp_minfile.replace('.css', '.smap.css') # this holds the css and the source comments
with open(tmp_minfile, 'w', encoding='utf-8') as f, open(mapfile, 'w', encoding='utf-8') as smf, open(smapfile, 'w', encoding='utf-8') as sma:
for sassfile in self._css[minfile]:
if sassfile.endswith('.scss'):
ost = 'compressed'
if self._debug:
ost = 'expanded'
sc, sm = sass.compile(filename=sassfile, source_comments=True, source_map_filename=mapfile, output_style=ost)
sc_clean = sass.compile(filename=sassfile, source_comments=False, output_style=ost) # without source comments
f.write(sc_clean)
smf.write(sm)
sma.write(sc)
else:
sc = open(sassfile, 'r', encoding='utf-8').read()
if not self._debug:
sc = compress(sc)
f.write(sc)
shutil.copy(tmp_minfile, minfile)
shutil.copy(mapfile, minfile.replace('.css', '.css.map'))
shutil.copy(smapfile, minfile.replace('.css', '.smap.css'))
except sass.CompileError as e:
print(Fore.RED + 'SASS Error: {}'.format(e))
print(Style.RESET_ALL)
# in debug mode we break things on purpose here
if self._debug:
shutil.copy(tmp_minfile, minfile)
shutil.copy(mapfile, minfile.replace('.css', '.css.map'))
shutil.copy(smapfile, minfile.replace('.css', '.smap.css'))
print('finished')
self._update_timestamp()
| 37.262745 | 162 | 0.537676 | 9,265 | 0.975058 | 0 | 0 | 0 | 0 | 0 | 0 | 1,898 | 0.199747 |
8963fdbff15b6cc0ff84b30bac45aa1b2f8b6b3e | 1,311 | py | Python | Ejercicios Entrada y Salida de Datos/Ejercicio 03.py | jaramosperez/Pythonizando | 3571a6451b383ed5fea35f84e3444fd946c6560d | [
"MIT"
] | 1 | 2020-07-13T04:34:34.000Z | 2020-07-13T04:34:34.000Z | Ejercicios Entrada y Salida de Datos/Ejercicio 03.py | jaramosperez/Pythonizando | 3571a6451b383ed5fea35f84e3444fd946c6560d | [
"MIT"
] | null | null | null | Ejercicios Entrada y Salida de Datos/Ejercicio 03.py | jaramosperez/Pythonizando | 3571a6451b383ed5fea35f84e3444fd946c6560d | [
"MIT"
] | null | null | null | # Ejercicio 3
# Crea un script llamado descomposicion.py que realice las siguientes tareas:
#
# Debe tomar 1 argumento que será un número entero positivo.
# En caso de no recibir un argumento, debe mostrar información acerca de cómo utilizar el script.
# El objetivo del script es descomponer el número en unidades, decenas, centenas, miles...
# tal que por ejemplo si se introduce el número 3647:
#
#
# python descomposicion.py 3647
# El programa deberá devolver una descomposición línea a línea como la siguiente utilizando las técnicas de formateo:
#
#
# 0007
# 0040
# 0600
# 3000
# Pista
#
# Que el valor sea un número no significa necesariamente que deba serlo para formatearlo.
# Necesitarás jugar muy bien con los índices y realizar muchas conversiones entre tipos cadenas, números y viceversa
import sys
if len(sys.argv) == 2:
numero = int(sys.argv[1])
if numero < 0 or numero > 9999:
print("Error - Número es incorrecto")
print("Ejemplo: descomposicion.py [0-9999]")
else:
# Aqui va la lógica
cadena = str(numero)
longitud = len(cadena)
for i in range(longitud):
print("{:04d}".format(int(cadena[longitud - 1 - i]) * 10 ** i))
else:
print("Error - Argumentos incorrectos")
print("Ejemplo: descomposicion.py [0-9999]")
| 31.97561 | 117 | 0.701754 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 960 | 0.722892 |
89643825185d3b753c782bbf4419c3b345d1d58b | 2,616 | py | Python | ansiscaf/ansiscaf.py | terryshi96/ansi | 6292277c54057bef13c56184467c1de2e8a69136 | [
"MIT"
] | 3 | 2017-02-10T07:40:16.000Z | 2017-12-08T01:56:25.000Z | ansiscaf/ansiscaf.py | terryshi96/ansiscaf | 6292277c54057bef13c56184467c1de2e8a69136 | [
"MIT"
] | null | null | null | ansiscaf/ansiscaf.py | terryshi96/ansiscaf | 6292277c54057bef13c56184467c1de2e8a69136 | [
"MIT"
] | null | null | null | import os
import sys
import argparse
_version_ = '0.0.1'
class scaffold():
result = []
def new_project(self):
if os.path.exists(self.result.project):
print("project has been existed")
exit(1)
os.mkdir(self.result.project)
os.chdir(self.result.project)
os.system("touch hosts.yml")
os.system("touch sites.yml")
dir1 = ["group_vars", "host_vars", "roles"]
for dir in dir1:
os.mkdir(dir)
if dir == "group_vars":
os.system("touch group_vars/all")
dir2 = ["tasks", "files", "templates", "handlers", "vars"]
os.chdir("roles")
for dir in dir2:
os.mkdir(dir)
if dir == "tasks":
os.system("touch tasks/main.yml")
print("create project %s successfully" % self.result.project)
def new_role(self):
if os.path.exists(self.result.role):
print("dir has been existed")
exit(1)
os.mkdir(self.result.role)
dirs = ["tasks", "files", "templates", "handlers", "vars"]
os.chdir(self.result.role)
for dir in dirs:
os.mkdir(dir)
if dir == "tasks":
os.system("touch tasks/main.yml")
print("create role %s successfully" % self.result.role)
def find_dir(self,rootdir):
for lists in os.listdir(rootdir):
path = os.path.join(rootdir,lists)
if os.path.isdir(path):
if not os.listdir(path):
os.rmdir(path)
else:
self.find_dir(path)
def clean_dir(self):
print("are you sure to clean?(y)")
flag = input()
if flag != "y":
exit(1)
self.find_dir(self.result.dir)
def parse_opt(self):
if len(sys.argv) > 3:
print("error argv number,please check")
exit(1)
parser = argparse.ArgumentParser(usage="ansiscaf [opt] [argv]",description='ansible scaffold')
parser.add_argument('-new', action="store", dest="project",help="create file tree")
parser.add_argument('-add', action="store", dest="role",help="create role dir tree")
parser.add_argument('-rm', action="store", dest="dir",help="delete all empty dir")
self.result = parser.parse_args()
if self.result.project:
self.new_project()
elif self.result.role:
self.new_role()
elif self.result.dir:
self.clean_dir()
if __name__ == '__main__':
ansi = scaffold()
ansi.parse_opt()
| 29.393258 | 102 | 0.546254 | 2,480 | 0.948012 | 0 | 0 | 0 | 0 | 0 | 0 | 594 | 0.227064 |
896451db24951d71242afacbaa48addf165d4f98 | 7,131 | py | Python | server.py | alexa-griffin/shared-folders | 78224b4bc74be55ce58ed2f448e6c1cbcd69752e | [
"CC0-1.0"
] | null | null | null | server.py | alexa-griffin/shared-folders | 78224b4bc74be55ce58ed2f448e6c1cbcd69752e | [
"CC0-1.0"
] | null | null | null | server.py | alexa-griffin/shared-folders | 78224b4bc74be55ce58ed2f448e6c1cbcd69752e | [
"CC0-1.0"
] | null | null | null | import os
import socket
import threading
import json
import sys
import math
IP = socket.gethostbyname_ex(socket.gethostname())[-1][-1]
PORT = 4450
ADDR = (IP, PORT)
SIZE = 2**10
FORMAT = "utf-8"
SERVER_PATH = "server"
LOGIN = "admin"
PASS = "admin"
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} is attempting to connect.")
conn.send("OK@CONNECT@SUCCEED!".encode(FORMAT))
data = conn.recv(SIZE).decode(FORMAT)
data = data.split("@", 1)
login = data[0]
password = data[1]
if login == LOGIN and password == PASS:
print(f"[NEW CONNECTION] {addr} logged in successfully.")
conn.send("OK@CONNECT@Welcome to the server".encode(FORMAT))
else:
conn.send("ERR@CONNECT@LoginFailed".encode(FORMAT))
print(f"[FAILED CONNECTION] {addr} login/password refused.")
conn.close()
cwd = SERVER_PATH
while True:
data = conn.recv(SIZE).decode(FORMAT)
data = data.split("@", 1)
cmd = data[0]
send_data = ""
if cmd == "LOGOUT":
break
elif cmd == "CREATE":
files = os.listdir(cwd)
filename = data[1]
if filename in files: # condition if file already exist in the server.
send_data = "ERR@CREATE@File exists."
else:
buff = b""
with open(os.path.join(cwd, filename), 'wb') as temp_file: # creating the file
temp_file.write(buff)
send_data = "OK@CREATE@File created"
conn.send(send_data.encode(FORMAT))
elif cmd == "UPLOAD":
filename = data[1].split("@")[0]
numbytes = int(data[1].split("@")[1])
active_file = None
try:
if filename in os.listdir(os.path.join(cwd)):
active_file = open(os.path.join(
cwd, filename), "wb")
else:
active_file = open(os.path.join(
cwd, filename), "xb")
except:
conn.send(
f"ERR@UPLOAD@unable to upload at this time".encode(FORMAT))
continue
conn.send(f"OK@UPLOAD@{filename}".encode(FORMAT))
received = 0
while received < numbytes:
data = conn.recv(SIZE)
received += len(data)
active_file.write(data)
active_file.close()
conn.send(
f"OK@UPLOAD_END@Successfully uploaded file".encode(FORMAT))
print(f"[FILE TRANSFER] {addr} uploaded file.")
elif cmd == "DOWNLOAD":
filename = data[1]
if filename not in os.listdir(cwd):
conn.send("ERR@DOWNLOAD@File does not exist.".encode(FORMAT))
else:
numbytes = os.path.getsize(os.path.join(cwd, filename))
conn.send(
f"OK@DOWNLOAD@{os.path.relpath(os.path.join(cwd, filename), SERVER_PATH)}@{numbytes}".encode(FORMAT))
file = open(os.path.join(cwd, filename), "rb")
fragment = file.read(SIZE)
while fragment:
conn.send(fragment)
fragment = file.read(SIZE)
# d = conn.recv(SIZE)
file.close()
print(f"[FILE TRANSFER] {addr} downloaded file.")
elif cmd == "DIR":
send_data = "OK@DIR@" + '{ "files": [' + \
','.join(map(lambda f: json.dumps({
'name': f.name,
'dir': f.is_dir(),
'last_modified': f.stat().st_mtime,
'size': f.stat().st_size
}), [
name for name in os.scandir(cwd)])) + "] }"
conn.send(send_data.encode(FORMAT))
elif cmd == "DELETE":
files = os.listdir(cwd)
filename = data[1]
if filename not in files: # condition if file already exist in the server.
send_data = f"ERR@DELETE@{filename} does not exist."
else:
try:
os.remove(os.path.join(cwd, filename))
send_data = f"OK@DELETE@{filename} deleted successfully"
except:
# print(sys.exc_info()[0])
send_data = f"ERR@DELETE@{filename} failed to be deleted."
conn.send(send_data.encode(FORMAT))
elif cmd == "MKDIR":
foldername = data[1].rstrip("./\\").lstrip("./\\")
if ".." in foldername or "/" in foldername or "\\" in foldername:
send_data = "ERR@MKDIR@Invalid path name."
else:
files = os.listdir(cwd)
if foldername in files:
send_data = "ERR@MKDIR@Folder already exists."
else:
os.mkdir(os.path.join(cwd, foldername))
send_data = f"OK@MKDIR@{foldername} created."
conn.send(send_data.encode(FORMAT))
elif cmd == "RMDIR":
foldername = data[1].rstrip("/\\").lstrip("/\\")
if ".." in foldername or "/" in foldername or "\\" in foldername:
send_data = "ERR@RMDIR@Invalid path name."
else:
files = os.listdir(cwd)
if foldername not in files:
send_data = "ERR@RMDIR@Folder does not exist."
elif os.path.isfile(os.path.join(cwd, foldername)):
send_data = "ERR@RMDIR@File is not a folder."
else:
try:
os.rmdir(os.path.join(cwd, foldername))
send_data = f"OK@RMDIR@{foldername} deleted."
except OSError:
send_data = f"ERR@RMDIR@Folder not empty."
conn.send(send_data.encode(FORMAT))
elif cmd == "CD":
foldername = data[1].rstrip("/\\").lstrip("/\\")
if os.path.exists(os.path.abspath(os.path.join(cwd, foldername))) and os.path.abspath(os.path.join(cwd, foldername)).startswith(os.path.abspath(SERVER_PATH)):
cwd = os.path.normpath(os.path.join(cwd, foldername))
send_data = f"OK@CD@{os.path.relpath(cwd, SERVER_PATH)}"
else:
send_data = f"ERR@CD@Path does not exist"
conn.send(send_data.encode(FORMAT))
print(f"[LOST CONNECTION] {addr} disconnected from the server.")
conn.close()
def main():
print("Starting the server")
# used IPV4 and TCP connection
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR) # bind the address
server.listen() # start listening
print(f"Server is listening on {IP}: {PORT}")
while True:
conn, addr = server.accept() # accept a connection from a client
thread = threading.Thread(target=handle_client, args=(
conn, addr)) # assigning a thread for each client
thread.start()
if __name__ == "__main__":
main()
| 33.957143 | 170 | 0.51816 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,723 | 0.241621 |
8965115c33b6d2c569416895234b50bcedd7ba26 | 1,160 | py | Python | test/time_model_fitting.py | gaybro8777/pyPhenology | 2a58654126170eb304c71c5d453745c66058bd83 | [
"MIT"
] | 15 | 2018-11-22T16:36:27.000Z | 2022-02-14T10:58:40.000Z | test/time_model_fitting.py | gaybro8777/pyPhenology | 2a58654126170eb304c71c5d453745c66058bd83 | [
"MIT"
] | 52 | 2017-12-12T17:23:59.000Z | 2021-09-08T01:20:28.000Z | test/time_model_fitting.py | sdtaylor/phenology | 72d1d07dfc1a628a29de77447066ead23ee8b1ec | [
"MIT"
] | 8 | 2018-02-15T12:54:10.000Z | 2021-03-01T22:23:52.000Z | from pyPhenology import utils
observations, temp = utils.load_test_data(name='vaccinium')
import pandas as pd
import time
models_to_use = ['ThermalTime','Alternating','Uniforc','MSB','Unichill']
methods_to_use = ['DE','BF']
sensible_defaults = ['testing','practical','intensive']
timings=[]
for m in models_to_use:
for optimizer_method in methods_to_use:
for s_default in sensible_defaults:
model = utils.load_model(m)()
start_time = time.time()
model.fit(observations, temp, method=optimizer_method, optimizer_params=s_default)
fitting_time = round(time.time() - start_time,2)
num_parameters = len(model.get_params())
timings.append({'model':m,
'num_parameters':num_parameters,
'method':optimizer_method,
'sensible_default':s_default,
'time':fitting_time})
print(timings[-1])
print('#######################')
timings = pd.DataFrame(timings)
timings.to_csv('model_fit_timings.csv') | 36.25 | 94 | 0.576724 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 203 | 0.175 |
896518b91cc64ccabd9d1d0b09a31f091b4c06f2 | 9,394 | py | Python | BioExp/RCT/rct.py | parthnatekar/BioExp | 4d426b8f4d38be1d673e4371e5a5b34c7cabf770 | [
"MIT"
] | 9 | 2019-11-16T04:02:53.000Z | 2022-02-10T13:23:52.000Z | BioExp/RCT/rct.py | parthnatekar/BioExp | 4d426b8f4d38be1d673e4371e5a5b34c7cabf770 | [
"MIT"
] | 5 | 2020-01-28T22:17:05.000Z | 2022-02-09T23:40:53.000Z | BioExp/RCT/rct.py | parthnatekar/BioExp | 4d426b8f4d38be1d673e4371e5a5b34c7cabf770 | [
"MIT"
] | 6 | 2019-11-17T01:31:51.000Z | 2020-12-03T21:15:48.000Z | import keras
import random
import numpy as np
from glob import glob
from keras.models import Model
from keras.utils import np_utils
from keras.models import load_model
import matplotlib.pyplot as plt
import os
import keras.backend as K
import tensorflow as tf
from keras.utils import to_categorical
from tqdm import tqdm
import sys
sys.path.append('..')
from helpers.losses import *
from helpers.utils import load_vol_brats
class intervention():
def __init__(self, model, test_path):
self.model = model
self.vol_path = glob(test_path)
self.test_image, self.gt = load_vol_brats(self.vol_path[3], slicen = 78, pad = 0)
def mean_swap(self, plot = True, save_path='/home/parth/Interpretable_ML/BioExp/results/RCT'):
channel = 3
f_index = 0
test_image, gt = load_vol_brats(self.vol_path[f_index], slicen = 78, pad = 0)
prediction = np.argmax(self.model.predict(test_image[None, ...]), axis = -1)[0]
n_classes = (len(np.unique(prediction)))
corr = np.zeros((n_classes, n_classes))
slices = [78]
plt.figure(figsize = (20,20))
for vol in range(len(test_path)):
for slicen in slices:
test_image, gt = load_vol_brats(self.vol_path[vol], slicen = slicen, pad = 0)
prediction = np.argmax(self.model.predict(test_image[None, ...]), axis = -1)[0]
print("Original Dice Whole:", dice_whole_coef(prediction, gt))
class_dict = {0:'bg', 1:'core', 2:'edema', 3:'enhancing'}
corr_temp = np.zeros((n_classes, n_classes))
for i in range(n_classes):
for j in range(n_classes):
new_mean = np.mean(test_image[gt == i], axis = 0)
old_mean = np.mean(test_image[gt == j], axis = 0)
test_image_intervention = np.copy(test_image)
test_image_intervention[gt == j] += (new_mean - old_mean)
prediction_intervention = np.argmax(self.model.predict(test_image_intervention[None, ...]), axis = -1)[0]
corr[i,j] += dice_label_coef(prediction, gt, (j,)) - dice_label_coef(prediction_intervention, gt, (j,))
corr_temp[i,j] += dice_label_coef(prediction, gt, (j,)) - dice_label_coef(prediction_intervention, gt, (j,))
if plot == True:
plt.subplot(n_classes, n_classes, 1+4*i+j)
plt.xticks([])
plt.yticks([])
plt.title("{} --> {}, Dice Change={}".format(class_dict[j], class_dict[i], "{0:.2f}".format(-corr[i,j])))
plt.imshow(prediction_intervention, cmap = plt.cm.RdBu, vmin = 0, vmax = 3)
plt.colorbar()
print(corr_temp)#/(vol*len(slices))
np.set_printoptions(precision = 2)
plt.rcParams.update({'font.size': 24})
intervention_importance = corr /(len(self.vol_path)*len(slices))
print(intervention_importance)
os.makedirs(save_path, exist_ok = True)
# np.save(save_path + '/mean_swap_all_images.npy', intervention_importance)
if plot == True:
plt.show()
def blocks(self):
test_image, gt = load_vol_brats(self.vol_path[1], slicen = 78, pad = 8)
prediction = np.argmax(self.model.predict(test_image[None, ...]), axis = -1)[0]
n_classes = (len(np.unique(prediction)))
corr = np.zeros((n_classes, n_classes))
slices = [78]
intervention_image = np.empty(test_image.shape)
for _modality in range(4):
for i in range(2):
for j in range(2):
try:
intervention_image[:,:,_modality][test_image.shape[0]//2*i:test_image.shape[0]//2*(i+1),
test_image.shape[1]//2*j:test_image.shape[1]//2*(j+1)].fill(np.mean(test_image[gt == 2*i+j], axis = 0)[_modality])
except Exception as e:
print(e)
prediction_intervention = model.predict(intervention_image[None, ...])
plt.imshow(intervention_image[:, :, 0])
plt.colorbar()
plt.show()
plt.imshow(np.argmax(prediction_intervention, axis = -1)[0], vmin=0, vmax=3)
plt.colorbar()
plt.show()
def adverserial(self, epochs=100, epsilon = 0.01, mode = 'gradient', plot=False, test_image=None, gt=None):
sess = K.get_session()
keras.layers.core.K.set_learning_phase(0)
image = test_image[None, ...] # if test_image is not None else self.test_image[None, ...]
gt = gt[None, ...] # if gt is not None else self.gt[None, ...]
noise = np.zeros_like(image)
adverserial_image = image.copy()
if mode == 'gradient':
loss = keras.losses.categorical_crossentropy(self.model.output, tf.convert_to_tensor(to_categorical(gt, num_classes=4)))
elif mode == 'random':
loss = -keras.losses.categorical_crossentropy(self.model.output,
tf.convert_to_tensor(self.generate_random_classification(mode='random')))
elif mode =='swap':
loss = -keras.losses.categorical_crossentropy(self.model.output,
tf.convert_to_tensor(self.generate_random_classification(mode='swap')))
grads = K.gradients(loss, self.model.input)
delta = K.sign(grads[0])
noise = noise + delta
adverserial_image = adverserial_image+epsilon*delta
adverserial_image, noise_ar, delta_ = sess.run([adverserial_image, noise, delta], feed_dict={self.model.input: image})
delta_image_perc = (np.mean(np.abs(image - adverserial_image))*100)/np.ptp(image)
delta_dice_perc = (dice_whole_coef(self.model.predict(image).argmax(axis=-1),
gt) - dice_whole_coef(self.model.predict(adverserial_image).argmax(axis=-1),
gt))*100/dice_whole_coef(self.model.predict(image).argmax(axis=-1),
gt)
# print("perc. change in image:{}, perc. change in dice:{}, Sensitivity:{}".format(delta_image_perc,
# delta_dice_perc, delta_dice_perc/delta_image_perc))
imshape = image.shape[1]
if plot==True:
plt.figure(figsize = (40,10))
plt.rcParams.update({'font.size': 34})
plt.subplot(1,4,1)
plt.title("Original image")
plt.imshow(image[:, :, :, 0].reshape((imshape, imshape)))
plt.xticks([])
plt.yticks([])
# plt.subplot(1,6,2)
# plt.title("Added Noise")
# plt.imshow(noise_ar[:, :, :, 0].reshape((imshape, imshape)))
# plt.xticks([])
# plt.yticks([])
plt.subplot(1,4,2)
plt.title("Image + Noise, % Change = {}".format("{0:.2f}".format(delta_image_perc)))
plt.imshow(adverserial_image[:, :, :, 0].reshape((imshape, imshape)))
plt.xticks([])
plt.yticks([])
# plt.subplot(1,6,4)
# plt.title("Ground Truth")
# plt.imshow(self.gt, vmin = 0, vmax=3)
# plt.xticks([])
# plt.yticks([])
plt.subplot(1,4,3)
plt.title("Old Seg, Dice = {}".format("{0:.2f}".format(dice_whole_coef(self.model.predict(image).argmax(axis=-1), gt))))
plt.imshow(np.argmax(self.model.predict(image), axis = -1).reshape((imshape, imshape)), vmin = 0, vmax=3)
plt.xticks([])
plt.yticks([])
plt.subplot(1,4,4)
plt.title("New Seg, Dice={}, Sensitivity={}".format("{0:.2f}".format(dice_whole_coef(self.model.predict(adverserial_image).argmax(axis=-1),
gt)), "{0:.2f}".format(delta_dice_perc/delta_image_perc)))
plt.imshow(np.argmax(self.model.predict(adverserial_image), axis = -1).reshape((imshape, imshape)), vmin = 0, vmax=3)
plt.xticks([])
plt.yticks([])
plt.tight_layout(pad=0)
plt.show()
# plt.savefig('/home/parth/Interpretable_ML/Adverserial Examples/adv_{}.png'.format(epsilon))
return(delta_image_perc, delta_dice_perc, delta_dice_perc/delta_image_perc)
def generate_random_classification(self, mode='random'):
if mode == 'random':
true_target = self.gt.flatten()
true_target[true_target==4] = 3
index_list = [0, 1, 2, 3]
adverserial_random = np.zeros_like(true_target)
for i in range(adverserial_random.shape[0]):
adverserial_random[i] = np.random.choice(np.setdiff1d(index_list, true_target[i]))
print("Target image")
plt.imshow(adverserial_random.reshape((256, 256)), vmin=0., vmax=3.)
plt.show()
return to_categorical(adverserial_random, num_classes=4).reshape(self.test_image.shape)
elif mode == 'swap':
true_target = self.gt.flatten()
true_target[true_target==4] = 3
index_list = [0, 1, 2, 3]
adverserial_random = np.zeros_like(true_target)
for i in index_list:
adverserial_random[true_target == i] = np.random.choice(np.setdiff1d(index_list, i))
print("Target image")
plt.imshow(adverserial_random.reshape((256, 256)), vmin=0., vmax=3.)
plt.show()
return to_categorical(adverserial_random, num_classes=4).reshape(self.test_image.shape)
if __name__ == "__main__":
model = load_model('/home/parth/Interpretable_ML/saved_models/SimUnet/model_lrsch.hdf5',
custom_objects={'gen_dice_loss':gen_dice_loss,
'dice_whole_metric':dice_whole_metric,
'dice_core_metric':dice_core_metric,
'dice_en_metric':dice_en_metric})
model.load_weights('/home/parth/Interpretable_ML/saved_models/SimUnet/SimUnet.40_0.060.hdf5')
I = intervention(model, '/media/parth/DATA/datasets/brats_2018/val/**')
test_path = glob('/media/parth/DATA/datasets/brats_2018/val/**')
average_change = []
for epsilon in [0.7]: #, 0.07, 0.21, 0.7]:
for i in tqdm(range(len(test_path))):
test_image, gt = load_vol_brats(test_path[i], slicen = 78, pad = 0)
if len(np.unique(gt)) == 4:
print(len(np.unique(gt)))
# I.blocks('/home/parth/Interpretable_ML/BioExp/sample_vol/brats/**')
adv = I.adverserial(epsilon = epsilon, mode='gradient', test_image=test_image, gt=gt)
if adv[1] > 0:
average_change.append(adv)
print(adv)
print(np.mean(average_change, axis = 0))
# I.generate_random_classification(mode='swap')
# I.mean_swap(plot = False)
| 34.284672 | 143 | 0.678838 | 7,745 | 0.824462 | 0 | 0 | 0 | 0 | 0 | 0 | 1,579 | 0.168086 |
896699d0cdac3f9975a021f32ab3c6fa4c1799b6 | 758 | py | Python | convolut/metric/loss.py | convolut/convolut | e7168ace62f70f9df084a652a2b8fa70a6902e55 | [
"Apache-2.0"
] | 9 | 2020-01-07T06:05:58.000Z | 2020-07-03T12:24:31.000Z | convolut/metric/loss.py | convolut/convolut | e7168ace62f70f9df084a652a2b8fa70a6902e55 | [
"Apache-2.0"
] | null | null | null | convolut/metric/loss.py | convolut/convolut | e7168ace62f70f9df084a652a2b8fa70a6902e55 | [
"Apache-2.0"
] | null | null | null | from decouple import Module
from .events import MetricEvent
from ..model import ModelLossEndEvent
class LossMetric(Module):
def __init__(self):
super().__init__()
self.sub(ModelLossEndEvent, self.loss)
def loss(self, event: ModelLossEndEvent):
metric_value = event.loss.item()
self.pub(MetricEvent(metric_name="loss",
metric_value=metric_value,
periods={
"loader_name": event.loader_name,
"epoch_index": event.epoch_index,
"step_index": event.step_index,
"batch_index": event.batch_index,
}))
| 31.583333 | 66 | 0.51715 | 656 | 0.865435 | 0 | 0 | 0 | 0 | 0 | 0 | 57 | 0.075198 |
896a754ac448192eaca4541a428db50fe08184cd | 303 | py | Python | inputs/json_file.py | Eugene-Kuzmenko/render_html_from_json | c3c3152b3c9969f4f54874d361a81d5e5b7f33a0 | [
"MIT"
] | null | null | null | inputs/json_file.py | Eugene-Kuzmenko/render_html_from_json | c3c3152b3c9969f4f54874d361a81d5e5b7f33a0 | [
"MIT"
] | null | null | null | inputs/json_file.py | Eugene-Kuzmenko/render_html_from_json | c3c3152b3c9969f4f54874d361a81d5e5b7f33a0 | [
"MIT"
] | null | null | null | import json
from collections import OrderedDict
def json_file(filename, converter):
with open(filename, 'r') as file:
raw = json.load(
file,
object_pairs_hook=OrderedDict # to insure that order of items in json won't be broken
)
return converter(raw)
| 23.307692 | 98 | 0.650165 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 58 | 0.191419 |
896aca4891e1316e8534c9060978e02eed953f41 | 1,963 | py | Python | board.py | screw-pack/MacGyver | 04ae8ac78168393c6c607ca792026dc71a5c2905 | [
"MIT"
] | null | null | null | board.py | screw-pack/MacGyver | 04ae8ac78168393c6c607ca792026dc71a5c2905 | [
"MIT"
] | null | null | null | board.py | screw-pack/MacGyver | 04ae8ac78168393c6c607ca792026dc71a5c2905 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# board.py
# Author: Germain GAILLARD <gaillard.germain@gmail.com>
# Version: 0.1
# License: MIT
"""Import modules"""
from random import sample
class Board:
"""board object which regroup the coordinates of the game's elements
(walls, start, end, guard, components...)"""
def __init__(self, x_tile, y_tile, tile_size):
self.x_tile = x_tile
self.y_tile = y_tile
self.tile_size = tile_size
self.walls = []
self.corridors = []
@property
def width(self):
"""board's width in px"""
return self.x_tile * self.tile_size
@property
def height(self):
"""board's height in px"""
return self.y_tile * self.tile_size
def read_map(self, map_path):
"""reads a .txt : 'w'=wall, 's'=start, 'e'=end, 'g'=guard, ' '=empty"""
with open(map_path, 'r') as data:
for y_index, line in enumerate(data):
for x_index, char in enumerate(line.strip('\n')):
coord = ((x_index * self.tile_size,
y_index * self.tile_size))
if char == 'w':
self.walls.append(coord)
elif char == 's':
setattr(self, 'start', coord)
elif char == 'e':
setattr(self, 'end', coord)
elif char == 'g':
setattr(self, 'guard', coord)
else:
self.corridors.append(coord)
def set_components(self):
"""randomly pick-up 3 coordinates in a list of available tiles
and create a dict {coordinate : index}"""
components = {}
component_list = sample(self.corridors, 3)
for index, component in enumerate(component_list):
components[component] = index
setattr(self, 'components', components)
| 33.271186 | 79 | 0.529292 | 1,767 | 0.900153 | 0 | 0 | 218 | 0.111055 | 0 | 0 | 566 | 0.288334 |
896dffe0883e57092304362b802eda6ae2176fcc | 9,362 | py | Python | services/core/DNP3Agent/tests/unit_test_point_definitions.py | rmay-intwine/volttron | a449f70e32f73ff0136a838d0feddb928ede6298 | [
"Apache-2.0"
] | 406 | 2015-01-20T03:08:53.000Z | 2022-03-31T20:59:07.000Z | services/core/DNP3Agent/tests/unit_test_point_definitions.py | rmay-intwine/volttron | a449f70e32f73ff0136a838d0feddb928ede6298 | [
"Apache-2.0"
] | 2,031 | 2015-01-05T21:35:45.000Z | 2022-03-29T21:44:36.000Z | services/core/DNP3Agent/tests/unit_test_point_definitions.py | rmay-intwine/volttron | a449f70e32f73ff0136a838d0feddb928ede6298 | [
"Apache-2.0"
] | 219 | 2015-01-20T14:53:57.000Z | 2022-03-06T00:37:41.000Z | # -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2018, 8minutenergy / Kisensum.
#
# 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.
#
# Neither 8minutenergy nor Kisensum, nor any of their
# employees, nor any jurisdiction or organization that has cooperated in the
# development of these materials, makes any warranty, express or
# implied, or assumes any legal liability or responsibility for the accuracy,
# completeness, or usefulness or any information, apparatus, product,
# software, or process disclosed, or represents that its use would not infringe
# privately owned rights. Reference herein to any specific commercial product,
# process, or service by trade name, trademark, manufacturer, or otherwise
# does not necessarily constitute or imply its endorsement, recommendation, or
# favoring by 8minutenergy or Kisensum.
# }}}
import pytest
try:
import dnp3
except ImportError:
pytest.skip("pydnp3 not found!", allow_module_level=True)
from dnp3.points import ArrayHeadPointDefinition, PointDefinitions, PointValue
from dnp3.mesa.agent import MesaAgent
from dnp3.mesa.functions import FunctionDefinitions
from test_mesa_agent import POINT_DEFINITIONS_PATH, FUNCTION_DEFINITIONS_PATH
def test_point_definition_load():
point_defs = PointDefinitions(point_definitions_path=POINT_DEFINITIONS_PATH)
import pprint
pprint.pprint(point_defs._points)
pprint.pprint(point_defs._point_name_dict)
print("_point_variations_dict")
pprint.pprint(point_defs._point_variation_dict)
def test_point_definition():
test_dict = {
"name": "CurveStart-X",
"type": "array", # Start of the curve's X/Y array
"array_times_repeated": 100,
"group": 40,
"variation": 1,
"index": 207,
"description": "Starting index for a curve of up to 99 X/Y points",
"array_points": [
{
"name": "Curve-X"
},
{
"name": "Curve-Y"
}
]
}
test_def = ArrayHeadPointDefinition(test_dict)
print(test_def)
def send_points(mesa_agent, some_points):
for name, value, index in some_points:
pdef = mesa_agent.point_definitions.get_point_named(name,index)
point_value = PointValue('Operate',
None,
value,
pdef,
pdef.index,
None) # What is op_type used for?
print(point_value)
mesa_agent._process_point_value(point_value)
def test_mesa_agent():
mesa_agent = MesaAgent(point_topic='points_foobar', local_ip='127.0.0.1', port=8999, outstation_config={},
function_topic='functions_foobar', outstation_status_topic='',
local_point_definitions_path=POINT_DEFINITIONS_PATH,
local_function_definitions_path=FUNCTION_DEFINITIONS_PATH)
mesa_agent._configure('', '', {})
point_definitions = mesa_agent.point_definitions
supported_pdef = point_definitions.get_point_named("Supports Charge/Discharge Mode")
mesa_agent.update_input_point(supported_pdef, True)
test_points = (
# ("DCHD.WinTms (out)", 1.0),
# ("DCHD.RmpTms (out)", 2.0),
# ("DCHD.RevtTms (out)", 3.0),
("CurveStart-X", 1.0, None),
("CurveStart-X", 2.0, 208),
)
send_points(mesa_agent, test_points)
def test_mesa_agent_2():
mesa_agent = MesaAgent(point_topic='points_foobar', local_ip='127.0.0.1', port=8999, outstation_config={},
function_topic='functions_foobar', outstation_status_topic='',
local_point_definitions_path=POINT_DEFINITIONS_PATH,
local_function_definitions_path=FUNCTION_DEFINITIONS_PATH)
mesa_agent._configure('', '', {})
point_definitions = mesa_agent.point_definitions
supported_pdef = point_definitions.get_point_named("Supports Charge/Discharge Mode")
mesa_agent.update_input_point(supported_pdef, True)
test_points = (
("DCHD.WinTms (out)", 1.0, None),
#("DCHD.RmpTms (out)", 2.0, None),
("DCHD.RevtTms (out)", 3.0, None),
)
send_points(mesa_agent, test_points)
def test_function_definitions():
point_definitions = PointDefinitions(point_definitions_path=POINT_DEFINITIONS_PATH)
fdefs = FunctionDefinitions(point_definitions, function_definitions_path=FUNCTION_DEFINITIONS_PATH)
fd = fdefs.function_for_id("curve")
print(fd)
pdef = point_definitions.get_point_named("DCHD.WinTms (out)")
print(pdef)
print(fdefs.step_definition_for_point(pdef))
def test_selector_block():
"""
Test send a Curve function / selector block (including an array of points) to MesaAgent.
Get MesaAgent's selector block and confirm that it has the correct contents.
Do this for a variety of Edit Selectors and array contents.
"""
def process_block_points(agt, block_points, edit_selector):
"""Send each point value in block_points to the MesaAgent."""
# print('Processing {}'.format(block_points))
for name, value, index in block_points:
point_definitions = agt.point_definitions
pdef = point_definitions.get_point_named(name, index)
point_value = PointValue('Operate', None, value, pdef, pdef.index, None)
agt._process_point_value(point_value)
returned_block = mesa_agent.get_selector_block('Curve Edit Selector', edit_selector)
# print('get_selector_block returned {}'.format(returned_block))
return returned_block
mesa_agent = MesaAgent(point_topic='points_foobar', local_ip='127.0.0.1', port=8999, outstation_config={},
function_topic='functions_foobar', outstation_status_topic='',
local_point_definitions_path=POINT_DEFINITIONS_PATH,
local_function_definitions_path=FUNCTION_DEFINITIONS_PATH)
mesa_agent._configure('', '', {})
block_1_points = [('Curve Edit Selector', 1, None), # index 191 - Function and SelectorBlock start
('CurveStart-X', 1.0, None), # Point #1-X: index 207 - Array start
('CurveStart-X', 2.0, 208), # Point #1-Y
('Curve Number of Points', 1, None)] # index 196 - Curve function end
block_2_points = [('Curve Edit Selector', 2, None), # index 191 - Function and SelectorBlock start
('CurveStart-X', 1.0, None), # Point #1-X: index 207 - Array start
('CurveStart-X', 2.0, 208), # Point #1-Y
('CurveStart-X', 3.0, 209), # Point #2-X
('CurveStart-X', 4.0, 210), # Point #2-Y
('Curve Number of Points', 2, None)] # index 196 - Curve function end
block_2a_points = [('Curve Edit Selector', 2, None), # index 191 - Function and SelectorBlock start
('CurveStart-X', 1.0, None), # Point #1-X: index 207 - Array start
('CurveStart-X', 2.0, 208), # Point #1-Y
('CurveStart-X', 5.0, 211), # Point #3-X
('CurveStart-X', 6.0, 212), # Point #3-Y
('Curve Number of Points', 3, None)] # index 196 - Curve function end
# Send block #1. Confirm that its array has a point with Y=2.0.
block = process_block_points(mesa_agent, block_1_points, 1)
assert block['CurveStart-X'][0]['Curve-Y'] == 2.0
# Send block #2. Confirm that its array has a point #2 with Y=4.0.
block = process_block_points(mesa_agent, block_2_points, 2)
assert block['CurveStart-X'][1]['Curve-Y'] == 4.0
# Send an updated block #2 with no point #2 and a new point #3.
block = process_block_points(mesa_agent, block_2a_points, 2)
# Confirm that its array still has a point #2 with Y=4.0, even though it wasn't just sent.
assert block['CurveStart-X'][1]['Curve-Y'] == 4.0
# Confirm that its array now has a point #3 with Y=6.0.
assert block['CurveStart-X'][2]['Curve-Y'] == 6.0
# Re-send block #1. Confirm that selector block initialization reset the point cache: the array has no second point.
block = process_block_points(mesa_agent, block_1_points, 1)
assert len(block['CurveStart-X']) == 1
if __name__ == "__main__":
# test_mesa_agent()
# test_mesa_agent_2()
# test_function_definitions()
# test_point_definition()
test_point_definition_load()
# test_selector_block()
| 43.953052 | 120 | 0.638112 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,923 | 0.419034 |
89730fea2cfd2a597b98eac7b0559f46c95c3edb | 381 | py | Python | Opencart/tests.py | BahrmaLe/otus_python_homework | 510a4f1971b35048d760fcc45098e511b81bea31 | [
"MIT"
] | 1 | 2021-02-25T15:37:21.000Z | 2021-02-25T15:37:21.000Z | Opencart/tests.py | BahrmaLe/otus_python_homework | 510a4f1971b35048d760fcc45098e511b81bea31 | [
"MIT"
] | null | null | null | Opencart/tests.py | BahrmaLe/otus_python_homework | 510a4f1971b35048d760fcc45098e511b81bea31 | [
"MIT"
] | null | null | null | def test_open_home_page(driver, request):
url = 'opencart/'
return driver.get("".join([request.config.getoption("--address"), url]))
element = driver.find_elements_by_xpath("//base[contains(@href, 'http://192.168.56.103/opencart/]")
assert element == 'http://192.168.56.103/opencart/'
assert driver.find_element_by_class_name('col-sm-4').text == 'Your Store'
| 42.333333 | 103 | 0.692913 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 137 | 0.35958 |
89738170301569f699c91bba33c6010b3ec65d70 | 430 | py | Python | misago/misago/core/tests/test_frontendcontext_middleware.py | vascoalramos/misago-deployment | 20226072138403108046c0afad9d99eb4163cedc | [
"MIT"
] | 2 | 2021-03-06T21:06:13.000Z | 2021-03-09T15:05:12.000Z | misago/misago/core/tests/test_frontendcontext_middleware.py | vascoalramos/misago-deployment | 20226072138403108046c0afad9d99eb4163cedc | [
"MIT"
] | null | null | null | misago/misago/core/tests/test_frontendcontext_middleware.py | vascoalramos/misago-deployment | 20226072138403108046c0afad9d99eb4163cedc | [
"MIT"
] | null | null | null | from django.test import TestCase
from ..middleware import FrontendContextMiddleware
class MockRequest:
pass
class FrontendContextMiddlewareTests(TestCase):
def test_middleware_frontend_context_dict(self):
"""Middleware sets frontend_context dict on request"""
request = MockRequest()
FrontendContextMiddleware().process_request(request)
self.assertEqual(request.frontend_context, {})
| 25.294118 | 62 | 0.75814 | 339 | 0.788372 | 0 | 0 | 0 | 0 | 0 | 0 | 54 | 0.125581 |
8974ae2b1100d7ceb895be22b8023f6f5d9849a1 | 11,589 | py | Python | tests/test_schema.py | repole/drowsy | 1360068c52d4ef4fbb7bcb2db2e4a5ce9c3c7294 | [
"MIT"
] | 4 | 2016-06-16T20:16:38.000Z | 2020-08-18T19:51:40.000Z | tests/test_schema.py | repole/drowsy | 1360068c52d4ef4fbb7bcb2db2e4a5ce9c3c7294 | [
"MIT"
] | 2 | 2017-10-05T11:14:39.000Z | 2018-04-15T00:54:35.000Z | tests/test_schema.py | repole/drowsy | 1360068c52d4ef4fbb7bcb2db2e4a5ce9c3c7294 | [
"MIT"
] | null | null | null | """
tests.test_parser
~~~~~~~~~~~~~~~~~
Parser tests for Drowsy.
"""
# :copyright: (c) 2016-2020 by Nicholas Repole and contributors.
# See AUTHORS for more details.
# :license: MIT - See LICENSE for more details.
from marshmallow import fields
from marshmallow.exceptions import ValidationError
from drowsy.convert import ModelResourceConverter
from drowsy.exc import PermissionValidationError
from drowsy.schema import NestedOpts, ResourceSchema
from tests.base import DrowsyDatabaseTests
from tests.schemas import (
AlbumSchema, AlbumCamelSchema, ArtistSchema,
CustomerSchema, TrackPermissionsSchema, TrackSchema
)
import tests.resources
from tests.models import Album, Track, ForeignPkExample
from pytest import raises
def test_schema_default_get_instance():
"""Test a ResourceSchema handles get_instance properly."""
class TestSchema(ResourceSchema):
class Meta:
instance_cls = Album
assert TestSchema().get_instance({}) is None
def test_schema_fail_missing_key():
"""Test schema failure missing key error message."""
schema = AlbumSchema()
with raises(AssertionError):
schema.make_error(key="test")
def test_schema_default_id_keys():
"""Test a ResourceSchema handles given id_keys properly."""
class TestSchema(ResourceSchema):
class Meta:
instance_cls = Album
id_keys = ["album_id"]
assert "album_id" in TestSchema().id_keys
def test_schema_empty_id_keys():
"""Test a ResourceSchema handles no id_keys properly."""
class TestSchema(ResourceSchema):
class Meta:
instance_cls = Album
assert isinstance(TestSchema().id_keys, list)
def test_schema_make_instance_default():
"""Test making an instance from a non model schema."""
class TestSchema(ResourceSchema):
"""Simple schema for this test."""
class Meta:
"""Meta options for this schema."""
instance_cls = Album
id_keys = ["album_id"]
def get_instance(self, data):
"""Allows testing of the resource property."""
return None
schema = TestSchema()
result = schema.make_instance({"album_id": 1, "title": "test"})
assert result.album_id == 1
assert result.title == "test"
assert isinstance(result, Album)
def test_convert_property2field_instance():
"""Test property2field can return a column type."""
converter = ModelResourceConverter()
result = converter.property2field(Album.album_id.prop, instance=False)
assert result == fields.Integer
def test_convert_fk_as_pk():
"""Test converter handles ForeignKey as part of Primary properly."""
converter = ModelResourceConverter()
converted_fields = converter.fields_for_model(
ForeignPkExample,
include_fk=False,
include_relationships=True,
fields=None,
exclude=None,
base_fields=None,
dict_cls=dict
)
assert "parent_id" in converted_fields is not None
class TestDrowsySchema(DrowsyDatabaseTests):
"""Test drowsy schema classes are working as expected."""
@staticmethod
def test_schema_embed_top_level(db_session):
"""Test embedding a non nested field is treated like only."""
schema = AlbumCamelSchema(session=db_session)
schema.embed("album_id")
assert "album_id" in schema.only
@staticmethod
def test_schema_embed_fail(db_session):
"""Test trying to embed a non-existent field fails."""
schema = AlbumCamelSchema(session=db_session)
with raises(AttributeError):
schema.embed("test")
@staticmethod
def test_schema_disallow_all_op_permissions_many(db_session):
"""Make sure permission denial on a list resource works."""
schema = ArtistSchema(session=db_session)
data = {
"artist_id": 1,
"name": "test",
"albums": [
{"album_id": 1}
]
}
errors = {}
try:
schema.load(data=data)
except ValidationError as exc:
errors = exc.messages
assert errors["albums"][0]["$op"][0]
@staticmethod
def test_schema_disallow_all_op_permissions(db_session):
"""Make sure permission denial works."""
schema = TrackPermissionsSchema(session=db_session, partial=True)
data = {
"track_id": 1,
"album": {"album_id": 1}
}
errors = {}
try:
schema.load(data=data)
except ValidationError as exc:
errors = exc.messages
assert errors["album"]
@staticmethod
def test_schema_disallow_all_op_permissions_strict(db_session):
"""Make sure permission denial works."""
schema = TrackPermissionsSchema(session=db_session, partial=True)
data = {
"track_id": 1,
"album": {"album_id": 1}
}
with raises(ValidationError):
schema.load(data=data)
@staticmethod
def test_schema_relationship_bad_data(db_session):
"""Test bad data supplied to a relationship fails properly."""
schema = AlbumSchema(session=db_session, partial=True)
data = {
"tracks": [{"bytes": "TEST"}]
}
errors = {}
try:
schema.load(data=data)
except ValidationError as exc:
errors = exc.messages
assert errors["tracks"][0]["bytes"]
@staticmethod
def test_convert_doc_string(db_session):
"""Test converter properly handles a doc string."""
schema = CustomerSchema(session=db_session)
assert (schema.fields["state"].metadata["description"] ==
"Two Character Abbreviation")
@staticmethod
def test_relationship_set_child(db_session):
"""Test setting a non list relationship works."""
data = {
"track_id": 1,
"album": {
"album_id": 347,
}
}
schema = TrackSchema(session=db_session)
result = schema.load(data, partial=True)
assert result.album.album_id == 347
@staticmethod
def test_many_load(db_session):
"""Test loading many objects at once works."""
data = [
{"track_id": 1, "name": "test1"},
{"track_id": 2, "name": "test2"},
{"track_id": 3, "name": "test3"},
{"track_id": 4, "name": "test4"},
{"track_id": 5, "name": "test5"}
]
schema = TrackSchema(session=db_session, many=True)
result = schema.load(data, partial=True, many=True)
assert len(result) == 5
@staticmethod
def test_many_load_failure(db_session):
"""Test loading many objects with bad data fails accordingly."""
data = [
{"track_id": 1, "name": 1},
{"track_id": 2, "name": 2},
{"track_id": 3, "name": "test3"},
{"track_id": 4, "name": "test4"},
{"track_id": 5, "name": "test5"}
]
schema = TrackSchema(session=db_session, many=True)
errors = {}
try:
schema.load(data, partial=True, many=True)
except ValidationError as exc:
errors = exc.messages
assert len(errors.keys()) == 2
assert 0 in errors and 1 in errors
@staticmethod
def test_base_instance_relationship_set_child(db_session):
"""Test setting a child when loading with a base instance."""
album = db_session.query(Album).filter(
Album.album_id == 1).first()
instance = Track(track_id=9999, album=album)
data = {
"track_id": 9999,
"album": {
"album_id": 1,
},
"name": "New TestTrack",
"media_type": {
"media_type_id": 1
},
"milliseconds": 1,
"unit_price": 1.0
}
schema = TrackSchema(session=db_session)
result = schema.load(data, partial=True, instance=instance)
assert result.album.album_id == 1
@staticmethod
def test_base_instance_relationship_add_child(db_session):
"""Test adding a child when loading with a base instance."""
track = db_session.query(Track).filter(
Track.track_id == 1).first()
instance = Album(album_id=9999)
instance.tracks.append(track)
data = {
"album_id": 1,
"tracks": [
{"track_id": 1}
]
}
schema = AlbumSchema(session=db_session, partial=True)
result = schema.load(data, instance=instance)
assert result.tracks[0].track_id == 1
@staticmethod
def test_relationship_invalid_remove(db_session):
"""Test trying to remove a child from the wrong parent fails."""
data = {
"album_id": 1,
"tracks": [{
"track_id": 597,
"$op": "remove"
}]
}
schema = AlbumSchema(
session=db_session, partial=True)
with raises(ValidationError):
schema.load(data)
@staticmethod
def test_relationship_invalid_op(db_session):
"""Test an invalid operation on a relationship fails."""
data = {
"album_id": 1,
"tracks": [{
"track_id": 1,
"$op": "test"
}]
}
schema = AlbumSchema(
session=db_session, partial=True)
with raises(ValidationError):
schema.load(data)
@staticmethod
def test_instance_relationship_nested_opts(db_session):
"""Test nested opts enable complete relation replacement."""
data = {
"album_id": 2,
"tracks": [
{"track_id": 1}
]
}
nested_opts = {"tracks": NestedOpts(partial=False)}
schema = AlbumSchema(session=db_session, nested_opts=nested_opts,
partial=True)
result = schema.load(data)
assert result.tracks[0].track_id == 1
assert len(result.tracks) == 1
@staticmethod
def test_nested_relationship_nested_opts(db_session):
"""Test nested opts enable complete relation replacement."""
data = {
"album_id": 2,
"tracks": [
{"track_id": 1,
"playlists": [
{"playlist_id": 1}
]}
]
}
nested_opts = {
"tracks": NestedOpts(partial=False),
"tracks.playlists": NestedOpts(partial=False)}
schema = AlbumSchema(session=db_session, nested_opts=nested_opts,
partial=True)
result = schema.load(data)
assert len(result.tracks[0].playlists) == 1
@staticmethod
def test_permission_denied(db_session):
"""Test permission denied errors work as expected."""
data = {
"album_id": 340,
"title": "Denied"
}
schema = AlbumSchema(session=db_session, partial=True)
with raises(PermissionValidationError):
schema.load(data)
@staticmethod
def test_permission_denied_list(db_session):
"""Test permission denied errors for lists work as expected."""
data = [{"track_id": 1, "name": "Denied"}]
schema = TrackSchema(session=db_session, partial=True)
with raises(PermissionValidationError):
schema.load(data, many=True)
| 32.923295 | 74 | 0.592199 | 9,179 | 0.792044 | 0 | 0 | 8,337 | 0.719389 | 0 | 0 | 2,725 | 0.235137 |
8975af95154909e66feae919c1c23a3719a39dc8 | 66,893 | py | Python | Assignment2_lastrun.py | iamnavya-agg/Emotion-Categorization-experiemnt | c7cc1a17cbdb414a07cecddb88b4299a1ba51629 | [
"MIT"
] | null | null | null | Assignment2_lastrun.py | iamnavya-agg/Emotion-Categorization-experiemnt | c7cc1a17cbdb414a07cecddb88b4299a1ba51629 | [
"MIT"
] | 4 | 2020-03-12T19:22:46.000Z | 2022-03-12T00:09:38.000Z | Assignment2_lastrun.py | iamnavya-agg/Emotion-Categorization-experiemnt | c7cc1a17cbdb414a07cecddb88b4299a1ba51629 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.2.3),
on Sun Oct 13 21:34:23 2019
If you publish work using this script the most relevant publication is:
Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, Lindeløv JK. (2019)
PsychoPy2: Experiments in behavior made easy Behav Res 51: 195.
https://doi.org/10.3758/s13428-018-01193-y
"""
from __future__ import absolute_import, division
from psychopy import locale_setup
from psychopy import prefs
from psychopy import sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.2.3'
expName = 'Assignment2' # from the Builder filename that created this script
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='/Users/pragyagandhi/Desktop/FinalExperiment/Assignment2_lastrun.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
frameTolerance = 0.001 # how close to onset before 'same' frame
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=[1440, 900], fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()
# Initialize components for Routine "Intoduction"
IntoductionClock = core.Clock()
text = visual.TextStim(win=win, name='text',
text='Hello,\nWelcome to the experiment!\nIn this experiment, there are two parts. \nPress enter!',
font='Arial',
pos=(0,0), height=0.05, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
key_resp = keyboard.Keyboard()
# Initialize components for Routine "trial1"
trial1Clock = core.Clock()
text_9 = visual.TextStim(win=win, name='text_9',
text='Welcome to part 1.\nPress enter to see the rules.',
font='Arial',
pos=(0, 0), height=0.07, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
key_resp_7 = keyboard.Keyboard()
# Initialize components for Routine "Rules"
RulesClock = core.Clock()
text_6 = visual.TextStim(win=win, name='text_6',
text='In this experiment your task is to guess if the shown face was happy or not.\nFirst, you will be shown a face.\nThen, there will a noise for 0.1 seconds.\nNext, there will be a blank screen for 2 seconds.\nIn this,\n press the right key if shown face was happy.\n press the left key if shown face was sad.\n\n\n\nPress enter to start the experiment!',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
key_resp_3 = keyboard.Keyboard()
# Initialize components for Routine "plus"
plusClock = core.Clock()
text_4 = visual.TextStim(win=win, name='text_4',
text='+',
font='Arial',
pos=(0, 0), height=0.2, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
# Initialize components for Routine "Experiment1"
Experiment1Clock = core.Clock()
imageGuess = visual.ImageStim(
win=win,
name='imageGuess',
image='sin', mask=None,
ori=0, pos=(0, 0), size=(0.5, 0.5),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
# Initialize components for Routine "sound1"
sound1Clock = core.Clock()
image_2 = visual.ImageStim(
win=win,
name='image_2',
image='noise.jpg', mask=None,
ori=0, pos=(0, 0), size=(0.5, 0.5),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
# Initialize components for Routine "empty1"
empty1Clock = core.Clock()
text_8 = visual.TextStim(win=win, name='text_8',
text=None,
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
key_resp_8 = keyboard.Keyboard()
# Initialize components for Routine "trial2"
trial2Clock = core.Clock()
text_3 = visual.TextStim(win=win, name='text_3',
text='Welcome to Experiment 2.\nPress enter to see the rules',
font='Arial',
pos=(0, 0), height=0.07, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
key_resp_4 = keyboard.Keyboard()
# Initialize components for Routine "Rules2"
Rules2Clock = core.Clock()
text_7 = visual.TextStim(win=win, name='text_7',
text="In this experiment you have to tell if the face was happy,sad or angry.\nYou will be shown a face.\nThen, there will be a noise for 0.1 seconds.\nNext,There will be blank screen for 2 seconds.\nYou have to:\n -Press 'h' if the face is happy.\n -Press 's' if the face is sad.\n -Press 'a' if the face is angry.\nPress enter to start the experiment",
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
key_resp_5 = keyboard.Keyboard()
# Initialize components for Routine "Plus"
PlusClock = core.Clock()
text_5 = visual.TextStim(win=win, name='text_5',
text='+',
font='Arial',
pos=(0, 0), height=0.2, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
# Initialize components for Routine "Experiment2"
Experiment2Clock = core.Clock()
image = visual.ImageStim(
win=win,
name='image',
image='sin', mask=None,
ori=0, pos=(0, 0), size=(0.5, 0.5),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
# Initialize components for Routine "sound2"
sound2Clock = core.Clock()
image_3 = visual.ImageStim(
win=win,
name='image_3',
image='noise.jpg', mask=None,
ori=0, pos=(0, 0), size=(0.5, 0.5),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
# Initialize components for Routine "empty2"
empty2Clock = core.Clock()
text_10 = visual.TextStim(win=win, name='text_10',
text=None,
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
key_resp_2 = keyboard.Keyboard()
# Initialize components for Routine "Thankyou"
ThankyouClock = core.Clock()
text_2 = visual.TextStim(win=win, name='text_2',
text='Thankyou!!',
font='Arial',
pos=(0,0), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "Intoduction"-------
routineTimer.add(5.000000)
# update component parameters for each repeat
key_resp.keys = []
key_resp.rt = []
# keep track of which components have finished
IntoductionComponents = [text, key_resp]
for thisComponent in IntoductionComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
IntoductionClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "Intoduction"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = IntoductionClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=IntoductionClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text* updates
if text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
text.frameNStart = frameN # exact frame index
text.tStart = t # local t and not account for scr refresh
text.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(text, 'tStartRefresh') # time at next scr refresh
text.setAutoDraw(True)
if text.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > text.tStartRefresh + 5-frameTolerance:
# keep track of stop time/frame for later
text.tStop = t # not accounting for scr refresh
text.frameNStop = frameN # exact frame index
win.timeOnFlip(text, 'tStopRefresh') # time at next scr refresh
text.setAutoDraw(False)
# *key_resp* updates
waitOnFlip = False
if key_resp.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp.frameNStart = frameN # exact frame index
key_resp.tStart = t # local t and not account for scr refresh
key_resp.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp, 'tStartRefresh') # time at next scr refresh
key_resp.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > key_resp.tStartRefresh + 5-frameTolerance:
# keep track of stop time/frame for later
key_resp.tStop = t # not accounting for scr refresh
key_resp.frameNStop = frameN # exact frame index
win.timeOnFlip(key_resp, 'tStopRefresh') # time at next scr refresh
key_resp.status = FINISHED
if key_resp.status == STARTED and not waitOnFlip:
theseKeys = key_resp.getKeys(keyList=['return'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp.keys = theseKeys.name # just the last key pressed
key_resp.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in IntoductionComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "Intoduction"-------
for thisComponent in IntoductionComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('text.started', text.tStartRefresh)
thisExp.addData('text.stopped', text.tStopRefresh)
# check responses
if key_resp.keys in ['', [], None]: # No response was made
key_resp.keys = None
thisExp.addData('key_resp.keys',key_resp.keys)
if key_resp.keys != None: # we had a response
thisExp.addData('key_resp.rt', key_resp.rt)
thisExp.addData('key_resp.started', key_resp.tStartRefresh)
thisExp.addData('key_resp.stopped', key_resp.tStopRefresh)
thisExp.nextEntry()
# ------Prepare to start Routine "trial1"-------
# update component parameters for each repeat
key_resp_7.keys = []
key_resp_7.rt = []
# keep track of which components have finished
trial1Components = [text_9, key_resp_7]
for thisComponent in trial1Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
trial1Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "trial1"-------
while continueRoutine:
# get current time
t = trial1Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=trial1Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text_9* updates
if text_9.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
text_9.frameNStart = frameN # exact frame index
text_9.tStart = t # local t and not account for scr refresh
text_9.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(text_9, 'tStartRefresh') # time at next scr refresh
text_9.setAutoDraw(True)
# *key_resp_7* updates
waitOnFlip = False
if key_resp_7.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_7.frameNStart = frameN # exact frame index
key_resp_7.tStart = t # local t and not account for scr refresh
key_resp_7.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_7, 'tStartRefresh') # time at next scr refresh
key_resp_7.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_7.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_7.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_7.status == STARTED and not waitOnFlip:
theseKeys = key_resp_7.getKeys(keyList=['return'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_7.keys = theseKeys.name # just the last key pressed
key_resp_7.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trial1Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial1"-------
for thisComponent in trial1Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('text_9.started', text_9.tStartRefresh)
thisExp.addData('text_9.stopped', text_9.tStopRefresh)
# check responses
if key_resp_7.keys in ['', [], None]: # No response was made
key_resp_7.keys = None
thisExp.addData('key_resp_7.keys',key_resp_7.keys)
if key_resp_7.keys != None: # we had a response
thisExp.addData('key_resp_7.rt', key_resp_7.rt)
thisExp.addData('key_resp_7.started', key_resp_7.tStartRefresh)
thisExp.addData('key_resp_7.stopped', key_resp_7.tStopRefresh)
thisExp.nextEntry()
# the Routine "trial1" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "Rules"-------
# update component parameters for each repeat
key_resp_3.keys = []
key_resp_3.rt = []
# keep track of which components have finished
RulesComponents = [text_6, key_resp_3]
for thisComponent in RulesComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
RulesClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "Rules"-------
while continueRoutine:
# get current time
t = RulesClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=RulesClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text_6* updates
if text_6.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
text_6.frameNStart = frameN # exact frame index
text_6.tStart = t # local t and not account for scr refresh
text_6.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(text_6, 'tStartRefresh') # time at next scr refresh
text_6.setAutoDraw(True)
# *key_resp_3* updates
waitOnFlip = False
if key_resp_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_3.frameNStart = frameN # exact frame index
key_resp_3.tStart = t # local t and not account for scr refresh
key_resp_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_3, 'tStartRefresh') # time at next scr refresh
key_resp_3.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_3.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_3.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_3.status == STARTED and not waitOnFlip:
theseKeys = key_resp_3.getKeys(keyList=['return'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_3.keys = theseKeys.name # just the last key pressed
key_resp_3.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in RulesComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "Rules"-------
for thisComponent in RulesComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('text_6.started', text_6.tStartRefresh)
thisExp.addData('text_6.stopped', text_6.tStopRefresh)
# check responses
if key_resp_3.keys in ['', [], None]: # No response was made
key_resp_3.keys = None
thisExp.addData('key_resp_3.keys',key_resp_3.keys)
if key_resp_3.keys != None: # we had a response
thisExp.addData('key_resp_3.rt', key_resp_3.rt)
thisExp.addData('key_resp_3.started', key_resp_3.tStartRefresh)
thisExp.addData('key_resp_3.stopped', key_resp_3.tStopRefresh)
thisExp.nextEntry()
# the Routine "Rules" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('psychtest.xlsx'),
seed=None, name='trials')
thisExp.addLoop(trials) # add the loop to the experiment
thisTrial = trials.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
for paramName in thisTrial:
exec('{} = thisTrial[paramName]'.format(paramName))
for thisTrial in trials:
currentLoop = trials
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
for paramName in thisTrial:
exec('{} = thisTrial[paramName]'.format(paramName))
# ------Prepare to start Routine "plus"-------
routineTimer.add(0.200000)
# update component parameters for each repeat
# keep track of which components have finished
plusComponents = [text_4]
for thisComponent in plusComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
plusClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "plus"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = plusClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=plusClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text_4* updates
if text_4.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
text_4.frameNStart = frameN # exact frame index
text_4.tStart = t # local t and not account for scr refresh
text_4.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(text_4, 'tStartRefresh') # time at next scr refresh
text_4.setAutoDraw(True)
if text_4.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > text_4.tStartRefresh + 0.200-frameTolerance:
# keep track of stop time/frame for later
text_4.tStop = t # not accounting for scr refresh
text_4.frameNStop = frameN # exact frame index
win.timeOnFlip(text_4, 'tStopRefresh') # time at next scr refresh
text_4.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in plusComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "plus"-------
for thisComponent in plusComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials.addData('text_4.started', text_4.tStartRefresh)
trials.addData('text_4.stopped', text_4.tStopRefresh)
# ------Prepare to start Routine "Experiment1"-------
routineTimer.add(0.080000)
# update component parameters for each repeat
imageGuess.setImage(Image1)
# keep track of which components have finished
Experiment1Components = [imageGuess]
for thisComponent in Experiment1Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
Experiment1Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "Experiment1"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = Experiment1Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=Experiment1Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *imageGuess* updates
if imageGuess.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
imageGuess.frameNStart = frameN # exact frame index
imageGuess.tStart = t # local t and not account for scr refresh
imageGuess.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(imageGuess, 'tStartRefresh') # time at next scr refresh
imageGuess.setAutoDraw(True)
if imageGuess.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > imageGuess.tStartRefresh + 0.08-frameTolerance:
# keep track of stop time/frame for later
imageGuess.tStop = t # not accounting for scr refresh
imageGuess.frameNStop = frameN # exact frame index
win.timeOnFlip(imageGuess, 'tStopRefresh') # time at next scr refresh
imageGuess.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in Experiment1Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "Experiment1"-------
for thisComponent in Experiment1Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials.addData('imageGuess.started', imageGuess.tStartRefresh)
trials.addData('imageGuess.stopped', imageGuess.tStopRefresh)
# ------Prepare to start Routine "sound1"-------
routineTimer.add(0.100000)
# update component parameters for each repeat
# keep track of which components have finished
sound1Components = [image_2]
for thisComponent in sound1Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
sound1Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "sound1"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = sound1Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=sound1Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *image_2* updates
if image_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
image_2.frameNStart = frameN # exact frame index
image_2.tStart = t # local t and not account for scr refresh
image_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(image_2, 'tStartRefresh') # time at next scr refresh
image_2.setAutoDraw(True)
if image_2.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > image_2.tStartRefresh + 0.1-frameTolerance:
# keep track of stop time/frame for later
image_2.tStop = t # not accounting for scr refresh
image_2.frameNStop = frameN # exact frame index
win.timeOnFlip(image_2, 'tStopRefresh') # time at next scr refresh
image_2.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in sound1Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "sound1"-------
for thisComponent in sound1Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials.addData('image_2.started', image_2.tStartRefresh)
trials.addData('image_2.stopped', image_2.tStopRefresh)
# ------Prepare to start Routine "empty1"-------
routineTimer.add(2.000000)
# update component parameters for each repeat
key_resp_8.keys = []
key_resp_8.rt = []
# keep track of which components have finished
empty1Components = [text_8, key_resp_8]
for thisComponent in empty1Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
empty1Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "empty1"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = empty1Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=empty1Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text_8* updates
if text_8.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
text_8.frameNStart = frameN # exact frame index
text_8.tStart = t # local t and not account for scr refresh
text_8.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(text_8, 'tStartRefresh') # time at next scr refresh
text_8.setAutoDraw(True)
if text_8.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > text_8.tStartRefresh + 2.0-frameTolerance:
# keep track of stop time/frame for later
text_8.tStop = t # not accounting for scr refresh
text_8.frameNStop = frameN # exact frame index
win.timeOnFlip(text_8, 'tStopRefresh') # time at next scr refresh
text_8.setAutoDraw(False)
# *key_resp_8* updates
waitOnFlip = False
if key_resp_8.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_8.frameNStart = frameN # exact frame index
key_resp_8.tStart = t # local t and not account for scr refresh
key_resp_8.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_8, 'tStartRefresh') # time at next scr refresh
key_resp_8.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_8.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_8.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_8.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > key_resp_8.tStartRefresh + 2-frameTolerance:
# keep track of stop time/frame for later
key_resp_8.tStop = t # not accounting for scr refresh
key_resp_8.frameNStop = frameN # exact frame index
win.timeOnFlip(key_resp_8, 'tStopRefresh') # time at next scr refresh
key_resp_8.status = FINISHED
if key_resp_8.status == STARTED and not waitOnFlip:
theseKeys = key_resp_8.getKeys(keyList=['right', 'left'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_8.keys = theseKeys.name # just the last key pressed
key_resp_8.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in empty1Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "empty1"-------
for thisComponent in empty1Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials.addData('text_8.started', text_8.tStartRefresh)
trials.addData('text_8.stopped', text_8.tStopRefresh)
# check responses
if key_resp_8.keys in ['', [], None]: # No response was made
key_resp_8.keys = None
trials.addData('key_resp_8.keys',key_resp_8.keys)
if key_resp_8.keys != None: # we had a response
trials.addData('key_resp_8.rt', key_resp_8.rt)
trials.addData('key_resp_8.started', key_resp_8.tStartRefresh)
trials.addData('key_resp_8.stopped', key_resp_8.tStopRefresh)
thisExp.nextEntry()
# completed 1 repeats of 'trials'
# ------Prepare to start Routine "trial2"-------
# update component parameters for each repeat
key_resp_4.keys = []
key_resp_4.rt = []
# keep track of which components have finished
trial2Components = [text_3, key_resp_4]
for thisComponent in trial2Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
trial2Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "trial2"-------
while continueRoutine:
# get current time
t = trial2Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=trial2Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text_3* updates
if text_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
text_3.frameNStart = frameN # exact frame index
text_3.tStart = t # local t and not account for scr refresh
text_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(text_3, 'tStartRefresh') # time at next scr refresh
text_3.setAutoDraw(True)
# *key_resp_4* updates
waitOnFlip = False
if key_resp_4.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_4.frameNStart = frameN # exact frame index
key_resp_4.tStart = t # local t and not account for scr refresh
key_resp_4.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_4, 'tStartRefresh') # time at next scr refresh
key_resp_4.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_4.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_4.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_4.status == STARTED and not waitOnFlip:
theseKeys = key_resp_4.getKeys(keyList=['return'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_4.keys = theseKeys.name # just the last key pressed
key_resp_4.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trial2Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial2"-------
for thisComponent in trial2Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('text_3.started', text_3.tStartRefresh)
thisExp.addData('text_3.stopped', text_3.tStopRefresh)
# check responses
if key_resp_4.keys in ['', [], None]: # No response was made
key_resp_4.keys = None
thisExp.addData('key_resp_4.keys',key_resp_4.keys)
if key_resp_4.keys != None: # we had a response
thisExp.addData('key_resp_4.rt', key_resp_4.rt)
thisExp.addData('key_resp_4.started', key_resp_4.tStartRefresh)
thisExp.addData('key_resp_4.stopped', key_resp_4.tStopRefresh)
thisExp.nextEntry()
# the Routine "trial2" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "Rules2"-------
# update component parameters for each repeat
key_resp_5.keys = []
key_resp_5.rt = []
# keep track of which components have finished
Rules2Components = [text_7, key_resp_5]
for thisComponent in Rules2Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
Rules2Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "Rules2"-------
while continueRoutine:
# get current time
t = Rules2Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=Rules2Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text_7* updates
if text_7.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
text_7.frameNStart = frameN # exact frame index
text_7.tStart = t # local t and not account for scr refresh
text_7.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(text_7, 'tStartRefresh') # time at next scr refresh
text_7.setAutoDraw(True)
# *key_resp_5* updates
waitOnFlip = False
if key_resp_5.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_5.frameNStart = frameN # exact frame index
key_resp_5.tStart = t # local t and not account for scr refresh
key_resp_5.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_5, 'tStartRefresh') # time at next scr refresh
key_resp_5.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_5.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_5.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_5.status == STARTED and not waitOnFlip:
theseKeys = key_resp_5.getKeys(keyList=['return'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_5.keys = theseKeys.name # just the last key pressed
key_resp_5.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in Rules2Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "Rules2"-------
for thisComponent in Rules2Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('text_7.started', text_7.tStartRefresh)
thisExp.addData('text_7.stopped', text_7.tStopRefresh)
# check responses
if key_resp_5.keys in ['', [], None]: # No response was made
key_resp_5.keys = None
thisExp.addData('key_resp_5.keys',key_resp_5.keys)
if key_resp_5.keys != None: # we had a response
thisExp.addData('key_resp_5.rt', key_resp_5.rt)
thisExp.addData('key_resp_5.started', key_resp_5.tStartRefresh)
thisExp.addData('key_resp_5.stopped', key_resp_5.tStopRefresh)
thisExp.nextEntry()
# the Routine "Rules2" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
trials_2 = data.TrialHandler(nReps=1, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('psychtest.xlsx'),
seed=None, name='trials_2')
thisExp.addLoop(trials_2) # add the loop to the experiment
thisTrial_2 = trials_2.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial_2.rgb)
if thisTrial_2 != None:
for paramName in thisTrial_2:
exec('{} = thisTrial_2[paramName]'.format(paramName))
for thisTrial_2 in trials_2:
currentLoop = trials_2
# abbreviate parameter names if possible (e.g. rgb = thisTrial_2.rgb)
if thisTrial_2 != None:
for paramName in thisTrial_2:
exec('{} = thisTrial_2[paramName]'.format(paramName))
# ------Prepare to start Routine "Plus"-------
routineTimer.add(0.200000)
# update component parameters for each repeat
# keep track of which components have finished
PlusComponents = [text_5]
for thisComponent in PlusComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
PlusClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "Plus"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = PlusClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=PlusClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text_5* updates
if text_5.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
text_5.frameNStart = frameN # exact frame index
text_5.tStart = t # local t and not account for scr refresh
text_5.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(text_5, 'tStartRefresh') # time at next scr refresh
text_5.setAutoDraw(True)
if text_5.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > text_5.tStartRefresh + 0.2-frameTolerance:
# keep track of stop time/frame for later
text_5.tStop = t # not accounting for scr refresh
text_5.frameNStop = frameN # exact frame index
win.timeOnFlip(text_5, 'tStopRefresh') # time at next scr refresh
text_5.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in PlusComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "Plus"-------
for thisComponent in PlusComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials_2.addData('text_5.started', text_5.tStartRefresh)
trials_2.addData('text_5.stopped', text_5.tStopRefresh)
# ------Prepare to start Routine "Experiment2"-------
routineTimer.add(0.080000)
# update component parameters for each repeat
image.setImage(Image1)
# keep track of which components have finished
Experiment2Components = [image]
for thisComponent in Experiment2Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
Experiment2Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "Experiment2"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = Experiment2Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=Experiment2Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *image* updates
if image.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
image.frameNStart = frameN # exact frame index
image.tStart = t # local t and not account for scr refresh
image.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(image, 'tStartRefresh') # time at next scr refresh
image.setAutoDraw(True)
if image.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > image.tStartRefresh + 0.08-frameTolerance:
# keep track of stop time/frame for later
image.tStop = t # not accounting for scr refresh
image.frameNStop = frameN # exact frame index
win.timeOnFlip(image, 'tStopRefresh') # time at next scr refresh
image.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in Experiment2Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "Experiment2"-------
for thisComponent in Experiment2Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials_2.addData('image.started', image.tStartRefresh)
trials_2.addData('image.stopped', image.tStopRefresh)
# ------Prepare to start Routine "sound2"-------
routineTimer.add(0.100000)
# update component parameters for each repeat
# keep track of which components have finished
sound2Components = [image_3]
for thisComponent in sound2Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
sound2Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "sound2"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = sound2Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=sound2Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *image_3* updates
if image_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
image_3.frameNStart = frameN # exact frame index
image_3.tStart = t # local t and not account for scr refresh
image_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(image_3, 'tStartRefresh') # time at next scr refresh
image_3.setAutoDraw(True)
if image_3.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > image_3.tStartRefresh + 0.1-frameTolerance:
# keep track of stop time/frame for later
image_3.tStop = t # not accounting for scr refresh
image_3.frameNStop = frameN # exact frame index
win.timeOnFlip(image_3, 'tStopRefresh') # time at next scr refresh
image_3.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in sound2Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "sound2"-------
for thisComponent in sound2Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials_2.addData('image_3.started', image_3.tStartRefresh)
trials_2.addData('image_3.stopped', image_3.tStopRefresh)
# ------Prepare to start Routine "empty2"-------
routineTimer.add(2.000000)
# update component parameters for each repeat
key_resp_2.keys = []
key_resp_2.rt = []
# keep track of which components have finished
empty2Components = [text_10, key_resp_2]
for thisComponent in empty2Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
empty2Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "empty2"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = empty2Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=empty2Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text_10* updates
if text_10.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
text_10.frameNStart = frameN # exact frame index
text_10.tStart = t # local t and not account for scr refresh
text_10.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(text_10, 'tStartRefresh') # time at next scr refresh
text_10.setAutoDraw(True)
if text_10.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > text_10.tStartRefresh + 2.0-frameTolerance:
# keep track of stop time/frame for later
text_10.tStop = t # not accounting for scr refresh
text_10.frameNStop = frameN # exact frame index
win.timeOnFlip(text_10, 'tStopRefresh') # time at next scr refresh
text_10.setAutoDraw(False)
# *key_resp_2* updates
waitOnFlip = False
if key_resp_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_2.frameNStart = frameN # exact frame index
key_resp_2.tStart = t # local t and not account for scr refresh
key_resp_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_2, 'tStartRefresh') # time at next scr refresh
key_resp_2.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_2.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_2.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_2.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > key_resp_2.tStartRefresh + 2-frameTolerance:
# keep track of stop time/frame for later
key_resp_2.tStop = t # not accounting for scr refresh
key_resp_2.frameNStop = frameN # exact frame index
win.timeOnFlip(key_resp_2, 'tStopRefresh') # time at next scr refresh
key_resp_2.status = FINISHED
if key_resp_2.status == STARTED and not waitOnFlip:
theseKeys = key_resp_2.getKeys(keyList=['a', 's', 'h'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_2.keys = theseKeys.name # just the last key pressed
key_resp_2.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in empty2Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "empty2"-------
for thisComponent in empty2Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials_2.addData('text_10.started', text_10.tStartRefresh)
trials_2.addData('text_10.stopped', text_10.tStopRefresh)
# check responses
if key_resp_2.keys in ['', [], None]: # No response was made
key_resp_2.keys = None
trials_2.addData('key_resp_2.keys',key_resp_2.keys)
if key_resp_2.keys != None: # we had a response
trials_2.addData('key_resp_2.rt', key_resp_2.rt)
trials_2.addData('key_resp_2.started', key_resp_2.tStartRefresh)
trials_2.addData('key_resp_2.stopped', key_resp_2.tStopRefresh)
thisExp.nextEntry()
# completed 1 repeats of 'trials_2'
# ------Prepare to start Routine "Thankyou"-------
# update component parameters for each repeat
# keep track of which components have finished
ThankyouComponents = [text_2]
for thisComponent in ThankyouComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
ThankyouClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "Thankyou"-------
while continueRoutine:
# get current time
t = ThankyouClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=ThankyouClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text_2* updates
if text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
text_2.frameNStart = frameN # exact frame index
text_2.tStart = t # local t and not account for scr refresh
text_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(text_2, 'tStartRefresh') # time at next scr refresh
text_2.setAutoDraw(True)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in ThankyouComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "Thankyou"-------
for thisComponent in ThankyouComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('text_2.started', text_2.tStartRefresh)
thisExp.addData('text_2.stopped', text_2.tStopRefresh)
# the Routine "Thankyou" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 44.358753 | 375 | 0.663956 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 24,479 | 0.365921 |
8976ac3ed7f5bc537c2e56c41551cfde83e492fd | 1,996 | py | Python | two-phase-v2/OPE-master/run_ope.py | zizuzi/DeepEmbedding | d8762a94863fadced35b1dcc59996dcd02b1acaf | [
"MIT"
] | 1 | 2019-07-10T05:59:26.000Z | 2019-07-10T05:59:26.000Z | two-phase-v2/OPE-master/run_ope.py | zizuzi/DeepEmbedding | d8762a94863fadced35b1dcc59996dcd02b1acaf | [
"MIT"
] | 7 | 2019-03-20T00:28:15.000Z | 2021-09-07T23:48:46.000Z | two-phase-v2/OPE-master/run_ope.py | thaihungle/DeepTopicEmbedding | d8762a94863fadced35b1dcc59996dcd02b1acaf | [
"MIT"
] | null | null | null | import sys
sys.path.insert(0, './')
sys.path.insert(0, './common')
sys.path.insert(0, './ML-FW')
sys.path.insert(0, './ML-OPE')
sys.path.insert(0, './Online-FW')
sys.path.insert(0, './Online-OPE')
sys.path.insert(0, './Streaming-FW')
sys.path.insert(0, './Streaming-OPE')
import time
import shutil
import utilities as ut
import run_ML_FW as mfw
import run_ML_OPE as mope
import run_Online_FW as ofw
import run_Online_OPE as oope
import run_Streaming_FW as sfw
import run_Streaming_OPE as sope
import os.path
'''
example command: python run.py ./data2/news20.dat ./settings.txt ML-FW
'''
if __name__ == '__main__':
# Get environment variables
train_file = sys.argv[1]
setting_file = sys.argv[2]
algo_name = sys.argv[3]
test_data_folder = None
if len(sys.argv)==5:
test_data_folder = sys.argv[4]
dataname=train_file.split('/')[-1].split('.')[0]
modelname='./models/%s/%s' % (algo_name, dataname)
train_file2=train_file+'.unsup'
if os.path.isfile(train_file2):
ut.convert_multilabel_unsupervised(train_file,train_file2)
train_file=train_file2
numdoc, numterm=ut.count_data(train_file)
print numdoc, numterm
rf=open(setting_file,'r')
rf.readline()
rf.readline()
newstr='num_docs: %d\nnum_terms: %d\n'%(numdoc, numterm)
wf=open(setting_file,'w')
wf.write(newstr)
shutil.copyfileobj(rf,wf)
wf.close()
start_time=time.time()
if algo_name=='ML-FW':
mfw.run(train_file,setting_file,modelname,test_data_folder)
if algo_name=='ML-OPE':
mope.run(train_file,setting_file,modelname,test_data_folder)
if algo_name=='Online-FW':
ofw.run(train_file,setting_file,modelname,test_data_folder)
if algo_name=='Online-OPE':
oope.run(train_file,setting_file,modelname,test_data_folder)
if algo_name=='Streaming-FW':
sfw.run(train_file,setting_file,modelname,test_data_folder)
if algo_name=='Streaming-OPE':
sope.run(train_file,setting_file,modelname,test_data_folder)
print '-----%s seconds------' %(time.time()-start_time)
| 30.707692 | 70 | 0.726954 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 365 | 0.182866 |
8976b5f8cdf877569418f78ed284774690ac4102 | 1,006 | py | Python | tests/test_helper.py | swills/pykwalify | f96b76efb810d7d559254d0ec58de628e09f525a | [
"MIT"
] | 275 | 2015-01-03T18:22:05.000Z | 2022-03-29T13:18:28.000Z | tests/test_helper.py | swills/pykwalify | f96b76efb810d7d559254d0ec58de628e09f525a | [
"MIT"
] | 172 | 2015-01-15T11:17:23.000Z | 2022-03-25T13:49:06.000Z | tests/test_helper.py | swills/pykwalify | f96b76efb810d7d559254d0ec58de628e09f525a | [
"MIT"
] | 90 | 2015-01-15T09:00:15.000Z | 2021-07-17T00:23:00.000Z | # -*- coding: utf-8 -*-
# python std lib
import logging
import logging.config
log = logging.getLogger()
# Set the root logger to be silent so all code that uses the python logger
# will not print anything unless we want it to, then it should be specified
# in each test and reseted after that test
def _set_log_lv(level=1337, loggers=None):
""" If no level is set then level will be so high all logging is silenced
"""
if loggers is None:
# If no additional loggers is specified then only apply to root logger
log.setLevel(level)
for handler in log.handlers:
handler.level = level
else:
# If we have other logging instances specified apply to root logger and them
if log not in loggers:
loggers.append(log)
for log_instance in loggers:
log_instance.setLevel(level)
for handler in log_instance.handlers:
handler.level = level
# Initially silence all logging
_set_log_lv()
| 29.588235 | 84 | 0.66998 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 488 | 0.485089 |
8977bd7b64038385d9857845a7707789f51dd14d | 216 | py | Python | setup.py | mechyai/RL-EmsPy | 01984a9bc37f35991073e17cf715687896d6ea8d | [
"Apache-2.0"
] | 8 | 2022-03-15T13:22:22.000Z | 2022-03-30T09:58:04.000Z | setup.py | mechyai/RL-EmsPy | 01984a9bc37f35991073e17cf715687896d6ea8d | [
"Apache-2.0"
] | null | null | null | setup.py | mechyai/RL-EmsPy | 01984a9bc37f35991073e17cf715687896d6ea8d | [
"Apache-2.0"
] | null | null | null | from distutils.core import setup
setup(
name='RL-EmsPy',
version='0.0.1',
packages=['emspy'],
url='https://github.com/mechyai/RL-EmsPy',
license='Apache License 2.0',
author='Chris Eubel',
)
| 19.636364 | 46 | 0.62963 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 94 | 0.435185 |
897a56ea0416972cc519745819a41aaa3ab7c3b3 | 2,017 | py | Python | src/hyperloop/geometry/inlet.py | uwhl/Hyperloop | b00a1a6570e1c3d94b3e0ce95bad75892eb6caec | [
"Apache-2.0"
] | 1 | 2016-09-03T09:46:04.000Z | 2016-09-03T09:46:04.000Z | src/hyperloop/geometry/inlet.py | uwhl/Hyperloop | b00a1a6570e1c3d94b3e0ce95bad75892eb6caec | [
"Apache-2.0"
] | null | null | null | src/hyperloop/geometry/inlet.py | uwhl/Hyperloop | b00a1a6570e1c3d94b3e0ce95bad75892eb6caec | [
"Apache-2.0"
] | null | null | null | from math import pi, sqrt
from openmdao.core.component import Component
class InletGeom(Component):
'''Calculates the dimensions for the inlet and compressor entrance'''
def __init__(self):
super(InletGeom, self).__init__()
self.add_param('wall_thickness', 0.05, desc='thickness of inlet wall', units='m')
# self.add_param('area_in', 0.0, desc='flow area required at front of inlet', units='m**2')
self.add_param('area_out', 0.0, desc='flow area required at back of inlet', units='m**2')
self.add_param('hub_to_tip', 0.4, desc='hub to tip ratio for compressor')
self.add_param('cross_section', 1.4, desc='cross sectional area of passenger capsule', units='m**2')
self.add_param('tube_area', 2.33, desc='cross sectional area inside of tube', units='m**2')
self.add_output('r_back_inner', 0.0, desc='inner radius of back of inlet', units='m')
self.add_output('r_back_outer', 0.0, desc='outer radius of back of inlet', units='m')
self.add_output('bypass_area', 0.0, desc='available flow area round capsule', units='m**2')
self.add_output('area_frontal', 0.0, desc='total capsule frontal area', units='m**2')
def solve_nonlinear(self, params, unknowns, resids):
unknowns['r_back_inner'] = sqrt(params['area_out'] / pi / (1.0 - params['hub_to_tip'] ** 2))
unknowns['r_back_outer'] = unknowns['r_back_inner'] + params['wall_thickness']
unknowns['bypass_area'] = params['tube_area'] - params['cross_section']
unknowns['area_frontal'] = pi * (unknowns['r_back_outer']) ** 2
if __name__ == '__main__':
from openmdao.core.problem import Problem
from openmdao.core.group import Group
p = Problem(root=Group())
p.root.add('comp', InletGeom())
p.setup()
p.run()
for var_name, units in (('r_back_inner', 'm'), ('r_back_outer', 'm'), ('bypass_area', 'm**2'), ('area_frontal', 'm**2')):
print '%s (%s): %f' % (var_name, units, p.root.comp.unknowns[var_name])
| 53.078947 | 125 | 0.655429 | 1,526 | 0.756569 | 0 | 0 | 0 | 0 | 0 | 0 | 874 | 0.433317 |
897b0d5575db6738618190b9753ec16b27afe1e4 | 2,988 | py | Python | gza/gzatcp.py | ynadji/drop | 848107d4869963170a0c5e8c70ad3f53792d5e6f | [
"Unlicense"
] | 6 | 2015-04-13T16:51:13.000Z | 2019-04-21T12:10:55.000Z | gza/gzatcp.py | ynadji/drop | 848107d4869963170a0c5e8c70ad3f53792d5e6f | [
"Unlicense"
] | null | null | null | gza/gzatcp.py | ynadji/drop | 848107d4869963170a0c5e8c70ad3f53792d5e6f | [
"Unlicense"
] | null | null | null | #!/usr/bin/env python
#
# DNS gameplay
from scapy.all import *
import sys,os,time
import nfqueue
import socket
from gzacommon import GZA
# time.windows, damballa, damballa, local
WHITELIST_IPS = ["207.46.232.", "172.22.0.", "172.22.10.", "192.168.", "0.0.0.0", "255.255.255.255"]
seen_ips = []
class TCPGZA(GZA):
def __init__(self, vmnum, opts):
super(TCPGZA, self).__init__(vmnum, opts)
if self.game == 'dropn':
sys.stderr.write('--drop-n not implemented in %s, terminating\n'
% self.__class__.__name__)
sys.exit(2)
elif self.game == 'taken':
self.count = self.opts.taken
def remove_computed_fields(self, pkt):
del(pkt[IP].chksum)
del(pkt[TCP].chksum)
del(pkt[IP].len)
#del(pkt[TCP].len)
def rst(self, qpkt):
"""Returns TCP RST version of qpkt"""
p = qpkt.copy()
# ACK/RST
p[TCP].flags = 0x16
self.remove_computed_fields(p)
return Ether(dst=self.mac)/p
def reset(self, signum, frame):
if self.game == 'taken':
sys.stderr.write('Reset self.count in %s\n' % self.__class__.__name__)
self.count = self.opts.taken
super(TCPGZA, self).reset(signum, frame)
def forge(self, packet):
print('TCP RST for %s on %s' % (packet[IP].src, self.iface))
p = self.rst(packet)
sendp(p, iface=self.iface)
return True
# spoof function
def spoof(self, packet):
"""Spoof TCP streams with TCP RST"""
src_ip = packet[IP].src
print("%s: IP address: %s" % (self.iface, src_ip))
# IP for time.windows.com. See gzadns.py to see why this requires its
# own separate "whitelist".
if src_ip == '202.89.231.60':
return False
if self.opts.whitelist and self.whitelistedip(src_ip):
print('%s is whitelisted' % src_ip)
return False
if self.game == 'dropall':
return self.forge(packet)
elif self.game == 'taken':
# Game over, reject all.
if self.gamestate[src_ip] == 'whitelisted':
print("%s was a --take-n packet, accepting" % src_ip)
return False
elif self.count == 0:
return self.forge(packet)
else:
self.count -= 1
self.gamestate[src_ip] = 'whitelisted'
print('--take-n, let the packet through. %d more free packets left!'
% self.count)
return False
print('Fell through game ifelif chain, do not spoof')
return False
def playgame(self, payload):
"""docstring for main"""
data = payload.get_data()
packet = IP(data)
if self.spoof(packet):
payload.set_verdict(nfqueue.NF_DROP)
return
else:
payload.set_verdict(nfqueue.NF_ACCEPT)
return
| 31.125 | 100 | 0.553548 | 2,690 | 0.900268 | 0 | 0 | 0 | 0 | 0 | 0 | 766 | 0.256359 |
897b4e6d0cd4fcb2d42922fef3503586389e4297 | 170 | py | Python | static/images/uploads/convert-to-web.py | KrishSkywalker/krishgoel.com-v2 | a27f6bd9541f354a6ded37e6dcd9ca930c2264ff | [
"MIT"
] | null | null | null | static/images/uploads/convert-to-web.py | KrishSkywalker/krishgoel.com-v2 | a27f6bd9541f354a6ded37e6dcd9ca930c2264ff | [
"MIT"
] | 2 | 2021-10-09T06:50:53.000Z | 2021-10-09T06:56:21.000Z | static/images/uploads/convert-to-web.py | KrishSkywalker/krishgoel.com-v2 | a27f6bd9541f354a6ded37e6dcd9ca930c2264ff | [
"MIT"
] | null | null | null | import os
from cv2 import cv2
for d in os.listdir():
if not d.endswith(".png"): continue
img = cv2.imread(d)
cv2.imwrite(d.replace(".png",".webp"), img)
os.remove(d) | 21.25 | 44 | 0.670588 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 19 | 0.111765 |
897b64057889d6f4e8ff4affe28b5a7f47a4113d | 16,328 | bzl | Python | test/internal/opts/process_compiler_opts_tests.bzl | buildbuddy-io/rules_xcodeproj | 79a54779d530d3907a69a7910c71c06fec4aefeb | [
"MIT"
] | 30 | 2022-02-11T16:36:24.000Z | 2022-03-31T18:18:06.000Z | test/internal/opts/process_compiler_opts_tests.bzl | buildbuddy-io/rules_xcodeproj | 79a54779d530d3907a69a7910c71c06fec4aefeb | [
"MIT"
] | 93 | 2022-02-10T23:46:22.000Z | 2022-03-30T14:57:40.000Z | test/internal/opts/process_compiler_opts_tests.bzl | buildbuddy-io/rules_xcodeproj | 79a54779d530d3907a69a7910c71c06fec4aefeb | [
"MIT"
] | 3 | 2022-03-09T00:14:47.000Z | 2022-03-31T11:16:16.000Z | """Tests for compiler options processing functions."""
load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest")
load("//test:utils.bzl", "stringify_dict")
# buildifier: disable=bzl-visibility
load("//xcodeproj/internal:opts.bzl", "testable")
process_compiler_opts = testable.process_compiler_opts
def _process_compiler_opts_test_impl(ctx):
env = unittest.begin(ctx)
build_settings = {}
search_paths = process_compiler_opts(
conlyopts = ctx.attr.conlyopts,
cxxopts = ctx.attr.cxxopts,
full_swiftcopts = ctx.attr.full_swiftcopts,
user_swiftcopts = ctx.attr.user_swiftcopts,
package_bin_dir = ctx.attr.package_bin_dir,
build_settings = build_settings,
)
string_build_settings = stringify_dict(build_settings)
json_search_paths = json.encode(search_paths)
expected_build_settings = {
"SWIFT_OBJC_INTERFACE_HEADER_NAME": "",
"SWIFT_OPTIMIZATION_LEVEL": "-Onone",
"SWIFT_VERSION": "5",
}
expected_build_settings.update(ctx.attr.expected_build_settings)
asserts.equals(
env,
expected_build_settings,
string_build_settings,
"build_settings",
)
asserts.equals(
env,
ctx.attr.expected_search_paths,
json_search_paths,
"search_paths",
)
return unittest.end(env)
process_compiler_opts_test = unittest.make(
impl = _process_compiler_opts_test_impl,
attrs = {
"conlyopts": attr.string_list(mandatory = True),
"cxxopts": attr.string_list(mandatory = True),
"expected_build_settings": attr.string_dict(mandatory = True),
"expected_search_paths": attr.string(mandatory = True),
"package_bin_dir": attr.string(mandatory = True),
"full_swiftcopts": attr.string_list(mandatory = True),
"user_swiftcopts": attr.string_list(mandatory = True),
},
)
def process_compiler_opts_test_suite(name):
"""Test suite for `process_compiler_opts`.
Args:
name: The base name to be used in things created by this macro. Also the
name of the test suite.
"""
test_names = []
def _add_test(
*,
name,
expected_build_settings,
expected_search_paths = {"quote_includes": [], "includes": [], "system_includes": []},
conlyopts = [],
cxxopts = [],
full_swiftcopts = [],
user_swiftcopts = [],
package_bin_dir = ""):
test_names.append(name)
process_compiler_opts_test(
name = name,
conlyopts = conlyopts,
cxxopts = cxxopts,
full_swiftcopts = full_swiftcopts,
user_swiftcopts = user_swiftcopts,
package_bin_dir = package_bin_dir,
expected_build_settings = stringify_dict(expected_build_settings),
expected_search_paths = json.encode(expected_search_paths),
timeout = "short",
)
# Base
_add_test(
name = "{}_swift_integration".format(name),
full_swiftcopts = [
"-target",
"arm64-apple-ios15.0-simulator",
"-sdk",
"__BAZEL_XCODE_SDKROOT__",
"-F__BAZEL_XCODE_DEVELOPER_DIR__/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks",
"-F__BAZEL_XCODE_SDKROOT__/Developer/Library/Frameworks",
"-I__BAZEL_XCODE_DEVELOPER_DIR__/Platforms/iPhoneSimulator.platform/Developer/usr/lib",
"-emit-object",
"-output-file-map",
"bazel-out/ios-sim_arm64-min15.0-applebin_ios-ios_sim_arm64-fastbuild-ST-4e6c2a19403f/bin/examples/ExampleUITests/ExampleUITests.library.output_file_map.json",
"-Xfrontend",
"-no-clang-module-breadcrumbs",
"-emit-module-path",
"bazel-out/ios-sim_arm64-min15.0-applebin_ios-ios_sim_arm64-fastbuild-ST-4e6c2a19403f/bin/examples/ExampleUITests/ExampleUITests.swiftmodule",
"-DDEBUG",
"-Onone",
"-Xfrontend",
"-serialize-debugging-options",
"-enable-testing",
"-application-extension",
"weird",
"-gline-tables-only",
"-Xwrapped-swift=-debug-prefix-pwd-is-dot",
"-Xwrapped-swift=-ephemeral-module-cache",
"-Xcc",
"-iquote.",
"-Xcc",
"-iquotebazel-out/ios-sim_arm64-min15.0-applebin_ios-ios_sim_arm64-fastbuild-ST-4e6c2a19403f/bin",
"-Xfrontend",
"-color-diagnostics",
"-enable-batch-mode",
"-unhandled",
"-module-name",
"ExampleUITests",
"-parse-as-library",
"-Xcc",
"-O0",
"-Xcc",
"-DDEBUG=1",
"examples/xcode_like/ExampleUITests/ExampleUITests.swift",
"examples/xcode_like/ExampleUITests/ExampleUITestsLaunchTests.swift",
],
user_swiftcopts = [],
expected_build_settings = {
"ENABLE_TESTABILITY": "True",
"APPLICATION_EXTENSION_API_ONLY": "True",
"OTHER_SWIFT_FLAGS": "weird -unhandled",
"SWIFT_ACTIVE_COMPILATION_CONDITIONS": "DEBUG",
},
)
_add_test(
name = "{}_empty".format(name),
conlyopts = [],
cxxopts = [],
full_swiftcopts = [],
user_swiftcopts = [],
expected_build_settings = {},
)
# Skips
## C and C++
# Anything with __BAZEL_XCODE_
# -isysroot
# -mios-simulator-version-min
# -miphoneos-version-min
# -mmacosx-version-min
# -mtvos-simulator-version-min
# -mtvos-version-min
# -mwatchos-simulator-version-min
# -mwatchos-version-min
# -target
## Swift:
# Anything with __BAZEL_XCODE_
# -Ipath
# -emit-module-path
# -emit-object
# -enable-batch-mode
# -gline-tables-only
# -module-name
# -num-threads
# -output-file-map
# -parse-as-library
# -sdk
# -target
# -Xcc
# -Xfrontend
# -Xwrapped-swift
# Other things that end with ".swift", but don't start with "-"
_add_test(
name = "{}_skips".format(name),
conlyopts = [
"-mtvos-simulator-version-min=8.0",
"-passthrough",
"-isysroot",
"other",
"-mios-simulator-version-min=11.2",
"-miphoneos-version-min=9.0",
"-passthrough",
"-mtvos-version-min=12.1",
"-I__BAZEL_XCODE_SOMETHING_/path",
"-mwatchos-simulator-version-min=10.1",
"-passthrough",
"-mwatchos-version-min=9.2",
"-target",
"ios",
"-mmacosx-version-min=12.0",
"-passthrough",
],
cxxopts = [
"-isysroot",
"something",
"-miphoneos-version-min=9.4",
"-mmacosx-version-min=10.9",
"-passthrough",
"-mtvos-version-min=12.2",
"-mwatchos-simulator-version-min=9.3",
"-passthrough",
"-mtvos-simulator-version-min=12.1",
"-mwatchos-version-min=10.2",
"-I__BAZEL_XCODE_BOSS_",
"-target",
"macos",
"-passthrough",
"-mios-simulator-version-min=14.0",
],
full_swiftcopts = [
"-output-file-map",
"path",
"-passthrough",
"-emit-module-path",
"path",
"-passthrough",
"-Xfrontend",
"-hidden",
"-emit-object",
"-enable-batch-mode",
"-passthrough",
"-gline-tables-only",
"-sdk",
"something",
"-module-name",
"name",
"-passthrough",
"-I__BAZEL_XCODE_SOMETHING_/path",
"-num-threads",
"6",
"-passthrough",
"-Ibazel-out/...",
"-parse-as-library",
"-passthrough",
"-parse-as-library",
"-keep-me=something.swift",
"reject-me.swift",
"-target",
"ios",
"-Xcc",
"-weird",
"-Xwrapped-swift",
"-passthrough",
],
expected_build_settings = {
"OTHER_CFLAGS": [
"-passthrough",
"-passthrough",
"-passthrough",
"-passthrough",
],
"OTHER_CPLUSPLUSFLAGS": [
"-passthrough",
"-passthrough",
"-passthrough",
],
"OTHER_SWIFT_FLAGS": """\
-passthrough \
-passthrough \
-passthrough \
-passthrough \
-passthrough \
-passthrough \
-keep-me=something.swift \
-passthrough\
""",
},
)
# Specific Xcode build settings
# CLANG_CXX_LANGUAGE_STANDARD
_add_test(
name = "{}_options-std".format(name),
conlyopts = ["-std=c++42"],
cxxopts = ["-std=c++42"],
expected_build_settings = {
"CLANG_CXX_LANGUAGE_STANDARD": "c++42",
"OTHER_CFLAGS": ["-std=c++42"],
},
)
_add_test(
name = "{}_options-std=c++0x".format(name),
cxxopts = ["-std=c++11"],
expected_build_settings = {
"CLANG_CXX_LANGUAGE_STANDARD": "c++0x",
},
)
# CLANG_CXX_LIBRARY
_add_test(
name = "{}_options-stdlib".format(name),
conlyopts = ["-stdlib=random"],
cxxopts = ["-stdlib=random"],
expected_build_settings = {
"CLANG_CXX_LIBRARY": "random",
"OTHER_CFLAGS": ["-stdlib=random"],
},
)
## ENABLE_TESTABILITY
_add_test(
name = "{}_swift_option-enable-testing".format(name),
full_swiftcopts = ["-enable-testing"],
expected_build_settings = {
"ENABLE_TESTABILITY": "True",
},
)
## APPLICATION_EXTENSION_API_ONLY
_add_test(
name = "{}_swift_option-application-extension".format(name),
full_swiftcopts = ["-application-extension"],
expected_build_settings = {
"APPLICATION_EXTENSION_API_ONLY": "True",
},
)
## GCC_OPTIMIZATION_LEVEL
_add_test(
name = "{}_differing_gcc_optimization_level".format(name),
conlyopts = ["-O0"],
cxxopts = ["-O1"],
expected_build_settings = {
"OTHER_CFLAGS": ["-O0"],
"OTHER_CPLUSPLUSFLAGS": ["-O1"],
},
)
_add_test(
name = "{}_differing_gcc_optimization_level_common_first".format(name),
conlyopts = ["-O1", "-O0"],
cxxopts = ["-O1", "-O2"],
expected_build_settings = {
"GCC_OPTIMIZATION_LEVEL": "1",
"OTHER_CFLAGS": ["-O0"],
"OTHER_CPLUSPLUSFLAGS": ["-O2"],
},
)
_add_test(
name = "{}_multiple_gcc_optimization_levels".format(name),
conlyopts = ["-O1", "-O0"],
cxxopts = ["-O0", "-O1"],
expected_build_settings = {
"OTHER_CFLAGS": ["-O1", "-O0"],
"OTHER_CPLUSPLUSFLAGS": ["-O0", "-O1"],
},
)
_add_test(
name = "{}_common_gcc_optimization_level".format(name),
conlyopts = ["-O1"],
cxxopts = ["-O1"],
expected_build_settings = {
"GCC_OPTIMIZATION_LEVEL": "1",
},
)
## GCC_PREPROCESSOR_DEFINITIONS
_add_test(
name = "{}_gcc_optimization_preprocessor_definitions".format(name),
conlyopts = ["-DDEBUG", "-DDEBUG", "-DA=1", "-DZ=1", "-DB", "-DE"],
cxxopts = ["-DDEBUG", "-DDEBUG", "-DA=1", "-DZ=2", "-DC", "-DE"],
expected_build_settings = {
"GCC_PREPROCESSOR_DEFINITIONS": ["DEBUG", "A=1"],
"OTHER_CFLAGS": ["-DZ=1", "-DB", "-DE"],
"OTHER_CPLUSPLUSFLAGS": ["-DZ=2", "-DC", "-DE"],
},
)
## SWIFT_ACTIVE_COMPILATION_CONDITIONS
_add_test(
name = "{}_defines".format(name),
full_swiftcopts = [
"-DDEBUG",
"-DBAZEL",
"-DDEBUG",
"-DBAZEL",
],
expected_build_settings = {
"SWIFT_ACTIVE_COMPILATION_CONDITIONS": "DEBUG BAZEL",
},
)
## SWIFT_COMPILATION_MODE
_add_test(
name = "{}_multiple_swift_compilation_modes".format(name),
full_swiftcopts = [
"-wmo",
"-no-whole-module-optimization",
],
expected_build_settings = {
"SWIFT_COMPILATION_MODE": "singlefile",
},
)
_add_test(
name = "{}_swift_option-incremental".format(name),
full_swiftcopts = ["-incremental"],
expected_build_settings = {
"SWIFT_COMPILATION_MODE": "singlefile",
},
)
_add_test(
name = "{}_swift_option-whole-module-optimization".format(name),
full_swiftcopts = ["-whole-module-optimization"],
expected_build_settings = {
"SWIFT_COMPILATION_MODE": "wholemodule",
},
)
_add_test(
name = "{}_swift_option-wmo".format(name),
full_swiftcopts = ["-wmo"],
expected_build_settings = {
"SWIFT_COMPILATION_MODE": "wholemodule",
},
)
_add_test(
name = "{}_swift_option-no-whole-module-optimization".format(name),
full_swiftcopts = ["-no-whole-module-optimization"],
expected_build_settings = {
"SWIFT_COMPILATION_MODE": "singlefile",
},
)
## SWIFT_OBJC_INTERFACE_HEADER_NAME
_add_test(
name = "{}_generated_header".format(name),
full_swiftcopts = [
"-emit-objc-header-path",
"a/b/c/TestingUtils-Custom.h",
],
package_bin_dir = "a/b",
expected_build_settings = {
"SWIFT_OBJC_INTERFACE_HEADER_NAME": "c/TestingUtils-Custom.h",
},
)
## SWIFT_OPTIMIZATION_LEVEL
_add_test(
name = "{}_multiple_swift_optimization_levels".format(name),
full_swiftcopts = [
"-Osize",
"-Onone",
"-O",
],
expected_build_settings = {
"SWIFT_OPTIMIZATION_LEVEL": "-O",
},
)
_add_test(
name = "{}_swift_option-Onone".format(name),
full_swiftcopts = ["-Onone"],
expected_build_settings = {
"SWIFT_OPTIMIZATION_LEVEL": "-Onone",
},
)
_add_test(
name = "{}_swift_option-O".format(name),
full_swiftcopts = ["-O"],
expected_build_settings = {
"SWIFT_OPTIMIZATION_LEVEL": "-O",
},
)
_add_test(
name = "{}_swift_option-Osize".format(name),
full_swiftcopts = ["-Osize"],
expected_build_settings = {
"SWIFT_OPTIMIZATION_LEVEL": "-Osize",
},
)
## SWIFT_VERSION
_add_test(
name = "{}_swift_option-swift-version".format(name),
full_swiftcopts = ["-swift-version=42"],
expected_build_settings = {
"SWIFT_VERSION": "42",
},
)
# Search Paths
_add_test(
name = "{}_search_paths".format(name),
conlyopts = [
"-iquote",
"a/b/c",
"-Ix/y/z",
"-I",
"1/2/3",
"-iquote",
"0/9",
"-isystem",
"s1/s2",
],
cxxopts = [
"-iquote",
"y/z",
"-Ix/y/z",
"-I",
"aa/bb",
"-isystem",
"s3/s4",
],
user_swiftcopts = ["-Xcc", "-Ic/d/e", "-Xcc", "-iquote4/5", "-Xcc", "-isystems5/s6"],
expected_build_settings = {},
expected_search_paths = {
"quote_includes": [
"a/b/c",
"0/9",
"y/z",
"4/5",
],
"includes": [
"x/y/z",
"1/2/3",
"aa/bb",
"c/d/e",
],
"system_includes": [
"s1/s2",
"s3/s4",
"s5/s6",
],
},
)
# Test suite
native.test_suite(
name = name,
tests = test_names,
)
| 28.545455 | 171 | 0.524008 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6,945 | 0.425343 |
897d57f6cf656888dc6cf65082c8947d3a604a80 | 58,821 | py | Python | nltk-drt/src/presuppdrt.py | napsternxg/nltk-drt | 71a1218847b5bcc623f72151d36cad8528ee2b19 | [
"Apache-2.0"
] | 1 | 2017-06-22T17:11:23.000Z | 2017-06-22T17:11:23.000Z | nltk-drt/src/presuppdrt.py | napsternxg/nltk-drt | 71a1218847b5bcc623f72151d36cad8528ee2b19 | [
"Apache-2.0"
] | null | null | null | nltk-drt/src/presuppdrt.py | napsternxg/nltk-drt | 71a1218847b5bcc623f72151d36cad8528ee2b19 | [
"Apache-2.0"
] | 3 | 2021-11-20T09:52:59.000Z | 2022-03-31T13:09:48.000Z | """
NLTK DRT module extended with presuppositions
"""
__author__ = "Alex Kislev, Emma Li, Peter Makarov"
__version__ = "1.0"
__date__ = "Tue, 24 Aug 2010"
import re
import operator
from nltk.sem.logic import Variable
from nltk.sem.logic import EqualityExpression, ApplicationExpression, ExistsExpression, AndExpression
from nltk.sem.logic import IndividualVariableExpression
from nltk.sem.logic import _counter, is_eventvar, is_funcvar
from nltk.sem.logic import BasicType
from nltk.sem.logic import Expression
from nltk.sem.logic import ParseException
from nltk.sem.drt import DrsDrawer, AnaphoraResolutionException
import nltk.sem.drt as drt
class TimeType(BasicType):
"""
Basic type of times added on top of nltk.sem.logic.
"""
def __str__(self):
return 'i'
def str(self):
return 'TIME'
TIME_TYPE = TimeType()
class StateType(BasicType):
"""
Basic type of states added on top of nltk.sem.logic.
"""
def __str__(self):
return 's'
def str(self):
return 'STATE'
STATE_TYPE = StateType()
def is_indvar(expr):
"""
An individual variable must be a single lowercase character other than 'e', 't', 'n', 's',
followed by zero or more digits.
@param expr: C{str}
@return: C{boolean} True if expr is of the correct form
"""
assert isinstance(expr, str), "%s is not a string" % expr
return re.match(r'^[a-df-mo-ru-z]\d*$', expr)
def is_timevar(expr):
"""
An time variable must be a single lowercase 't' or 'n' character followed by
zero or more digits. Do we need a separate type for utterance time n?
@param expr: C{str}
@return: C{boolean} True if expr is of the correct form
"""
assert isinstance(expr, str), "%s is not a string" % expr
return re.match(r'^[tn]\d*$', expr)
def is_statevar(expr):
"""
An state variable must be a single lowercase 's' character followed by
zero or more digits.
@param expr: C{str}
@return: C{boolean} True if expr is of the correct form
"""
assert isinstance(expr, str), "%s is not a string" % expr
return re.match(r'^s\d*$', expr)
def is_uttervar(expr):
"""
An utterance time variable must be a single lowercase 'n' character followed by
zero or more digits.
@param expr: C{str}
@return: C{boolean} True if expr is of the correct form
"""
assert isinstance(expr, str), "%s is not a string" % expr
return re.match(r'^n\d*$', expr)
def unique_variable(pattern=None, ignore=None):
"""
Return a new, unique variable.
param pattern: C{Variable} that is being replaced. The new variable must
be the same type.
param term: a C{set} of C{Variable}s that should not be returned from
this function.
return: C{Variable}
"""
if pattern is not None:
if is_indvar(pattern.name):
prefix = 'z'
elif is_funcvar(pattern.name):
prefix = 'F'
elif is_eventvar(pattern.name):
prefix = 'e0'
elif is_timevar(pattern.name):
prefix = 't0'
elif is_statevar(pattern.name):
prefix = 's0'
else:
assert False, "Cannot generate a unique constant"
else:
prefix = 'z'
v = Variable(prefix + str(_counter.get()))
while ignore is not None and v in ignore:
v = Variable(prefix + str(_counter.get()))
return v
class TimeVariableExpression(IndividualVariableExpression):
"""This class represents variables that take the form of a single lowercase
'i' character followed by zero or more digits."""
type = TIME_TYPE
class StateVariableExpression(IndividualVariableExpression):
"""This class represents variables that take the form of a single lowercase
's' character followed by zero or more digits."""
type = STATE_TYPE
def is_unary_predicate(expr):
"""check whether the given expression is an unary predicate"""
return isinstance(expr, DrtApplicationExpression) and isinstance(expr.function, DrtAbstractVariableExpression)
class ReverseIterator:
"""A generator which yields the given sequence in a reverse order"""
def __init__(self, sequence, start= -1):
self.sequence = sequence
self.start = start
def __iter__(self):
if self.start > 0:
i = self.start + 1
else:
i = len(self.sequence) + self.start + 1
while i > 0:
i -= 1
yield self.sequence[i]
class Reading(list):
"""
A single reading, consists of a list of operations
each operation is a tuple of a DRS and a function,
where the function would be executed on the given DRS
when the reading is generated
"""
pass
class Binding(Reading):
pass
class LocalAccommodation(Reading):
pass
class IntermediateAccommodation(Reading):
pass
class GlobalAccommodation(Reading):
pass
class VariableReplacer(object):
"""A generic variable replacer functor to be used in readings"""
def __init__(self, var, new_var, remove_ref=True):
self.var = var
self.new_var = new_var
self.remove_ref = remove_ref
def __call__(self, drs):
if self.remove_ref:
drs.refs.remove(self.var)
return drs.__class__(drs.refs, [cond.replace(self.var, self.new_var, False) for cond in drs.conds])
class ConditionReplacer(object):
"""
A generic condition replacer functor to be used in readings
replace the condition at the given index with any number of
conditions, optionally adds a referent
"""
def __init__(self, index, conds, ref=None):
self.index = index
self.conds = conds
self.ref = ref
def __call__(self, drs):
if self.ref:
drs.refs.append(self.ref)
drs.conds[self.index:self.index + 1] = self.conds
return drs
class ConditionRemover(object):
"""A generic condition remover functor to be used in readings"""
def __init__(self, cond_index):
self.cond_index = cond_index
def __call__(self, drs):
drs.conds.pop(self.cond_index)
return drs
class ResolutionException(Exception):
pass
class DrtTokens(drt.DrtTokens):
OPEN_BRACE = '{'
CLOSE_BRACE = '}'
PUNCT = [OPEN_BRACE, CLOSE_BRACE]
SYMBOLS = drt.DrtTokens.SYMBOLS + PUNCT
TOKENS = drt.DrtTokens.TOKENS + PUNCT
NEWINFO_DRS = 'NEWINFO'
PROPER_NAME_DRS = 'PROP'
DEFINITE_DESCRIPTION_DRS = 'DEF'
PRONOUN_DRS = 'PRON'
PRESUPPOSITION_DRS = [PROPER_NAME_DRS, DEFINITE_DESCRIPTION_DRS, PRONOUN_DRS]
PRONOUN = 'PRO'
REFLEXIVE_PRONOUN = 'RPRO'
POSSESSIVE_PRONOUN = 'PPRO'
class AbstractDrs(drt.AbstractDrs):
"""
A base abstract DRT Expression from which every DRT Expression inherits.
"""
def applyto(self, other):
return DrtApplicationExpression(self, other)
def __neg__(self):
return DrtNegatedExpression(self)
def __or__(self, other):
assert isinstance(other, AbstractDrs)
return DrtOrExpression(self, other)
def __gt__(self, other):
assert isinstance(other, AbstractDrs)
return DrtImpExpression(self, other)
def __lt__(self, other):
assert isinstance(other, AbstractDrs)
return DrtIffExpression(self, other)
def __add__(self, other):
return ConcatenationDRS(self, other)
def __deepcopy__(self, memo):
return self.deepcopy()
def make_EqualityExpression(self, first, second):
return DrtEqualityExpression(first, second)
def make_VariableExpression(self, variable):
return DrtVariableExpression(variable)
def normalize(self):
"""Rename auto-generated unique variables"""
def f(e):
if isinstance(e, Variable):
if re.match(r'^z\d+$', e.name) or re.match(r'^[est]0\d+$', e.name):
return set([e])
else:
return set([])
else:
combinator = lambda * parts: reduce(operator.or_, parts)
return e.visit(f, combinator, set())
result = self
for i, v in enumerate(sorted(list(f(self)))):
if is_eventvar(v.name):
newVar = 'e0%s' % (i + 1)
elif is_timevar(v.name):
newVar = 't0%s' % (i + 1)
elif is_statevar(v.name):
newVar = 's0%s' % (i + 1)
else:
newVar = 'z%s' % (i + 1)
result = result.replace(v,
self.make_VariableExpression(Variable(newVar)), True)
return result
def substitute_bindings(self, bindings):
expr = self
for var in expr.variables():
val = bindings.get(var, None)
if val:
if isinstance(val, Variable):
val = DrtVariableExpression(val)
elif isinstance(val, Expression):
val = val.substitute_bindings(bindings)
elif isinstance(val, str):
val = DrtFeatureExpression(Variable(val))
else:
raise ValueError('Can not substitute a non-expression '
'value into an expression: %r' % (val,))
expr = expr.replace(var, val)
return expr.simplify()
RESOLUTION_ORDER = {Binding:0,
GlobalAccommodation:1,
IntermediateAccommodation:2,
LocalAccommodation:3}
def resolve(self, inference_check=None, verbose=False):
"""
This method does the whole job of collecting multiple readings.
We aim to get new readings from the old ones by resolving
presuppositional DRSs one by one. Every time one presupposition
is resolved, new readings are created and replace the old ones,
until there are no presuppositions left to resolve.
"""
readings = []
errors = []
if inference_check:
failed_readings = []
def traverse(base_reading, operations):
for operation in sorted(operations, key=lambda o: AbstractDrs.RESOLUTION_ORDER[type(o)]):
new_reading = base_reading.deepcopy(operation)
if verbose:
print("reading: %s" % new_reading)
try:
new_operations = new_reading.readings()
except Exception as ex:
errors.append(str(ex))
continue
if not new_operations:
if inference_check:
success, error = inference_check(new_reading)
if success:
readings.append(new_reading)
return True
else:
failed_readings.append((new_reading, error))
else:
readings.append(new_reading)
else:
if traverse(new_reading, new_operations[0]):
if len(operations) == 1 or AbstractDrs.RESOLUTION_ORDER[type(operation)] != 0:
return True
return False
operations = self.readings()
if operations:
traverse(self, operations[0])
else:
return [self]
if not readings and errors:
raise ResolutionException(". ".join(errors))
return readings, failed_readings if inference_check else readings
def readings(self, trail=[]):
raise NotImplementedError()
class DRS(AbstractDrs, drt.DRS):
"""A Temporal Discourse Representation Structure."""
def fol(self):
if not self.conds:
raise Exception("Cannot convert DRS with no conditions to FOL.")
accum = reduce(AndExpression, [c.fol() for c in self.conds])
for ref in ReverseIterator(self.refs):
accum = ExistsExpression(ref, AndExpression(accum, self._ref_type(ref).fol()))
return accum
def _ref_type(self, referent):
"""Checks a referent type and returns corresponding predicate"""
ref_cond = None
if is_eventvar(referent.name):
ref_cond = drt.DrtConstantExpression(Variable("event"))
elif is_statevar(referent.name):
ref_cond = drt.DrtConstantExpression(Variable("state"))
elif is_timevar(referent.name):
ref_cond = drt.DrtConstantExpression(Variable("time"))
else:
ref_cond = drt.DrtConstantExpression(Variable("individual"))
return DrtApplicationExpression(ref_cond, DrtAbstractVariableExpression(referent))
def replace(self, variable, expression, replace_bound=False):
"""Replace all instances of variable v with expression E in self,
where v is free in self."""
if variable in self.get_refs():
#if a bound variable is the thing being replaced
if not replace_bound:
return self
else:
if variable in self.refs:
i = self.refs.index(variable)
refs = self.refs[:i] + [expression.variable] + self.refs[i + 1:]
else:
refs = self.refs
return self.__class__(refs,
[cond.replace(variable, expression, True) for cond in self.conds])
else:
#variable not bound by this DRS
# any bound variable that appears in the expression must
# be alpha converted to avoid a conflict
for ref in (set(self.get_refs()) & expression.free()):
newvar = unique_variable(ref)
newvarex = DrtVariableExpression(newvar)
if ref in self.refs:
i = self.refs.index(ref)
refs = self.refs[:i] + [newvar] + self.refs[i + 1:]
else:
refs = self.refs
self = self.__class__(refs,
[cond.replace(ref, newvarex, True)
for cond in self.conds])
#replace in the conditions
return self.__class__(self.refs,
[cond.replace(variable, expression, replace_bound)
for cond in self.conds])
def free(self, indvar_only=True):
"""@see: Expression.free()"""
conds_free = reduce(operator.or_,
[c.free(indvar_only) for c in self.conds], set())
return conds_free - (set(self.refs) | reduce(operator.or_, [set(c.refs) for c in self.conds if isinstance(c, PresuppositionDRS)], set()))
def get_refs(self, recursive=False):
"""@see: AbstractExpression.get_refs()"""
if recursive:
cond_refs = reduce(operator.add,
[c.get_refs(True) for c in self.conds], [])
return self.refs + cond_refs
else:
return self.refs + reduce(operator.add, [c.refs for c in self.conds if isinstance(c, PresuppositionDRS)], [])
def deepcopy(self, operations=[]):
"""This method returns a deep copy of the DRS.
Optionally, it can take a list of lists of tuples (DRS, function)
as an argument and generate a reading by performing
a substitution in the DRS as specified by the function.
@param operations: a list of lists of tuples
"""
functions = [function for drs, function in operations if drs is self]
newdrs = self.__class__(list(self.refs), [cond.deepcopy(operations) for cond in self.conds])
for function in functions:
newdrs = function(newdrs)
return newdrs
def simplify(self):
return self.__class__(self.refs, [cond.simplify() for cond in self.conds])
def readings(self, trail=[]):
"""get the readings for this DRS"""
for i, cond in enumerate(self.conds):
_readings = cond.readings(trail + [self])
if _readings:
if _readings[1]:
for reading in _readings[0]:
reading.append((self, ConditionRemover(i)))
return _readings[0], False
def str(self, syntax=DrtTokens.NLTK):
if syntax == DrtTokens.PROVER9:
return self.fol().str(syntax)
else:
return '([%s],[%s])' % (','.join([str(r) for r in self.refs]),
', '.join([c.str(syntax) for c in self.conds]))
def DrtVariableExpression(variable):
"""
This is a factory method that instantiates and returns a subtype of
C{DrtAbstractVariableExpression} appropriate for the given variable.
"""
if is_indvar(variable.name):
return DrtIndividualVariableExpression(variable)
elif is_funcvar(variable.name):
return DrtFunctionVariableExpression(variable)
elif is_eventvar(variable.name):
return DrtEventVariableExpression(variable)
elif is_statevar(variable.name):
return DrtStateVariableExpression(variable)
elif is_uttervar(variable.name):
return DrtUtterVariableExpression(variable)
elif is_timevar(variable.name):
return DrtTimeVariableExpression(variable)
else:
return DrtConstantExpression(variable)
class DrtAbstractVariableExpression(AbstractDrs, drt.DrtAbstractVariableExpression):
def readings(self, trail=[]):
return None
def deepcopy(self, operations=[]):
return self.__class__(self.variable)
class DrtIndividualVariableExpression(DrtAbstractVariableExpression, drt.DrtIndividualVariableExpression):
pass
class DrtFunctionVariableExpression(DrtAbstractVariableExpression, drt.DrtFunctionVariableExpression):
pass
class DrtEventVariableExpression(DrtIndividualVariableExpression, drt.DrtEventVariableExpression):
pass
class DrtTimeVariableExpression(DrtIndividualVariableExpression, TimeVariableExpression):
"""expression of discourse referents of time"""
pass
class DrtStateVariableExpression(DrtIndividualVariableExpression, StateVariableExpression):
"""expression of discourse referents of state"""
pass
class DrtConstantExpression(DrtAbstractVariableExpression, drt.DrtConstantExpression):
pass
class DrtUtterVariableExpression(DrtTimeVariableExpression):
"""expression of utterance time referent"""
pass
class DrtFeatureExpression(DrtConstantExpression):
"""expression for a single syntactic feature"""
pass
class DrtFeatureConstantExpression(DrtConstantExpression):
"""A constant expression with syntactic features attached"""
def __init__(self, variable, features):
DrtConstantExpression.__init__(self, variable)
self.features = features
def replace(self, variable, expression, replace_bound=False):
"""@see: Expression.replace()"""
assert isinstance(variable, Variable), "%s is not a Variable" % variable
assert isinstance(expression, Expression), "%s is not an Expression" % expression
return self.__class__(DrtConstantExpression.replace(self, variable, expression, replace_bound).variable, [feature.replace(variable, expression, replace_bound) for feature in self.features])
def visit(self, function, combinator, default):
"""@see: Expression.visit()"""
re = combinator(function(self.variable), reduce(combinator,
[function(e) for e in self.features], default))
return re
def str(self, syntax=DrtTokens.NLTK):
return str(self.variable) + "{" + ",".join([str(feature) for feature in self.features]) + "}"
def deepcopy(self, operations=[]):
return self.__class__(self.variable, self.features)
def fol(self):
return DrtConstantExpression(self.variable)
class DrtProperNameExpression(DrtConstantExpression):
"""proper names"""
pass
class DrtNegatedExpression(AbstractDrs, drt.DrtNegatedExpression):
def readings(self, trail=[]):
return self.term.readings(trail + [self])
def deepcopy(self, operations=None):
return self.__class__(self.term.deepcopy(operations))
class DrtLambdaExpression(AbstractDrs, drt.DrtLambdaExpression):
def alpha_convert(self, newvar):
"""Rename all occurrences of the variable introduced by this variable
binder in the expression to @C{newvar}.
@param newvar: C{Variable}, for the new variable
"""
return self.__class__(newvar, self.term.replace(self.variable,
DrtVariableExpression(newvar), True))
def replace(self, variable, expression, replace_bound=False):
"""@see: Expression.replace()"""
assert isinstance(variable, Variable), "%s is not a Variable" % variable
assert isinstance(expression, Expression), "%s is not an Expression" % expression
#if the bound variable is the thing being replaced
if self.variable == variable:
if replace_bound:
assert isinstance(expression, DrtAbstractVariableExpression), \
"%s is not a AbstractVariableExpression" % expression
return self.__class__(expression.variable,
self.term.replace(variable, expression, True))
else:
return self
else:
# if the bound variable appears in the expression, then it must
# be alpha converted to avoid a conflict
if self.variable in expression.free():
self = self.alpha_convert(unique_variable(pattern=self.variable))
#replace in the term
return self.__class__(self.variable,
self.term.replace(variable, expression, replace_bound))
def readings(self, trail=[]):
return self.term.readings(trail + [self])
def deepcopy(self, operations=[]):
return self.__class__(self.variable, self.term.deepcopy(operations))
def get_refs(self, recursive=False):
"""@see: AbstractExpression.get_refs()"""
return []
class DrtBooleanExpression(AbstractDrs, drt.DrtBooleanExpression):
def readings(self, trail=[]):
first_readings = self.first.readings(trail + [self])
if first_readings:
return first_readings
else:
return self.second.readings(trail + [self])
def deepcopy(self, operations=[]):
return self.__class__(self.first.deepcopy(operations), self.second.deepcopy(operations))
def simplify(self):
"""When dealing with DRSs, it is good to have unique names for
the referents bound by each DRS."""
if isinstance(self.first, DRS) and isinstance(self.second, DRS):
new_second = self.second
for ref in set(self.first.get_refs(True)) & set(self.second.get_refs(True)):
newref = DrtVariableExpression(unique_variable(ref))
new_second = self.second.replace(ref, newref, True)
return drt.DrtBooleanExpression.simplify(self.__class__(self.first, new_second))
else:
return drt.DrtBooleanExpression.simplify(self)
class DrtOrExpression(DrtBooleanExpression, drt.DrtOrExpression):
pass
class DrtImpExpression(DrtBooleanExpression, drt.DrtImpExpression):
def readings(self, trail=[]):
first_readings = self.first.readings(trail + [self])
if first_readings:
return first_readings
else:
return self.second.readings(trail + [self, self.first])
def __eq__(self, other):
if (isinstance(self, other.__class__) or isinstance(other, self.__class__)):
if isinstance(self.first, DRS) and isinstance(self.second, DRS) and isinstance(other.first, DRS) and isinstance(other.second, DRS):
if len(self.first.conds) == len(other.first.conds) and len(self.second.conds) == len(other.second.conds):
for (r1, r2) in zip(self.first.refs + self.second.refs, other.first.refs + other.second.refs):
varex = self.make_VariableExpression(r1)
other = other.replace(r2, varex, True)
return self.first.conds == other.first.conds and self.second.conds == other.second.conds
else:
return self.first == other.first and self.second == other.second
return False
class DrtIffExpression(DrtBooleanExpression, drt.DrtIffExpression):
pass
class DrtEqualityExpression(AbstractDrs, drt.DrtEqualityExpression):
def readings(self, trail=[]):
return None
def deepcopy(self, operations=[]):
return self.__class__(self.first.deepcopy(operations), self.second.deepcopy(operations))
class ConcatenationDRS(DrtBooleanExpression, drt.ConcatenationDRS):
"""DRS of the form '(DRS + DRS)'"""
def replace(self, variable, expression, replace_bound=False):
"""Replace all instances of variable v with expression E in self,
where v is free in self."""
first = self.first
second = self.second
# If variable is bound by both first and second
if isinstance(first, DRS) and isinstance(second, DRS) and \
variable in (set(first.get_refs(True)) & set(second.get_refs(True))):
first = first.replace(variable, expression, True)
second = second.replace(variable, expression, True)
# If variable is bound by first
elif isinstance(first, DRS) and variable in first.refs:
if replace_bound:
first = first.replace(variable, expression, replace_bound)
second = second.replace(variable, expression, replace_bound)
# If variable is bound by second
elif isinstance(second, DRS) and variable in second.refs:
if replace_bound:
first = first.replace(variable, expression, replace_bound)
second = second.replace(variable, expression, replace_bound)
else:
# alpha convert every ref that is free in 'expression'
for ref in (set(self.get_refs(True)) & expression.free()):
v = DrtVariableExpression(unique_variable(ref))
first = first.replace(ref, v, True)
second = second.replace(ref, v, True)
first = first.replace(variable, expression, replace_bound)
second = second.replace(variable, expression, replace_bound)
return self.__class__(first, second)
def simplify(self):
first = self.first.simplify()
second = self.second.simplify()
if isinstance(first, DRS) and isinstance(second, DRS):
# For any ref that is in both 'first' and 'second'
for ref in (set(first.get_refs(True)) & set(second.get_refs(True))):
# alpha convert the ref in 'second' to prevent collision
newvar = DrtVariableExpression(unique_variable(ref))
second = second.replace(ref, newvar, True)
#DRS type is derived from the first member or from the second one
drs_type = first.__class__ if isinstance(first, PresuppositionDRS) else second.__class__
return drs_type(first.refs + second.refs, first.conds + second.conds)
else:
return self.__class__(first, second)
class DrtApplicationExpression(AbstractDrs, drt.DrtApplicationExpression):
def fol(self):
if self.is_propername():
return EqualityExpression(self.function.fol(),
self.argument.fol())
else: return ApplicationExpression(self.function.fol(),
self.argument.fol())
def is_propername(self):
"""
A proper name is capitalised. We assume that John(x) uniquely
identifies the bearer of the name John and so, when going from Kamp & Reyle's
DRT format into classical FOL logic, we change a condition like that into John = x.
@return: C{boolean} True if expr is of the correct form
"""
return isinstance(self.function, DrtConstantExpression) and\
self.function.variable.name.istitle()
def readings(self, trail=[]):
function_readings = self.function.readings(trail + [self])
if function_readings:
return function_readings
else:
return self.argument.readings(trail + [self])
def deepcopy(self, operations=[]):
return self.__class__(self.function.deepcopy(operations), self.argument.deepcopy(operations))
class DrtEventualityApplicationExpression(DrtApplicationExpression):
"""application expression with state or event argument"""
pass
class PresuppositionDRS(DRS):
def readings(self, trail=[]):
inner_readings = DRS.readings(self, trail)
if inner_readings:
return inner_readings
else:
self._init_presupp_data()
return self._presupposition_readings(trail)
def _find_outer_drs(self, trail):
for expr in trail:
if expr.__class__ is DRS:
return expr
def _find_local_drs(self, trail):
drs = None
for expr in ReverseIterator(trail):
if drs:
if not isinstance(expr, DrtNegatedExpression):
return drs
else: drs = None
if expr.__class__ is DRS:
drs = expr
return drs
def is_possible_binding(self, cond):
return is_unary_predicate(cond) and self.has_same_features(cond) and cond.argument.__class__ is DrtIndividualVariableExpression
def find_bindings(self, trail, collect_event_data=False, filter=lambda x: type(x) is DRS, individuals=None):
bindings = []
if collect_event_data:
event_data_map = {}
event_strings_map = {}
is_bindable = True # do not allow forward binding
for drs in (expr for expr in trail if filter(expr)):
for cond in drs.conds:
# Ignore conditions following the presupposition DRS
if cond is self:
if not collect_event_data:
break # assuming that the filtered_trail has drss ordered from the outermost to the innermost
if not isinstance(cond, DrtApplicationExpression):
continue
is_bindable = False
if is_bindable and self.is_possible_binding(cond):
bindings.append(cond)
if collect_event_data:
self.collect_event_data(cond, event_data_map, event_strings_map, individuals)
if collect_event_data:
self._enrich_event_data_map(event_data_map, event_strings_map)
return (bindings, event_data_map) if collect_event_data else bindings
def collect_event_data(self, cond, event_data_map, event_strings_map, individuals=None):
if isinstance(cond.function, DrtApplicationExpression) and \
isinstance(cond.argument, DrtIndividualVariableExpression) and not isinstance(cond.argument, DrtTimeVariableExpression):
event_data_map.setdefault(cond.argument.variable, []).append((cond.function.argument, cond.function.function.variable.name))
elif cond.__class__ == DrtEventualityApplicationExpression and \
(isinstance(cond.argument, DrtEventVariableExpression) or isinstance(cond.argument, DrtStateVariableExpression)) and\
not isinstance(cond.function, DrtApplicationExpression):
assert cond.argument not in event_strings_map
event_strings_map[cond.argument] = cond.function.variable.name
# The rest are nouns and attributive adjectives
elif individuals is not None and cond.__class__ == DrtApplicationExpression and \
not isinstance(cond.function, DrtApplicationExpression):
individuals.setdefault(cond.argument.variable, []).append(cond)
def _enrich_event_data_map(self, event_data_map, event_strings_map):
for individual in event_data_map:
new_event_list = []
for event_tuple in event_data_map[individual]:
new_event_list.append((event_tuple[0], event_tuple[1], event_strings_map.get(event_tuple[0], None)))
event_data_map[individual] = new_event_list
def is_presupposition_cond(self, cond):
return True
def _init_presupp_data(self):
presupp_cond_list = [cond for cond in self.conds if is_unary_predicate(cond) and cond.argument.variable == self.refs[0] and self.is_presupposition_cond(cond)]
for cond in presupp_cond_list:
if isinstance(cond.function, DrtFeatureConstantExpression): # this is the one
# There can be more than one DrtFeatureConstantExpression on the conditions on list, e.g.
# "Tom, a kind boy, took her hand", or "Tom, who is a kind boy,...", or "Linguist Grimm suggested ...",
# or "The distinguished physicist Einstein ...". But 'is_presupposition_cond' helps us find the right one.
self.variable = cond.argument.variable
self.features = cond.function.features
self.function_name = cond.function.variable.name
self.cond = cond
return
self.variable = self.refs[0]
self.features = None
self.function_name = presupp_cond_list[0].variable.name
self.cond = presupp_cond_list[0]
def has_same_features(self, cond):
return (not isinstance(cond.function, DrtFeatureConstantExpression) and not self.features) \
or (isinstance(cond.function, DrtFeatureConstantExpression) and cond.function.features == self.features)
def _get_condition_index(self, superordinate_drs, trail, condition_index_cache={}):
# Keep a condition index cache
if not condition_index_cache:
condition_index_cache = {}
superordinate_drs_index = id(superordinate_drs)
if superordinate_drs_index in condition_index_cache:
return condition_index_cache[superordinate_drs_index]
# Use a for loop and 'is' to find the condition.
# Do not use index(), because it calls a time-consuming equals method.
for ind, trailee in enumerate(trail):
if trailee is superordinate_drs:
# The condition might be not in superordinate_drs, but inside one of its conditions (however deep we might need to go)
look_for = trail[ind + 1] if ind < len(trail) - 1 else self
for i, cond in enumerate(superordinate_drs.conds):
if cond is look_for:
condition_index_cache[superordinate_drs_index] = i
return i # condition_index
return None
class Operation(object):
"""An interface for all operations"""
def __call__(self, drs):
raise NotImplementedError
class Accommodate(Operation):
def __init__(self, presupp_drs, condition_index):
# We need the condition index so that the conditions are not just appended to the list of conditions of the DRS,
# but inserted where the presuppositional DRS had been. The order of conditions is important, because it reflects
# the proximity of a possible antecedent, which affects antecedent ranking (and our architecture does not allow us to use the
# index on the list of referents to reflect the proximity/thematic role).
self.presupp_drs = presupp_drs
self.condition_index = condition_index
def __call__(self, drs):
"""Accommodation: put all referents and conditions from
the presupposition DRS into the given DRS"""
drs.refs.extend(self.presupp_drs.refs)
if self.condition_index is None:
drs.conds.extend(self.presupp_drs.conds)
else:
drs.conds = drs.conds[:self.condition_index + 1] + self.presupp_drs.conds + drs.conds[self.condition_index + 1:]
return drs
class Bind(Operation):
def __init__(self, presupp_drs, presupp_variable, presupp_funcname, antecedent_cond, condition_index):
self.presupp_drs = presupp_drs
self.presupp_variable = presupp_variable
self.presupp_funcname = presupp_funcname
self.antecedent_cond = antecedent_cond
self.condition_index = condition_index
def __call__(self, drs):
"""Put all conditions from the presuppositional DRS into the DRS (but do not create duplicates),
and replace the presupposition condition referent in them with antecedent referent"""
newdrs = self.presupp_drs.replace(self.presupp_variable, self.antecedent_cond.argument, True)
# There will be referents and conditions to move
# if there is a relative clause modifying the noun that has triggered the presuppositon
drs.refs.extend([ref for ref in newdrs.refs \
if ref != self.antecedent_cond.argument.variable])
conds_to_move = [cond for cond in newdrs.conds \
if not cond in drs.conds]
# Put the conditions at the position of the original presupposition DRS
if self.condition_index is None: # it is an index, it can be zero
drs.conds.extend(conds_to_move)
else:
drs.conds = drs.conds[:self.condition_index + 1] + conds_to_move + drs.conds[self.condition_index + 1:]
return drs
class InnerReplace(Operation):
def __init__(self, presupp_variable, antecedent_ref):
self.presupp_variable = presupp_variable
self.antecedent_ref = antecedent_ref
def __call__(self, drs):
"""In the conditions of the local DRS, replace the
referent of the presupposition condition with antecedent_ref"""
return drs.replace(self.presupp_variable, self.antecedent_ref, True)
class MoveTemporalConditions(Operation):
def __init__(self, temporal_conditions):
self.temporal_conditions = temporal_conditions
def __call__(self, drs):
drs.conds.extend(self.temporal_conditions)
return drs
class DoMultipleOperations(Operation):
def __init__(self, operations_list):
self.operations_list = operations_list
def __call__(self, drs):
"""Do the operations one by one"""
for operation in self.operations_list:
drs = operation(drs)
return drs
def binding_reading(self, inner_drs, target_drs, antecedent_cond, trail, temporal_conditions=None, local_drs=None):
condition_index = self._get_condition_index(target_drs, trail)
binder = self.Bind(self, self.variable, self.function_name, antecedent_cond, condition_index)
inner_replacer = self.InnerReplace(self.variable, antecedent_cond.argument)
temp_cond_mover = self.MoveTemporalConditions(temporal_conditions) if temporal_conditions else None
if inner_drs is target_drs:
if temp_cond_mover:
if local_drs is target_drs:
return Binding([(inner_drs, binder), (inner_drs, temp_cond_mover), (inner_drs, inner_replacer)])
else:
return Binding([(local_drs, temp_cond_mover),
(inner_drs, binder), (inner_drs, inner_replacer)])
else:
return Binding([(inner_drs, binder), (inner_drs, inner_replacer)])
else:
if temp_cond_mover:
if local_drs is target_drs:
return Binding([(target_drs, binder), (target_drs, temp_cond_mover),
(inner_drs, inner_replacer)])
elif local_drs is inner_drs:
return Binding([(target_drs, binder),
(inner_drs, temp_cond_mover), (inner_drs, inner_replacer)])
else:
return Binding([(target_drs, binder),
(local_drs, temp_cond_mover),
(inner_drs, inner_replacer)])
else:
return Binding([(target_drs, binder),
(inner_drs, inner_replacer)])
def accommodation_reading(self, target_drs, trail, temporal_conditions=None, local_drs=None, reading_type=Binding):
condition_index = self._get_condition_index(target_drs, trail)
accommodator = self.Accommodate(self, condition_index)
if temporal_conditions:
temp_cond_mover = self.MoveTemporalConditions(temporal_conditions)
if local_drs is target_drs:
return reading_type([(target_drs, temp_cond_mover), (target_drs, accommodator)])
else:
return reading_type([(target_drs, accommodator),
(local_drs, temp_cond_mover)])
else:
return reading_type([(target_drs, accommodator)])
class PronounDRS(PresuppositionDRS):
"""
A class for DRSs for personal, reflexive, and possessive pronouns
"""
PRONOUNS = [DrtTokens.PRONOUN, DrtTokens.REFLEXIVE_PRONOUN, DrtTokens.POSSESSIVE_PRONOUN]
def is_presupposition_cond(self, cond):
return cond.function.variable.name in PronounDRS.PRONOUNS
def _presupposition_readings(self, trail=[]):
#trail[0].draw()
possible_bindings, event_data = self.find_bindings(trail, True, filter=lambda x: x.__class__ is DRS or isinstance(x, PresuppositionDRS))
bindings = [cond for cond in possible_bindings if self._is_binding(cond, self._get_pro_events(event_data), event_data)]
ranked_bindings = self._rank_bindings(bindings, event_data)
return [Binding([(trail[-1], VariableReplacer(self.variable, cond.argument, False))]) for cond, rank in sorted(ranked_bindings, key=lambda e: e[1], reverse=True)], True
def _get_pro_events(self, event_data):
#in case pronoun participates in only one eventuality, which has no other participants,
#try to extend it with interlinked eventualities
#f.e. THEME(z5,z3), THEME(e,z5) where z3 only participates in eventuality z5
#will be extended to participate in e, but only in case z5 has one participant
pro_events = [event for event, role, event_string in event_data.get(self.variable, ())]
if len(pro_events) == 1:
pro_event = pro_events[0]
#number of participants in the pro_event
participant_count = sum((1 for event_list in event_data.itervalues() for event, role, event_string in event_list if event == pro_event))
# if there is only one participant in the pro_event and pro_event itself participates in other eventualities
if participant_count == 1 and pro_event.variable in event_data:
pro_events.extend((event for event, role, event_string in event_data[pro_event.variable]))
return set(pro_events)
def _rank_bindings(self, bindings, event_data):
#ranking system
#increment ranking for matching roles and map the positions of antecedents
if len(bindings) == 0:
raise AnaphoraResolutionException("Variable '%s' does not "
"resolve to anything." % self.variable)
elif len(bindings) == 1:
bindings[0] = (bindings[0], 0)
else:
pro_roles = set((role for event, role, event_string in event_data.get(self.variable, ())))
for index, variable in enumerate(bindings):
var_roles = set((role for event_list in event_data.get(variable, ()) for event, role, event_string in event_list))
bindings[index] = (variable, index + len(var_roles.intersection(pro_roles)))
return bindings
def _is_binding(self, cond, pro_events, event_data):
#non reflexive pronouns can not resolve to variables having a role in the same eventuality
if self.function_name == DrtTokens.POSSESSIVE_PRONOUN:
return True
else:
variable = cond.argument.variable
variable_events = set((event for event, role, event_string in event_data.get(variable, ())))
if self.function_name == DrtTokens.PRONOUN:
return variable_events.isdisjoint(pro_events)
elif self.function_name == DrtTokens.REFLEXIVE_PRONOUN:
return not variable_events.isdisjoint(pro_events)
else:
return True
class ProperNameDRS(PresuppositionDRS):
def _presupposition_readings(self, trail=[]):
"""A proper name always has one reading: it is either global binding
or global accommodation (if binding is not possible)"""
outer_drs = self._find_outer_drs(trail)
inner_drs = trail[-1]
possible_bindings = self.find_bindings([outer_drs])
assert len(possible_bindings) <= 1
if possible_bindings:
# Return the reading
return [self.binding_reading(inner_drs, outer_drs, possible_bindings[0], trail)], True
# If no suitable antecedent has been found in the outer DRS,
# binding is not possible, so we go for accommodation instead.
return [self.accommodation_reading(outer_drs, trail)], True
def is_possible_binding(self, cond):
return super(ProperNameDRS, self).is_possible_binding(cond) and cond.is_propername() and cond.function.variable.name == self.function_name
def is_presupposition_cond(self, cond):
return cond.is_propername()
class DefiniteDescriptionDRS(PresuppositionDRS):
def _presupposition_readings(self, trail=[], overgenerate=False, generate_intermediate=True):
# If there is a restrictive clause or an adjunct PP, find the perfect binding or accommodate the presupposition
presupp_event_data = {}
presupp_event_strings = {}
presupp_individuals = {}
# Are there any states/events in this presuppositional DRS that the presupposition referent takes part in?
for cond in (c for c in self.conds if isinstance(c, DrtApplicationExpression)):
self.collect_event_data(cond, presupp_event_data, presupp_event_strings, presupp_individuals)
self._enrich_event_data_map(presupp_event_data, presupp_event_strings)
possible_bindings = {}
event_data = {}
individuals = {}
accommod_indices = set()
intermediate_next = False # find the closest antecedent DRS
outer_drs = self._find_outer_drs(trail)
local_drs = self._find_local_drs(trail)
all_refs = []
free, temporal_conditions = self._get_free()
# Go through the filtered trail, find bindings and find the intermediate DRS for possible accommodation
for index, drs in enumerate(trail):
if isinstance(drs, DrtImpExpression): intermediate_next = True
if not drs.__class__ is DRS: continue
# Free variable check
if not self._free_variable_check(drs, free, all_refs):
intermediate_next = False
continue
# Find the (maximum) three DRSs
if drs is outer_drs or drs is local_drs or intermediate_next:
accommod_indices.add(index)
intermediate_next = False
# Find the bindings
drs_possible_bindings, drs_event_data = self.find_bindings([drs], True, individuals=individuals)
for var in drs_event_data: event_data.setdefault(var, []).extend(drs_event_data[var])
if drs_possible_bindings:
possible_bindings[index] = drs_possible_bindings
# Make accommodation indices a sorted list
accommod_indices = sorted(list(accommod_indices))
def accommodation_cite(drsindex):#LocalAccommodation, IntermediateAccommodation, GlobalAccommodation
if not drsindex in accommod_indices:
return None
ind = accommod_indices.index(drsindex)
if ind == 0:
return [LocalAccommodation, GlobalAccommodation, GlobalAccommodation][len(accommod_indices) - 1]
elif ind == 1:
return [LocalAccommodation, IntermediateAccommodation][len(accommod_indices) - 2]
else:
assert ind == 2
return LocalAccommodation
# Filter the bindings, create the readings
antecedent_tracker = [] # do not bind to the same referent twice
readings = []
inner_drs = trail[-1]
for drsindex, drs in enumerate(trail):
drs_readings = []
if drsindex in possible_bindings:
for cond in ReverseIterator(possible_bindings[drsindex]):
variable = cond.argument.variable
if self._is_binding(variable, individuals[variable], self._get_defdescr_events(event_data), event_data, presupp_event_data, presupp_individuals) and \
not cond.argument in antecedent_tracker:
antecedent_tracker.append(cond.argument)
drs_readings.append(self.binding_reading(inner_drs, drs, \
cond, trail, temporal_conditions, local_drs))
# If binding is possible, no accommodation at this level or below will take place
# (unless we set the 'overgenerate' parameter to True)
if not overgenerate and drs_readings: accommod_indices = [None]
else:
acc_cite = accommodation_cite(drsindex)
if acc_cite and not (generate_intermediate is False and acc_cite is IntermediateAccommodation):
drs_readings.append(self.accommodation_reading(drs, trail, temporal_conditions, local_drs, acc_cite))
accommod_indices.remove(drsindex)
readings.extend(drs_readings)
return readings, True
def _get_free(self):
free = self.free(True)
return free, []
def _get_defdescr_events(self, event_data):
return [item[0] for item in event_data.get(self.variable, ())]
def _is_binding(self, variable, var_individuals, defdescr_events, event_data, presupp_event_data, presupp_individuals):
# No binding is possible to variables having a role in the same eventuality (look for eventualities in DRSs other than self)
variable_events = set((event for event, role, event_string in event_data.get(variable, ())))
if not variable_events.isdisjoint(defdescr_events):
return False
# Don't allow binding if the potential antecedent participates in the same eventuality (in the relative clause) as self.variable, e.g.:
# If John has a child, the child that likes him (him = the child in the antecedent of the impl. cond) is away.
variable_presupp_events = set((event for event, role, event_string in presupp_event_data.get(variable, ())))
defdescr_presupp_events = set((event for event, role, event_string in presupp_event_data.get(self.variable, ())))
if not variable_presupp_events.isdisjoint(defdescr_presupp_events):
return False
# Don't allow binding x to y if there are conditions like POSS(x,y), POSS(y,x), REL(x,y), REL(y,x) and suchlike
for event_tuple in presupp_event_data.get(variable, []):
event = event_tuple[0]
if event.__class__ == DrtIndividualVariableExpression and event.variable == self.variable:
return False
for event_tuple in presupp_event_data.get(self.variable, []):
event = event_tuple[0]
if event.__class__ == DrtIndividualVariableExpression and event.variable == variable:
return False
# Perform the semantic check
return self.semantic_check(var_individuals, presupp_individuals)
def semantic_check(self, individuals, presupp_individuals, strict=False):
""" Users can plug in their more sophisticated semantic checks here.
As for this project, we confine ourselves to ontologies provided by WordNet.
See the other file for how this is supposed to work."""
if strict:
# ------------------------ Plug in ontologies here
if isinstance(self.cond, DrtFeatureConstantExpression):
for individual in individuals:
if isinstance(individual, DrtFeatureConstantExpression) and self.function_name == individual.function.variable.name:
return True
return False
else:
# If no features are used, we cannot guarantee that the condition we got self.function_name from wasn't an adjective
for individual in individuals:
for presupp_individual in presupp_individuals[self.variable]:
if presupp_individual.function.variable.name == individual.function.variable.name:
return True
return False
else:
return True
def _free_variable_check(self, drs, free, all_refs):
if free:
all_refs.extend(drs.refs)
for variable in free:
if not variable in all_refs:
return False
return True
class DrtParser(drt.DrtParser):
def get_all_symbols(self):
return DrtTokens.SYMBOLS
def isvariable(self, tok):
return tok not in DrtTokens.TOKENS
def handle(self, tok, context):
"""We add new types of DRS to represent presuppositions"""
if tok.upper() in DrtTokens.PRESUPPOSITION_DRS:
return self.handle_PresuppositionDRS(tok.upper(), context)
else:
return drt.DrtParser.handle(self, tok, context)
def handle_PresuppositionDRS(self, tok, context):
"""Parse all the Presuppositon DRSs."""
self.assertNextToken(DrtTokens.OPEN)
drs = self.handle_DRS(tok, context)
if tok == DrtTokens.PROPER_NAME_DRS:
return ProperNameDRS(drs.refs, drs.conds)
elif tok == DrtTokens.DEFINITE_DESCRIPTION_DRS:
return DefiniteDescriptionDRS(drs.refs, drs.conds)
elif tok == DrtTokens.PRONOUN_DRS:
return PronounDRS(drs.refs, drs.conds)
def handle_variable(self, tok, context):
#It's either: 1) a predicate expression: sees(x,y)
# 2) an application expression: P(x)
# 3) a solo variable: john OR x
accum = self.make_VariableExpression(tok)
# handle the feature structure of the variable
features = []
try:
if self.token(0) == DrtTokens.OPEN_BRACE:
self.token() # swallow the OPEN_BRACE
while self.token(0) != DrtTokens.CLOSE_BRACE:
features.append(DrtFeatureExpression(Variable(self.token())))
if self.token(0) == drt.DrtTokens.COMMA:
self.token() # swallow the comma
self.token() # swallow the CLOSE_BRACE
except ParseException:
#we've reached the end of input, this constant has no features
pass
if self.inRange(0) and self.token(0) == DrtTokens.OPEN:
if features:
accum = DrtFeatureConstantExpression(accum.variable, features)
#The predicate has arguments
if isinstance(accum, drt.DrtIndividualVariableExpression):
raise ParseException(self._currentIndex,
'\'%s\' is an illegal predicate name. '
'Individual variables may not be used as '
'predicates.' % tok)
self.token() #swallow the Open Paren
#curry the arguments
accum = self.make_ApplicationExpression(accum,
self.parse_Expression('APP'))
while self.inRange(0) and self.token(0) == DrtTokens.COMMA:
self.token() #swallow the comma
accum = self.make_ApplicationExpression(accum,
self.parse_Expression('APP'))
self.assertNextToken(DrtTokens.CLOSE)
elif features:
accum = DrtFeatureConstantExpression(accum.variable, map(Variable, features))
return accum
def handle_DRS(self, tok, context):
drs = drt.DrtParser.handle_DRS(self, tok, context)
return DRS(drs.refs, drs.conds)
def get_BooleanExpression_factory(self, tok):
"""This method serves as a hook for other logic parsers that
have different boolean operators"""
if tok == DrtTokens.DRS_CONC:
return ConcatenationDRS
elif tok in DrtTokens.OR:
return DrtOrExpression
elif tok in DrtTokens.IMP:
return DrtImpExpression
elif tok in DrtTokens.IFF:
return DrtIffExpression
else:
return None
def make_VariableExpression(self, name):
return DrtVariableExpression(Variable(name))
def make_ApplicationExpression(self, function, argument):
return DrtApplicationExpression(function, argument)
def make_ConstantExpression(self, name):
return DrtConstantExpression(Variable(name))
def make_NegatedExpression(self, expression):
return DrtNegatedExpression(expression)
def make_EqualityExpression(self, first, second):
"""This method serves as a hook for other logic parsers that
have different equality expression classes"""
return DrtEqualityExpression(first, second)
def make_LambdaExpression(self, variables, term):
return DrtLambdaExpression(variables, term)
| 44.527631 | 197 | 0.629639 | 54,612 | 0.928444 | 219 | 0.003723 | 0 | 0 | 0 | 0 | 11,649 | 0.198042 |
897de8f5d65cb6ce9cd237f74627ca6c99222851 | 1,669 | py | Python | deploy_python/openem/Detect/__init__.py | bryan-flywire/openem | 1510ecbbb6b4a43b9f1f9503c87ec66216200677 | [
"MIT"
] | 10 | 2019-01-23T23:58:01.000Z | 2021-08-30T19:42:35.000Z | deploy_python/openem/Detect/__init__.py | bryan-flywire/openem | 1510ecbbb6b4a43b9f1f9503c87ec66216200677 | [
"MIT"
] | 3 | 2020-03-20T15:21:41.000Z | 2020-09-18T18:49:38.000Z | deploy_python/openem/Detect/__init__.py | bryan-flywire/openem | 1510ecbbb6b4a43b9f1f9503c87ec66216200677 | [
"MIT"
] | 2 | 2020-05-08T17:39:12.000Z | 2020-10-09T01:27:17.000Z | from openem.models import ImageModel
from openem.models import Preprocessor
import cv2
import numpy as np
import tensorflow as tf
from collections import namedtuple
import csv
Detection=namedtuple('Detection', ['location',
'confidence',
'species',
'frame',
'video_id'])
# Bring in SSD detector to top-level
from openem.Detect.SSD import SSDDetector
class IO:
def from_csv(filepath_like):
detections=[]
with open(filepath_like, 'r') as csv_file:
reader = csv.DictReader(csv_file)
last_idx = -1
for row in reader:
location=np.array([float(row['x']),
float(row['y']),
float(row['w']),
float(row['h'])])
item = Detection(location=location,
confidence=float(row['detection_conf']),
species=int(float(row['detection_species'])),
frame=int(row['frame']),
video_id=row['video_id'])
frame_num = int(float(row['frame']))
if last_idx == frame_num:
detections[last_idx].append(item)
else:
# Add empties
for _ in range(frame_num-1-last_idx):
detections.append([])
detections.append([item])
last_idx = frame_num
return detections
| 34.061224 | 78 | 0.460755 | 1,173 | 0.702816 | 0 | 0 | 0 | 0 | 0 | 0 | 182 | 0.109047 |
898103c6939f84b86c66b0636276a738603f0eb9 | 515 | py | Python | convert.py | FrilledShark/pi_graph | e5bb85d6f507f252ddad3375b7d24270cd4dcbb4 | [
"MIT"
] | null | null | null | convert.py | FrilledShark/pi_graph | e5bb85d6f507f252ddad3375b7d24270cd4dcbb4 | [
"MIT"
] | null | null | null | convert.py | FrilledShark/pi_graph | e5bb85d6f507f252ddad3375b7d24270cd4dcbb4 | [
"MIT"
] | null | null | null | import os
import re
filenames = sorted([frame for frame in os.listdir("frames")], key=lambda x: int(re.search(r'\d+', os.path.splitext(x)[0]).group()))
print("creating gif")
import imageio
with imageio.get_writer('storage/pi.gif', mode='I') as writer:
for filename in filenames:
image = imageio.imread(os.path.join("frames", filename))
writer.append_data(image)
print("creating mp4")
import moviepy.editor as mp
clip = mp.VideoFileClip("storage/pi.gif")
clip.write_videofile("storage/pi.mp4") | 32.1875 | 131 | 0.712621 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 101 | 0.196117 |
89814cfc0355efd923e5153ed731438042bdc436 | 2,283 | py | Python | module2-sql-for-analysis/insert_titanic.py | nsriniva/DS-Unit-3-Sprint-2-SQL-and-Databases | e5a2b5acb6a6b962a7206334f3efb79c1c65f6ed | [
"MIT"
] | null | null | null | module2-sql-for-analysis/insert_titanic.py | nsriniva/DS-Unit-3-Sprint-2-SQL-and-Databases | e5a2b5acb6a6b962a7206334f3efb79c1c65f6ed | [
"MIT"
] | null | null | null | module2-sql-for-analysis/insert_titanic.py | nsriniva/DS-Unit-3-Sprint-2-SQL-and-Databases | e5a2b5acb6a6b962a7206334f3efb79c1c65f6ed | [
"MIT"
] | null | null | null | import os
import psycopg2
from psycopg2 import extras
import json
import pandas as pd
from dotenv import load_dotenv
def execute_values(conn, df, table):
"""
Using psycopg2.extras.execute_values() to insert the dataframe
"""
# Create a list of tupples from the dataframe values
tuples = [tuple(x) for x in df.to_numpy()]
# Comma-separated dataframe columns
cols = ','.join(list(df.columns))
# SQL quert to execute
query = f"INSERT INTO {table}({cols}) VALUES %s"
cursor = conn.cursor()
try:
extras.execute_values(cursor, query, tuples)
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print("Error: %s" % error)
conn.rollback()
cursor.close()
return 1
print("execute_values() done")
cursor.close()
load_dotenv()
DB_NAME = os.getenv("DB_NAME")
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_HOST = os.getenv("DB_HOST")
connection = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST)
print("CONNECTION", type(connection))
cursor = connection.cursor()
print("CURSOR", type(cursor))
print("-------------------")
query = "SELECT usename, usecreatedb, usesuper, passwd FROM pg_user;"
print("SQL:", query)
cursor.execute(query)
for row in cursor.fetchall()[0:10]:
print(row)
df = pd.read_csv('titanic.csv')
print(df.columns)
cols = {'Survived':'survived', 'Pclass':'pclass', 'Name':'name', 'Sex':'sex', 'Age':'age', 'Siblings/Spouses Aboard':'si_sp_aboard',
'Parents/Children Aboard':'pa_ch_aboard', 'Fare':'fare'}
df.rename(columns=cols, inplace=True)
print(df.columns)
df = df.astype({'survived':'bool'})
#
# CREATE THE TABLE
#
table_name = "titanic"
print("-------------------")
query = f"""
-- CREATE TYPE gender AS ENUM ('male', 'female');
CREATE TABLE IF NOT EXISTS {table_name} (
id SERIAL PRIMARY KEY,
survived BOOLEAN NOT NULL,
pclass SMALLINT NOT NULL,
name varchar NOT NULL,
sex gender NOT NULL,
age SMALLINT NOT NULL,
si_sp_aboard SMALLINT NOT NULL,
pa_ch_aboard SMALLINT NOT NULL,
fare REAL NOT NULL
);
"""
print("SQL:", query)
cursor.execute(query)
connection.commit()
execute_values(connection, df, table_name)
cursor.close()
connection.close()
| 24.031579 | 132 | 0.676741 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,002 | 0.438896 |
8981fdc323f9b82729d0de70d9c1a8da39c46c47 | 118,682 | py | Python | modules/bot.py | RkyFissy/Fortnite-LobbyBot-v2 | ea37b1b193cd80bbf6499cca51764dd642670d85 | [
"MIT"
] | 1 | 2022-03-15T00:48:50.000Z | 2022-03-15T00:48:50.000Z | modules/bot.py | namakemono-san/Fortnite-LobbyBot-v2 | ea37b1b193cd80bbf6499cca51764dd642670d85 | [
"MIT"
] | null | null | null | modules/bot.py | namakemono-san/Fortnite-LobbyBot-v2 | ea37b1b193cd80bbf6499cca51764dd642670d85 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import asyncio
import datetime
import importlib
import io
import json
import logging
import os
import platform
import re
import subprocess
import sys
import textwrap
import traceback
from contextlib import redirect_stderr, redirect_stdout
from functools import partial
from glob import glob
from logging import WARNING, getLogger
from typing import Any, Callable, List, Optional, Tuple, Union
import aiohttp
from aioconsole import ainput
from aiofiles import open as aopen
from aiofiles.os import remove as aremove
from tzlocal import get_localzone
from .auth import MyAdvancedAuth
from .auto_updater import Updater
from .client import Client, MyClientParty, MyClientPartyMember
from .colors import cyan, green, yellow
from .commands import Command, DefaultCommands, MyMessage, PartyPrivacy
from .cosmetics import CaseInsensitiveDict, Searcher
from .discord_client import DiscordClient
from .encoder import MyJSONEncoder
from .formatter import EvalFormatter
from .http import HTTPClient
from .localize import LocalizedText
from .web import Web, WebMessage, WebUser
from .webhook import WebhookClient
if (os.getenv('REPLIT_DB_URL') is not None
and os.getcwd().startswith('/home/runner')
and sys.platform == 'linux'):
from replit import db
else:
db = None
discord = importlib.import_module('discord')
fortnitepy = importlib.import_module('fortnitepy')
_ = importlib.import_module('pykakasi')
kakasi = _.kakasi
Message = Union[
fortnitepy.FriendMessage,
fortnitepy.PartyMessage,
discord.Message,
WebMessage
]
Author = Union[
fortnitepy.Friend,
fortnitepy.PartyMember,
discord.User,
discord.Member,
WebUser
]
class Bot:
BACKEND_TO_API_CONVERTER = {
'AthenaBackpack': 'backpack',
'AthenaPickaxe': 'pickaxe',
'AthenaItemWrap': 'wrap',
'AthenaGlider': 'glider',
'AthenaCharacter': 'outfit',
'AthenaPet': 'pet',
'AthenaMusicPack': 'music',
'AthenaLoadingScreen': 'loadingscreen',
'AthenaDance': 'emote',
'AthenaSpray': 'spray',
'AthenaEmoji': 'emoji',
'AthenaSkyDiveContrail': 'contrail',
'AthenaPetCarrier': 'petcarrier',
'AthenaToy': 'toy',
'AthenaConsumableEmote': 'consumableemote',
'AthenaBattleBus': 'battlebus',
'AthenaVictoryPose': 'ridethepony',
'BannerToken': 'banner'
}
API_TO_BACKEND_CONVERTER = {
v: k for k, v in BACKEND_TO_API_CONVERTER.items()
}
BACKEND_TO_KEY_CONVERTER = {
'AthenaBackpack': 'backpack',
'AthenaPickaxe': 'pickaxe',
'AthenaItemWrap': 'wrap',
'AthenaGlider': 'glider',
'AthenaCharacter': 'outfit',
'AthenaPet': 'backpack',
'AthenaMusicPack': 'music',
'AthenaLoadingScreen': 'loadingscreen',
'AthenaDance': 'emote',
'AthenaSpray': 'emote',
'AthenaEmoji': 'emote',
'AthenaSkyDiveContrail': 'contrail',
'AthenaPetCarrier': 'backpack',
'AthenaToy': 'emote',
'AthenaConsumableEmote': 'emote',
'AthenaBattleBus': 'battlebus',
'AthenaVictoryPose': 'emote',
'BannerToken': 'banner'
}
BACKEND_TO_ID_CONVERTER = {
'AthenaCharacter': 'CID',
'AthenaBackpack': 'BID',
'AthenaPetCarrier': 'PetCarrier',
'AthenaPet': 'PetID',
'AthenaPickaxe': 'Pickaxe_ID',
'AthenaDance': 'EID',
'AthenaEmoji': 'Emoji',
'AthenaToy': 'Toy',
'AthenaConsumableEmote': 'EID',
}
VARIANT_FORMATS = [
'Mat',
'Stage',
'Emissive',
'Stage',
'Particle'
'Numeric.',
'Color.'
]
def __init__(self, mode: str, loop: asyncio.AbstractEventLoop,
dev: Optional[bool] = False,
use_device_code: Optional[bool] = False,
use_device_auth: Optional[bool] = False) -> None:
self.mode = mode
self.loop = loop
self.dev = dev
self.use_device_code = use_device_code
self.use_device_auth = use_device_auth
self.clients = []
self.updater = Updater(self)
self.web = Web(self, __name__)
self.web_text = ''
self.server = None
self.lang_dir = 'lang'
self.item_dir = 'item'
os.makedirs(self.item_dir, exist_ok=True)
self.booted_at = None
self.email_pattern = re.compile(
r'[a-zA-Z0-9.+-_]+@[a-zA-Z0-9-_]+\.[a-zA-Z0-9]+'
)
self.return_pattern = re.compile(
r'(?P<space>\s*)(return|return\s+(?P<text>.*))\s*'
)
self.formatter = EvalFormatter()
self.kakasi = kakasi()
self.kakasi.setMode('J', 'H')
self.converter = self.kakasi.getConverter()
self.localize = None
self.all_commands = {
attr.name: attr
for attr in DefaultCommands.__dict__.values()
if isinstance(attr, Command)
}
self.none_data = {
'real_value': None,
'value': 'null',
'display_value': self.l('none_none', default='null')
}
self.select_bool = [
{
'real_value': True,
'value': 'true',
'display_value': self.l('bool_true', default='true')
},
{
'real_value': False,
'value': 'false',
'display_value': self.l('bool_false', default='false')
}
]
self.select_event = [
{
'real_value': i,
'value': i,
'display_value': self.l(f'event_{i}', default=i)
} for i in ['me', 'user']
]
self.select_platform = [
{
'real_value': i,
'value': i,
'display_value': self.l(f'platform_{i}', default=i)
} for i in ['WIN', 'MAC', 'PSN', 'PS5', 'XBL',
'XBX', 'XBS', 'SWT', 'IOS', 'AND']
]
self.select_privacy = [
{
'real_value': i,
'value': i,
'display_value': self.l(f'privacy_{i.lower()}', default=i.upper())
} for i in ['PUBLIC', 'FRIENDS_ALLOW_FRIENDS_OF_FRIENDS',
'FRIENDS', 'PRIVATE_ALLOW_FRIENDS_OF_FRIENDS',
'PRIVATE']
]
self.select_status = [
{
'real_value': i,
'value': i,
'display_value': self.l(f'status_type_{i}', default=i)
} for i in ['playing', 'streaming', 'listening', 'watching', 'competing']
]
self.select_matchmethod = [
{
'real_value': i,
'value': i,
'display_value': self.l(f'matchmethod_{i}', default=i)
} for i in ['full', 'contains', 'starts', 'ends']
]
self.select_lang = [
{
'real_value': re.sub(r'lang(\\|/)', '', i).replace('.json', ''),
'value': re.sub(r'lang(\\|/)', '', i).replace('.json', ''),
'display_value': re.sub(r'lang(\\|/)', '', i).replace('.json', '')
} for i in glob('lang/*.json') if not i.endswith('_old.json')
]
self.select_api_lang = [
{
'real_value': i,
'value': i,
'display_value': i
} for i in ['ar', 'de', 'en', 'es', 'es-419', 'fr', 'it', 'ja',
'ko', 'pl', 'pt-BR', 'ru', 'tr', 'zh-CN', 'zh-Hant']
]
self.select_api = [
{
'real_value': i,
'value': i,
'display_value': i
} for i in ['BenBot', 'Fortnite-API', 'FortniteApi.io']
]
self.select_loglevel = [
{
'real_value': i,
'value': i,
'display_value': self.l(f'loglevel_{i}', default=i)
} for i in ['normal', 'info', 'debug']
]
self.select_run_when = [
{
'real_value': i,
'value': i,
'display_value': self.l(f'run_when_{i}', default=i)
} for i in ['before_command', 'after_command']
]
self.multiple_select_user_type = [
{
'real_value': i,
'value': i,
'display_value': self.l(f'multiple_select_user_{i}', default=i)
} for i in ['user', 'whitelist', 'blacklist', 'owner', 'bot']
]
self.multiple_select_user_operation = [
{
'real_value': i,
'value': i,
'display_value': self.l(f'multiple_select_operation_{i}', default=i)
} for i in ['kick', 'chatban', 'remove', 'block', 'blacklist']
]
self.multiple_select_platform = self.select_platform
self.config = None
self.config_tags = {
"['clients']": [list, dict, 'client_config'],
"['discord']": [dict],
"['discord']['enabled']": [bool, 'select_bool'],
"['discord']['token']": [str],
"['discord']['owner']": [list, str, 'can_be_none'],
"['discord']['channels']": [list, str],
"['discord']['status']": [str],
"['discord']['status_type']": [str, 'select_status'],
"['discord']['chat_max']": [int, 'can_be_none'],
"['discord']['chat_max_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['discord']['command_enable_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['discord']['blacklist']": [list, str],
"['discord']['whitelist']": [list, str],
"['discord']['prefix']": [list, str, 'can_be_none'],
"['discord']['exec']": [dict],
"['discord']['exec']['ready']": [list, str, 'can_be_none', 'accept_empty'],
"['web']": [dict],
"['web']['enabled']": [bool, 'select_bool'],
"['web']['ip']": [str],
"['web']['port']": [int],
"['web']['password']": [str],
"['web']['login_required']": [bool, 'select_bool'],
"['web']['command_web']": [bool, 'select_bool'],
"['web']['access_log']": [bool, 'select_bool'],
"['web']['prefix']": [list, str, 'can_be_none'],
"['check_update_on_startup']": [bool, 'select_bool'],
"['restart_in']": [int, 'can_be_none'],
"['lang']": [str, 'select_lang'],
"['search_lang']": [str, 'select_api_lang'],
"['sub_search_lang']": [str, 'select_api_lang'],
"['api']": [str, 'select_api'],
"['api_key']": [str, 'can_be_none'],
"['discord_log']": [str, 'can_be_none'],
"['omit_over2000']": [bool, 'select_bool'],
"['skip_if_overflow']": [bool, 'select_bool'],
"['hide_email']": [bool, 'select_bool'],
"['hide_password']": [bool, 'select_bool'],
"['hide_token']": [bool, 'select_bool'],
"['hide_webhook']": [bool, 'select_bool'],
"['no_logs']": [bool, 'select_bool'],
"['loglevel']": [str, 'select_loglevel'],
"['debug']": [bool, 'select_bool']
}
self.client_config_tags = {
"['fortnite']": [dict],
"['fortnite']['email']": [str, 'lambda x: x and self.email_pattern.match(x) is not None'],
"['fortnite']['nickname']": [str, 'can_be_none'],
"['fortnite']['owner']": [list, str, 'can_be_none'],
"['fortnite']['outfit']": [str, 'can_be_none'],
"['fortnite']['outfit_style']": [list, str, 'can_be_none'],
"['fortnite']['ng_outfits']": [list, str, 'can_be_none'],
"['fortnite']['ng_outfit_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['ng_outfit_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'],
"['fortnite']['ng_outfit_reply']": [str, 'can_be_none'],
"['fortnite']['join_outfit']": [str, 'can_be_none'],
"['fortnite']['join_outfit_style']": [list, str, 'can_be_none'],
"['fortnite']['join_outfit_on']": [str, 'select_event'],
"['fortnite']['leave_outfit']": [str, 'can_be_none'],
"['fortnite']['leave_outfit_style']": [list, str, 'can_be_none'],
"['fortnite']['leave_outfit_on']": [str, 'select_event'],
"['fortnite']['outfit_mimic_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['outfit_lock_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['backpack']": [str, 'can_be_none'],
"['fortnite']['backpack_style']": [list, str, 'can_be_none'],
"['fortnite']['ng_backpacks']": [list, str, 'can_be_none'],
"['fortnite']['ng_backpack_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['ng_backpack_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'],
"['fortnite']['ng_backpack_reply']": [str, 'can_be_none'],
"['fortnite']['join_backpack']": [str, 'can_be_none'],
"['fortnite']['join_backpack_style']": [list, str, 'can_be_none'],
"['fortnite']['join_backpack_on']": [str, 'select_event'],
"['fortnite']['leave_backpack']": [str, 'can_be_none'],
"['fortnite']['leave_backpack_style']": [list, str, 'can_be_none'],
"['fortnite']['leave_backpack_on']": [str, 'select_event'],
"['fortnite']['backpack_mimic_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['backpack_lock_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['pickaxe']": [str, 'can_be_none'],
"['fortnite']['pickaxe_style']": [list, str, 'can_be_none'],
"['fortnite']['do_point']": [bool, 'select_bool'],
"['fortnite']['ng_pickaxes']": [list, str, 'can_be_none'],
"['fortnite']['ng_pickaxe_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['ng_pickaxe_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'],
"['fortnite']['ng_pickaxe_reply']": [str, 'can_be_none'],
"['fortnite']['join_pickaxe']": [str, 'can_be_none'],
"['fortnite']['join_pickaxe_style']": [list, str, 'can_be_none'],
"['fortnite']['join_pickaxe_on']": [str, 'select_event'],
"['fortnite']['leave_pickaxe']": [str, 'can_be_none'],
"['fortnite']['leave_pickaxe_style']": [list, str, 'can_be_none'],
"['fortnite']['leave_pickaxe_on']": [str, 'select_event'],
"['fortnite']['pickaxe_mimic_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['pickaxe_lock_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['emote']": [str],
"['fortnite']['emote_section']": [int, 'can_be_none'],
"['fortnite']['repeat_emote_when_join']": [bool, 'select_bool'],
"['fortnite']['ng_emotes']": [list, str, 'can_be_none'],
"['fortnite']['ng_emote_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['ng_emote_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'],
"['fortnite']['ng_emote_reply']": [str, 'can_be_none'],
"['fortnite']['join_emote']": [str, 'can_be_none'],
"['fortnite']['join_emote_section']": [int, 'can_be_none'],
"['fortnite']['join_emote_on']": [str, 'select_event'],
"['fortnite']['leave_emote']": [str, 'can_be_none'],
"['fortnite']['leave_emote_section']": [int, 'can_be_none'],
"['fortnite']['leave_emote_on']": [str, 'select_event'],
"['fortnite']['emote_mimic_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['emote_lock_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['leave_delay_for']": [float],
"['fortnite']['refresh_on_reload']": [bool, 'select_bool'],
"['fortnite']['party']": [dict],
"['fortnite']['party']['privacy']": [str, 'select_privacy'],
"['fortnite']['party']['max_size']": [int, 'lambda x: 1 <= x <= 16'],
"['fortnite']['party']['allow_swap']": [bool, 'select_bool'],
"['fortnite']['party']['playlist']": [str],
"['fortnite']['party']['disable_voice_chat']": [bool, 'select_bool'],
"['fortnite']['avatar_id']": [str, 'can_be_none'],
"['fortnite']['avatar_color']": [str, 'can_be_multiple', 'lambda x: x and (len(x.split(",")) >= 3) if "," in x else (getattr(fortnitepy.KairosBackgroundColorPreset, x.upper(), None) is not None)'], # noqa
"['fortnite']['banner_id']": [str],
"['fortnite']['banner_color']": [str],
"['fortnite']['level']": [int],
"['fortnite']['tier']": [int],
"['fortnite']['platform']": [str, 'select_platform'],
"['fortnite']['ng_platforms']": [list, str, 'multiple_select_platform', 'can_be_none'],
"['fortnite']['ng_platform_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['ng_platform_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'],
"['fortnite']['ng_platform_reply']": [str, 'can_be_none'],
"['fortnite']['ng_names']": [list, dict, 'ng_names_config'],
"['fortnite']['ng_name_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['ng_name_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'],
"['fortnite']['ng_name_reply']": [str, 'can_be_none'],
"['fortnite']['status']": [str],
"['fortnite']['accept_invite_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['decline_invite_when']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['invite_interval']": [float, 'can_be_none'],
"['fortnite']['invite_interval_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['accept_friend_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['send_friend_request']": [bool, 'select_bool'],
"['fortnite']['whisper_enable_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['party_chat_enable_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['permission_command_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'],
"['fortnite']['accept_join_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['join_message']": [list, str, 'can_be_none', 'accept_empty'],
"['fortnite']['join_message_whisper']": [list, str, 'can_be_none', 'accept_empty'],
"['fortnite']['random_message']": [list, list, str, 'can_be_none', 'accept_empty'],
"['fortnite']['random_message_whisper']": [list, list, str, 'can_be_none', 'accept_empty'],
"['fortnite']['chat_max']": [int, 'can_be_none'],
"['fortnite']['chat_max_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['chat_max_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'],
"['fortnite']['kick_disconnect']": [bool, 'select_bool'],
"['fortnite']['kick_in_match']": [bool, 'select_bool'],
"['fortnite']['hide_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['fortnite']['blacklist']": [list, str],
"['fortnite']['blacklist_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'],
"['fortnite']['whitelist']": [list, str],
"['fortnite']['invitelist']": [list, str],
"['fortnite']['botlist']": [list, str],
"['fortnite']['botlist_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'],
"['fortnite']['prefix']": [list, str, 'can_be_none'],
"['fortnite']['exec']": [dict],
"['fortnite']['exec']['ready']": [list, str, 'can_be_none'],
"['fortnite']['exec']['party_join_request']": [list, str, 'can_be_none'],
"['fortnite']['exec']['party_invite']": [list, str, 'can_be_none'],
"['fortnite']['exec']['friend_request']": [list, str, 'can_be_none'],
"['fortnite']['exec']['friend_add']": [list, str, 'can_be_none'],
"['fortnite']['exec']['friend_remove']": [list, str, 'can_be_none'],
"['fortnite']['exec']['party_member_join']": [list, str, 'can_be_none'],
"['fortnite']['exec']['party_member_leave']": [list, str, 'can_be_none'],
"['fortnite']['exec']['party_member_confirm']": [list, str, 'can_be_none'],
"['fortnite']['exec']['party_member_kick']": [list, str, 'can_be_none'],
"['fortnite']['exec']['party_member_promote']": [list, str, 'can_be_none'],
"['fortnite']['exec']['party_update']": [list, str, 'can_be_none'],
"['fortnite']['exec']['party_member_update']": [list, str, 'can_be_none'],
"['fortnite']['exec']['party_member_disconnect']": [list, str, 'can_be_none'],
"['discord']": [dict],
"['discord']['enabled']": [bool, 'select_bool'],
"['discord']['token']": [str],
"['discord']['owner']": [list, str, 'can_be_none'],
"['discord']['channels']": [list, str],
"['discord']['status']": [str],
"['discord']['status_type']": [str, 'select_status'],
"['discord']['chat_max']": [int, 'can_be_none'],
"['discord']['chat_max_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['discord']['command_enable_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['discord']['blacklist']": [list, str],
"['discord']['whitelist']": [list, str],
"['discord']['prefix']": [list, str, 'can_be_none'],
"['discord']['exec']": [dict],
"['discord']['exec']['ready']": [list, str, 'can_be_none'],
"['ng_words']": [list, dict, 'ng_words_config'],
"['ng_word_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['ng_word_operation']": [list, str, 'multiple_select_user_operation', 'can_be_none'],
"['ng_word_reply']": [str, 'can_be_none'],
"['relogin_in']": [int, 'can_be_none'],
"['search_max']": [int, 'can_be_none'],
"['no_logs']": [bool, 'select_bool'],
"['loglevel']": [str, 'select_loglevel'],
"['discord_log']": [str, 'can_be_none'],
"['omit_over2000']": [bool, 'select_bool'],
"['skip_if_overflow']": [bool, 'select_bool'],
"['case_insensitive']": [bool, 'select_bool'],
"['convert_kanji']": [bool, 'select_bool']
}
self.ng_names_config_tags = {
"['matchmethod']": [str, 'select_matchmethod'],
"['word']": [str]
}
self.ng_words_config_tags = {
"['count']": [int],
"['matchmethod']": [str, 'select_matchmethod'],
"['words']": [list, str]
}
self.commands = None
tags = [list, str, 'can_be_multiple']
tags2 = [list, str, 'can_be_multiple', 'lambda x: len(x) > 0']
self.commands_tags = {
**{
"['whitelist_commands']": tags,
"['user_commands']": tags,
"['prefix_to_item_search']": [bool, 'select_bool'],
"['command']": tags2,
"['ng_word']": tags2,
"['most']": tags2,
"['user']": tags2,
"['whitelist']": tags2,
"['blacklist']": tags2,
"['owner']": tags2,
"['bot']": tags2,
"['null']": tags2,
"['operation_kick']": tags2,
"['operation_chatban']": tags2,
"['operation_remove']": tags2,
"['operation_block']": tags2,
"['operation_blacklist']": tags2,
"['add']": tags2,
"['remove']": tags2,
"['true']": tags2,
"['false']": tags2,
"['accept']": tags2,
"['decline']": tags2,
"['me']": tags2,
"['public']": tags2,
"['friends_allow_friends_of_friends']": tags2,
"['friends']": tags2,
"['private_allow_friends_of_friends']": tags2,
"['private']": tags2,
"['outfit']": tags2,
"['backpack']": tags2,
"['pickaxe']": tags2,
"['save']": tags2,
"['load']": tags2,
"['commands']": [dict]
},
**{
f"['commands']['{command}']": tags
for command in self.all_commands.keys()
}
}
self.custom_commands = None
self.custom_commands_tags = {
"['run_when']": [str, 'select_run_when'],
"['commands']": [list, dict, 'custom_commands_config']
}
self.custom_commands_config_tags = {
"['word']": [str],
"['allow_for']": [list, str, 'multiple_select_user_type', 'can_be_none'],
"['run']": [list, str, 'can_be_multiple']
}
self.replies = None
self.replies_tags = {
"['run_when']": [str, 'select_run_when'],
"['prefix_to_replies']": [bool, 'select_bool'],
"['replies']": [list, dict, 'replies_config']
}
self.replies_config_tags = {
"['matchmethod']": [str, 'select_matchmethod'],
"['word']": [str],
"['reply']": [list, str, 'can_be_multiple', 'accept_empty'],
"['ct']": [int, 'can_be_none']
}
self.cosmetic_presets = None
self.config_item_pattern = re.compile(
r"<Item name='(?P<name>.+)' "
r"id='(?P<id>.+)' "
r"path='(?P<path>.+)'>"
)
self.config_playlist_pattern = re.compile(
r"<Playlist name='(?P<name>.+)' "
r"id='(?P<id>.+)'>"
)
self.config_variant_pattern = re.compile(
r"<Variant name='(?P<name>.+)' "
r"channel='(?P<channel>.+)' "
r"tag='(?P<tag>.+)'>"
)
self.http = HTTPClient(aiohttp.ClientSession())
self.webhook = None
self.discord_client = None
@property
def loaded_clients(self) -> List[Client]:
return [client for client in self.clients if client.is_ready()]
@property
def loaded_client_ids(self) -> List[Client]:
return [client.user.id for client in self.loaded_clients]
def add_command(self, command: Command) -> None:
if not isinstance(command, Command):
raise TypeError(f'command argument must be instance of {Command.__name__}')
if command.name in self.all_commands:
raise ValueError(f"Command '{command.name}' is already registered")
self.all_commands[command.name] = command
for client in self.clients:
client.add_command(command)
def is_error(self) -> bool:
return (
self.error_config
or self.error_commands
or self.error_custom_commands
or self.error_replies
)
def get_device_auth_details(self) -> dict:
if self.isfile('device_auths'):
return self.load_json('device_auths')
else:
return {}
def store_device_auth_details(self, email: str, details: dict) -> None:
existing = self.get_device_auth_details()
existing[email.lower()] = details
self.save_json('device_auths', existing)
def get_refresh_tokens(self) -> dict:
if self.isfile('refresh_tokens'):
return self.load_json('refresh_tokens')
else:
return {}
def store_refresh_token(self, email: str, refresh_token: str) -> None:
existing = self.get_refresh_tokens()
existing[email.lower()] = refresh_token
self.save_json('refresh_tokens', existing)
def get_cosmetic_presets(self) -> dict:
if self.isfile('cosmetic_presets'):
return self.load_json('cosmetic_presets')
else:
return {}
async def store_cosmetic_presets(self, account_id: str, details: dict) -> None:
existing = self.get_cosmetic_presets()
existing[account_id] = details
self.save_json('cosmetic_presets', existing)
def get_command_stats(self) -> dict:
if self.isfile('command_stats'):
return self.load_json('command_stats')
else:
return {}
def store_command_stats(self) -> None:
self.save_json('command_stats', self.command_stats)
def convert_td(self, td: datetime.timedelta) -> Tuple[int, int, int, int]:
m, s = divmod(td.seconds, 60)
h, m = divmod(m, 60)
return td.days, h, m, s
def isfile(self, key: str, force_file: Optional[bool] = False) -> bool:
if self.mode == 'repl' and not force_file:
if db.get(key) is None:
return False
else:
if not os.path.isfile(f'{key}.json'):
return False
return True
def remove(self, key: str, force_file: Optional[bool] = False) -> None:
if self.mode == 'repl' and not force_file:
try:
del db[key]
except KeyError as e:
raise FileNotFoundError from e
else:
os.remove(f'{key}.json')
async def aremove(self, key: str, force_file: Optional[bool] = False) -> None:
if self.mode == 'repl' and not force_file:
try:
del db[key]
except KeyError as e:
raise FileNotFoundError from e
else:
await aremove(f'{key}.json')
def rename(self, key_src: str, key_dst: str, force_file: Optional[bool] = False) -> None:
if self.mode == 'repl' and not force_file:
try:
db[key_dst] = db[key_src]
del db[key_src]
except KeyError as e:
raise FileNotFoundError from e
else:
os.rename(f'{key_src}.json', f'{key_dst}.json')
def load_json(self, key: str, force_file: Optional[bool] = False) -> Union[dict, list]:
if self.mode == 'repl' and not force_file:
data = db[key]['value']
if isinstance(data, str):
return json.loads(db[key]['value'])
return data
else:
try:
with open(f'{key}.json', encoding='utf-8') as f:
data = f.read()
except UnicodeDecodeError:
try:
with open(f'{key}.json', encoding='utf-8-sig') as f:
data = f.read()
except UnicodeDecodeError:
with open(f'{key}.json', encoding='shift_jis') as f:
data = f.read()
return json.loads(data)
async def aload_json(self, key: str, force_file: Optional[bool] = False) -> Union[dict, list]:
if self.mode == 'repl' and not force_file:
data = db[key]['value']
if isinstance(data, str):
return json.loads(db[key]['value'])
return data
else:
try:
async with aopen(f'{key}.json', encoding='utf-8') as f:
data = await f.read()
except UnicodeDecodeError:
try:
async with aopen(f'{key}.json', encoding='utf-8-sig') as f:
data = await f.read()
except UnicodeDecodeError:
async with aopen(f'{key}.json', encoding='shift_jis') as f:
data = await f.read()
return json.loads(data)
def save_json(self, key: str, value: Union[dict, list],
force_file: Optional[bool] = False,
compact: Optional[bool] = False) -> None:
if self.mode == 'repl' and not force_file:
db[key] = {
'last_edited': self.utcnow(),
'value': json.dumps(
value,
ensure_ascii=False,
cls=MyJSONEncoder
)
}
else:
with open(f'{key}.json', 'w', encoding='utf-8') as f:
if compact:
json.dump(
value,
f,
ensure_ascii=False,
cls=MyJSONEncoder
)
else:
json.dump(
value,
f,
indent=4,
ensure_ascii=False,
cls=MyJSONEncoder
)
def dumps(self, data: Union[dict, list]) -> str:
return json.dumps(
data,
ensure_ascii=False,
cls=MyJSONEncoder
)
def get_last_edited(self, key: str, force_file: Optional[bool] = False) -> datetime.datetime:
if self.mode == 'repl' and not force_file:
return datetime.datetime.fromisoformat(db[key]['last_edited'])
else:
stat = os.stat(f'{key}.json')
return datetime.datetime.fromtimestamp(stat.st_mtime)
def is_not_edited_for(self, key: str, td: datetime.timedelta, force_file: Optional[bool] = False) -> bool:
last_edited = self.get_last_edited(key, force_file=force_file)
if last_edited < (datetime.datetime.utcnow() - td):
return True
return False
def l(self, key: str, *args: tuple, default: Optional[str] = '', **kwargs: dict) -> LocalizedText:
return LocalizedText(self, ['main', key], default, *args, **kwargs)
def send(self, content: Any,
user_name: Optional[str] = None,
color: Optional[Callable] = None,
add_p: Optional[Union[Callable, List[Callable]]] = None,
add_d: Optional[Union[Callable, List[Callable]]] = None,
file: Optional[io.IOBase] = None) -> Optional[str]:
file = file or sys.stdout
content = str(content)
color = color or (lambda x: x)
add_p = (add_p if isinstance(add_p, list) else [add_p or (lambda x: x)])
add_d = (add_d if isinstance(add_d, list) else [add_d or (lambda x: x)])
if file == sys.stderr:
add_d.append(self.discord_error)
if not self.config['no_logs'] if self.config else True:
text = content
for func in add_p:
text = func(text)
print(color(text), file=file)
if self.webhook:
content = discord.utils.escape_markdown(content)
name = user_name or 'Fortnite-LobbyBot'
text = content
for func in add_d:
text = func(text)
self.webhook.send(text, name)
def time(self, text: str) -> str:
return f'[{self.now()}] {text}'
def discord_error(self, text: str) -> str:
texts = []
for line in text.split('\n'):
texts.append(f'> {line}')
return '\n'.join(texts)
def debug_message(self, text: str) -> str:
return f'```\n{text}\n```'
def format_exception(self, exc: Optional[Exception] = None) -> str:
if exc is not None:
return ''.join(list(traceback.TracebackException.from_exception(exc).format()))
return traceback.format_exc()
def print_exception(self, exc: Optional[Exception] = None) -> None:
if exc is not None:
self.send(
''.join(['Ignoring exception\n']
+ list(traceback.TracebackException.from_exception(exc).format())),
file=sys.stderr
)
else:
self.send(
traceback.format_exc(),
file=sys.stderr
)
def debug_print_exception(self, exc: Optional[Exception] = None) -> None:
if self.config is not None and self.config['loglevel'] == 'debug':
self.print_exception(exc)
def now(self) -> str:
return datetime.datetime.now().strftime('%H:%M:%S')
def utcnow(self) -> str:
return datetime.datetime.utcnow().strftime('%H:%M:%S')
def strftime(self, dt: datetime.datetime) -> str:
dt = dt.astimezone(get_localzone())
if dt.hour >= 12 and self.config['lang'] == 'en':
dt -= datetime.timedelta(hours=12)
return f"{dt.strftime('%H:%M PM')}"
return f"{dt.strftime('%H:%M')}"
def str_to_bool(self, text: str) -> bool:
if text.lower() == 'true':
return True
elif text.lower() == 'false':
return False
raise ValueError(f"{text!r} does not match to any of True, False")
def get_list_index(self, data: list, index: int, default: Optional[Any] = None) -> Any:
return data[index] if data[index:index + 1] else default
def eval_format(self, text: str, variables: dict) -> str:
return self.formatter.format(text, **variables)
def eval_dict(self, data: dict, keys: list) -> str:
text = ''
for key in keys:
text += f"[{repr(key)}]"
return text
def get_dict_key(self, data: dict, keys: list,
func: Optional[Callable] = None) -> Any:
func = func or (lambda x: x)
text = self.eval_dict(data, keys)
return func(eval(f'data{text}'))
def set_dict_key(self, data: dict, keys: list, value: Any,
func: Optional[Callable] = None) -> None:
func = func or (lambda x: x)
text = self.eval_dict(data, keys)
exec(f'data{text} = func(value)')
def eval_dict_default(self, data: dict, keys: list) -> Tuple[str, str]:
text = ''
text2 = ''
for nest, key in enumerate(keys, 1):
text += f"[{repr(key)}]"
if nest == len(keys):
if isinstance(key, str):
text2 += f".get('{key}', default)"
else:
text2 = f"self.get_list_index(data{text2}, key, default)"
else:
text2 += f"[{repr(key)}]"
return text, text2
def get_dict_key_default(self, data: dict, keys: list, default: Any,
func: Optional[Callable] = None) -> Any:
func = func or (lambda x: x)
_, text2 = self.eval_dict_default(data, keys)
try:
value = eval(f'data{text2}')
except (TypeError, KeyError):
value = default
return func(value)
def set_dict_key_default(self, data: dict, keys: list, default: Any,
func: Optional[Callable] = None) -> None:
func = func or (lambda x: x)
text, text2 = self.eval_dict_default(data, keys)
try:
value = eval(f'data{text2}') # noqa
except ValueError:
value = default # noqa
exec(f'data{text} = func(value)')
def load_config(self) -> Optional[Tuple[dict, list]]:
try:
config = self.load_json('config')
except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e:
self.send(
(f'{self.format_exception(e)}\n{e}\n'
+ self.l(
'load_failed_json',
'config',
default=(
"'{0}' ファイルの読み込みに失敗しました。正しく書き込めているか確認してください\n"
"Failed to load '{0}' file. Make sure you wrote correctly"
)
)),
file=sys.stderr
)
return None, None
except FileNotFoundError as e:
self.send(
(f'{self.format_exception(e)}\n{e}\n'
+ self.l(
'load_failed_not_found',
'config',
default=(
"'{0}' ファイルが存在しません\n"
"'{0}' file does not exist"
)
)),
file=sys.stderr
)
return None, None
self.set_dict_key_default(config, ['clients'], [])
self.set_dict_key_default(config, ['web'], {})
self.set_dict_key_default(config, ['web', 'enabled'], True)
self.set_dict_key_default(config, ['web', 'ip'], '{ip}')
self.set_dict_key_default(config, ['web', 'port'], 8000)
self.set_dict_key_default(config, ['check_update_on_startup'], True)
self.set_dict_key_default(config, ['lang'], 'en')
self.set_dict_key_default(config, ['api'], 'BenBot')
self.set_dict_key_default(config, ['api_key'], None)
self.set_dict_key_default(config, ['discord_log'], None)
self.set_dict_key_default(config, ['loglevel'], 'normal')
self.set_dict_key_default(config, ['no_logs'], 'normal')
self.set_dict_key_default(config, ['debug'], False)
self.set_dict_key_default(config, ['status'], 0)
if self.mode != 'pc':
replace = '0.0.0.0'
else:
replace = 'localhost'
config['web']['ip'] = config['web']['ip'].format(ip=replace)
error_config = []
self.tag_check(config, error_config, '', self.config_tags)
if config['loglevel'] == 'debug':
self.send(json.dumps(config, indent=4, ensure_ascii=False),
color=yellow, add_d=lambda x: f'{self.debug_message(x)}\n')
self.save_json('config', config)
if config['api'] == 'FortniteApi.io' and not config['api_key']:
self.send(
self.l('api_key_required'),
add_p=self.time,
file=sys.stderr
)
error_config.append("['api_key']")
return config, error_config
def load_localize(self, lang: str) -> Optional[dict]:
try:
localize = self.load_json(f'{self.lang_dir}/{lang}', force_file=True)
except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e:
self.send(
(f'{self.format_exception(e)}\n{e}\n'
+ self.l(
'load_failed_json',
f'{self.lang_dir}/{lang}',
default=(
"'{0}' ファイルの読み込みに失敗しました。正しく書き込めているか確認してください\n"
"Failed to load '{0}' file. Make sure you wrote correctly"
)
)),
file=sys.stderr
)
return None
except FileNotFoundError as e:
self.send(
(f'{self.format_exception(e)}\n{e}\n'
+ self.l(
'load_failed_not_found',
f'{self.lang_dir}/{lang}',
default=(
"'{0}' ファイルが存在しません\n"
"'{0}' file does not exist"
)
)),
file=sys.stderr
)
return None
return localize
def load_commands(self) -> Optional[Tuple[dict, list]]:
try:
commands = self.load_json('commands')
except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e:
self.send(
(f'{self.format_exception(e)}\n{e}\n'
+ self.l(
'load_failed_json',
'commands',
default=(
"'{0}' ファイルの読み込みに失敗しました。正しく書き込めているか確認してください\n"
"Failed to load '{0}' file. Make sure you wrote correctly"
)
)),
file=sys.stderr
)
return None, None
except FileNotFoundError as e:
self.send(
(f'{self.format_exception(e)}\n{e}\n'
+ self.l(
'load_failed_not_found',
'commands',
default=(
"'{0}' ファイルが存在しません\n"
"'{0}' file does not exist"
)
)),
file=sys.stderr
)
return None, None
error_commands = []
self.tag_check(commands, error_commands, '', self.commands_tags)
if self.config['loglevel'] == 'debug':
self.send(json.dumps(commands, indent=4, ensure_ascii=False),
color=yellow, add_d=lambda x: f'{self.debug_message(x)}\n')
self.save_json('commands', commands)
return commands, error_commands
def load_custom_commands(self) -> Optional[Tuple[dict, list]]:
try:
custom_commands = self.load_json('custom_commands')
except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e:
self.send(
(f'{self.format_exception(e)}\n{e}\n'
+ self.l(
'load_failed_json',
'custom_commands',
default=(
"'{0}' ファイルの読み込みに失敗しました。正しく書き込めているか確認してください\n"
"Failed to load '{0}' file. Make sure you wrote correctly"
)
)),
file=sys.stderr
)
return None, None
except FileNotFoundError as e:
self.send(
(f'{self.format_exception(e)}\n{e}\n'
+ self.l(
'load_failed_not_found',
'custom_commands',
default=(
"'{0}' ファイルが存在しません\n"
"'{0}' file does not exist"
)
)),
file=sys.stderr
)
return None, None
error_custom_commands = []
self.tag_check(custom_commands, error_custom_commands, '', self.custom_commands_tags)
if self.config['loglevel'] == 'debug':
self.send(json.dumps(custom_commands, indent=4, ensure_ascii=False),
color=yellow, add_d=lambda x: f'{self.debug_message(x)}\n')
self.save_json('custom_commands', custom_commands)
return custom_commands, error_custom_commands
def load_replies(self) -> Optional[Tuple[dict, list]]:
try:
replies = self.load_json('replies')
except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e:
self.send(
(f'{self.format_exception(e)}\n{e}\n'
+ self.l(
'load_failed_json',
'replies',
default=(
"'{0}' ファイルの読み込みに失敗しました。正しく書き込めているか確認してください\n"
"Failed to load '{0}' file. Make sure you wrote correctly"
)
)),
file=sys.stderr
)
return None, None
except FileNotFoundError as e:
self.send(
(f'{self.format_exception(e)}\n{e}\n'
+ self.l(
'load_failed_not_found',
'replies',
default=(
"'{0}' ファイルが存在しません\n"
"'{0}' file does not exist"
)
)),
file=sys.stderr
)
return None, None
error_replies = []
self.tag_check(replies, error_replies, '', self.replies_tags)
if self.config['loglevel'] == 'debug':
self.send(json.dumps(replies, indent=4, ensure_ascii=False),
color=yellow, add_d=lambda x: f'{self.debug_message(x)}\n')
self.save_json('replies', replies)
return replies, error_replies
def get_select_tag(self, data: list) -> Optional[str]:
for tag in data:
if isinstance(tag, str) and tag.startswith('select'):
return tag
def get_multiple_select_tag(self, data: list) -> Optional[str]:
for tag in data:
if isinstance(tag, str) and tag.startswith('multiple_select'):
return tag
def get_config_tag(self, data: list) -> Optional[str]:
for tag in data:
if isinstance(tag, str) and tag.endswith('_config'):
return tag
def flat_dict(self, data: dict) -> dict:
final = {}
for key, value in data.items():
if isinstance(value, dict):
for k, v in self.flat_dict(value).items():
final[f"[{repr(key)}]{k}"] = v
elif isinstance(value, list):
for num, val in enumerate(value):
if isinstance(val, dict):
for k, v in self.flat_dict(val).items():
final[f"[{repr(key)}][{num}]{k}"] = v
elif isinstance(val, list):
for n, v in enumerate(val):
final[f"[{repr(key)}][{num}][{n}]"] = v
else:
final[f"[{repr(key)}][{num}]"] = val
else:
final[f"[{repr(key)}]"] = value
return final
def tag_check(self, data: dict, error_list: list,
prefix: str, tag_data: dict) -> None:
for key, tags in tag_data.items():
self.value_check(data, error_list, prefix, key, tags)
def value_check(self, data: dict, error_list: list,
prefix: str, key: str, tags: list) -> None:
try:
value = eval(f'data{key}')
except Exception:
self.send(
self.l(
'is_missing',
f'{prefix}{key}',
default=(
"{0} がありません\n"
"{0} is missing"
)
),
file=sys.stderr
)
error_list.append(f'{prefix}{key}')
else:
select_tag = self.get_select_tag(tags)
multiple_select_tag = self.get_multiple_select_tag(tags)
config_tag = self.get_config_tag(tags)
valid_tags = (tags[0],)
if tags[0] is float:
valid_tags = (*valid_tags, int)
if 'can_be_none' in tags:
valid_tags = (*valid_tags, None.__class__)
if select_tag is not None:
tag_data = getattr(self, select_tag)
if self.none_data not in tag_data:
tag_data.append(self.none_data)
if multiple_select_tag is not None:
tag_data = getattr(self, multiple_select_tag)
if self.none_data not in tag_data:
tag_data.append(self.none_data)
if not isinstance(value, valid_tags):
expected = f'{tags[0].__name__}'
if 'can_be_none' in tags:
expected += f', {None.__class__.__name__}'
provided = type(value).__name__
converter = None
if tags[0] is bool:
if isinstance(value, str):
converter = 'self.str_to_bool(value)'
else:
converter = 'tags[0](value)'
elif tags[0] in [str, int]:
converter = 'tags[0](value)'
elif tags[0] is list:
if tags[1] is list:
converter = 'json.loads(value)'
elif tags[1] is str:
if isinstance(value, str):
converter = 'value.split(",")'
elif tags[1] is int:
if isinstance(value, int):
converter = '[value]'
else:
converter = '[int(value)]'
success = False
if converter is not None:
try:
exec(f'data{key} = {converter}')
value = eval(f'data{key}')
except Exception as e:
self.debug_print_exception(e)
else:
success = True
if not success:
self.send(
self.l(
'type_mismatch',
f'{prefix}{key}',
expected,
provided,
default=(
"'{0}' 型が一致しません(予想: '{1}' 実際: '{2}')\n"
"'{0}' type mismatch(Expected: '{1}' Provided: '{2}')\n"
)
),
file=sys.stderr
)
error_list.append(f'{prefix}{key}')
else:
self.send(
self.l(
'type_mismatch_fixed',
f'{prefix}{key}',
expected,
provided,
eval(f'data{key}'),
default=(
"'{0}' 型が一致しません(予想: '{1}' 実際: '{2}') -> 修正されました: '{3}'\n"
"'{0}' type mismatch(Expected: '{1}' Provided: '{2}') -> Fixed to: '{3}'\n"
)
),
color=yellow,
add_d=self.discord_error
)
if f'{prefix}{key}' not in error_list:
if tags[0] is list and value is not None:
try:
exec(f'data{key} = self.cleanup_list(value, "accept_empty" not in tags)')
except Exception as e:
self.debug_print_exception(e)
else:
if config_tag is None:
for num, val in enumerate(value):
tags_ = tags[1:].copy()
if select_tag is not None:
tags_.remove(select_tag)
if multiple_select_tag is not None:
tags_.remove(multiple_select_tag)
self.value_check(data, error_list,
prefix,
f'{key}[{num}]',
tags_)
if select_tag is not None:
values = [
(i['real_value'].lower()
if isinstance(i['real_value'], str) else
i['real_value'])
for i in getattr(self, select_tag)
]
if (value.lower()
if isinstance(value, str) else
value) not in values:
self.send(
self.l(
'not_in_select',
f'{prefix}{key}',
value,
values,
default=(
"'{0}' '{1}' は {2} のどれにも一致しません\n"
"'{0}' '{1}' don't match to any of {2}\n"
)
),
file=sys.stderr
)
error_list.append(f'{prefix}{key}')
else:
v = CaseInsensitiveDict({i['real_value']: i for i in getattr(self, select_tag)})
exec(f"data{key} = v[value]['real_value']")
if multiple_select_tag is not None and value is not None:
values = [
(i['real_value'].lower()
if isinstance(i['real_value'], str) else
i['real_value'])
for i in getattr(self, multiple_select_tag)
]
for num, val in enumerate(value):
if (val.lower()
if isinstance(val, str) else
val) not in values:
self.send(
self.l(
'not_in_select',
f'{prefix}{key}',
value,
values,
default=(
"'{0}' '{1}' は {2} のどれにも一致しません\n"
"'{0}' '{1}' don't match to any of {2}\n"
)
),
file=sys.stderr
)
error_list.append(f'{prefix}{key}')
break
else:
v = CaseInsensitiveDict({i['real_value']: i for i in getattr(self, multiple_select_tag)})
value[num] = v[val]['real_value']
func_str = tags[-1]
if isinstance(func_str, str) and func_str.startswith('lambda '):
try:
func = eval(func_str, {**globals(), **locals()})
except Exception:
pass
else:
if not func(value):
self.send(
self.l(
'check_failed',
f'{prefix}{key}',
value,
func_str,
default=(
"{0} '{1}' はチェック '{2}' に一致しません\n"
"{0} '{1}' don't match to check '{2}'\n"
)
),
file=sys.stderr
)
error_list.append(f'{prefix}{key}')
if config_tag is not None:
for num, val in enumerate(value):
self.tag_check(eval(f'data{key}[{num}]'),
error_list, f'{prefix}{key}[{num}]',
getattr(self, f'{config_tag}_tags'))
def cleanup_email(self, email: str) -> str:
return re.sub(r'\.|\+', '', email).lower()
def cleanup_code(self, content: str) -> str:
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
return content.strip(' \n')
def cleanup_list(self, data: list, remove_empty: Optional[bool] = True) -> list:
return [d for d in data if d is not None and (d != '' if remove_empty else True)]
def cleanup_channel_name(self, text: str) -> str:
converter = {
' ': '-',
'.': '-',
',': '-',
'--': '-'
}
for word, replace in converter.items():
text = text.replace(word, replace)
return text.lower()
def convert_backend_type(self, backendType: str) -> str:
return self.BACKEND_TO_API_CONVERTER.get(backendType)
def convert_to_backend_type(self, type: str) -> str:
return self.API_TO_BACKEND_CONVERTER.get(type)
def convert_backend_to_key(self, backendType: str) -> str:
return self.BACKEND_TO_KEY_CONVERTER.get(backendType)
def convert_backend_to_id(self, backendType: str) -> str:
return self.BACKEND_TO_ID_CONVERTER.get(backendType)
def convert_variant(self, variants: list) -> list:
if variants is None:
return None
return [
{
'name': option['name'],
'variants': [
{
'c': variant['channel'],
'v': (
option['tag']
if any([option['tag'].startswith(fmt) for fmt in self.VARIANT_FORMATS]) else
f'Color.{option["tag"]}'
),
'dE': 0
}
]
} for variant in variants for option in variant.get('options', [])
]
def get_item_str(self, item: dict) -> str:
return "<Item name='{0[name]}' id='{0[id]}' path='{0[path]}'>".format(
item
)
def get_playlist_str(self, playlist: dict) -> str:
return '<Playlist name={0[name]!r} id={0[id]!r}>'.format(
playlist
)
def get_variant_str(self, variant: dict) -> str:
return ('<Variant name={0[name]!r} '
'channel={1[c]!r} '
'tag={1[v]!r}>'.format(
variant,
variant['variants'][0]
))
def get_config_item_id(self, text: str) -> str:
if text is None:
return None
match = self.config_item_pattern.match(text)
if match is None:
return None
return match.group('id')
def get_config_item_path(self, text: str) -> str:
if text is None:
return None
match = self.config_item_pattern.match(text)
if match is None:
return None
return match.group('path')
def get_config_playlist_id(self, text: str) -> str:
if text is None:
return None
match = self.config_playlist_pattern.match(text)
if match is None:
return None
return match.group('id')
def get_config_variant(self, text: str) -> dict:
if text is None:
return None
match = self.config_variant_pattern.match(text)
if match is None:
return None
return {
'name': match.group('name'),
'variants': [
{
'c': match.group('channel'),
'v': match.group('tag'),
'dE': 0
}
]
}
def port_file(self, filename: str, backup: Optional[bool] = True) -> None:
if self.mode == 'repl' and os.path.isfile(f'{filename}.json'):
data = self.load_json(filename, force_file=True)
if backup:
if self.isfile(f'{filename}_old', force_file=True):
self.remove(f'{filename}_old', force_file=True)
self.rename(filename, f'{filename}_old', force_file=True)
try:
self.remove(filename, force_file=True)
except Exception as e:
self.debug_print_exception(e)
self.save_json(filename, data)
def remove_unneeded_files(self) -> None:
pc_only = [
'INSTALL.bat',
'requirements.txt',
'RUN.bat'
]
repl_only = [
'.replit',
'pyproject.toml'
]
if self.mode == 'pc':
for filename in repl_only:
if os.path.isfile(filename):
os.remove(filename)
windows_only = [
'INSTALL.bat',
'RUN.bat'
]
else_only = [
'INSTALL.sh',
'RUN.sh'
]
if sys.platform == 'win32':
for filename in else_only:
if os.path.isfile(filename):
os.remove(filename)
else:
for filename in windows_only:
if os.path.isfile(filename):
os.remove(filename)
elif self.mode == 'repl':
for filename in pc_only:
if os.path.isfile(filename):
os.remove(filename)
def setup(self) -> None:
self.remove_unneeded_files()
files = [
('config',),
('commands',),
('custom_commands',),
('replies',),
('cosmetic_preset',),
('command_stats', False),
('device_auths', False)
]
for detail in files:
self.port_file(*detail)
self.config, self.error_config = self.load_config()
if self.config is None and self.error_config is None:
sys.exit(1)
if self.error_config:
self.send(
self.l(
'error_keys',
'\n'.join(self.error_config),
default=(
"以下のキーに問題がありました\n{0}\n"
"There was an error on these keys\n{0}\n"
)
),
file=sys.stderr
)
self.webhook = WebhookClient(self, self, self.loop, self.http)
self.webhook.start()
if self.config['discord']['enabled']:
self.discord_client = DiscordClient(self, self.config, loop=self.loop)
if self.isfile(f"{self.lang_dir}/{self.config['lang']}", force_file=True):
self.localize = self.load_localize(self.config['lang'])
else:
self.localize = self.load_localize('en')
self.commands, self.error_commands = self.load_commands()
if self.commands is None and self.error_commands is None:
sys.exit(1)
if self.error_commands:
self.send(
self.l(
'error_keys',
'\n'.join(self.error_commands),
default=(
"以下のキーに問題がありました\n{0}\n"
"There was an error on keys\n{0}\n"
)
),
file=sys.stderr
)
self.custom_commands, self.error_custom_commands = self.load_custom_commands()
if self.custom_commands is None and self.error_custom_commands is None:
sys.exit(1)
if self.error_custom_commands:
self.send(
self.l(
'error_keys',
'\n'.join(self.error_custom_commands),
default=(
"以下のキーに問題がありました\n{0}\n"
"There was an error on keys\n{0}\n"
)
),
file=sys.stderr
)
self.replies, self.error_replies = self.load_replies()
if self.replies is None and self.error_replies is None:
sys.exit(1)
if self.error_replies:
self.send(
self.l(
'error_keys',
'\n'.join(self.error_replies),
default=(
"以下のキーに問題がありました\n{0}\n"
"There was an error on keys\n{0}\n"
)
),
file=sys.stderr
)
ids = [f'{prefix}_'.lower() for prefix in self.BACKEND_TO_ID_CONVERTER.values()]
self.whitelist_commands = []
for identifier in self.commands['whitelist_commands']:
identifier = identifier.lower()
command = self.all_commands.get(identifier)
if command is None and identifier not in [*ids, 'playlist_', 'item_search']:
self.send(
self.l(
'command_not_found',
self.l('whitelist_command'),
identifier
)
)
else:
self.whitelist_commands.append(identifier)
self.user_commands = []
for identifier in self.commands['user_commands']:
identifier = identifier.lower()
command = self.all_commands.get(identifier)
if command is None and identifier not in [*ids, 'playlist_', 'item_search']:
self.send(
self.l(
'command_not_found',
self.l('user_command'),
identifier
)
)
else:
self.user_commands.append(identifier)
if not self.is_error():
self.send(
self.l(
'load_success',
default=(
"正常に読み込みが完了しました\n"
"Loading successfully finished\n"
)
),
color=green
)
elif self.config['web']['enabled']:
self.send(
self.l(
'load_failed_web',
default=(
"正常に読み込みが完了しませんでした。ファイルを直接修正するか、Webから修正してください\n"
"Loading didn't finish successfully. Please fix files directly or fix from web\n"
)
),
file=sys.stderr
)
else:
self.send(
self.l(
'load_failed',
default=(
"正常に読み込みが完了しませんでした。ファイルを修正してください\n"
"Loading didn't finish successfully. Please fix files\n"
)
),
file=sys.stderr
)
sys.exit(1)
try:
self.cosmetic_presets = self.get_cosmetic_presets()
except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e:
self.debug_print_exception(e)
if self.isfile('cosmetic_presets_old'):
self.remove('cosmetic_presets_old')
self.rename('cosmetic_presets', 'cosmetic_presets_old')
try:
self.remove('cosmetic_presets')
except Exception as e:
self.debug_print_exception(e)
self.cosmetic_presets = {}
try:
self.command_stats = self.get_command_stats()
except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e:
self.debug_print_exception(e)
if self.isfile('command_stats_old'):
self.remove('command_stats_old')
self.rename('command_stats', 'command_stats_old')
try:
self.remove('command_stats')
except Exception as e:
self.debug_print_exception(e)
self.command_stats = {}
async def aexec(self, body: str, variables: dict) -> Tuple[Any, str, str]:
body = self.cleanup_code(body)
stdout = io.StringIO()
stderr = io.StringIO()
exc = f"async def __exc__():\n{textwrap.indent(body,' ')}"
exec(exc, variables)
func = variables['__exc__']
with redirect_stdout(stdout), redirect_stderr(stderr):
return await func(), stdout.getvalue(), stderr.getvalue()
def format_item(self, data: dict, mode: str) -> dict:
if mode == 'BenBot':
return {
'id': data['id'],
'path': f"{self.convert_backend_type(data['backendType'])}ItemDefinition'{data['path'].replace('FortniteGame/Content', '/Game')}.{data['path'].split('/')[-1]}'",
'name': data['name'],
'url': data['icons']['icon'],
'type': {
'value': self.convert_backend_type(data['backendType']),
'displayValue': data['shortDescription'],
'backendValue': data['backendType']
},
'set': data['set'],
'variants': self.convert_variant(data['variants'])
}
elif mode == 'Fortnite-API':
return {
'id': data['id'],
'path': f"{data['type']['backendValue']}ItemDefinition'{data['path'].replace('FortniteGame/Content', '/Game')}.{data['path'].split('/')[-1]}'",
'name': data['name'],
'url': data['images']['icon'],
'type': data['type'],
'set': data['set']['value'] if data['set'] is not None else None,
'variants': self.convert_variant(data['variants'])
}
elif mode == 'FortniteApi.io':
return {
'id': data['id'],
'path': MyClientPartyMember.get_asset_path(self.convert_to_backend_type(data['type']), data['id']),
'name': data['name'],
'url': data['images']['icon'],
'type': {
'value': data['type'],
'displayValue': (
self.l(data['type']).get_text()
),
'backendValue': self.convert_to_backend_type(data['type'])
},
'set': data['set'] if data['set'] else None,
'variants': None
}
def format_items(self, data: list, mode: str) -> list:
types = [
'AthenaCharacter',
'AthenaBackpack',
'AthenaPet',
'AthenaPetCarrier',
'AthenaPickaxe',
'AthenaDance',
'AthenaEmoji',
'AthenaToy'
]
return [item for item in [
self.format_item(item, mode)
for item in sorted(data, key=lambda x: x['id'])
] if item['type']['backendValue'] in types]
async def get_item_data(self, lang: str) -> list:
if self.config['api'] == 'BenBot':
return self.format_items(await self.http.get(
'http://benbot.app/api/v1/cosmetics/br',
params={'lang': lang}
), self.config['api'])
elif self.config['api'] == 'Fortnite-API':
return self.format_items((await self.http.get(
'https://fortnite-api.com/v2/cosmetics/br',
params={'language': lang}
))['data'], self.config['api'])
elif self.config['api'] == 'FortniteApi.io':
items = (await self.http.get(
'https://fortniteapi.io/v1/items/list',
params={'lang': lang},
headers={'Authorization': self.config['api_key']}
))['items']
return self.format_items(
sum(
[v for k, v in items.items() if k not in [
'bannertoken',
'bundle',
'cosmeticvariant'
]],
[]
),
self.config['api']
)
async def store_item_data(self, lang: str) -> None:
if self.isfile(f'{self.item_dir}/items_{lang}', force_file=True):
items = await self.aload_json(f'{self.item_dir}/items_{lang}', force_file=True)
items['items'] = CaseInsensitiveDict(items['items'])
else:
items = {'api': None, 'items': CaseInsensitiveDict()}
data = await self.get_item_data(lang)
if self.config['api'] == 'FortniteApi.io':
for item in data:
i = items['items'].get(item['id'])
if i is None:
items['items'][item['id']] = item
elif i['variants'] is not None:
item['variants'] = i['variants']
items['items'][item['id']] = item
else:
for item in data:
items['items'][item['id']] = item
items['api'] = self.config['api']
self.save_json(
f'{self.item_dir}/items_{lang}',
items,
force_file=True,
compact=True
)
async def get_new_item_data(self, lang: str) -> list:
if self.config['api'] == 'BenBot':
return self.format_items((await self.http.get(
'http://benbot.app/api/v1/newCosmetics',
params={'lang': lang}
))['items'], self.config['api'])
elif self.config['api'] == 'Fortnite-API':
return self.format_items((await self.http.get(
'https://fortnite-api.com/v2/cosmetics/br/new',
params={'language': lang}
))['data']['items'], self.config['api'])
elif self.config['api'] == 'FortniteApi.io':
return self.format_items((await self.http.get(
'https://fortniteapi.io/v1/items/upcoming',
params={'lang': lang},
headers={'Authorization': self.config['api_key']}
))['items'], self.config['api'])
async def store_new_item_data(self, lang: str) -> None:
if self.isfile(f'{self.item_dir}/new_items_{lang}', force_file=True):
items = await self.aload_json(f'{self.item_dir}/new_items_{lang}', force_file=True)
items['items'] = CaseInsensitiveDict(items['items'])
else:
items = {'api': None, 'items': CaseInsensitiveDict()}
data = {i['id']: i for i in await self.get_new_item_data(lang)}
if self.config['api'] == 'FortniteApi.io':
for item in items['items'].values():
i = data.get(item['id'])
if i is None:
continue
if item['variants'] is not None:
data[item['id']]['variants'] = item['variants']
items['api'] = self.config['api']
self.save_json(
f'{self.item_dir}/new_items_{lang}',
{'api': self.config['api'], 'items': data},
force_file=True,
compact=True
)
def format_playlist(self, data: dict, mode: str) -> dict:
if mode == 'Fortnite-API':
return {
'id': data['id'],
'name': data['name']
}
elif mode == 'FortniteApi.io':
return {
'id': f'Playlist_{data["id"]}',
'name': data['name']
}
def format_playlists(self, data: list, mode: str) -> list:
return [
self.format_playlist(playlist, mode)
for playlist in sorted(data, key=lambda x: x['id'])
]
async def get_playlists_data(self, lang: str) -> list:
if self.config['api'] == 'BenBot':
return []
elif self.config['api'] == 'Fortnite-API':
return self.format_playlists(
(await self.http.get(
'https://fortnite-api.com/v1/playlists',
params={'language': lang}
))['data'], self.config['api']
)
elif self.config['api'] == 'FortniteApi.io':
return self.format_playlists(
(await self.http.get(
'https://fortniteapi.io/v1/game/modes',
params={'lang': lang},
headers={'Authorization': self.config['api_key']}
))['modes'], self.config['api']
)
async def store_playlists_data(self, lang: str) -> None:
if self.isfile(f'{self.item_dir}/playlists_{lang}', force_file=True):
playlists = await self.aload_json(f'{self.item_dir}/playlists_{lang}', force_file=True)
playlists['playlists'] = CaseInsensitiveDict(playlists['playlists'])
else:
playlists = {'api': None, 'playlists': CaseInsensitiveDict()}
data = await self.get_playlists_data(lang)
for playlist in data:
playlists['playlists'][playlist['id']] = playlist
playlists['api'] = self.config['api']
self.save_json(
f'{self.item_dir}/playlists_{lang}',
playlists,
force_file=True,
compact=True
)
async def get_banner_data(self) -> dict:
if self.config['api'] == 'BenBot':
data = await self.http.get(
'https://benbot.app/api/v1/files/search',
params={
'matchMethod': 'starts',
'path': 'FortniteGame/Content/Items/BannerIcons/'
}
)
url = 'https://benbot.app/api/v1/exportAsset?path={}&rawIcon=true'
return {
banner[39:-7]: url.format(banner) for banner in data
}
elif self.config['api'] == 'Fortnite-API':
data = (await self.http.get(
'https://fortnite-api.com/v1/banners'
))['data']
return {
banner['id']: banner['images']['icon'] for banner in data
}
elif self.config['api'] == 'FortniteApi.io':
return {}
async def store_banner_data(self) -> None:
if self.isfile(f'{self.item_dir}/banners', force_file=True):
banners = await self.aload_json(f'{self.item_dir}/banners', force_file=True)
banners['banners'] = CaseInsensitiveDict(banners['banners'])
else:
banners = {'api': None, 'banners': CaseInsensitiveDict()}
data = await self.get_banner_data()
for id, image in data.items():
banners['banners'][id] = image
banners['api'] = self.config['api']
self.save_json(
f'{self.item_dir}/banners',
banners,
force_file=True,
compact=True
)
def get_banner_url(self, banner_id: str) -> Optional[str]:
return self.banners.get(banner_id, self.web.url_for('static', filename='images/banner.jpg'))
async def error_callback(self, client: Client, e: Exception):
if isinstance(e, fortnitepy.AuthException):
if 'Invalid device auth details passed.' in e.args[0]:
self.debug_print_exception(e)
self.send(
self.l(
'device_auth_error',
client.config['fortnite']['email']
),
add_p=self.time,
file=sys.stderr
)
details = self.get_device_auth_details()
details.pop(client.config['fortnite']['email'])
self.save_json('device_auths', details)
else:
self.print_exception(e)
self.send(
self.l(
'login_failed',
client.config['fortnite']['email']
),
add_p=self.time,
file=sys.stderr
)
else:
self.print_exception(e)
self.send(
self.l(
'login_failed',
client.config['fortnite']['email']
),
add_p=self.time,
file=sys.stderr
)
async def all_ready_callback(self):
if len(self.clients) > 1:
await asyncio.gather(*[client.wait_until_ready() for client in self.clients])
self.send(
self.l(
'all_login'
),
color=green,
add_p=self.time
)
async def update_data(self) -> None:
# Cosmetics
tasks = []
if self.isfile(f"{self.item_dir}/items_{self.config['search_lang']}", force_file=True):
try:
items = await self.aload_json(f"{self.item_dir}/items_{self.config['search_lang']}", force_file=True)
except json.decoder.JSONDecodeError as e:
self.debug_print_exception(e)
await self.aremove(f"{self.item_dir}/items_{self.config['search_lang']}", force_file=True)
flag = True
else:
if items['api'] != self.config['api']:
flag = True
else:
flag = self.is_not_edited_for(
f"{self.item_dir}/items_{self.config['search_lang']}",
datetime.timedelta(hours=2),
force_file=True
)
else:
flag = True
if flag:
tasks.append(self.loop.create_task(self.store_item_data(self.config['search_lang'])))
if self.isfile(f"{self.item_dir}/items_{self.config['sub_search_lang']}", force_file=True):
try:
items = await self.aload_json(f"{self.item_dir}/items_{self.config['sub_search_lang']}", force_file=True)
except json.decoder.JSONDecodeError as e:
self.debug_print_exception(e)
await self.aremove(f"{self.item_dir}/items_{self.config['sub_search_lang']}", force_file=True)
flag = True
else:
if items['api'] != self.config['api']:
flag = True
else:
flag = self.is_not_edited_for(
f"{self.item_dir}/items_{self.config['sub_search_lang']}",
datetime.timedelta(hours=2),
force_file=True
)
else:
flag = True
if flag:
tasks.append(self.loop.create_task(self.store_item_data(self.config['sub_search_lang'])))
exception = False
if tasks:
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
for p in pending:
if not p.done():
p.cancel()
for d in done:
if d.exception() is not None:
exception = True
self.print_exception(d.exception())
if exception:
self.send(
self.l(
'get_item_failed'
),
file=sys.stderr
)
for lang in (self.config['search_lang'], self.config['sub_search_lang']):
if not self.isfile(f'{self.item_dir}/items_{lang}', force_file=True):
sys.exit(1)
# New cosmetics
tasks = []
if self.isfile(f"{self.item_dir}/new_items_{self.config['search_lang']}", force_file=True):
try:
items = await self.aload_json(f"{self.item_dir}/new_items_{self.config['search_lang']}", force_file=True)
except json.decoder.JSONDecodeError as e:
self.debug_print_exception(e)
await self.aremove(f"{self.item_dir}/new_items_{self.config['search_lang']}", force_file=True)
flag = True
else:
if items['api'] != self.config['api']:
flag = True
else:
flag = self.is_not_edited_for(
f"{self.item_dir}/new_items_{self.config['search_lang']}",
datetime.timedelta(hours=2),
force_file=True
)
else:
flag = True
if flag:
try:
await self.store_new_item_data(self.config['search_lang'])
except Exception as e:
self.print_exception(e)
self.send(
self.l(
'get_item_failed'
),
file=sys.stderr
)
# Playlists
tasks = []
if self.isfile(f"{self.item_dir}/playlists_{self.config['search_lang']}", force_file=True):
try:
playlists = await self.aload_json(f"{self.item_dir}/playlists_{self.config['search_lang']}", force_file=True)
except json.decoder.JSONDecodeError as e:
self.debug_print_exception(e)
await self.aremove(f"{self.item_dir}/playlists_{self.config['search_lang']}", force_file=True)
flag = True
else:
if playlists['api'] != self.config['api']:
flag = True
else:
flag = self.is_not_edited_for(
f"{self.item_dir}/playlists_{self.config['search_lang']}",
datetime.timedelta(hours=2),
force_file=True
)
else:
flag = True
if flag:
tasks.append(self.loop.create_task(self.store_playlists_data(self.config['search_lang'])))
if self.isfile(f"{self.item_dir}/playlists_{self.config['sub_search_lang']}", force_file=True):
try:
playlists = await self.aload_json(f"{self.item_dir}/playlists_{self.config['sub_search_lang']}", force_file=True)
except json.decoder.JSONDecodeError as e:
self.debug_print_exception(e)
await self.aremove(f"{self.item_dir}/playlists_{self.config['sub_search_lang']}", force_file=True)
flag = True
else:
if playlists['api'] != self.config['api']:
flag = True
else:
flag = self.is_not_edited_for(
f"{self.item_dir}/playlists_{self.config['sub_search_lang']}",
datetime.timedelta(hours=2),
force_file=True
)
else:
flag = True
if flag:
tasks.append(self.loop.create_task(self.store_playlists_data(self.config['sub_search_lang'])))
exception = False
if tasks:
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
for p in pending:
if not p.done():
p.cancel()
for d in done:
if d.exception() is not None:
exception = True
self.print_exception(d.exception())
if exception:
self.send(
self.l(
'get_playlist_failed'
),
file=sys.stderr
)
for lang in (self.config['search_lang'], self.config['sub_search_lang']):
if not self.isfile(f'{self.item_dir}/playlists_{lang}', force_file=True):
sys.exit(1)
# Banner
if not exception:
if self.isfile(f'{self.item_dir}/banners', force_file=True):
try:
banners = await self.aload_json(f"{self.item_dir}/banners", force_file=True)
except json.decoder.JSONDecodeError as e:
self.debug_print_exception(e)
await self.aremove(f"{self.item_dir}/banners", force_file=True)
flag = True
else:
if banners['api'] != self.config['api']:
flag = True
else:
flag = self.is_not_edited_for(
f'{self.item_dir}/banners',
datetime.timedelta(hours=2),
force_file=True
)
else:
flag = True
if flag:
await self.store_banner_data()
def load_data(self) -> None:
self.main_items = CaseInsensitiveDict(self.load_json(
f'{self.item_dir}/items_{self.config["search_lang"]}',
force_file=True
)['items'])
self.sub_items = CaseInsensitiveDict(self.load_json(
f'{self.item_dir}/items_{self.config["sub_search_lang"]}',
force_file=True
)['items'])
self.new_items = CaseInsensitiveDict(self.load_json(
f'{self.item_dir}/new_items_{self.config["search_lang"]}',
force_file=True
)['items'])
self.main_playlists = CaseInsensitiveDict(self.load_json(
f'{self.item_dir}/playlists_{self.config["search_lang"]}',
force_file=True
)['playlists'])
self.sub_playlists = CaseInsensitiveDict(self.load_json(
f'{self.item_dir}/playlists_{self.config["sub_search_lang"]}',
force_file=True
)['playlists'])
self.banners = CaseInsensitiveDict(self.load_json(
f'{self.item_dir}/banners',
force_file=True
)['banners'])
def fix_config(self, config: dict) -> None:
if isinstance(config['fortnite']['party']['privacy'], str):
config['fortnite']['party']['privacy'] = getattr(
PartyPrivacy,
config['fortnite']['party']['privacy'].upper()
)
if isinstance(config['fortnite']['platform'], str):
config['fortnite']['platform'] = fortnitepy.Platform(
config['fortnite']['platform'].upper()
)
for num, channel in enumerate(config['discord']['channels']):
config['discord']['channels'][num] = self.cleanup_channel_name(channel)
if isinstance(config['discord']['status_type'], str):
config['discord']['status_type'] = getattr(
discord.ActivityType,
config['discord']['status_type'].lower()
)
if config['fortnite']['ng_platforms'] is not None:
for num, ng_platform in enumerate(config['fortnite']['ng_platforms']):
config['fortnite']['ng_platforms'][num] = fortnitepy.Platform(
ng_platform.upper()
)
self.fix_cosmetic_config(config)
def fix_config_all(self) -> None:
if isinstance(self.config['discord']['status_type'], str):
self.config['discord']['status_type'] = getattr(
discord.ActivityType,
self.config['discord']['status_type'].lower()
)
for num, channel in enumerate(self.config['discord']['channels']):
self.config['discord']['channels'][num] = self.cleanup_channel_name(channel)
for config in self.config['clients']:
self.fix_config(config)
def fix_cosmetic_config(self, config: dict) -> None:
if config['fortnite']['party']['playlist']:
if self.get_config_playlist_id(config['fortnite']['party']['playlist']) is None:
playlist = self.searcher.get_playlist(
config['fortnite']['party']['playlist']
)
if playlist is None:
playlists = self.searcher.search_playlist_name_id(
config['fortnite']['party']['playlist']
)
if len(playlists) != 0:
playlist = playlists[0]
if playlist is not None:
config['fortnite']['party']['playlist'] = (
self.get_playlist_str(playlist)
)
else:
self.send(
self.l(
'not_found',
self.l('playlist'),
config['fortnite']['party']['playlist']
),
add_p=self.time,
file=sys.stderr
)
for item in ['AthenaCharacter',
'AthenaBackpack,AthenaPet,AthenaPetCarrier',
'AthenaPickaxe',
'AthenaDance,AthenaEmoji,AthenaToy']:
lang_key = self.convert_backend_type(item.split(",")[0])
for prefix in ['', 'join_', 'leave_']:
key = f'{prefix}{lang_key}'
style_key = f'{key}_style'
if not config['fortnite'][key]:
continue
def fix_cosmetic_style_config():
if 'AthenaDance' in item or not config['fortnite'][style_key]:
return
for num, style_info in enumerate(config['fortnite'][style_key]):
if self.get_config_variant(style_info) is not None:
continue
styles = self.searcher.search_style(
self.get_config_item_id(config['fortnite'][key]),
style_info
)
if len(styles) != 0:
style = styles[0]
config['fortnite'][style_key][num] = (
self.get_variant_str(style)
)
else:
self.send(
self.l(
'not_found',
self.l('style'),
config['fortnite'][key]
),
add_p=self.time,
file=sys.stderr
)
if self.get_config_item_id(config['fortnite'][key]) is not None:
fix_cosmetic_style_config()
continue
if config['fortnite'][key]:
old = re.compile(
r"<Item name='(?P<name>.+)' "
r"id='(?P<id>.+)'>"
)
match = old.match(config['fortnite'][key])
cosmetic = self.searcher.get_item(
match.group('id') if match is not None else config['fortnite'][key]
)
if cosmetic is None:
cosmetics = self.searcher.search_item_name_id(
config['fortnite'][key],
item
)
if len(cosmetics) != 0:
cosmetic = cosmetics[0]
if cosmetic is not None:
config['fortnite'][key] = (
self.get_item_str(cosmetic)
)
fix_cosmetic_style_config()
else:
self.send(
self.l(
'not_found',
self.l(lang_key),
config['fortnite'][key]
),
add_p=self.time,
file=sys.stderr
)
key = f'ng_{lang_key}s'
if not config['fortnite'][key]:
continue
for num, value in enumerate(config['fortnite'][key]):
if self.get_config_item_id(value) is not None:
continue
if value:
cosmetic = self.searcher.get_item(
value
)
if cosmetic is None:
cosmetics = self.searcher.search_item_name_id(
value,
item
)
if len(cosmetics) != 0:
cosmetic = cosmetics[0]
if cosmetic is not None:
config['fortnite'][key][num] = (
self.get_item_str(cosmetic)
)
else:
self.send(
self.l(
'not_found',
self.l(lang_key),
value
),
add_p=self.time,
file=sys.stderr
)
def fix_cosmetic_config_all(self) -> None:
for config in self.config['clients']:
self.fix_cosmetic_config(config)
async def reboot(self) -> None:
await self.close()
os.execv(sys.executable, [sys.executable, sys.argv[0], *sys.argv[1:]])
async def close(self) -> None:
if self.server is not None:
await self.server.close()
coros = {client.wait_until_ready() for client in self.clients}
if coros:
await asyncio.wait(coros)
await fortnitepy.close_multiple(
[client for client in self.clients if client.is_ready() or client.is_booting()]
)
await self.http.close()
async def rebooter(self) -> None:
await asyncio.sleep(self.config['restart_in'])
await self.reboot()
async def save_command_stats(self) -> None:
while True:
await asyncio.sleep(60)
self.store_command_stats()
async def keep_alive(self) -> None:
url = None
if self.mode == 'glitch':
url = f'https://{os.getenv("PROJECT_DOMAIN")}.glitch.me'
elif self.mode == 'repl':
url = f'https://{os.getenv("REPL_SLUG")}.{os.getenv("REPL_OWNER")}.repl.co'
await self.http.post('https://PublicPinger.gomashio1596.repl.co/api/add', json={'url': url})
while True:
await asyncio.sleep(300)
await self.http.get(url)
async def start(self) -> None:
self.send(
self.l('credit'),
color=cyan
)
self.send(
f'{self.l("loglevel", self.l("loglevel_" + self.config["loglevel"]))}\n',
color=green
)
if self.config['debug']:
logger = logging.getLogger('fortnitepy.auth')
logger.setLevel(level=logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('\u001b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \u001b[0m'))
logger.addHandler(handler)
logger = logging.getLogger('fortnitepy.http')
logger.setLevel(level=logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('\u001b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \u001b[0m'))
logger.addHandler(handler)
logger = logging.getLogger('fortnitepy.xmpp')
logger.setLevel(level=logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('\u001b[35m %(asctime)s:%(levelname)s:%(name)s: %(message)s \u001b[0m'))
logger.addHandler(handler)
version = sys.version_info
if version.minor != 7:
self.send(
self.l(
'not_recommended_version',
platform.python_version()
),
color=yellow
)
python_64bit = sys.maxsize > 2 ** 32
if sys.platform == 'win32':
os_64bit = os.getenv('PROCESSOR_ARCHITECTURE') != 'x86'
elif sys.platform == 'linux':
output = subprocess.check_output(['uname', '-a']).decode()
os_64bit = 'x86_64' in output or 'amd64' in output
elif sys.platform == 'darwin':
os_64bit = (
subprocess.check_output(['uname', '-a']).decode()
).endswith('x86_64')
else:
os_64bit = python_64bit
if os_64bit and not python_64bit:
self.send(
self.l(
'bit_mismatch',
'64' if python_64bit else '32',
'64' if os_64bit else '32'
),
color=yellow
)
if self.config['check_update_on_startup']:
if await self.updater.check_updates(self.dev):
await self.reboot()
sys.exit(0)
if not self.is_error() and self.config['status'] == 1:
self.send(
self.l(
'updating',
),
add_p=self.time
)
await self.update_data()
self.load_data()
self.searcher = Searcher(
self,
self.main_items,
self.sub_items,
self.main_playlists,
self.sub_playlists,
True,
False
)
self.send(
self.l(
'booting',
),
add_p=self.time
)
if self.config['restart_in']:
self.loop.create_task(self.rebooter())
self.loop.create_task(self.save_command_stats())
if self.mode != 'pc' and self.config['web']['enabled']:
self.loop.create_task(self.keep_alive())
if self.config['web']['enabled'] or self.config['status'] == 0:
if not self.config['web']['access_log']:
logger = getLogger('sanic.root')
logger.setLevel(WARNING)
try:
self.server = await self.web.create_server(
host=self.config['web']['ip'],
port=self.config['web']['port'],
access_log=self.config['web']['access_log'],
return_asyncio_server=True
)
except OSError as e:
self.debug_print_exception(e)
self.send(
self.l(
'web_already_running'
),
add_p=self.time,
file=sys.stderr
)
else:
if self.mode == 'glitch':
url = f'https://{os.getenv("PROJECT_DOMAIN")}.glitch.me'
elif self.mode == 'repl':
url = f'https://{os.getenv("REPL_SLUG")}--{os.getenv("REPL_OWNER")}.repl.co'
else:
url = f"http://{self.config['web']['ip']}:{self.config['web']['port']}"
self.send(
self.l(
'web_running',
url
),
color=green,
add_p=self.time
)
if (self.mode == 'repl' and (not self.config['web']['login_required']
or (self.config['web']['login_required'] and not self.config['web']['password']))):
self.send(
self.l('password_not_set'),
color=yellow
)
if not self.is_error() and self.config['status'] == 1:
self.fix_config_all()
self.save_json('config', self.config)
refresh_tokens = {}
device_auths = {}
if self.use_device_auth:
try:
device_auths = self.get_device_auth_details()
except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e:
self.debug_print_exception(e)
if self.isfile('device_auths_old'):
self.remove('device_auths_old')
self.rename('device_auths', 'device_auths_old')
try:
self.remove('device_auths')
except Exception as e:
self.debug_print_exception(e)
else:
try:
refresh_tokens = self.get_refresh_tokens()
except (json.decoder.JSONDecodeError, UnicodeDecodeError) as e:
self.debug_print_exception(e)
if self.isfile('refresh_tokens_old'):
self.remove('refresh_tokens_old')
self.rename('refresh_tokens', 'refresh_tokens_old')
try:
self.remove('refresh_tokens')
except Exception as e:
self.debug_print_exception(e)
def session_id(email):
async def _session_id():
while True:
text = self.l('session_id', email).get_text()
self.web_text = text
data = await ainput(f'{text}\n')
match = re.search(r'[a-z0-9]{32}', data)
if match is not None:
return match.group()
return _session_id
for num, config in enumerate(self.config['clients']):
refresh_token = refresh_tokens.get(config['fortnite']['email'].lower(), None)
device_auth_details = device_auths.get(config['fortnite']['email'].lower(), {})
party_meta = []
if config['fortnite']['party']['playlist']:
party_meta.append(partial(
MyClientParty.set_playlist,
playlist=(self.get_config_playlist_id(config['fortnite']['party']['playlist'])
or config['fortnite']['party']['playlist'])
))
if config['fortnite']['party']['disable_voice_chat']:
party_meta.append(partial(
MyClientParty.disable_voice_chat
))
member_meta = [
partial(
MyClientPartyMember.set_banner,
icon=config['fortnite']['banner_id'],
color=config['fortnite']['banner_color'],
season_level=config['fortnite']['level']
),
partial(
MyClientPartyMember.set_battlepass_info,
has_purchased=True,
level=config['fortnite']['tier']
)
]
items = [
'AthenaCharacter',
'AthenaBackpack',
'AthenaPickaxe',
'AthenaDance'
]
for item in items:
conf = self.convert_backend_type(item)
variants = []
if item != 'AthenaDance' and config['fortnite'][f'{conf}_style'] is not None:
for style in config['fortnite'][f'{conf}_style']:
variant = self.get_config_variant(style)
if variant is not None:
variants.extend(variant['variants'])
section = 0
if item == 'AthenaDance':
section = config['fortnite'][f'{conf}_section']
coro = fortnitepy.EditEntry(
MyClientPartyMember.change_asset,
item,
(self.get_config_item_path(config['fortnite'][conf])
or config['fortnite'][conf]),
variants=variants,
section=section,
keep=False,
name=f'ClientPartyMember.set_{conf}'
)
member_meta.append(coro)
avatar = fortnitepy.kairos.get_random_default_avatar()
background_colors = (
config['fortnite']['avatar_color'].split(',')
if ',' in config['fortnite']['avatar_color'] else
getattr(fortnitepy.KairosBackgroundColorPreset, config['fortnite']['avatar_color'].upper())
)
auth = None
if self.use_device_auth and device_auth_details:
auth = fortnitepy.DeviceAuth(**device_auth_details)
if auth is None:
if self.use_device_code:
auth = MyAdvancedAuth(refresh_token)
else:
auth = MyAdvancedAuth(refresh_token, session_id(config['fortnite']['email']))
client = Client(
self,
config,
num,
auth=auth,
avatar=fortnitepy.Avatar(
asset=(
config['fortnite']['avatar_id']
or avatar.asset
),
background_colors=(
background_colors
if config['fortnite']['avatar_color'] else
avatar.background_colors
)
),
status=config['fortnite']['status'],
platform=config['fortnite']['platform'],
wait_for_member_meta_in_events=False,
loop=self.loop
)
client.default_party_config = fortnitepy.DefaultPartyConfig(
cls=MyClientParty,
privacy=config['fortnite']['party']['privacy'],
team_change_allowed=config['fortnite']['party']['allow_swap'],
max_size=config['fortnite']['party']['max_size'],
meta=party_meta
)
client.default_party_member_config = fortnitepy.DefaultPartyMemberConfig(
cls=MyClientPartyMember,
meta=member_meta
)
self.clients.append(client)
if len(self.clients) == 0:
self.send(
self.l('no_clients')
)
while True:
await asyncio.sleep(0.1)
else:
tasks = [
fortnitepy.start_multiple(
self.clients,
shutdown_on_error=False,
error_callback=self.error_callback,
all_ready_callback=self.all_ready_callback
)
]
if self.discord_client is not None and self.config['discord']['token']:
tasks.append(self.discord_client.start(self.config['discord']['token']))
try:
await asyncio.gather(*tasks)
except Exception as e:
self.print_exception(e)
while True:
await asyncio.sleep(0.1)
async def process_command(self, message: MyMessage, *args: Any, **kwargs: Any) -> None:
if not message.args:
return
for client in self.clients:
message.client = client
self.loop.create_task(client.process_command(message, None))
| 42.568867 | 218 | 0.469296 | 117,815 | 0.985224 | 0 | 0 | 255 | 0.002132 | 34,156 | 0.285628 | 28,771 | 0.240596 |
8981fe86ea2397da714b6b0b5707eb9553a6410d | 1,573 | py | Python | metagraph/tests/translators/test_matrix.py | paul-tqh-nguyen/metagraph | 362f97059f8344042d376edc5b470e27bd69b46e | [
"Apache-2.0"
] | 18 | 2020-08-07T19:15:46.000Z | 2022-01-25T09:24:18.000Z | metagraph/tests/translators/test_matrix.py | paul-tqh-nguyen/metagraph | 362f97059f8344042d376edc5b470e27bd69b46e | [
"Apache-2.0"
] | 49 | 2020-08-07T20:05:11.000Z | 2022-03-24T20:46:31.000Z | metagraph/tests/translators/test_matrix.py | paul-tqh-nguyen/metagraph | 362f97059f8344042d376edc5b470e27bd69b46e | [
"Apache-2.0"
] | 9 | 2020-08-07T19:15:56.000Z | 2022-01-19T01:45:05.000Z | import pytest
grblas = pytest.importorskip("grblas")
from metagraph.tests.util import default_plugin_resolver
from . import RoundTripper
from metagraph.plugins.numpy.types import NumpyMatrixType
from metagraph.plugins.graphblas.types import GrblasMatrixType
import numpy as np
def test_matrix_roundtrip_dense_square(default_plugin_resolver):
rt = RoundTripper(default_plugin_resolver)
mat = np.array([[1.1, 2.2, 3.3], [3.3, 3.3, 9.9], [3.3, 0.0, -3.3]])
rt.verify_round_trip(mat)
rt.verify_round_trip(mat.astype(int))
rt.verify_round_trip(mat.astype(bool))
def test_matrix_roundtrip_dense_rect(default_plugin_resolver):
rt = RoundTripper(default_plugin_resolver)
mat = np.array(
[[1.1, 2.2, 3.3], [3.3, 3.3, 9.9], [3.3, 0.0, -3.3], [-1.1, 2.7, 3.3]]
)
rt.verify_round_trip(mat)
rt.verify_round_trip(mat.astype(int))
rt.verify_round_trip(mat.astype(bool))
def test_numpy_2_grblas(default_plugin_resolver):
dpr = default_plugin_resolver
x = np.array([[1, 2, 3], [3, 3, 9], [3, 0, 3], [4, 2, 2]])
assert x.shape == (4, 3)
# Convert numpy -> grblas.Matrix
intermediate = grblas.Matrix.from_values(
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3],
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2],
[1, 2, 3, 3, 3, 9, 3, 0, 3, 4, 2, 2],
nrows=4,
ncols=3,
dtype=grblas.dtypes.INT64,
)
y = dpr.translate(x, grblas.Matrix)
dpr.assert_equal(y, intermediate)
# Convert numpy <- grblas.Matrix
x2 = dpr.translate(y, NumpyMatrixType)
dpr.assert_equal(x, x2)
| 32.770833 | 78 | 0.649078 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 72 | 0.045772 |
89828c0654558e8c377c4fd94ac3978afd1581ea | 1,259 | py | Python | src/by_hand_code/acm.py | vishalbelsare/parametric_modeling | 9bfe5df35671930043215c8f6c855af8f49e28bf | [
"BSD-3-Clause"
] | 37 | 2015-02-01T12:03:48.000Z | 2021-12-23T14:38:38.000Z | src/by_hand_code/acm.py | vishalbelsare/parametric_modeling | 9bfe5df35671930043215c8f6c855af8f49e28bf | [
"BSD-3-Clause"
] | 2 | 2015-07-27T11:34:24.000Z | 2019-12-11T13:39:18.000Z | src/by_hand_code/acm.py | vishalbelsare/parametric_modeling | 9bfe5df35671930043215c8f6c855af8f49e28bf | [
"BSD-3-Clause"
] | 19 | 2016-09-06T20:23:19.000Z | 2021-11-07T16:07:40.000Z | #!/usr/bin/env python
""" This file is a Python translation of the MATLAB file acm.m
Python version by RDL 29 Mar 2012
Copyright notice from acm.m:
copyright 1996, by M.H. Hayes. For use with the book
"Statistical Digital Signal Processing and Modeling"
(John Wiley & Sons, 1996).
"""
from __future__ import print_function,division
import numpy as np
from convm import convm
def acm(x,p):
""" Find an all-pole model using the autocorrelation method
Usage: a,err = acm(x,p)
The input sequence x is modeled as the unit sample response of
a filter having a system function of the form
H(z) = b(0)/A(z)
where the coefficients of A(z) are contained in the vector
a=[1, a(1), ... a(p)]
The input p defines the number of poles in the model.
The modeling error is returned in err.
The numerator b(0) is typically set equal to the square
root of err.
"""
x = x.flatten()
N = len(x)
if p > N:
print('ERROR: model order too large')
else:
X = convm(x, p+1)
Xq = X[0:N+p-1,0:p]
xq1 = -X[1:N+p, 0]
a = np.linalg.lstsq(Xq, xq1)[0]
a = np.insert(a, 0, 1)
err = np.dot(X[0:N+p,0].conj().T, X)
err = np.dot(err, a)
err = np.abs(err)
return a, err
| 28.613636 | 63 | 0.629071 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 800 | 0.635425 |
898370d5e67056fc24a2ff2429d8f2a713ae1d63 | 9,153 | py | Python | crds/tests/test_checksum.py | sean-lockwood/crds | f071f59deca98aac4bee04d688805a127761f3d2 | [
"BSD-3-Clause"
] | null | null | null | crds/tests/test_checksum.py | sean-lockwood/crds | f071f59deca98aac4bee04d688805a127761f3d2 | [
"BSD-3-Clause"
] | 1 | 2019-04-11T18:19:16.000Z | 2019-04-11T18:19:16.000Z | crds/tests/test_checksum.py | sean-lockwood/crds | f071f59deca98aac4bee04d688805a127761f3d2 | [
"BSD-3-Clause"
] | null | null | null | import os
import shutil
import doctest
from crds.core import log, utils
from crds import tests, data_file
from crds.tests import test_config
from crds.refactoring import checksum
from crds.refactoring.checksum import ChecksumScript
def dt_checksum_script_fits_add():
"""
>>> old_state = test_config.setup()
>>> _ = shutil.copy("data/s7g1700gl_dead.fits", "added.fits")
>>> header = data_file.get_header("./added.fits")
>>> assert "CHECKSUM" not in header
>>> assert "DATASUM" not in header
>>> ChecksumScript("crds.refactor.checksum ./added.fits")() # doctest: +ELLIPSIS
CRDS - INFO - Adding checksum for './added.fits'
0
>>> utils.clear_function_caches()
>>> header = data_file.get_header("./added.fits")
>>> assert "CHECKSUM" in header
>>> assert "DATASUM" in header
>>> ChecksumScript("crds.refactor.checksum --verify ./added.fits")() # doctest: +ELLIPSIS
CRDS - INFO - Verifying checksum for './added.fits'
0
>>> os.remove("added.fits")
>>> test_config.cleanup(old_state)
"""
def dt_checksum_script_fits_remove():
"""
>>> old_state = test_config.setup()
>>> _ = shutil.copy("data/s7g1700gl_dead_good_xsum.fits", "removed.fits")
>>> header = data_file.get_header("./removed.fits")
>>> assert "CHECKSUM" in header
>>> assert "DATASUM" in header
>>> ChecksumScript("crds.refactor.checksum --remove ./removed.fits")() # doctest: +ELLIPSIS
CRDS - INFO - Removing checksum for './removed.fits'
0
>>> utils.clear_function_caches()
>>> header = data_file.get_header("./removed.fits")
>>> assert "CHECKSUM" not in header
>>> assert "DATASUM" not in header
>>> ChecksumScript("crds.refactor.checksum --verify ./removed.fits")() # doctest: +ELLIPSIS
CRDS - INFO - Verifying checksum for './removed.fits'
0
>>> os.remove("removed.fits")
>>> test_config.cleanup(old_state)
"""
def dt_checksum_script_fits_verify_good():
"""
>>> old_state = test_config.setup()
>>> _ = shutil.copy("data/s7g1700gl_dead_good_xsum.fits", "verify_good.fits")
>>> header = data_file.get_header("verify_good.fits")
>>> header["CHECKSUM"]
'i2PMi1MJi1MJi1MJ'
>>> header["DATASUM"]
'0'
>>> ChecksumScript("crds.refactor.checksum --verify ./verify_good.fits")() # doctest: +ELLIPSIS
CRDS - INFO - Verifying checksum for './verify_good.fits'
0
>>> os.remove("verify_good.fits")
>>> test_config.cleanup(old_state)
"""
def dt_checksum_script_fits_verify_bad():
"""
>>> old_state = test_config.setup()
>>> _ = shutil.copy("data/s7g1700gl_dead_bad_xsum.fits", "./verify_bad.fits")
>>> ChecksumScript("crds.refactor.checksum --verify ./verify_bad.fits")() # doctest: +ELLIPSIS
CRDS - INFO - Verifying checksum for './verify_bad.fits'
CRDS - WARNING - AstropyUserWarning : astropy.io.fits.hdu.base : Checksum verification failed for HDU ('', 1).
CRDS - WARNING - AstropyUserWarning : astropy.io.fits.hdu.base : Datasum verification failed for HDU ('', 1).
0
>>> os.remove("verify_bad.fits")
>>> test_config.cleanup(old_state)
"""
# ----------------------------------------------------------------------
def dt_checksum_script_rmap_verify_good():
"""
>>> old_state = test_config.setup()
>>> ChecksumScript("crds.refactor.checksum --verify data/hst.pmap")() # doctest: +ELLIPSIS
CRDS - INFO - Verifying checksum for 'data/hst.pmap'
0
>>> test_config.cleanup(old_state)
"""
def dt_checksum_script_rmap_add_bad():
"""
>>> old_state = test_config.setup()
>>> _ = shutil.copy("data/hst-bad-xsum.rmap", "./add_bad.rmap")
>>> ChecksumScript("crds.refactor.checksum ./add_bad.rmap")() # doctest: +ELLIPSIS
CRDS - INFO - Adding checksum for './add_bad.rmap'
0
>>> ChecksumScript("crds.refactor.checksum --verify ./add_bad.rmap")() # doctest: +ELLIPSIS
CRDS - INFO - Verifying checksum for './add_bad.rmap'
0
>>> os.remove("add_bad.rmap")
>>> test_config.cleanup(old_state)
"""
def dt_checksum_script_rmap_verify_bad():
"""
>>> old_state = test_config.setup()
>>> _ = shutil.copy("data/hst-bad-xsum.rmap", "./verify_bad.rmap")
>>> ChecksumScript("crds.refactor.checksum --verify ./verify_bad.rmap")() # doctest: +ELLIPSIS
CRDS - INFO - Verifying checksum for './verify_bad.rmap'
CRDS - ERROR - Checksum operation FAILED : sha1sum mismatch in 'verify_bad.rmap'
1
>>> os.remove("verify_bad.rmap")
>>> test_config.cleanup(old_state)
"""
def dt_checksum_script_rmap_remove_bad():
"""
>>> old_state = test_config.setup()
>>> _ = shutil.copy("data/hst-bad-xsum.rmap", "./remove_bad.rmap")
>>> ChecksumScript("crds.refactor.checksum --remove ./remove_bad.rmap")() # doctest: +ELLIPSIS
CRDS - INFO - Removing checksum for './remove_bad.rmap'
CRDS - ERROR - Checksum operation FAILED : Mapping checksums cannot be removed for: './remove_bad.rmap'
1
>>> os.remove("remove_bad.rmap")
>>> test_config.cleanup(old_state)
"""
def dt_checksum_script_rmap_verify_missing():
"""
>>> old_state = test_config.setup()
>>> _ = shutil.copy("data/hst-missing-xsum.rmap", "./verify_missing.rmap")
>>> ChecksumScript("crds.refactor.checksum --verify ./verify_missing.rmap")() # doctest: +ELLIPSIS
CRDS - INFO - Verifying checksum for './verify_missing.rmap'
CRDS - ERROR - Checksum operation FAILED : sha1sum is missing in 'verify_missing.rmap'
1
>>> os.remove("verify_missing.rmap")
>>> test_config.cleanup(old_state)
"""
def dt_checksum_script_unsupported_asdf():
"""
>>> old_state = test_config.setup()
>>> ChecksumScript("crds.refactor.checksum data/valid.asdf")() # doctest: +ELLIPSIS
CRDS - INFO - Adding checksum for 'data/valid.asdf'
CRDS - ERROR - Failed updating checksum for 'data/valid.asdf' : Method 'add_checksum' is not supported for file format 'ASDF'
1
>>> ChecksumScript("crds.refactor.checksum --remove data/valid.asdf")() # doctest: +ELLIPSIS
CRDS - INFO - Removing checksum for 'data/valid.asdf'
CRDS - ERROR - Checksum operation FAILED : Method 'remove_checksum' is not supported for file format 'ASDF'
1
>>> ChecksumScript("crds.refactor.checksum --verify data/valid.asdf")() # doctest: +ELLIPSIS
CRDS - INFO - Verifying checksum for 'data/valid.asdf'
CRDS - ERROR - Checksum operation FAILED : Method 'verify_checksum' is not supported for file format 'ASDF'
1
>>> test_config.cleanup(old_state)
"""
def dt_checksum_script_unsupported_json():
"""
>>> old_state = test_config.setup()
>>> ChecksumScript("crds.refactor.checksum data/valid.json")() # doctest: +ELLIPSIS
CRDS - INFO - Adding checksum for 'data/valid.json'
CRDS - ERROR - Failed updating checksum for 'data/valid.json' : Method 'add_checksum' is not supported for file format 'JSON'
1
>>> ChecksumScript("crds.refactor.checksum --remove data/valid.json")() # doctest: +ELLIPSIS
CRDS - INFO - Removing checksum for 'data/valid.json'
CRDS - ERROR - Checksum operation FAILED : Method 'remove_checksum' is not supported for file format 'JSON'
1
>>> ChecksumScript("crds.refactor.checksum --verify data/valid.json")() # doctest: +ELLIPSIS
CRDS - INFO - Verifying checksum for 'data/valid.json'
CRDS - ERROR - Checksum operation FAILED : Method 'verify_checksum' is not supported for file format 'JSON'
1
>>> test_config.cleanup(old_state)
"""
def dt_checksum_script_unsupported_text():
"""
>>> old_state = test_config.setup()
>>> ChecksumScript("crds.refactor.checksum data/opaque_fts.tmp")() # doctest: +ELLIPSIS
CRDS - INFO - Adding checksum for 'data/opaque_fts.tmp'
CRDS - ERROR - Checksum operation FAILED : File 'data/opaque_fts.tmp' does not appear to be a CRDS reference or mapping file.
1
>>> ChecksumScript("crds.refactor.checksum --remove ddata/opaque_fts.tmp")() # doctest: +ELLIPSIS
CRDS - INFO - Removing checksum for 'ddata/opaque_fts.tmp'
CRDS - ERROR - Checksum operation FAILED : File 'ddata/opaque_fts.tmp' does not appear to be a CRDS reference or mapping file.
1
>>> ChecksumScript("crds.refactor.checksum --verify data/opaque_fts.tmp")() # doctest: +ELLIPSIS
CRDS - INFO - Verifying checksum for 'data/opaque_fts.tmp'
CRDS - ERROR - Checksum operation FAILED : File 'data/opaque_fts.tmp' does not appear to be a CRDS reference or mapping file.
1
>>> test_config.cleanup(old_state)
"""
def test():
"""Run module tests, for now just doctests only.
test_config.setup() and cleanup() are done inline above because bracketing
the tests here does not get picked up by nose test discovery. Combining
tests into one giant docstring works but is hard to analyze and debug when
things go wrong.
"""
from crds.tests import test_checksum, tstmod
return tstmod(test_checksum)
if __name__ == "__main__":
print(test())
| 39.623377 | 131 | 0.662843 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8,197 | 0.895553 |
8984014330a4fe7c818a1839453bfab2acca57d7 | 2,955 | py | Python | fspipe/pipe.py | adamvinueza/fspipe | 9df2d42c6907e851a39d4823b98aa26086ec4c96 | [
"MIT"
] | null | null | null | fspipe/pipe.py | adamvinueza/fspipe | 9df2d42c6907e851a39d4823b98aa26086ec4c96 | [
"MIT"
] | null | null | null | fspipe/pipe.py | adamvinueza/fspipe | 9df2d42c6907e851a39d4823b98aa26086ec4c96 | [
"MIT"
] | null | null | null | from fsspec import AbstractFileSystem # type: ignore
from fsspec.implementations.local import LocalFileSystem # type: ignore
from typing import Callable, Optional
class Pipe(object):
"""A container for piping data through transformations.
Args:
src_fs (AbstractFileSystem): The source file system.
dest_fs (AbstractFileSystem): The destination file system.
"""
src_fs: AbstractFileSystem
dest_fs: AbstractFileSystem
min_s3_blocksize: int = 5242880
@staticmethod
def _get_block_size(bufsize: int, fs: AbstractFileSystem, filepath: str):
"""Instead of checking for an S3 file system, just be mindful of the S3
minimum block size.
"""
if bufsize < 0:
# block size is the file size unless min block size is bigger
filesize = fs.size(filepath)
blocksize = max(filesize, Pipe.min_s3_blocksize)
else:
# block size is buffer size unless min block size is bigger
blocksize = max(bufsize, Pipe.min_s3_blocksize)
return blocksize
def __init__(self, src_fs: Optional[AbstractFileSystem] = None,
dest_fs: Optional[AbstractFileSystem] = None):
if src_fs is None and dest_fs is None:
src_fs = dest_fs = LocalFileSystem()
elif bool(src_fs is None) != bool(dest_fs is None):
if src_fs is None:
raise ValueError("src_fs is empty")
if dest_fs is None:
raise ValueError("dest_fs is empty")
self.src_fs = src_fs
self.dest_fs = dest_fs
def copy(self, src: str, dest: str, readmode: str = 'rb',
writemode: str = 'wb', bufsize: int = -1) -> None:
"""Copies src to dest.
Both src and dest paths must be valid in the respective file systems.
"""
block_size = Pipe._get_block_size(bufsize, self.src_fs, src)
with self.src_fs.open(src, readmode, block_size) as rdr:
with self.dest_fs.open(dest, writemode, block_size) as wr:
wr.write(rdr.read())
def fcopy(self, src: str, dest: str, fltr: Callable, readmode: str = 'rb',
writemode: str = 'wb', bufsize: int = -1, **kwargs) -> None:
"""Copies src to dest, passing read bytes through a filter.
The filter takes a sequence of bytes and whatever keyword arguments are
passed in, and returns a sequence of bytes.
Both src and dest paths must be valid in the respective file systems.
"""
block_size = Pipe._get_block_size(bufsize, self.src_fs, src)
with self.src_fs.open(src, readmode, block_size) as rdr:
with self.dest_fs.open(dest, writemode, block_size) as wr:
while True:
b = rdr.read(bufsize)
if not b:
wr.flush()
break
wr.write(fltr(b, **kwargs))
| 40.479452 | 79 | 0.611168 | 2,787 | 0.943147 | 0 | 0 | 582 | 0.196954 | 0 | 0 | 908 | 0.307276 |
8985b0fa229c59111784df2a65cc9891d6eea937 | 2,677 | py | Python | gitsy.py | GINMOT/GITSY | 8ef7fcbbcdd33ee6afd0692ab53e092ade7a5c6c | [
"MIT"
] | 1 | 2021-05-30T16:09:42.000Z | 2021-05-30T16:09:42.000Z | gitsy.py | GINMOT/GITSY | 8ef7fcbbcdd33ee6afd0692ab53e092ade7a5c6c | [
"MIT"
] | null | null | null | gitsy.py | GINMOT/GITSY | 8ef7fcbbcdd33ee6afd0692ab53e092ade7a5c6c | [
"MIT"
] | null | null | null | import os
from time import sleep
import sys
from sys import platform
import subprocess
import platform
#Main Service Initalizations
#def upcred():
#def multirep():
def clonehistory():
print(">>>>>>>> History >>>>>>>>")
print(" repositories cloned")
print(">>>>>>>>> ----- >>>>>>>>")
gethist = open('reposnit.txt', 'r')
print(gethist.read())
sleep(5)
gbck = input("Menu (0) : ")
if gbck == "0":
mainlaunch()
mainopt()
elif gbck == "":
print("Invalid Option ..... exiting")
def fetchrep():
print("Github / Gitlab repository")
grep = input("> ")
with open('reposnit.txt', 'w') as f:
f.write(grep)
runsys = os.system("git clone " + grep)
print(runsys)
print(" >>>>>>>>>>>>>> ----- >>>>>>>>>>>>>")
sleep (5)
gmenu = input("Menu (0): ")
if gmenu == "0":
mainlaunch()
mainopt()
elif gmenu == "":
print("Invalid Option.... Exiting")
def sclear():
sysproc = sys.platform
if sysproc == ['linux2', 'linux']:
_ = os.system("clear")
elif sysproc == ['Windows', 'win64']:
_= os.system("cls")
#Main screen
sclear()
def mainlaunch():
printmain = print("""
________.____________________________.___.
/ _____/| \__ ___/ _____/\__ | |
/ \ ___| | | | \_____ \ / | |
\ \_\ \ | | | / \ \____ |
\______ /___| |____| /_______ / / ______|
\/ \/ \/
(1) ---> Clone Repository
(2) ---> Clone History
(3) ---> Multiple Repos
(4) --> Update & Credits
(5) ---> Exit Program
(6) ---> Get Resources
""")
mainlaunch()
def mainopt():
uoption = input("Option: ")
if uoption == "1":
sclear()
print("We are working on it.....")
sleep(2)
fetchrep()
elif uoption == "2":
print("We are working on it.....")
sleep(2)
sclear()
clonehistory()
elif uoption == "4":
sclear()
print("We are working on it.....")
sleep(2)
# multirep()
elif uoption == "4":
print("We are working on it.....")
sleep(2)
elif uoption == "5":
try:
print("Exiting....")
except:
os.system(exit)
mainopt()
| 20.914063 | 53 | 0.415017 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,005 | 0.37542 |
8986e74c9d5d0f3e83c77fa1bbe488f8b8c7d861 | 1,163 | py | Python | convert.py | 9Knight9n/crawler-legislation-uk | 6f91ccf8323933a1926245a6dd0de747658ec6dd | [
"MIT"
] | null | null | null | convert.py | 9Knight9n/crawler-legislation-uk | 6f91ccf8323933a1926245a6dd0de747658ec6dd | [
"MIT"
] | null | null | null | convert.py | 9Knight9n/crawler-legislation-uk | 6f91ccf8323933a1926245a6dd0de747658ec6dd | [
"MIT"
] | null | null | null | # from os import listdir
# from os.path import isfile, join
#
# from save import xht_files_dir, txt_files_dir_converted
# from utils import convert_xht_to_txt,convert_xht_to_txt_2
# only_files = [f for f in listdir(xht_files_dir) if isfile(join(xht_files_dir, f))]
# for index,file_ in enumerate(only_files):
# print(f'doc {index+1}.{file_} converted.')
# f = open(xht_files_dir+"/"+file_, "r")
# text = f.read()
# text = convert_xht_to_txt_2(text)
# f = open(txt_files_dir_converted+"/"+file_[:-3]+"txt", "w")
# for line in text:
# f.write(line)
# f.close()
# break
# f = open(xht_files_dir+"/"+"The Air Navigation (Restriction of Flying) (Abingdon Air and Country Show) Regulations 2021.xht", "r")
# text = f.read()
# text = convert_xht_to_txt_2(text)
# if len(text) == 0:
# print("hello")
# f = open(txt_files_dir_converted+"/"+"The Air Navigation (Restriction of Flying) (Abingdon Air and Country Show) Regulations 2021."+"txt", "w")
# for line in text:
# f.write(line)
# f.close()
# import re
#
# regexes = [
# r'“.*”',
#
# ]
#
# pair = re.compile(regexes[0])
# print(pair.search('““dalam means”dwdw')) | 30.605263 | 145 | 0.656062 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,132 | 0.965047 |
898730ea9a49096e8b6161edc2af4f23006465d6 | 2,757 | py | Python | tests/regressiontests/custom_managers_regress/models.py | huicheese/Django-test3 | ac11d2dce245b48392e52d1f4acfd5e7433b243e | [
"BSD-3-Clause"
] | 19 | 2015-05-01T19:59:03.000Z | 2021-12-09T08:03:16.000Z | tests/regressiontests/custom_managers_regress/models.py | joetyson/django | c3699190186561d5c216b2a77ecbfc487d42a734 | [
"BSD-3-Clause"
] | 1 | 2018-01-03T15:26:49.000Z | 2018-01-03T15:26:49.000Z | tests/regressiontests/custom_managers_regress/models.py | joetyson/django | c3699190186561d5c216b2a77ecbfc487d42a734 | [
"BSD-3-Clause"
] | 30 | 2015-03-25T19:40:07.000Z | 2021-05-28T22:59:26.000Z | """
Regression tests for custom manager classes.
"""
from django.db import models
class RestrictedManager(models.Manager):
"""
A manager that filters out non-public instances.
"""
def get_query_set(self):
return super(RestrictedManager, self).get_query_set().filter(is_public=True)
class RelatedModel(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class RestrictedModel(models.Model):
name = models.CharField(max_length=50)
is_public = models.BooleanField(default=False)
related = models.ForeignKey(RelatedModel)
objects = RestrictedManager()
plain_manager = models.Manager()
def __unicode__(self):
return self.name
class OneToOneRestrictedModel(models.Model):
name = models.CharField(max_length=50)
is_public = models.BooleanField(default=False)
related = models.OneToOneField(RelatedModel)
objects = RestrictedManager()
plain_manager = models.Manager()
def __unicode__(self):
return self.name
__test__ = {"tests": """
Even though the default manager filters out some records, we must still be able
to save (particularly, save by updating existing records) those filtered
instances. This is a regression test for #8990, #9527
>>> related = RelatedModel.objects.create(name="xyzzy")
>>> obj = RestrictedModel.objects.create(name="hidden", related=related)
>>> obj.name = "still hidden"
>>> obj.save()
# If the hidden object wasn't seen during the save process, there would now be
# two objects in the database.
>>> RestrictedModel.plain_manager.count()
1
Deleting related objects should also not be distracted by a restricted manager
on the related object. This is a regression test for #2698.
>>> RestrictedModel.plain_manager.all().delete()
>>> for name, public in (('one', True), ('two', False), ('three', False)):
... _ = RestrictedModel.objects.create(name=name, is_public=public, related=related)
# Reload the RelatedModel instance, just to avoid any instance artifacts.
>>> obj = RelatedModel.objects.get(name="xyzzy")
>>> obj.delete()
# All of the RestrictedModel instances should have been deleted, since they
# *all* pointed to the RelatedModel. If the default manager is used, only the
# public one will be deleted.
>>> RestrictedModel.plain_manager.all()
[]
# The same test case as the last one, but for one-to-one models, which are
# implemented slightly different internally, so it's a different code path.
>>> obj = RelatedModel.objects.create(name="xyzzy")
>>> _ = OneToOneRestrictedModel.objects.create(name="foo", is_public=False, related=obj)
>>> obj = RelatedModel.objects.get(name="xyzzy")
>>> obj.delete()
>>> OneToOneRestrictedModel.plain_manager.all()
[]
"""
}
| 33.216867 | 88 | 0.730141 | 965 | 0.350018 | 0 | 0 | 0 | 0 | 0 | 0 | 1,799 | 0.652521 |
8987a8a45d351bbfef65dc5938b0c5ab50967bd0 | 1,685 | py | Python | test_code/python-plotter-serial-beta/plotter_freq_checker.py | ithallojunior/data_transmission | eaf1ef81c018dc5a42f1756b39e19bfaa7f34ed5 | [
"MIT"
] | null | null | null | test_code/python-plotter-serial-beta/plotter_freq_checker.py | ithallojunior/data_transmission | eaf1ef81c018dc5a42f1756b39e19bfaa7f34ed5 | [
"MIT"
] | null | null | null | test_code/python-plotter-serial-beta/plotter_freq_checker.py | ithallojunior/data_transmission | eaf1ef81c018dc5a42f1756b39e19bfaa7f34ed5 | [
"MIT"
] | null | null | null | import serial
import matplotlib.pyplot as plt
import numpy as np
import time
pd = "/dev/tty.wchusbserial1410"
#pd = "/dev/tty.usbmodem1421"
p = serial.Serial(port=pd, baudrate=115200,
bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE)
p.flush()
time.sleep(0.5)
#plt.axis([0, 10, 0, 1])
plt.ion()
samples = 4096#samples
fs = 2040. # samples/sec
freq = 0. # to start with
t_freq_checker = 2. # checks frequency every N seconds
time_window = samples/fs # seconds
to_show = 100
t = np.arange(0., time_window, 1./fs)
y = np.zeros(samples)
t1 = time.time()
while(1):
try:
plt.clf()
plt.xlabel("Time(s)")
plt.xlim(0, t[to_show])
plt.ylim(-0.1, 1.2)#(-0.1, 1.3)
i = 0;
while i < samples:
value1 = p.read()
value2 = p.read()
#print "read"
try:
v = ord(value1[0])*256 + ord(value2[0])
y[i] = float(v)*(1.1/1023.0)
i = i +1
#print "Values: ", v, ord(value1), ord(value2)
except IndexError:
print "Error"
pass
#print("Evlapsed time %f"%(time.time() -t1))
plt.plot(t, y)
plt.title("Fs: %.3f | Freq.: %.3f "%(fs, freq))
plt.grid()
plt.pause(1.0/30.0)
#print("time %f"%(time.time() -t1))
#updates freq
if ((time.time() - t1) >= t_freq_checker):
ymean = y - y.mean() #removes DC
fd = ( np.abs( np.fft.fft(ymean) ) )[:samples/2].argmax()
freq = fs * fd/samples
t1 = time.time()
except KeyboardInterrupt:
plt.close()
break
p.close()
| 26.328125 | 71 | 0.516914 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 375 | 0.222552 |
89881e729e1c5b8ecc3806d72f395c7bedce5068 | 2,203 | py | Python | leetcode/207_course_schedule.py | coocos/leetcode | 007bbeb46fa4b32e1c92fc894edeb2100eb6ba21 | [
"MIT"
] | null | null | null | leetcode/207_course_schedule.py | coocos/leetcode | 007bbeb46fa4b32e1c92fc894edeb2100eb6ba21 | [
"MIT"
] | null | null | null | leetcode/207_course_schedule.py | coocos/leetcode | 007bbeb46fa4b32e1c92fc894edeb2100eb6ba21 | [
"MIT"
] | null | null | null | import unittest
import collections
from typing import List
class Solution:
"""
This solution performs a topological sort using Kahn's algorithm.
First a graph is constructed in the form of a dictionary which contains the
courses, their requirements and the courses that they themselves enable. Then
a queue is constructed which contains the courses with no initial requirements.
As such courses are dequeued from the queue, each course is removed from the graph
and it is removed from the requirements of all the courses it enables. If a course
ends up having no requirements after this process then it itself is added to the
queue. This process repeats until the graph has been completely emptied in which
case the course schedule is possible. If the graph is non-empty then the course
schedule is impossible.
"""
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
courses = {
course: {"id": course, "requirements": set(), "enables": set()}
for course in range(numCourses)
}
for course, *requirements in prerequisites:
for requirement in requirements:
courses[course]["requirements"].add(requirement)
courses[requirement]["enables"].add(course)
possible_courses = collections.deque(
[course for course in courses.values() if not course["requirements"]]
)
while possible_courses:
course = possible_courses.popleft()
for next_course in course["enables"]:
courses[next_course]["requirements"].remove(course["id"])
if not courses[next_course]["requirements"]:
possible_courses.append(courses[next_course])
del courses[course["id"]]
return not courses
class TestSolution(unittest.TestCase):
def test_true_example(self):
self.assertTrue(Solution().canFinish(2, [[1, 0]]))
def test_false_example(self):
self.assertFalse(Solution().canFinish(2, [[1, 0], [0, 1]]))
def test_failing_example(self):
self.assertTrue(Solution().canFinish(3, [[1, 0], [2, 1]]))
| 36.716667 | 86 | 0.66364 | 2,138 | 0.970495 | 0 | 0 | 0 | 0 | 0 | 0 | 893 | 0.405356 |
8988728d0b2235f53cc08dcd048278808b2a69e7 | 425 | py | Python | investment_report/migrations/0026_remove_howwecanhelp_sector.py | uktrade/pir-api | 79747ceab042c42c287e2b7471f6dade70f68693 | [
"MIT"
] | 1 | 2021-02-02T19:08:55.000Z | 2021-02-02T19:08:55.000Z | investment_report/migrations/0026_remove_howwecanhelp_sector.py | uktrade/invest-pir-api | be56efddf9dfdf81c8557441a9a54d9a4dd4bab1 | [
"MIT"
] | 21 | 2018-07-10T10:20:47.000Z | 2022-03-24T09:36:29.000Z | investment_report/migrations/0026_remove_howwecanhelp_sector.py | uktrade/pir-api | 79747ceab042c42c287e2b7471f6dade70f68693 | [
"MIT"
] | 1 | 2021-02-04T11:28:37.000Z | 2021-02-04T11:28:37.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-09-01 14:28
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('investment_report', '0025_howwecanhelp_smartworkforcesector'),
]
operations = [
migrations.RemoveField(
model_name='howwecanhelp',
name='sector',
),
]
| 21.25 | 72 | 0.642353 | 274 | 0.644706 | 0 | 0 | 0 | 0 | 0 | 0 | 153 | 0.36 |
898a1ef53ea78c92b3aad4b4f4f400878c4c775b | 3,740 | py | Python | src/models/transformer_encoder.py | sanket-pixel/attentive-mot | d9cdfadd6471524c835cb95f5789414afb6649d7 | [
"MIT"
] | 1 | 2021-08-14T20:09:55.000Z | 2021-08-14T20:09:55.000Z | src/models/transformer_encoder.py | sanket-pixel/attentive-mot | d9cdfadd6471524c835cb95f5789414afb6649d7 | [
"MIT"
] | null | null | null | src/models/transformer_encoder.py | sanket-pixel/attentive-mot | d9cdfadd6471524c835cb95f5789414afb6649d7 | [
"MIT"
] | null | null | null | import torch
import torch.nn.functional as f
from torch import nn
from einops import rearrange
def scaled_dot_product_attention(query, key, value):
attention = torch.einsum('bdtc,beuc->bdteu',[query,key])
mask = torch.zeros_like(attention)
for frame in torch.arange(mask.size(-2)):
mask[:, frame, :, frame:, :] = float('-inf')
attention +=mask
scale = query.size(-1) ** 0.5
attention = rearrange(attention, 'b f t g u->b f t (g u)')
softmax = f.softmax(attention / scale, dim=-1)
return softmax.bmm(value)
class AttentionHead(nn.Module):
def __init__(self, dim_in, dim_k, dim_v):
super(AttentionHead, self).__init__()
self.q = nn.Linear(dim_in, dim_k)
self.k = nn.Linear(dim_in, dim_k)
self.v = nn.Linear(dim_in, dim_v)
def forward(self, query, key, value):
return scaled_dot_product_attention(self.q(query), self.k(key), self.v(value))
class MultiHeadAttention(nn.Module):
def __init__(self, num_heads, dim_in, dim_k, dim_v):
super(MultiHeadAttention, self).__init__()
self.heads = nn.ModuleList(
[AttentionHead(dim_in, dim_k, dim_v) for _ in range(num_heads)]
)
self.linear = nn.Linear(num_heads * dim_v, dim_in)
def forward(self, query, key, value):
return self.linear(
torch.cat([h(query, key, value) for h in self.heads], dim=-1)
)
def feed_forward(dim_input, dim_feedforward):
return nn.Sequential(
nn.Linear(dim_input, dim_feedforward),
nn.ReLU(),
nn.Linear(dim_feedforward, dim_input),
)
class Residual(nn.Module):
def __init__(self, sublayer, dimension, dropout):
super(Residual, self).__init__()
self.sublayer = sublayer
self.norm = nn.LayerNorm(dimension)
self.dropout = nn.Dropout(dropout)
def forward(self, *tensors):
return self.norm(tensors[-1] + self.dropout(self.sublayer(*tensors)))
class TransformerEncoderLayer(nn.Module):
def __init__(self,
dim_model=64,
num_heads=8,
dim_feedforward=128,
dropout=0.1,
):
super(TransformerEncoderLayer, self).__init__()
dim_k = dim_v = dim_model // num_heads
self.attention = Residual(
MultiHeadAttention(num_heads, dim_model, dim_k, dim_v),
dimension=dim_model,
dropout=dropout,
)
self.feed_forward = Residual(
feed_forward(dim_model, dim_feedforward),
dimension=dim_model,
dropout=dropout,
)
def forward(self, src):
src = self.attention(src, src, src)
return self.feed_forward(src)
class TransformerEncoder(nn.Module):
def __init__(self,
num_layers=6,
dim_model=64,
num_heads=8,
dim_feedforward=128,
dropout=0.1,
):
super(TransformerEncoder, self).__init__()
self.layers = nn.ModuleList([
TransformerEncoderLayer(dim_model, num_heads, dim_feedforward, dropout)
for _ in range(num_layers)
])
def forward(self, src):
for layer in self.layers:
src = layer(src)
return src
# # head_params
# num_heads = 8
# dim_in = 64
# dim_k = dim_v = dim_in // num_heads
#
# # data params
# batch_size = 16
# sequence_length = 10
# num_features = 64
#
# query = torch.rand(batch_size, sequence_length, num_features)
# key = torch.rand(batch_size, sequence_length, num_features)
# value = torch.rand(batch_size, sequence_length, num_features)
#
# transformer_encoder = TransformerEncoder()
# transformer_encoder(value) | 30.16129 | 86 | 0.619786 | 2,551 | 0.682086 | 0 | 0 | 0 | 0 | 0 | 0 | 463 | 0.123797 |
898a5306afa3764a7edd628eb316f44d5054d18e | 628 | py | Python | src/default_parameters.py | Vivswan/ECE-2162-Tomasulo | 85a12be0d49a1229da062caa076321a6d2d5204c | [
"MIT"
] | null | null | null | src/default_parameters.py | Vivswan/ECE-2162-Tomasulo | 85a12be0d49a1229da062caa076321a6d2d5204c | [
"MIT"
] | null | null | null | src/default_parameters.py | Vivswan/ECE-2162-Tomasulo | 85a12be0d49a1229da062caa076321a6d2d5204c | [
"MIT"
] | null | null | null | TOMASULO_DEFAULT_PARAMETERS = {
"num_register": 32,
"num_rob": 128,
"num_cdb": 1,
"cdb_buffer_size": 0,
"nop_latency": 1,
"nop_unit_pipelined": 1,
"integer_adder_latency": 1,
"integer_adder_rs": 5,
"integer_adder_pipelined": 0,
"float_adder_latency": 3,
"float_adder_rs": 3,
"float_adder_pipelined": 1,
"float_multiplier_latency": 20,
"float_multiplier_rs": 2,
"float_multiplier_pipelined": 1,
"memory_unit_latency": 1,
"memory_unit_ram_latency": 4,
"memory_unit_queue_latency": 1,
"memory_unit_ram_size": 1024,
"memory_unit_queue_size": 8,
}
| 22.428571 | 36 | 0.66242 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 402 | 0.640127 |
898a5a3fc36cd33bb17ecf41c7c2ed55175536af | 639 | py | Python | hanlp/utils/__init__.py | antfootAlex/HanLP | e8044b27ae1de54b9070db08549853d3ca8271e2 | [
"Apache-2.0"
] | 27,208 | 2015-03-27T10:25:45.000Z | 2022-03-31T13:26:32.000Z | hanlp/utils/__init__.py | hushaoyun/HanLP | 967b52404c9d0adbc0cff2699690c127ecfca36e | [
"Apache-2.0"
] | 1,674 | 2015-03-30T06:36:44.000Z | 2022-03-16T01:52:56.000Z | hanlp/utils/__init__.py | hushaoyun/HanLP | 967b52404c9d0adbc0cff2699690c127ecfca36e | [
"Apache-2.0"
] | 7,710 | 2015-03-27T08:07:57.000Z | 2022-03-31T14:57:23.000Z | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-24 22:12
from . import rules
def ls_resource_in_module(root) -> dict:
res = dict()
for k, v in root.__dict__.items():
if k.startswith('_') or v == root:
continue
if isinstance(v, str):
if v.startswith('http') and not v.endswith('/') and not v.endswith('#') and not v.startswith('_'):
res[k] = v
elif type(v).__name__ == 'module':
res.update(ls_resource_in_module(v))
if 'ALL' in root.__dict__ and isinstance(root.__dict__['ALL'], dict):
root.__dict__['ALL'].update(res)
return res
| 31.95 | 110 | 0.577465 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 103 | 0.161189 |
898a6e4ec452715bf2182d06be96a7c637b49645 | 1,174 | py | Python | microbots/signup/crud.py | Varun11940/voice-enabled-chatbot | 0f6ed534adfd95139f817a033fcbf3f749738339 | [
"MIT"
] | 36 | 2019-05-07T16:26:35.000Z | 2022-02-08T06:02:45.000Z | microbots/signup/crud.py | Varun11940/voice-enabled-chatbot | 0f6ed534adfd95139f817a033fcbf3f749738339 | [
"MIT"
] | 53 | 2019-06-01T15:55:17.000Z | 2020-10-01T15:35:48.000Z | microbots/signup/crud.py | Varun11940/voice-enabled-chatbot | 0f6ed534adfd95139f817a033fcbf3f749738339 | [
"MIT"
] | 73 | 2019-05-08T03:16:04.000Z | 2022-01-17T05:56:59.000Z | import config
import models
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, inspect
engine = create_engine(config.DATABASE_URI)
Session = sessionmaker(bind=engine)
class crudOps:
def createTable(self):
models.Base.metadata.create_all(engine)
def recreate_database(self):
models.Base.metadata.drop_all(engine)
models.Base.metadata.create_all(engine)
def insertRow(self, row):
s = Session()
s.add(row)
s.commit()
s.close_all()
def allRow(self):
s = Session()
data = s.query(models.Register).all()
s.close_all()
return data
def primaryCol(self):
s = Session()
dataList = []
data = s.query(models.Register.col1)
for i in data:
for j in i:
dataList.append(j)
s.close_all()
return dataList
a = crudOps()
# Checking if register table present or not
inspector = inspect(engine)
table_present = False
for table_name in inspector.get_table_names():
if table_name == config.table_name:
table_present = True
if not table_present:
a.createTable()
| 23.019608 | 47 | 0.640545 | 707 | 0.602215 | 0 | 0 | 0 | 0 | 0 | 0 | 43 | 0.036627 |
898a7838615f25b4e91899e45ef134b30353cc97 | 14,270 | py | Python | capsNet.py | zhaoaite/ASTCapsNet | b9a13df952af65f13d3006df923d0ed5646915d4 | [
"MIT"
] | null | null | null | capsNet.py | zhaoaite/ASTCapsNet | b9a13df952af65f13d3006df923d0ed5646915d4 | [
"MIT"
] | null | null | null | capsNet.py | zhaoaite/ASTCapsNet | b9a13df952af65f13d3006df923d0ed5646915d4 | [
"MIT"
] | null | null | null | """
License: Apache-2.0
Author: Aite Zhao
E-mail: aitezhao@qq.com
"""
import tensorflow as tf
import rnn_cell_GRU as rnn_cell
import rnn
import numpy as np
from config import cfg
from utils import get_batch_data
from capsLayer import CapsLayer
from sklearn import metrics
import pickle
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing
from plot_confusion_matrix import plot_confusion_matrix
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import os
import tensorflow as tf
from tensorflow.contrib.tensor_forest.python import tensor_forest
from tensorflow.python.ops import resources
class CapsNet(object):
def __init__(self, is_training=True):
self.graph = tf.Graph()
with self.graph.as_default():
self.n_classes=52
self.X, self.labels = get_batch_data(cfg.dataset, cfg.batch_size, cfg.num_threads)
self.Y = tf.one_hot(self.labels, depth=self.n_classes, axis=1, dtype=tf.float32)
# LSTM Parameters
self.n_input=45
self.n_steps=45
# tf Graph input
self.lstm_x = tf.reshape(self.X, shape=(cfg.batch_size, self.n_steps, self.n_input))
self.lstm_y = tf.reshape(self.Y, shape=(cfg.batch_size, self.n_classes))
self.kernel_size1=13
self.kernel_size2=9
self.conv1_outa=self.n_input-self.kernel_size1+1
self.conv1_outb=self.n_steps-self.kernel_size1+1
# self.cap1_out=(self.conv1_outa-self.kernel_size+1)/2*((self.conv1_outb-self.kernel_size+1)/2)
# self.cap1_out=int((self.conv1_outa-self.kernel_size2+1)*(self.conv1_outb-self.kernel_size2+1)*32/4)
self.cap1_out=5408
self.n_hidden= self.conv1_outb
# Define weights
self.lstm_weights = {
'out': tf.Variable(tf.random_normal([self.n_hidden, self.n_classes]))
}
self.lstm_biases = {
'out': tf.Variable(tf.random_normal([self.n_classes]))
}
if is_training:
self.build_arch()
self.loss()
self._summary()
# t_vars = tf.trainable_variables()
self.global_step = tf.Variable(0, name='global_step', trainable=False)
self.optimizer = tf.train.AdamOptimizer()
self.train_op = self.optimizer.minimize(self.total_loss, global_step=self.global_step) # var_list=t_vars)
self.train_c1 = self.optimizer.minimize(self.lstm_cost, global_step=self.global_step)
self.train_c2 = self.optimizer.minimize(self.dense_cov1_cost, global_step=self.global_step)
self.train_c3 = self.optimizer.minimize(self.dense_caps1_cost, global_step=self.global_step)
print('end net')
else:
self.X = tf.placeholder(tf.float32, shape=(cfg.batch_size,self.n_input, self.n_steps, 1))
self.labels = tf.placeholder(tf.int32, shape=(cfg.batch_size, ))
self.Y = tf.reshape(self.labels, shape=(cfg.batch_size, self.n_classes, 1))
self.build_arch()
tf.logging.info('Seting up the main structure')
def RNN(self):
# Prepare data shape to match `rnn` function requirements
# Current data input shape: (batch_size, n_steps, n_input)
# Required shape: 'n_steps' tensors list of shape (batch_size, n_input)
# Permuting batch_size and n_steps
x = tf.transpose(self.lstm_x, [1, 0, 2])
# Reshaping to (n_steps*batch_size, n_input)
x = tf.reshape(tensor=x, shape=[-1, self.n_input])
# Split to get a list of 'n_steps' tensors of shape (batch_size, n_input)
x = tf.split(value=x, num_or_size_splits=self.n_steps, axis=0)
# Define a lstm cell with tensorflow
#lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1)
lstm_cell = rnn_cell.GRUCell(self.n_hidden)
#lstm_cell = rnn_cell.LSTMCell(n_hidden,use_peepholes=True)
# avoid overfitting
lstm_cell = rnn_cell.DropoutWrapper(lstm_cell, output_keep_prob=0.5)
# 2 layers lstm
lstm_cell = rnn_cell.MultiRNNCell([lstm_cell]*2)
# Get lstm cell output
outputs, states = rnn.rnn(cell=lstm_cell, inputs=x, dtype=tf.float32)
# Linear activation, using rnn inner loop last output
return tf.matmul(outputs[-1], self.lstm_weights['out']) + self.lstm_biases['out'],outputs[-1]
def build_arch(self):
with tf.variable_scope('LSTM_layer'):
#pred batch*4d out batch*128d
pred,out = self.RNN()
out=tf.reshape(out,(-1,1,self.n_hidden,1))
# cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=pred, labels=y))
# #Adam optimizer
# optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Evaluate model
# correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
# accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
with tf.variable_scope('Conv1_layer'):
# Conv1, [batch_size, 20, 20, 256]
conv1 = tf.contrib.layers.conv2d(self.X, num_outputs=256,
kernel_size=self.kernel_size1, stride=1,
padding='VALID')
# print(conv1.get_shape(),[cfg.batch_size, self.conv1_outa,self.conv1_outb, 256])
assert conv1.get_shape() == [cfg.batch_size, self.conv1_outa,self.conv1_outb, 256]
out=tf.tile(out,[1,self.conv1_outa,1,256])
self.conv1=tf.add(conv1,out)
# out_temp= tf.placeholder(tf.float32, shape=(cfg.batch_size,self.conv1_outa+1,self.conv1_outb, 256))
# self.dense1 = tf.layers.dense(inputs=tf.reshape(self.conv1,(cfg.batch_size,-1)), units=self.n_classes, activation=tf.nn.relu)
#全连接层
pool = tf.layers.max_pooling2d(inputs=self.conv1, pool_size=[2, 2], strides=2)
fc1 = tf.layers.dense(inputs=pool, units=1024, activation=tf.nn.relu)
fc2 = tf.layers.dense(inputs=fc1, units=512, activation=tf.nn.relu)
self.dense1 = tf.layers.dense(inputs=tf.reshape(fc2,(cfg.batch_size,-1)), units=self.n_classes, activation=None)
self.dense1_index = tf.to_int32(tf.argmax(tf.nn.softmax(self.dense1, axis=1), axis=1))
# Primary Capsules layer, return [batch_size, 1152, 8, 1]
with tf.variable_scope('PrimaryCaps_layer'):
primaryCaps = CapsLayer(num_outputs=32, vec_len=8, with_routing=False, layer_type='CONV', conv1_outa=self.conv1_outa, conv1_outb=self.conv1_outb, cap1_out=self.cap1_out,n_classes=self.n_classes)
(self.caps1,pred) = primaryCaps(self.conv1, kernel_size=self.kernel_size2, stride=2)
self.lstmpred=pred
assert self.caps1.get_shape() == [cfg.batch_size, self.cap1_out, 8, 1]
# self.dense2= tf.layers.dense(inputs=tf.reshape(self.caps1,(cfg.batch_size,-1)), units=self.n_classes, activation=tf.nn.relu)
pool = tf.layers.max_pooling2d(inputs=self.caps1, pool_size=[2, 2], strides=2)
fc1 = tf.layers.dense(inputs=pool, units=1024, activation=tf.nn.relu)
fc2 = tf.layers.dense(inputs=fc1, units=512, activation=tf.nn.relu)
self.dense2 = tf.layers.dense(inputs=tf.reshape(fc2,(cfg.batch_size,-1)), units=self.n_classes, activation=None)
self.dense2_index = tf.to_int32(tf.argmax(tf.nn.softmax(self.dense2, axis=1), axis=1))
# DigitCaps layer, return [batch_size, 10, 16, 1]
with tf.variable_scope('DigitCaps_layer'):
digitCaps = CapsLayer(num_outputs=self.n_classes, vec_len=8, with_routing=True, layer_type='FC',conv1_outa=self.conv1_outa, conv1_outb=self.conv1_outb, cap1_out=self.cap1_out,n_classes=self.n_classes)
self.caps2 = digitCaps(self.caps1)
# self.caps2 = tf.add(tf.tile(tf.reshape(self.lstmpred,(cfg.batch_size,self.n_classes,1,1)),[1,1,16,1]),self.caps2)
# Decoder structure in Fig. 2
# 1. Do masking, how:
with tf.variable_scope('Masking'):
# a). calc ||v_c||, then do softmax(||v_c||)
# [batch_size, 10, 16, 1] => [batch_size, 10, 1, 1]
self.v_length = tf.sqrt(tf.reduce_sum(tf.square(self.caps2),
axis=2, keepdims=True))
self.softmax_v = tf.nn.softmax(self.v_length, axis=1)
assert self.softmax_v.get_shape() == [cfg.batch_size, self.n_classes, 1, 1]
# b). pick out the index of max softmax val of the 10 caps
# [batch_size, 10, 1, 1] => [batch_size] (index)
self.argmax_idx = tf.to_int32(tf.argmax(self.softmax_v, axis=1))
assert self.argmax_idx.get_shape() == [cfg.batch_size, 1, 1]
self.argmax_idx = tf.reshape(self.argmax_idx, shape=(cfg.batch_size, ))
# self.max_index_list= tf.Variable(tf.ones([cfg.batch_size, ],dtype=tf.int32))
# index_list=tf.stack([self.dense1_index,self.dense2_index,self.argmax_idx],1)
#
# for i in range(cfg.batch_size):
# max_index=tf.to_int32(tf.argmax(tf.bincount(index_list[i])))
# self.update_op=tf.assign(self.max_index_list[i],max_index)
# # Method 1.
# if not cfg.mask_with_y:
# # c). indexing
# # It's not easy to understand the indexing process with argmax_idx
# # as we are 3-dim animal
# masked_v = []
# for batch_size in range(cfg.batch_size):
# v = self.caps2[batch_size][self.argmax_idx[batch_size], :]
# masked_v.append(tf.reshape(v, shape=(1, 1, 8, 1)))
#
# self.masked_v = tf.concat(masked_v, axis=0)
# assert self.masked_v.get_shape() == [cfg.batch_size, 1, 8, 1]
# # Method 2. masking with true label, default mode
# else:
# # self.masked_v = tf.matmul(tf.squeeze(self.caps2), tf.reshape(self.Y, (-1, 10, 1)), transpose_a=True)
# self.masked_v = tf.multiply(tf.squeeze(self.caps2), tf.reshape(self.Y, (-1, self.n_classes, 1)))
# self.v_length = tf.sqrt(tf.reduce_sum(tf.square(self.caps2), axis=2, keepdims=True) + epsilon)
#
# # 2. Reconstructe the MNIST images with 3 FC layers
# # [batch_size, 1, 16, 1] => [batch_size, 16] => [batch_size, 512]
# with tf.variable_scope('Decoder'):
# vector_j = tf.reshape(self.masked_v, shape=(cfg.batch_size, -1))
# fc1 = tf.contrib.layers.fully_connected(vector_j, num_outputs=512)
# assert fc1.get_shape() == [cfg.batch_size, 512]
# fc2 = tf.contrib.layers.fully_connected(fc1, num_outputs=1024)
# assert fc2.get_shape() == [cfg.batch_size, 1024]
# self.decoded = tf.contrib.layers.fully_connected(fc2, num_outputs=self.n_steps*self.n_input, activation_fn=tf.sigmoid)
def loss(self):
# 1. The margin loss
# [batch_size, 10, 1, 1]
# max_l = max(0, m_plus-||v_c||)^2
max_l = tf.square(tf.maximum(0., cfg.m_plus - self.v_length))
# max_r = max(0, ||v_c||-m_minus)^2
max_r = tf.square(tf.maximum(0., self.v_length - cfg.m_minus))
assert max_l.get_shape() == [cfg.batch_size,self.n_classes, 1, 1]
# reshape: [batch_size, 10, 1, 1] => [batch_size, 10]
max_l = tf.reshape(max_l, shape=(cfg.batch_size, -1))
max_r = tf.reshape(max_r, shape=(cfg.batch_size, -1))
# calc T_c: [batch_size, 10]
# T_c = Y, is my understanding correct? Try it.
T_c = self.Y
# [batch_size, 10], element-wise multiply
L_c = T_c * max_l + cfg.lambda_val * (1 - T_c) * max_r
self.margin_loss = tf.reduce_mean(tf.reduce_sum(L_c, axis=1))
# # 2. The reconstruction loss
# orgin = tf.reshape(self.X, shape=(cfg.batch_size, -1))
# squared = tf.square(self.decoded - orgin)
# self.reconstruction_err = tf.reduce_mean(squared)
# lstm loss
self.lstm_cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.lstmpred, labels=self.lstm_y))
self.lstm_index = tf.to_int32(tf.argmax(self.lstmpred, axis=1))
self.dense_cov1_cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.dense1, labels=self.lstm_y))
self.dense_caps1_cost= tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.dense2, labels=self.lstm_y))
# 3. Total loss
# The paper uses sum of squared error as reconstruction error, but we
# have used reduce_mean in `# 2 The reconstruction loss` to calculate
# mean squared error. In order to keep in line with the paper,the
# regularization scale should be 0.0005*784=0.392
# self.total_loss = self.margin_loss + cfg.regularization_scale * self.reconstruction_err+lstm_cost
# self.total_loss = self.margin_loss+self.lstm_cost
self.total_loss = self.margin_loss+self.lstm_cost+self.dense_cov1_cost+self.dense_caps1_cost
# Summary
def _summary(self):
train_summary = []
train_summary.append(tf.summary.scalar('train/margin_loss', self.margin_loss))
# train_summary.append(tf.summary.scalar('train/reconstruction_loss', self.reconstruction_err))
train_summary.append(tf.summary.scalar('train/total_loss', self.total_loss))
# train_summary.append(tf.summary.scalar('train/rf_loss', self.rf_loss_op))
# recon_img = tf.reshape(self.decoded, shape=(cfg.batch_size, self.n_input,self.n_steps, 1))
# train_summary.append(tf.summary.image('reconstruction_img', recon_img))
self.train_summary = tf.summary.merge(train_summary)
# correct_prediction = tf.equal(tf.to_int32(self.labels), self.max_index_list)
# self.accuracy = tf.reduce_sum(tf.cast(correct_prediction, tf.float32))
| 49.206897 | 212 | 0.632586 | 13,446 | 0.941729 | 0 | 0 | 0 | 0 | 0 | 0 | 6,083 | 0.42604 |
898b4036b6c035a6ca0b7f4734119239d1a58055 | 1,001 | py | Python | settings.py | jjeejj/alien_invasion | 446bb46f67cefd02660a44bdeff6e78ee697e828 | [
"MIT"
] | 1 | 2019-06-23T13:42:06.000Z | 2019-06-23T13:42:06.000Z | settings.py | jjeejj/alien_invasion | 446bb46f67cefd02660a44bdeff6e78ee697e828 | [
"MIT"
] | null | null | null | settings.py | jjeejj/alien_invasion | 446bb46f67cefd02660a44bdeff6e78ee697e828 | [
"MIT"
] | null | null | null | # 设置类
class Settings():
'''保存设置信息'''
def __init__(self):
'''初始化游戏的静态设置'''
self.screen_width = 850
self.screen_heght = 600
self.bg_color = (230, 230, 230)
# 玩家飞船数量设置
self.ship_limit = 3
# 子弹设置
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = 60, 60, 60
self.bullets_allowed = 10
# 外星人设置
## 外星人移动速度
self.fleet_drop_speed = 5
self.speedup_scale = 1.1
self.initialize_dynamic_settings()
def initialize_dynamic_settings(self):
self.fleet_direction = 1 # 1表示向右移,为-1表示向左移
self.ship_speed_factor = 5.3 # 移动步长
self.bullet_speed_factor = 30
self.alien_speed_factor = 1
def increase_speedO(self):
'''提高速度设置'''
self.alien_speed_factor *= self.speedup_scale
self.ship_speed_factor *= self.speedup_scale
self.alien_speed_factor *= self.speedup_scale | 27.805556 | 54 | 0.58042 | 1,118 | 0.988506 | 0 | 0 | 0 | 0 | 0 | 0 | 238 | 0.210433 |
898b41882896a96530a97d73e69f44d73c15b034 | 11,564 | py | Python | stream.py | MusikPolice/picamera-web-interface | c10f50fb394fd1089c69ef0faaa523c8ec98604d | [
"Apache-2.0"
] | null | null | null | stream.py | MusikPolice/picamera-web-interface | c10f50fb394fd1089c69ef0faaa523c8ec98604d | [
"Apache-2.0"
] | null | null | null | stream.py | MusikPolice/picamera-web-interface | c10f50fb394fd1089c69ef0faaa523c8ec98604d | [
"Apache-2.0"
] | null | null | null | # Based on code shamelessly stolen from https://picamera.readthedocs.io/en/latest/recipes2.html#web-streaming
import io
import picamera
import logging
import socketserver
import configparser
import json
from threading import Condition
from http import server
from string import Template
from gpiozero import LED
PAGE="""\
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>$title</title>
<link rel="stylesheet" href="style.css" />
</head
<body>
<script>
/*
* To prevent Firefox FOUC, this must be here
* See https://bugzilla.mozilla.org/show_bug.cgi?id=1404468
*/
let FF_FOUC_FIX;
function updateSettings() {
var settings = {
brightness: document.getElementById('brightness-range').value,
ir: document.getElementById('ir-toggle').checked
};
var json = JSON.stringify(settings);
fetch('/settings', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: json
});
}
</script>
<div id="content">
<img src="stream.mjpg" width="$width" height="$height" />
<div id="settings">
<div id="brightness" class="center-vertical">
<span>Brightness: </span>
<input type="range" id="brightness-range" min="40" max="75" value="50" onchange="updateSettings();">
</div>
<div id="ir" class="center-vertical">
<span>Infrared: </span>
<label class="switch">
<input id="ir-toggle" type="checkbox" onchange="updateSettings()">
<span class="slider round"></span>
</label>
</div>
</div>
</div>
</body>
</html>
"""
CSS="""\
body {
background: $color3;
}
img {
max-width: $width;
max-height: $height;
width: 98%;
height: auto;
margin: 5px 1vw 5px 1vw;
border: 3px solid #5E6472;
border-radius: 10px;
}
#brightness {
margin-left: 1vw;
height: 40px;
width: 98%;
}
#brightness span {
color: #5E6472;
font-family: verdana;
}
.center-vertical {
display: flex;
justify-content: left;
align-items: center;
}
/* As it turns out, styling input ranges is a nightmare */
input[type=range] {
width: 30%;
margin: 10px;
background-color: transparent;
-webkit-appearance: none;
}
input[type=range]:focus {
outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
background: $color2;
border: 0.2px solid $color4;
border-radius: 1.3px;
width: 100%;
height: 8.4px;
cursor: pointer;
}
input[type=range]::-webkit-slider-thumb {
margin-top: -11px;
width: 15px;
height: 30px;
backgorund: $color1;
border: 1px solid $color4;
border-radius: 5px;
cursor: pointer;
-webkit-appearance: none;
}
input[type=range]:focus::-webkit-slider-runnable-track {
background: #fdfbf3;
}
input[type=range]::-moz-range-track {
background: $color2;
border: 0.2px solid $color4;
border-radius: 1.3px;
width: 100%;
height: 8.4px;
cursor: pointer;
}
input[type=range]::-moz-range-thumb {
width: 15px;
height: 30px;
background: $color1;
border: 1px solid $color4;
border-radius: 5px;
cursor: pointer;
}
input[type=range]::-ms-track {
background: transparent;
border-color: transparent;
border-width: 14.1px 0;
color: transparent;
width: 100%;
height: 8.4px;
cursor: pointer;
}
input[type=range]::-ms-fill-lower {
background: #f7ebc7;
border: 0.2px solid $color4;
border-radius: 2.6px;
}
input[type=range]::-ms-fill-upper {
background: $color2;
border: 0.2px solid $color4;
border-radius: 2.6px;
}
input[type=range]::-ms-thumb {
width: 15px;
height: 30px;
background: $color1;
border: 1px solid $color4;
border-radius: 5px;
cursor: pointer;
margin-top: 0px;
/*Needed to keep the Edge thumb centred*/
}
input[type=range]:focus::-ms-fill-lower {
background: color2;
}
input[type=range]:focus::-ms-fill-upper {
background: $color4;
}
@supports (-ms-ime-align:auto) {
/* Pre-Chromium Edge only styles, selector taken from hhttps://stackoverflow.com/a/32202953/7077589 */
input[type=range] {
margin: 0;
/*Edge starts the margin from the thumb, not the track as other browsers do*/
}
}
/* style the IR toggle switch */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
"""
class StreamingOutput(object):
def __init__(self):
self.frame = None
self.buffer = io.BytesIO()
self.condition = Condition()
def write(self, buf):
if buf.startswith(b'\xff\xd8'):
# this is a new frame, copy the existing buffer's content and notify all clients that it's available
self.buffer.truncate()
with self.condition:
self.frame = self.buffer.getvalue()
self.condition.notify_all()
self.buffer.seek(0)
return self.buffer.write(buf)
class StreamingHandler(server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path =='/':
# redirect to index.html
self.send_response(301)
self.send_header('Location', '/index.html')
self.end_headers()
elif self.path == '/index.html':
# serve the web page containing the video stream
d = dict(title = config.get('General', 'name'), \
width = config.get('Stream', 'resolution.width'), \
height = config.get('Stream', 'resolution.height'))
content = Template(PAGE).substitute(d).encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
elif self.path == '/style.css':
# serve the CSS stylesheet
d = dict(width = config.get('Stream', 'resolution.width') + 'px', \
height = config.get('Stream', 'resolution.height') + 'px', \
color1 = config.get('Style', 'color1'), \
color2 = config.get('Style', 'color2'), \
color3 = config.get('Style', 'color3'), \
color4 = config.get('Style', 'color4'))
content = Template(CSS).substitute(d).encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/css')
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
elif self.path == '/stream.mjpg':
# serve the mjpeg video stream
self.send_response(200)
self.send_header('Age', 0)
self.send_header('Cache-Control', 'no-cache, private')
self.send_header('Pragma', 'no-cache')
self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
self.end_headers()
try:
while True:
with output.condition:
output.condition.wait()
frame = output.frame
self.wfile.write(b'--FRAME\r\n')
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-Length', len(frame))
self.end_headers()
self.wfile.write(frame)
self.wfile.write(b'\r\n')
except Exception as e:
logging.warning('Removed streaming client %s: %s', self.client_address, str(e))
else:
self.send_error(404)
self.end_headers()
def do_POST(self):
if self.path == '/settings':
try :
# parse request body json
contentLength = int(self.headers.get('Content-Length'))
request = json.loads(self.rfile.read(contentLength))
logger.info('POST request from %s: %s', self.client_address, str(request))
camera.brightness = int(request['brightness'])
# infrared is backward - pulling the pin low turns it on
# TODO: figure out how to flip the the pin to active low so this is nicer code
if request['ir'] == True:
ir.off()
else:
ir.on()
# if everything worked, respond with a 200 OK
self.send_response(200)
self.end_headers()
except Exception as e:
logger.error('Failed to process POST request from %s: %s', self.client_address, str(e))
self.send_response(400)
self.end_headers()
else:
self.send_error(404)
self.end_headers()
class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
allow_reuse_address = True
daemon_threads = True
# set up the logger
logger = logging.getLogger('stream')
logger.setLevel('DEBUG')
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
streamHandler = logging.StreamHandler()
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
# read the config file
config = configparser.ConfigParser()
config.read('settings.ini')
logger.info('Initializing stream: ' + config.get('General', 'name'))
# initialize the camera - turn off IR mode
ir = LED(4)
ir.on()
# start the camera rolling and the server listening on the configured port
resolutionString = config.get('Stream', 'resolution.width') + 'x' + config.get('Stream', 'resolution.height')
with picamera.PiCamera(resolution=resolutionString, framerate=24) as camera:
output = StreamingOutput()
camera.start_recording(output, format='mjpeg')
camera.brightness = 50
try:
address = ('', int(config.get('Stream', 'port')))
server = StreamingServer(address, StreamingHandler)
logger.info('Listening on port ' + config.get('Stream', 'port'))
server.serve_forever()
finally:
camera.stop_recording()
| 29.804124 | 120 | 0.579557 | 4,578 | 0.395884 | 0 | 0 | 0 | 0 | 0 | 0 | 7,117 | 0.615444 |
898c77e492dd4a9d199a1a4723672c492bb1ddb8 | 3,811 | py | Python | downloader.py | mathieuhendey/lastfm_downloader | 616ed6edad171e6eda05fd48b07a237d7c788fd5 | [
"MIT"
] | 3 | 2019-06-06T08:59:18.000Z | 2021-07-16T06:43:24.000Z | downloader.py | mathieuhendey/lastfm_downloader | 616ed6edad171e6eda05fd48b07a237d7c788fd5 | [
"MIT"
] | 1 | 2021-08-23T14:33:09.000Z | 2021-08-23T14:33:09.000Z | downloader.py | mathieuhendey/lastfm_downloader | 616ed6edad171e6eda05fd48b07a237d7c788fd5 | [
"MIT"
] | 1 | 2020-10-15T08:40:55.000Z | 2020-10-15T08:40:55.000Z | import sys
import pandas as pd
import requests
import pprint
from requests_toolbelt.threaded import pool
# Generate your own at https://www.last.fm/api/account/create
LASTFM_API_KEY = None
LASTFM_USER_NAME = None
TEXT = "#text"
ESTIMATED_TIME_FOR_PROCESSING_PAGE = 352
ESTIMATED_TIME_FOR_PROCESSING_DATAFRAME_PER_PAGE_OF_RESULTS = 275
if LASTFM_USER_NAME is None or LASTFM_API_KEY is None:
print(
"""
You need to generate some credentials, see the source code
"""
)
sys.exit(1)
def get_scrobbles(
endpoint="recenttracks",
username=LASTFM_USER_NAME,
key=LASTFM_API_KEY,
limit=200,
extended=0,
page=1,
pages=0,
):
"""
endpoint: API endpoint.
username: Last.fm username to fetch scrobbles for.
key: API key.
limit: The number of records per page. Maximum is 200.
extended: Extended results from API, such as whether user has "liked" the track.
page: First page to retrieve.
pages: How many pages of results after "page" argument to retrieve. If 0, get all pages.
"""
# initialize URL and lists to contain response fields
url = (
"https://ws.audioscrobbler.com/2.0/?method=user.get{}"
"&user={}"
"&api_key={}"
"&limit={}"
"&extended={}"
"&page={}"
"&format=json"
)
# get total number of pages
request_url = url.format(endpoint, username, key, limit, extended, page)
response = requests.get(request_url).json()
total_pages = int(response[endpoint]["@attr"]["totalPages"])
if pages > 0:
total_pages = min([total_pages, pages])
print(
"Total pages to retrieve: {}. Estimated time: {}".format(
total_pages, get_time_remaining(total_pages)
)
)
artist_names = []
album_names = []
track_names = []
timestamps = []
urls = []
# add formatted URLs to list to be requested in thread pool
for page in range(0, int(total_pages) + 1, 1):
urls.append(url.format(endpoint, username, key, limit, extended, page))
p = pool.Pool.from_urls(urls)
p.join_all()
for response in p.responses():
if endpoint in response.json():
response_json = response.json()[endpoint]["track"]
for track in response_json:
if "@attr" not in track:
artist_names.append(track["artist"][TEXT])
album_names.append(track["album"][TEXT])
track_names.append(track["name"])
timestamps.append(track["date"]["uts"])
# create and populate a dataframe to contain the data
df = pd.DataFrame()
df["artist"] = artist_names
df["album"] = album_names
df["track"] = track_names
df["timestamps"] = timestamps
# In UTC. Last.fm returns datetimes in the user's locale when they listened
df["datetime"] = pd.to_datetime(timestamps, unit="s")
df.sort_values("timestamps", ascending=False, inplace=True)
return df
def get_time_remaining(pages_remaining):
"""Calculate the estimated time remaining."""
millis_remaining = int(
(pages_remaining * ESTIMATED_TIME_FOR_PROCESSING_PAGE)
+ (
pages_remaining
* ESTIMATED_TIME_FOR_PROCESSING_DATAFRAME_PER_PAGE_OF_RESULTS
)
)
seconds_remaining = (millis_remaining / 1000) % 60
seconds_remaining = int(seconds_remaining)
minutes_remaining = (millis_remaining / (1000 * 60)) % 60
minutes_remaining = int(minutes_remaining)
return "{}m{:2}s".format(minutes_remaining, seconds_remaining)
scrobbles = get_scrobbles(page=1, pages=0) # Default to all Scrobbles
scrobbles.to_csv("./data/lastfm_scrobbles.csv", index=False, encoding="utf-8")
print("{:,} total rows".format(len(scrobbles)))
scrobbles.head()
| 32.02521 | 92 | 0.649173 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,247 | 0.327211 |
898eb33546671a512a010d7eaa79d1cab11f0acf | 1,652 | py | Python | src/trainer/fasttexttrainer.py | liuweiping2020/pyml | 0b9a7a307b93f9313d7e1bb92b33ae330d681c73 | [
"Apache-2.0"
] | null | null | null | src/trainer/fasttexttrainer.py | liuweiping2020/pyml | 0b9a7a307b93f9313d7e1bb92b33ae330d681c73 | [
"Apache-2.0"
] | null | null | null | src/trainer/fasttexttrainer.py | liuweiping2020/pyml | 0b9a7a307b93f9313d7e1bb92b33ae330d681c73 | [
"Apache-2.0"
] | null | null | null | import numpy as np
from modeler.fasttextmodel import FastTextModel
from trainer.tftrainer import TFTrainer
class FastTextTrainer(TFTrainer):
def __init__(self):
self.num_classes = 19
self.learning_rate = 0.01
self.batch_size = 8
self.decay_steps = 1000
self.decay_rate = 0.9
self.sequence_length = 5
self.vocab_size = 10000
self.embed_size = 100
self.is_training = True
self.dropout_keep_prob = 1
pass
def get_model(self):
self.fastText = FastTextModel(self.num_classes, self.learning_rate,
self.batch_size, self.decay_steps, self.decay_rate, 5,
self.sequence_length, self.vocab_size, self.embed_size, self.is_training)
def get_data(self):
self.input_x = np.zeros((self.batch_size, self.sequence_length), dtype=np.int32)
self.input_y = np.array([1, 0, 1, 1, 1, 2, 1, 1], dtype=np.int32)
def get_fetch_list(self):
self.fetch_list = [self.fastText.loss_val, self.fastText.accuracy,
self.fastText.predictions, self.fastText.train_op]
def get_feed_dict(self):
self.feed_dict = {self.fastText.sentence: self.input_x, self.fastText.labels: self.input_y}
def train(self):
for i in range(100):
loss, acc, predict, _ = self.session.run(self.fetch_list, feed_dict=self.feed_dict)
print("loss:", loss, "acc:", acc, "label:", self.input_y, "prediction:", predict)
if __name__ == '__main__':
FastTextTrainer = FastTextTrainer()
FastTextTrainer.run()
pass
| 34.416667 | 111 | 0.631961 | 1,436 | 0.869249 | 0 | 0 | 0 | 0 | 0 | 0 | 44 | 0.026634 |
898f280dfba7fad802966aff1e0af5464f293a16 | 13,358 | py | Python | release/stubs.min/Autodesk/Revit/DB/Structure/__init__.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | release/stubs.min/Autodesk/Revit/DB/Structure/__init__.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | release/stubs.min/Autodesk/Revit/DB/Structure/__init__.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | # encoding: utf-8
# module Autodesk.Revit.DB.Structure calls itself Structure
# from RevitAPI,Version=17.0.0.0,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
from __init___parts.AnalyticalAlignmentMethod import AnalyticalAlignmentMethod
from __init___parts.AnalyticalConsistencyChecking import AnalyticalConsistencyChecking
from __init___parts.AnalyticalCurveSelector import AnalyticalCurveSelector
from __init___parts.AnalyticalCurveType import AnalyticalCurveType
from __init___parts.AnalyticalDirection import AnalyticalDirection
from __init___parts.AnalyticalElementSelector import AnalyticalElementSelector
from __init___parts.AnalyticalFixityState import AnalyticalFixityState
from __init___parts.AnalyticalLink import AnalyticalLink
from __init___parts.AnalyticalLinkType import AnalyticalLinkType
from __init___parts.AnalyticalLoopType import AnalyticalLoopType
from __init___parts.AnalyticalModel import AnalyticalModel
from __init___parts.AnalyticalModelStick import AnalyticalModelStick
from __init___parts.AnalyticalModelColumn import AnalyticalModelColumn
from __init___parts.AnalyticalModelSelector import AnalyticalModelSelector
from __init___parts.AnalyticalModelSketchComponent import AnalyticalModelSketchComponent
from __init___parts.AnalyticalModelSupport import AnalyticalModelSupport
from __init___parts.AnalyticalModelSurface import AnalyticalModelSurface
from __init___parts.AnalyticalProjectionType import AnalyticalProjectionType
from __init___parts.AnalyticalRigidLinksOption import AnalyticalRigidLinksOption
from __init___parts.AnalyticalSupportChecking import AnalyticalSupportChecking
from __init___parts.AnalyticalSupportPriority import AnalyticalSupportPriority
from __init___parts.AnalyticalSupportType import AnalyticalSupportType
from __init___parts.AnalyzeAs import AnalyzeAs
from __init___parts.LoadBase import LoadBase
from __init___parts.AreaLoad import AreaLoad
from __init___parts.LoadTypeBase import LoadTypeBase
from __init___parts.AreaLoadType import AreaLoadType
from __init___parts.AreaReinforcement import AreaReinforcement
from __init___parts.AreaReinforcementCurve import AreaReinforcementCurve
from __init___parts.AreaReinforcementType import AreaReinforcementType
from __init___parts.BentFabricBendDirection import BentFabricBendDirection
from __init___parts.BentFabricStraightWiresLocation import (
BentFabricStraightWiresLocation,
)
from __init___parts.BentFabricWiresOrientation import BentFabricWiresOrientation
from __init___parts.BoundaryConditions import BoundaryConditions
from __init___parts.BoundaryConditionsOrientTo import BoundaryConditionsOrientTo
from __init___parts.BoundaryConditionsType import BoundaryConditionsType
from __init___parts.BracePlanRepresentation import BracePlanRepresentation
from __init___parts.CodeCheckingParameterServiceData import (
CodeCheckingParameterServiceData,
)
from __init___parts.DistributionType import DistributionType
from __init___parts.EndTreatmentType import EndTreatmentType
from __init___parts.FabricArea import FabricArea
from __init___parts.FabricAreaType import FabricAreaType
from __init___parts.FabricHostReference import FabricHostReference
from __init___parts.FabricLapSplicePosition import FabricLapSplicePosition
from __init___parts.FabricLocation import FabricLocation
from __init___parts.FabricReinSpanSymbol import FabricReinSpanSymbol
from __init___parts.ReinforcementRoundingManager import ReinforcementRoundingManager
from __init___parts.FabricRoundingManager import FabricRoundingManager
from __init___parts.FabricSheet import FabricSheet
from __init___parts.FabricSheetAlignment import FabricSheetAlignment
from __init___parts.FabricSheetLayoutPattern import FabricSheetLayoutPattern
from __init___parts.FabricSheetType import FabricSheetType
from __init___parts.FabricTagComponentReference import FabricTagComponentReference
from __init___parts.FabricWireItem import FabricWireItem
from __init___parts.FabricWireType import FabricWireType
from __init___parts.FamilyStructuralMaterialTypeFilter import (
FamilyStructuralMaterialTypeFilter,
)
from __init___parts.Hub import Hub
from __init___parts.ICodeCheckingParameterServer import ICodeCheckingParameterServer
from __init___parts.IMemberForcesServer import IMemberForcesServer
from __init___parts.IStructuralSectionsServer import IStructuralSectionsServer
from __init___parts.LineLoad import LineLoad
from __init___parts.LineLoadType import LineLoadType
from __init___parts.LoadCase import LoadCase
from __init___parts.LoadCaseCategory import LoadCaseCategory
from __init___parts.LoadCombination import LoadCombination
from __init___parts.LoadCombinationState import LoadCombinationState
from __init___parts.LoadCombinationType import LoadCombinationType
from __init___parts.LoadComponent import LoadComponent
from __init___parts.LoadNature import LoadNature
from __init___parts.LoadNatureCategory import LoadNatureCategory
from __init___parts.LoadOrientTo import LoadOrientTo
from __init___parts.LoadType import LoadType
from __init___parts.LoadUsage import LoadUsage
from __init___parts.MemberForces import MemberForces
from __init___parts.MemberForcesServiceData import MemberForcesServiceData
from __init___parts.MultiplanarOption import MultiplanarOption
from __init___parts.PathReinforcement import PathReinforcement
from __init___parts.PathReinforcementType import PathReinforcementType
from __init___parts.PathReinSpanSymbol import PathReinSpanSymbol
from __init___parts.PointLoad import PointLoad
from __init___parts.PointLoadType import PointLoadType
from __init___parts.Rebar import Rebar
from __init___parts.RebarBarType import RebarBarType
from __init___parts.RebarBendData import RebarBendData
from __init___parts.RebarConstrainedHandle import RebarConstrainedHandle
from __init___parts.RebarConstraint import RebarConstraint
from __init___parts.RebarConstraintsManager import RebarConstraintsManager
from __init___parts.RebarConstraintTargetHostFaceType import (
RebarConstraintTargetHostFaceType,
)
from __init___parts.RebarConstraintType import RebarConstraintType
from __init___parts.RebarContainer import RebarContainer
from __init___parts.RebarContainerItem import RebarContainerItem
from __init___parts.RebarContainerIterator import RebarContainerIterator
from __init___parts.RebarContainerParameterManager import RebarContainerParameterManager
from __init___parts.RebarContainerType import RebarContainerType
from __init___parts.RebarCoupler import RebarCoupler
from __init___parts.RebarCouplerError import RebarCouplerError
from __init___parts.RebarCoverType import RebarCoverType
from __init___parts.RebarDeformationType import RebarDeformationType
from __init___parts.RebarHandleType import RebarHandleType
from __init___parts.RebarHookOrientation import RebarHookOrientation
from __init___parts.RebarHookType import RebarHookType
from __init___parts.RebarHostCategory import RebarHostCategory
from __init___parts.RebarHostData import RebarHostData
from __init___parts.RebarInSystem import RebarInSystem
from __init___parts.RebarLayoutRule import RebarLayoutRule
from __init___parts.RebarPresentationMode import RebarPresentationMode
from __init___parts.ReinforcementData import ReinforcementData
from __init___parts.RebarReinforcementData import RebarReinforcementData
from __init___parts.RebarRoundingManager import RebarRoundingManager
from __init___parts.RebarShape import RebarShape
from __init___parts.RebarShapeArcReferenceType import RebarShapeArcReferenceType
from __init___parts.RebarShapeBendAngle import RebarShapeBendAngle
from __init___parts.RebarShapeConstraint import RebarShapeConstraint
from __init___parts.RebarShapeConstraint180DegreeBendArcLength import (
RebarShapeConstraint180DegreeBendArcLength,
)
from __init___parts.RebarShapeConstraint180DegreeBendRadius import (
RebarShapeConstraint180DegreeBendRadius,
)
from __init___parts.RebarShapeConstraint180DegreeDefaultBend import (
RebarShapeConstraint180DegreeDefaultBend,
)
from __init___parts.RebarShapeConstraintAngleFromFixedDir import (
RebarShapeConstraintAngleFromFixedDir,
)
from __init___parts.RebarShapeConstraintArcLength import RebarShapeConstraintArcLength
from __init___parts.RebarShapeConstraintChordLength import (
RebarShapeConstraintChordLength,
)
from __init___parts.RebarShapeConstraintCircumference import (
RebarShapeConstraintCircumference,
)
from __init___parts.RebarShapeConstraintDiameter import RebarShapeConstraintDiameter
from __init___parts.RebarShapeConstraintFixedSegmentDir import (
RebarShapeConstraintFixedSegmentDir,
)
from __init___parts.RebarShapeConstraintProjectedSegmentLength import (
RebarShapeConstraintProjectedSegmentLength,
)
from __init___parts.RebarShapeConstraintRadius import RebarShapeConstraintRadius
from __init___parts.RebarShapeConstraintSagittaLength import (
RebarShapeConstraintSagittaLength,
)
from __init___parts.RebarShapeConstraintSegmentLength import (
RebarShapeConstraintSegmentLength,
)
from __init___parts.RebarShapeDefinition import RebarShapeDefinition
from __init___parts.RebarShapeDefinitionByArc import RebarShapeDefinitionByArc
from __init___parts.RebarShapeDefinitionByArcType import RebarShapeDefinitionByArcType
from __init___parts.RebarShapeDefinitionBySegments import RebarShapeDefinitionBySegments
from __init___parts.RebarShapeMultiplanarDefinition import (
RebarShapeMultiplanarDefinition,
)
from __init___parts.RebarShapeParameters import RebarShapeParameters
from __init___parts.RebarShapeSegment import RebarShapeSegment
from __init___parts.RebarShapeSegmentEndReferenceType import (
RebarShapeSegmentEndReferenceType,
)
from __init___parts.RebarShapeVertex import RebarShapeVertex
from __init___parts.RebarShapeVertexTurn import RebarShapeVertexTurn
from __init___parts.RebarStyle import RebarStyle
from __init___parts.RebarSystemSpanSymbol import RebarSystemSpanSymbol
from __init___parts.ReinforcementAbbreviationObjectType import (
ReinforcementAbbreviationObjectType,
)
from __init___parts.ReinforcementAbbreviationTag import ReinforcementAbbreviationTag
from __init___parts.ReinforcementAbbreviationTagType import (
ReinforcementAbbreviationTagType,
)
from __init___parts.ReinforcementBarOrientation import ReinforcementBarOrientation
from __init___parts.ReinforcementRoundingSource import ReinforcementRoundingSource
from __init___parts.ReinforcementSettings import ReinforcementSettings
from __init___parts.ReleaseType import ReleaseType
from __init___parts.StickElementExtension import StickElementExtension
from __init___parts.StickElementProjectionY import StickElementProjectionY
from __init___parts.StickElementProjectionZ import StickElementProjectionZ
from __init___parts.StirrupTieAttachmentType import StirrupTieAttachmentType
from __init___parts.StructuralConnectionApplyTo import StructuralConnectionApplyTo
from __init___parts.StructuralConnectionApprovalType import (
StructuralConnectionApprovalType,
)
from __init___parts.StructuralConnectionCodeCheckingStatus import (
StructuralConnectionCodeCheckingStatus,
)
from __init___parts.StructuralConnectionHandler import StructuralConnectionHandler
from __init___parts.StructuralConnectionHandlerType import (
StructuralConnectionHandlerType,
)
from __init___parts.StructuralConnectionSettings import StructuralConnectionSettings
from __init___parts.StructuralConnectionType import StructuralConnectionType
from __init___parts.StructuralFramingUtils import StructuralFramingUtils
from __init___parts.StructuralInstanceUsage import StructuralInstanceUsage
from __init___parts.StructuralInstanceUsageFilter import StructuralInstanceUsageFilter
from __init___parts.StructuralMaterialType import StructuralMaterialType
from __init___parts.StructuralMaterialTypeFilter import StructuralMaterialTypeFilter
from __init___parts.StructuralSectionsServiceData import StructuralSectionsServiceData
from __init___parts.StructuralSettings import StructuralSettings
from __init___parts.StructuralType import StructuralType
from __init___parts.StructuralWallUsage import StructuralWallUsage
from __init___parts.StructuralWallUsageFilter import StructuralWallUsageFilter
from __init___parts.SurfaceElementExtension import SurfaceElementExtension
from __init___parts.SurfaceElementProjectionZ import SurfaceElementProjectionZ
from __init___parts.TargetRebarConstraintType import TargetRebarConstraintType
from __init___parts.TranslationRotationValue import TranslationRotationValue
from __init___parts.Truss import Truss
from __init___parts.TrussChordLocation import TrussChordLocation
from __init___parts.TrussCurveType import TrussCurveType
from __init___parts.TrussMemberInfo import TrussMemberInfo
from __init___parts.TrussMemberType import TrussMemberType
from __init___parts.TrussType import TrussType
from __init___parts.WireDistributionDirection import WireDistributionDirection
from __init___parts.YJustification import YJustification
from __init___parts.YZJustificationOption import YZJustificationOption
from __init___parts.ZJustification import ZJustification
| 57.577586 | 89 | 0.897365 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 215 | 0.016095 |
898fd3519ea3c73d1cfaf184b707740b9eadcd70 | 1,700 | py | Python | katana/pedals/booster.py | leon3110l/katana_tsl_patch | a88cb35f524ba1941ccb4f94e0dcaa02df11fd18 | [
"MIT"
] | null | null | null | katana/pedals/booster.py | leon3110l/katana_tsl_patch | a88cb35f524ba1941ccb4f94e0dcaa02df11fd18 | [
"MIT"
] | null | null | null | katana/pedals/booster.py | leon3110l/katana_tsl_patch | a88cb35f524ba1941ccb4f94e0dcaa02df11fd18 | [
"MIT"
] | null | null | null | from .pedal import BasePedal
from enum import IntEnum
class BoosterType(IntEnum):
DEFAULT = 10
MID_BOOST = 0
CLEAN_BOOST = 1
TREBLE_BOOST = 2
CRUNCH = 3
NATURAL_OD = 4
WARM_OD = 5
FAT_DS = 6
LEAD_DS = 7
METAL_DS = 8
OCT_FUZZ = 9
BLUES_OD = 10
OD_1 = 11
TUBESCREAMER = 12
TURBO_OD = 13
DIST = 14
RAT = 15
GUV_DS = 16
DST_PLUS = 17
METAL_ZONE = 18
SIXTIES_FUZZ = 19
MUFF_FUZZ = 20
CUSTOM = 21
class Booster(BasePedal):
CHAIN_POS = [15]
def __init__(self,
_type: BoosterType = BoosterType.DEFAULT,
on: bool = True,
bottom: int = 50,
custom_bottom: int = 50,
custom_character: int = 50,
custom_high: int = 50,
custom_low: int = 50,
custom_top: int = 50,
custom_type: int = 0,
direct_mix: int = 0,
drive: int = 20,
effect_level: int = 56,
solo_level: int = 50,
solo_sw: int = 0,
tone: int = 46,
**kwargs
):
super().__init__('od_ds', on)
self.type = _type
self.bottom = bottom
self.custom_bottom = custom_bottom
self.custom_character = custom_character
self.custom_high = custom_high
self.custom_low = custom_low
self.custom_top = custom_top
self.custom_type = custom_type
self.direct_mix = direct_mix
self.drive = drive
self.effect_level = effect_level
self.solo_level = solo_level
self.solo_sw = solo_sw
self.tone = tone | 26.153846 | 57 | 0.531765 | 1,643 | 0.966471 | 0 | 0 | 0 | 0 | 0 | 0 | 7 | 0.004118 |
899136c30078eb7beeeeeeb4e5ad870501ebb8f3 | 867 | py | Python | OpenCV/task5.py | Vishwajeetiitb/Autumn-of-Automation | bd8c78662734f867b6aa6fd9179a12913387a01c | [
"MIT"
] | null | null | null | OpenCV/task5.py | Vishwajeetiitb/Autumn-of-Automation | bd8c78662734f867b6aa6fd9179a12913387a01c | [
"MIT"
] | null | null | null | OpenCV/task5.py | Vishwajeetiitb/Autumn-of-Automation | bd8c78662734f867b6aa6fd9179a12913387a01c | [
"MIT"
] | null | null | null | import numpy as np
import cv2
img = cv2.imread("test_image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
camera = cv2.VideoCapture(0)
while True:
ret,img = camera.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# cv2.waitKey(0)
cv2.destroyAllWindows() | 32.111111 | 75 | 0.701269 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 98 | 0.113033 |
8992dfa1462e52b04396648a85e1fba269dd606d | 9,159 | py | Python | src/models/ns.py | mhw32/meta-inference-public | 3cad0b84acd407f3d790f3d75d3045f62bdbf250 | [
"MIT"
] | 11 | 2019-11-16T02:01:38.000Z | 2022-03-19T08:19:21.000Z | src/models/ns.py | mhw32/meta-inference-public | 3cad0b84acd407f3d790f3d75d3045f62bdbf250 | [
"MIT"
] | null | null | null | src/models/ns.py | mhw32/meta-inference-public | 3cad0b84acd407f3d790f3d75d3045f62bdbf250 | [
"MIT"
] | 1 | 2020-05-01T12:44:40.000Z | 2020-05-01T12:44:40.000Z | import os
import sys
import torch
from torch import nn
from torch.nn import functional as F, init
from src.utils import bernoulli_log_pdf
from src.objectives.elbo import \
log_bernoulli_marginal_estimate_sets
class Statistician(nn.Module):
def __init__(self, c_dim, z_dim, hidden_dim_statistic=3, hidden_dim=400):
super(Statistician, self).__init__()
self.c_dim = c_dim
self.z_dim = z_dim
self.hidden_dim_statistic = hidden_dim_statistic
self.hidden_dim = hidden_dim
self.input_dim = 784
self.statistic_net = LinearStatisticNetwork(
self.input_dim, self.c_dim, hidden_dim=self.hidden_dim_statistic)
self.inference_net = LinearInferenceNetwork(
self.input_dim, self.c_dim, self.z_dim,
hidden_dim=self.hidden_dim)
self.latent_decoder = LinearLatentDecoder(
self.input_dim, self.c_dim, self.z_dim,
hidden_dim=self.hidden_dim)
self.observation_decoder = LinearObservationDecoder(
self.input_dim, self.c_dim, self.z_dim,
hidden_dim=self.hidden_dim)
# initialize weights
self.apply(self.weights_init)
def forward(self, x):
batch_size, n_samples = x.size(0), x.size(1)
x = x.view(batch_size, n_samples, self.input_dim)
c_mean, c_logvar = self.statistic_net(x)
c = self.reparameterize_gaussian(c_mean, c_logvar)
qz_mu, qz_logvar = self.inference_net(x, c)
qz_mu = qz_mu.view(batch_size, -1, self.z_dim)
qz_logvar = qz_logvar.view(batch_size, -1, self.z_dim)
z = self.reparameterize_gaussian(qz_mu, qz_logvar)
qz_params = [qz_mu, qz_logvar]
cz_mu, cz_logvar = self.latent_decoder(c)
pz_params = [cz_mu, cz_logvar]
x_mu = self.observation_decoder(z, c)
outputs = (
(c_mean, c_logvar),
(qz_params, pz_params),
(x, x_mu),
)
return outputs
def bernoulli_elbo_loss_sets(self, outputs, reduce=True):
c_outputs, z_outputs, x_outputs = outputs
# 1. reconstruction loss
x, x_mu = x_outputs
recon_loss = bernoulli_log_pdf(x, x_mu) # (n_datasets, batch_size)
# a) Context divergence: this is the positive D_KL
c_mu, c_logvar = c_outputs
kl_c = -0.5 * (1 + c_logvar - c_mu.pow(2) - c_logvar.exp())
kl_c = torch.sum(kl_c, dim=-1) # (n_datasets)
# b) Latent divergence: this is also the positive D_KL
qz_params, pz_params = z_outputs
# this is kl(q_z||p_z)
p_mu, p_logvar = pz_params
q_mu, q_logvar = qz_params
# the dimensions won't line up, so you'll need to broadcast!
p_mu = p_mu.unsqueeze(1).expand_as(q_mu)
p_logvar = p_logvar.unsqueeze(1).expand_as(q_logvar)
kl_z = 0.5 * (p_logvar - q_logvar + ((q_mu - p_mu)**2 + q_logvar.exp())/p_logvar.exp() - 1)
kl_z = torch.sum(kl_z, dim=-1) # (n_datasets, batch_size)
# THESE ARE ALSO UNNORMALIZED!!!
ELBO = -recon_loss + kl_z # these will both be (n_datasets, batch_size)
ELBO = ELBO.sum(-1) / x.size()[1] # averaging over (batch_size == self.sample_size)
ELBO = ELBO + kl_c # now this is (n_datasets,)
if reduce:
return torch.mean(ELBO) # averaging over (n_datasets)
else:
return ELBO # (n_datasets)
def estimate_marginal(self, x, n_samples=100):
# need to compute a bunch of outputs
with torch.no_grad():
elbo_list = []
for i in range(n_samples):
outputs = self.forward(x)
elbo = self.bernoulli_elbo_loss_sets(outputs, reduce=False)
elbo_list.append(elbo)
# bernoulli decoder
log_p_x = log_bernoulli_marginal_estimate_sets(elbo_list)
return log_p_x
@staticmethod
def reparameterize_gaussian(mean, logvar):
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return eps.mul(std).add_(mean)
@staticmethod
def weights_init(m):
if isinstance(m, (nn.Linear, nn.Conv2d)):
init.xavier_normal(m.weight.data, gain=init.calculate_gain('relu'))
init.constant(m.bias.data, 0)
elif isinstance(m, nn.BatchNorm1d):
pass
def extract_codes(self, x):
batch_size, n_samples = x.size(0), x.size(1)
x = x.view(batch_size, n_samples, self.input_dim)
c_mean, c_logvar = self.statistic_net(x)
c = self.reparameterize_gaussian(c_mean, c_logvar)
z_mu, _ = self.inference_net(x, c)
return z_mu
class LinearStatisticNetwork(nn.Module):
def __init__(self, n_features, c_dim, hidden_dim=128):
super(LinearStatisticNetwork, self).__init__()
self.n_features = n_features
self.hidden_dim = hidden_dim
self.c_dim = c_dim
self.prepool = PrePool(self.n_features, self.hidden_dim)
self.postpool = PostPool(self.hidden_dim, self.c_dim)
def forward(self, h):
batch_size = h.size(0)
e = self.prepool(h)
e = e.view(batch_size, -1, self.hidden_dim)
e = self.pool(e)
e = self.postpool(e)
return e
def pool(self, e):
"""
average pooling WITHIN each dataset!
"""
e = e.mean(1).view(-1, self.hidden_dim)
return e
class LinearInferenceNetwork(nn.Module):
def __init__(self, n_features, c_dim, z_dim, hidden_dim=128):
super(LinearInferenceNetwork, self).__init__()
self.n_features = n_features
self.hidden_dim = hidden_dim
self.c_dim = c_dim
self.z_dim = z_dim
self.fc_h = nn.Linear(self.n_features, self.hidden_dim)
self.fc_c = nn.Linear(self.c_dim, self.hidden_dim)
self.fc1 = nn.Linear(2 * self.hidden_dim, self.hidden_dim)
self.fc_params = nn.Linear(self.hidden_dim, 2 * self.z_dim)
def forward(self, h, c):
batch_size = h.size(0)
eh = h.view(-1, self.n_features) # embed h
eh = self.fc_h(eh)
eh = eh.view(batch_size, -1, self.hidden_dim)
ec = self.fc_c(c)
ec = ec.view(batch_size, -1, self.hidden_dim).expand_as(eh)
e = torch.cat([eh, ec], dim=2)
e = F.elu(e.view(-1, 2 * self.hidden_dim))
e = F.elu(self.fc1(e))
e = self.fc_params(e)
mean, logvar = torch.chunk(e, 2, dim=1)
return mean, logvar
class LinearLatentDecoder(nn.Module):
def __init__(self, n_features, c_dim, z_dim, hidden_dim=128):
super(LinearLatentDecoder, self).__init__()
self.n_features = n_features
self.hidden_dim = hidden_dim
self.c_dim = c_dim
self.z_dim = z_dim
self.fc_c = nn.Linear(self.c_dim, self.hidden_dim)
self.fc1 = nn.Linear(self.hidden_dim, self.hidden_dim)
self.fc_params = nn.Linear(self.hidden_dim, 2 * self.z_dim)
def forward(self, c):
batch_size = c.size(0)
ec = self.fc_c(c)
ec = ec.view(batch_size, -1, self.hidden_dim)
e = F.elu(ec.view(-1, self.hidden_dim))
e = F.elu(self.fc1(e))
e = self.fc_params(e)
mean, logvar = torch.chunk(e, 2, dim=1)
return mean, logvar
class LinearObservationDecoder(nn.Module):
def __init__(self, n_features, c_dim, z_dim, hidden_dim=128):
super(LinearObservationDecoder, self).__init__()
self.n_features = n_features
self.hidden_dim = hidden_dim
self.c_dim = c_dim
self.z_dim = z_dim
self.fc_z = nn.Linear(self.z_dim, self.hidden_dim)
self.fc_c = nn.Linear(self.c_dim, self.hidden_dim)
self.fc_initial = nn.Linear(2 * self.hidden_dim, 256 * 4 * 4)
self.fc3 = nn.Linear(256 * 4 * 4, 784)
def forward(self, z, c):
batch_size = z.size(0)
ez = self.fc_z(z)
ez = ez.view(batch_size, -1, self.hidden_dim)
ec = self.fc_c(c)
ec = ec.view(batch_size, -1, self.hidden_dim).expand_as(ez)
e = torch.cat([ez, ec], dim=2)
e = F.elu(e)
e = e.view(-1, 2 * self.hidden_dim)
e = F.elu(self.fc_initial(e))
e = self.fc3(e)
e = e.view(batch_size, -1, 784)
e = torch.sigmoid(e)
return e
class PrePool(nn.Module):
def __init__(self, n_features, hidden_dim):
super(PrePool, self).__init__()
self.n_features = n_features
self.hidden_dim = hidden_dim
# modules: 1 fc layer
self.fc = nn.Linear(self.n_features, self.hidden_dim)
def forward(self, h):
# reshape and affine
e = h.view(-1, self.n_features) # batch_size * sample_size
e = F.elu(self.fc(e))
return e
class PostPool(nn.Module):
def __init__(self, hidden_dim, c_dim):
super(PostPool, self).__init__()
self.hidden_dim = hidden_dim
self.c_dim = c_dim
self.fc_params = nn.Linear(self.hidden_dim, 2 * self.c_dim)
def forward(self, e):
e = self.fc_params(e)
mean, logvar = torch.chunk(e, 2, dim=1)
return mean, logvar
| 33.064982 | 99 | 0.611639 | 8,925 | 0.974451 | 0 | 0 | 444 | 0.048477 | 0 | 0 | 690 | 0.075336 |
8992e36f7d78153b1e0074a9172a102ef80e8d67 | 3,795 | py | Python | posts/views.py | Agiruskiy/yatube | 57e3e7deaf87f8fc2fdb4b53e4daa632f1dc43f5 | [
"BSD-3-Clause"
] | null | null | null | posts/views.py | Agiruskiy/yatube | 57e3e7deaf87f8fc2fdb4b53e4daa632f1dc43f5 | [
"BSD-3-Clause"
] | null | null | null | posts/views.py | Agiruskiy/yatube | 57e3e7deaf87f8fc2fdb4b53e4daa632f1dc43f5 | [
"BSD-3-Clause"
] | null | null | null | from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post, Groups
from django.contrib.auth import get_user_model, get_user
from .forms import NewPost
from django.contrib.auth.decorators import login_required
# Create your views here.
def first(request):
post_list = Post.objects.order_by('-pub_date').all()
paginator = Paginator(post_list, 10) # показывать по 10 записей на странице.
page_number = request.GET.get('page') # переменная в URL с номером запрошенной страницы
page = paginator.get_page(page_number) # получить записи с нужным смещением
return render(request, 'index.html', {
'page': page,
'paginator': paginator
}
)
def group_posts(request, slug):
# функция get_object_or_404 получает по заданным критериям объект из базы данных
# или возвращает сообщение об ошибке, если объект не найден
group = get_object_or_404(Groups, slug=slug)
post_list = Post.objects.filter(group=group).order_by('-pub_date').all()
paginator = Paginator(post_list, 10) # показывать по 10 записей на странице.
page_number = request.GET.get('page') # переменная в URL с номером запрошенной страницы
page = paginator.get_page(page_number) # получить записи с нужным смещением
# Метод .filter позволяет ограничить поиск по критериям. Это аналог добавления
# условия WHERE group_id = {group_id}
return render(request, "group.html", {
"group": group,
'page': page,
'paginator': paginator
}
)
@login_required
def new_post(request):
form = NewPost()
return render(request, 'new_post.html', {
'form': form
})
def new_post_confirm(request):
text = request.POST.get('text')
group = request.POST.get('group')
author = get_user(request)
post = Post(text=text, group_id=group, author=author)
post.save()
return render(request, 'new_post_confirm.html')
def profile(request, username):
users = get_object_or_404(get_user_model(), username=username)
post_list = Post.objects.filter(author=users).order_by('-pub_date').all()
posts = Post.objects.filter(author=users).latest('-pub_date')
num = post_list.count()
paginator = Paginator(post_list, 10)
page_number = request.GET.get('page')
page = paginator.get_page(page_number)
return render(request, 'profile.html', {
'users': users,
'page': page,
'paginator': paginator,
'num': num,
'posts': posts
})
def post_view(request, username, post_id):
get_object_or_404(get_user_model(), username=username)
posts = get_object_or_404(Post, id=post_id)
users = posts.author
num = Post.objects.filter(author=users).count()
return render(request, 'post.html', {
'posts': posts,
'users': users,
'num': num
})
@login_required
def post_edit(request, username, post_id):
posts = Post.objects.get(id=post_id)
if posts.author.username == username:
form = NewPost()
return render(request, 'post_edit.html', {
'form': form,
'post_id': post_id,
'username': username
})
else:
return redirect(to=request.path)
# тут тело функции. Не забудьте проверить,
# что текущий пользователь — это автор записи.
# В качестве шаблона страницы редактирования укажите шаблон создания новой записи
# который вы создали раньше (вы могли назвать шаблон иначе)
def edit_confirm(request, username, post_id):
posts = Post.objects.get(id=post_id)
posts.text = request.POST.get('text')
posts.group_id = request.POST.get('group')
posts.save()
return redirect(to=f'../../profile/{username}')
| 32.435897 | 92 | 0.674835 | 0 | 0 | 0 | 0 | 939 | 0.21621 | 0 | 0 | 1,648 | 0.379461 |
89933c1df7105a66426ac059f6d21de37d3ae93b | 291,404 | py | Python | tests/examples/minlplib/robot200.py | ouyang-w-19/decogo | 52546480e49776251d4d27856e18a46f40c824a1 | [
"MIT"
] | 2 | 2021-07-03T13:19:10.000Z | 2022-02-06T10:48:13.000Z | tests/examples/minlplib/robot200.py | ouyang-w-19/decogo | 52546480e49776251d4d27856e18a46f40c824a1 | [
"MIT"
] | 1 | 2021-07-04T14:52:14.000Z | 2021-07-15T10:17:11.000Z | tests/examples/minlplib/robot200.py | ouyang-w-19/decogo | 52546480e49776251d4d27856e18a46f40c824a1 | [
"MIT"
] | null | null | null | # NLP written by GAMS Convert at 04/21/18 13:54:04
#
# Equation counts
# Total E G L N X C B
# 1603 1603 0 0 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 2213 2213 0 0 0 0 0 0
# FX 16 16 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL DLL
# 7807 2804 5003 0
#
# Reformulation has removed 1 variable and 1 equation
from pyomo.environ import *
model = m = ConcreteModel()
m.x1 = Var(within=Reals,bounds=(4.5,4.5),initialize=4.5)
m.x2 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x3 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x4 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x5 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x6 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x7 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x8 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x9 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x10 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x11 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x12 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x13 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x14 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x15 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x16 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x17 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x18 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x19 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x20 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x21 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x22 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x23 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x24 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x25 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x26 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x27 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x28 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x29 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x30 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x31 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x32 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x33 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x34 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x35 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x36 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x37 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x38 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x39 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x40 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x41 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x42 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x43 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x44 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x45 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x46 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x47 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x48 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x49 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x50 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x51 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x52 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x53 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x54 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x55 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x56 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x57 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x58 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x59 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x60 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x61 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x62 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x63 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x64 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x65 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x66 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x67 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x68 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x69 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x70 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x71 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x72 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x73 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x74 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x75 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x76 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x77 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x78 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x79 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x80 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x81 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x82 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x83 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x84 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x85 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x86 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x87 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x88 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x89 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x90 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x91 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x92 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x93 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x94 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x95 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x96 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x97 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x98 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x99 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x100 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x101 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x102 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x103 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x104 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x105 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x106 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x107 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x108 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x109 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x110 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x111 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x112 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x113 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x114 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x115 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x116 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x117 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x118 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x119 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x120 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x121 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x122 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x123 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x124 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x125 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x126 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x127 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x128 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x129 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x130 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x131 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x132 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x133 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x134 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x135 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x136 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x137 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x138 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x139 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x140 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x141 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x142 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x143 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x144 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x145 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x146 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x147 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x148 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x149 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x150 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x151 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x152 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x153 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x154 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x155 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x156 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x157 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x158 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x159 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x160 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x161 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x162 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x163 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x164 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x165 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x166 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x167 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x168 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x169 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x170 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x171 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x172 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x173 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x174 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x175 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x176 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x177 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x178 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x179 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x180 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x181 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x182 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x183 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x184 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x185 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x186 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x187 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x188 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x189 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x190 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x191 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x192 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x193 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x194 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x195 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x196 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x197 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x198 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x199 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x200 = Var(within=Reals,bounds=(0,5),initialize=4.5)
m.x201 = Var(within=Reals,bounds=(4.5,4.5),initialize=4.5)
m.x202 = Var(within=Reals,bounds=(0,0),initialize=0)
m.x203 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.00020943951023932)
m.x204 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.000471238898038469)
m.x205 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.000837758040957278)
m.x206 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.00130899693899575)
m.x207 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.00188495559215388)
m.x208 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.00256563400043166)
m.x209 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.00335103216382911)
m.x210 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.00424115008234622)
m.x211 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.00523598775598299)
m.x212 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.00633554518473942)
m.x213 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0075398223686155)
m.x214 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.00884881930761125)
m.x215 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0102625360017267)
m.x216 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0117809724509617)
m.x217 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0134041286553164)
m.x218 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0151320046147908)
m.x219 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0169646003293849)
m.x220 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0189019157990986)
m.x221 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.020943951023932)
m.x222 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.023090706003885)
m.x223 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0253421807389577)
m.x224 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.02769837522915)
m.x225 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.030159289474462)
m.x226 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0327249234748937)
m.x227 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.035395277230445)
m.x228 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.038170350741116)
m.x229 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0410501440069066)
m.x230 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0440346570278169)
m.x231 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0471238898038469)
m.x232 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0503178423349965)
m.x233 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0536165146212658)
m.x234 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0570199066626547)
m.x235 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0605280184591634)
m.x236 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0641408500107916)
m.x237 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0678584013175395)
m.x238 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0716806723794071)
m.x239 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0756076631963944)
m.x240 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0796393737685013)
m.x241 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0837758040957278)
m.x242 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.088016954178074)
m.x243 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0923628240155399)
m.x244 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.0968134136081254)
m.x245 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.101368722955831)
m.x246 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.106028752058656)
m.x247 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.1107935009166)
m.x248 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.115662969529664)
m.x249 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.120637157897848)
m.x250 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.125716066021152)
m.x251 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.130899693899575)
m.x252 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.136188041533118)
m.x253 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.14158110892178)
m.x254 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.147078896065562)
m.x255 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.152681402964464)
m.x256 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.158388629618485)
m.x257 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.164200576027627)
m.x258 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.170117242191887)
m.x259 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.176138628111268)
m.x260 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.182264733785768)
m.x261 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.188495559215388)
m.x262 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.194831104400127)
m.x263 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.201271369339986)
m.x264 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.207816354034965)
m.x265 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.214466058485063)
m.x266 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.221220482690281)
m.x267 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.228079626650619)
m.x268 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.235043490366076)
m.x269 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.242112073836653)
m.x270 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.24928537706235)
m.x271 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.256563400043166)
m.x272 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.263946142779102)
m.x273 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.271433605270158)
m.x274 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.279025787516333)
m.x275 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.286722689517628)
m.x276 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.294524311274043)
m.x277 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.302430652785577)
m.x278 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.310441714052231)
m.x279 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.318557495074005)
m.x280 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.326777995850898)
m.x281 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.335103216382911)
m.x282 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.343533156670044)
m.x283 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.352067816712296)
m.x284 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.360707196509668)
m.x285 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.36945129606216)
m.x286 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.378300115369771)
m.x287 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.387253654432502)
m.x288 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.396311913250352)
m.x289 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.405474891823323)
m.x290 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.414742590151413)
m.x291 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.424115008234622)
m.x292 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.433592146072951)
m.x293 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.4431740036664)
m.x294 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.452860581014969)
m.x295 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.462651878118657)
m.x296 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.472547894977465)
m.x297 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.482548631591392)
m.x298 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.492654087960439)
m.x299 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.502864264084606)
m.x300 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.513179159963893)
m.x301 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.523598775598299)
m.x302 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.534123110987825)
m.x303 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.54475216613247)
m.x304 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.555485941032235)
m.x305 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.56632443568712)
m.x306 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.577267650097124)
m.x307 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.588315584262249)
m.x308 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.599468238182492)
m.x309 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.610725611857856)
m.x310 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.622087705288339)
m.x311 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.633554518473942)
m.x312 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.645126051414664)
m.x313 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.656802304110506)
m.x314 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.668583276561468)
m.x315 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.680468968767549)
m.x316 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.69245938072875)
m.x317 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.704554512445071)
m.x318 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.716754363916511)
m.x319 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.729058935143071)
m.x320 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.741468226124751)
m.x321 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.75398223686155)
m.x322 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.766600967353469)
m.x323 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.779324417600508)
m.x324 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.792152587602666)
m.x325 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.805085477359944)
m.x326 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.818123086872342)
m.x327 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.831265416139859)
m.x328 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.844512465162496)
m.x329 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.857864233940253)
m.x330 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.871320722473129)
m.x331 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.884881930761125)
m.x332 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.898547858804241)
m.x333 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.912318506602476)
m.x334 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.926193874155831)
m.x335 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.940173961464306)
m.x336 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.9542587685279)
m.x337 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.968448295346614)
m.x338 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.982742541920447)
m.x339 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=0.9971415082494)
m.x340 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.01164519433347)
m.x341 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.02625360017267)
m.x342 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.04096672576698)
m.x343 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.05578457111641)
m.x344 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.07070713622096)
m.x345 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.08573442108063)
m.x346 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.10086642569542)
m.x347 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.11610315006533)
m.x348 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.13144459419036)
m.x349 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.14689075807051)
m.x350 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.16244164170578)
m.x351 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.17809724509617)
m.x352 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.19385756824168)
m.x353 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.20972261114231)
m.x354 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.22569237379806)
m.x355 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.24176685620893)
m.x356 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.25794605837491)
m.x357 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.27422998029602)
m.x358 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.29061862197225)
m.x359 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.30711198340359)
m.x360 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.32371006459006)
m.x361 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.34041286553165)
m.x362 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.35722038622835)
m.x363 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.37413262668018)
m.x364 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.39114958688712)
m.x365 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.40827126684918)
m.x366 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.42549766656637)
m.x367 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.44282878603867)
m.x368 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.4602646252661)
m.x369 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.47780518424864)
m.x370 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.4954504629863)
m.x371 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.51320046147908)
m.x372 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.53105517972699)
m.x373 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.54901461773001)
m.x374 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.56707877548815)
m.x375 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.58524765300141)
m.x376 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.60352125026979)
m.x377 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.62189956729329)
m.x378 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.64038260407191)
m.x379 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.65897036060565)
m.x380 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.67766283689451)
m.x381 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.69646003293849)
m.x382 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.71536194873759)
m.x383 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.73436858429181)
m.x384 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.75347993960114)
m.x385 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.7726960146656)
m.x386 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.79201680948518)
m.x387 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.81144232405987)
m.x388 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.83097255838969)
m.x389 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.85060751247463)
m.x390 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.87034718631468)
m.x391 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.89019157990986)
m.x392 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.91014069326015)
m.x393 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.93019452636557)
m.x394 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.9503530792261)
m.x395 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.97061635184176)
m.x396 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=1.99098434421253)
m.x397 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=2.01145705633842)
m.x398 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=2.03203448821944)
m.x399 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=2.05271663985557)
m.x400 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=2.07350351124682)
m.x401 = Var(within=Reals,bounds=(-3.14159265358979,3.14159265358979),initialize=2.0943951023932)
m.x402 = Var(within=Reals,bounds=(2.0943951023932,2.0943951023932),initialize=2.0943951023932)
m.x403 = Var(within=Reals,bounds=(0.785398163397448,0.785398163397448),initialize=0.785398163397448)
m.x404 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x405 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x406 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x407 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x408 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x409 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x410 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x411 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x412 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x413 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x414 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x415 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x416 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x417 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x418 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x419 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x420 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x421 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x422 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x423 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x424 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x425 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x426 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x427 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x428 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x429 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x430 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x431 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x432 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x433 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x434 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x435 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x436 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x437 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x438 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x439 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x440 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x441 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x442 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x443 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x444 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x445 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x446 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x447 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x448 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x449 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x450 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x451 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x452 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x453 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x454 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x455 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x456 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x457 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x458 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x459 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x460 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x461 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x462 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x463 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x464 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x465 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x466 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x467 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x468 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x469 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x470 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x471 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x472 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x473 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x474 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x475 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x476 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x477 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x478 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x479 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x480 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x481 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x482 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x483 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x484 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x485 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x486 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x487 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x488 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x489 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x490 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x491 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x492 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x493 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x494 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x495 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x496 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x497 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x498 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x499 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x500 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x501 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x502 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x503 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x504 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x505 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x506 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x507 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x508 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x509 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x510 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x511 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x512 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x513 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x514 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x515 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x516 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x517 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x518 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x519 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x520 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x521 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x522 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x523 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x524 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x525 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x526 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x527 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x528 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x529 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x530 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x531 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x532 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x533 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x534 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x535 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x536 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x537 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x538 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x539 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x540 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x541 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x542 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x543 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x544 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x545 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x546 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x547 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x548 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x549 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x550 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x551 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x552 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x553 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x554 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x555 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x556 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x557 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x558 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x559 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x560 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x561 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x562 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x563 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x564 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x565 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x566 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x567 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x568 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x569 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x570 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x571 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x572 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x573 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x574 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x575 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x576 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x577 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x578 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x579 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x580 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x581 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x582 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x583 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x584 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x585 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x586 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x587 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x588 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x589 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x590 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x591 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x592 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x593 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x594 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x595 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x596 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x597 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x598 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x599 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x600 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x601 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x602 = Var(within=Reals,bounds=(0,3.14159265358979),initialize=0.785398163397448)
m.x603 = Var(within=Reals,bounds=(0.785398163397448,0.785398163397448),initialize=0.785398163397448)
m.x604 = Var(within=Reals,bounds=(0,0),initialize=0)
m.x605 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x606 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x607 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x608 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x609 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x610 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x611 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x612 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x613 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x614 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x615 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x616 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x617 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x618 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x619 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x620 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x621 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x622 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x623 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x624 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x625 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x626 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x627 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x628 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x629 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x630 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x631 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x632 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x633 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x634 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x635 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x636 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x637 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x638 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x639 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x640 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x641 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x642 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x643 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x644 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x645 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x646 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x647 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x648 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x649 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x650 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x651 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x652 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x653 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x654 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x655 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x656 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x657 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x658 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x659 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x660 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x661 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x662 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x663 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x664 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x665 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x666 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x667 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x668 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x669 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x670 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x671 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x672 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x673 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x674 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x675 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x676 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x677 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x678 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x679 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x680 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x681 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x682 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x683 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x684 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x685 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x686 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x687 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x688 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x689 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x690 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x691 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x692 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x693 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x694 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x695 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x696 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x697 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x698 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x699 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x700 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x701 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x702 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x703 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x704 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x705 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x706 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x707 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x708 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x709 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x710 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x711 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x712 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x713 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x714 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x715 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x716 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x717 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x718 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x719 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x720 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x721 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x722 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x723 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x724 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x725 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x726 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x727 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x728 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x729 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x730 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x731 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x732 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x733 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x734 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x735 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x736 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x737 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x738 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x739 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x740 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x741 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x742 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x743 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x744 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x745 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x746 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x747 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x748 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x749 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x750 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x751 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x752 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x753 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x754 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x755 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x756 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x757 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x758 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x759 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x760 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x761 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x762 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x763 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x764 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x765 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x766 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x767 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x768 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x769 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x770 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x771 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x772 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x773 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x774 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x775 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x776 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x777 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x778 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x779 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x780 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x781 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x782 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x783 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x784 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x785 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x786 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x787 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x788 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x789 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x790 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x791 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x792 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x793 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x794 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x795 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x796 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x797 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x798 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x799 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x800 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x801 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x802 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x803 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x804 = Var(within=Reals,bounds=(0,0),initialize=0)
m.x805 = Var(within=Reals,bounds=(0,0),initialize=0)
m.x806 = Var(within=Reals,bounds=(None,None),initialize=0.0418879020478639)
m.x807 = Var(within=Reals,bounds=(None,None),initialize=0.0628318530717959)
m.x808 = Var(within=Reals,bounds=(None,None),initialize=0.0837758040957278)
m.x809 = Var(within=Reals,bounds=(None,None),initialize=0.10471975511966)
m.x810 = Var(within=Reals,bounds=(None,None),initialize=0.125663706143592)
m.x811 = Var(within=Reals,bounds=(None,None),initialize=0.146607657167524)
m.x812 = Var(within=Reals,bounds=(None,None),initialize=0.167551608191456)
m.x813 = Var(within=Reals,bounds=(None,None),initialize=0.188495559215388)
m.x814 = Var(within=Reals,bounds=(None,None),initialize=0.20943951023932)
m.x815 = Var(within=Reals,bounds=(None,None),initialize=0.230383461263251)
m.x816 = Var(within=Reals,bounds=(None,None),initialize=0.251327412287183)
m.x817 = Var(within=Reals,bounds=(None,None),initialize=0.272271363311115)
m.x818 = Var(within=Reals,bounds=(None,None),initialize=0.293215314335047)
m.x819 = Var(within=Reals,bounds=(None,None),initialize=0.314159265358979)
m.x820 = Var(within=Reals,bounds=(None,None),initialize=0.335103216382911)
m.x821 = Var(within=Reals,bounds=(None,None),initialize=0.356047167406843)
m.x822 = Var(within=Reals,bounds=(None,None),initialize=0.376991118430775)
m.x823 = Var(within=Reals,bounds=(None,None),initialize=0.397935069454707)
m.x824 = Var(within=Reals,bounds=(None,None),initialize=0.418879020478639)
m.x825 = Var(within=Reals,bounds=(None,None),initialize=0.439822971502571)
m.x826 = Var(within=Reals,bounds=(None,None),initialize=0.460766922526503)
m.x827 = Var(within=Reals,bounds=(None,None),initialize=0.481710873550435)
m.x828 = Var(within=Reals,bounds=(None,None),initialize=0.502654824574367)
m.x829 = Var(within=Reals,bounds=(None,None),initialize=0.523598775598299)
m.x830 = Var(within=Reals,bounds=(None,None),initialize=0.544542726622231)
m.x831 = Var(within=Reals,bounds=(None,None),initialize=0.565486677646163)
m.x832 = Var(within=Reals,bounds=(None,None),initialize=0.586430628670095)
m.x833 = Var(within=Reals,bounds=(None,None),initialize=0.607374579694027)
m.x834 = Var(within=Reals,bounds=(None,None),initialize=0.628318530717959)
m.x835 = Var(within=Reals,bounds=(None,None),initialize=0.64926248174189)
m.x836 = Var(within=Reals,bounds=(None,None),initialize=0.670206432765822)
m.x837 = Var(within=Reals,bounds=(None,None),initialize=0.691150383789754)
m.x838 = Var(within=Reals,bounds=(None,None),initialize=0.712094334813686)
m.x839 = Var(within=Reals,bounds=(None,None),initialize=0.733038285837618)
m.x840 = Var(within=Reals,bounds=(None,None),initialize=0.75398223686155)
m.x841 = Var(within=Reals,bounds=(None,None),initialize=0.774926187885482)
m.x842 = Var(within=Reals,bounds=(None,None),initialize=0.795870138909414)
m.x843 = Var(within=Reals,bounds=(None,None),initialize=0.816814089933346)
m.x844 = Var(within=Reals,bounds=(None,None),initialize=0.837758040957278)
m.x845 = Var(within=Reals,bounds=(None,None),initialize=0.85870199198121)
m.x846 = Var(within=Reals,bounds=(None,None),initialize=0.879645943005142)
m.x847 = Var(within=Reals,bounds=(None,None),initialize=0.900589894029074)
m.x848 = Var(within=Reals,bounds=(None,None),initialize=0.921533845053006)
m.x849 = Var(within=Reals,bounds=(None,None),initialize=0.942477796076938)
m.x850 = Var(within=Reals,bounds=(None,None),initialize=0.96342174710087)
m.x851 = Var(within=Reals,bounds=(None,None),initialize=0.984365698124802)
m.x852 = Var(within=Reals,bounds=(None,None),initialize=1.00530964914873)
m.x853 = Var(within=Reals,bounds=(None,None),initialize=1.02625360017267)
m.x854 = Var(within=Reals,bounds=(None,None),initialize=1.0471975511966)
m.x855 = Var(within=Reals,bounds=(None,None),initialize=1.06814150222053)
m.x856 = Var(within=Reals,bounds=(None,None),initialize=1.08908545324446)
m.x857 = Var(within=Reals,bounds=(None,None),initialize=1.11002940426839)
m.x858 = Var(within=Reals,bounds=(None,None),initialize=1.13097335529233)
m.x859 = Var(within=Reals,bounds=(None,None),initialize=1.15191730631626)
m.x860 = Var(within=Reals,bounds=(None,None),initialize=1.17286125734019)
m.x861 = Var(within=Reals,bounds=(None,None),initialize=1.19380520836412)
m.x862 = Var(within=Reals,bounds=(None,None),initialize=1.21474915938805)
m.x863 = Var(within=Reals,bounds=(None,None),initialize=1.23569311041199)
m.x864 = Var(within=Reals,bounds=(None,None),initialize=1.25663706143592)
m.x865 = Var(within=Reals,bounds=(None,None),initialize=1.27758101245985)
m.x866 = Var(within=Reals,bounds=(None,None),initialize=1.29852496348378)
m.x867 = Var(within=Reals,bounds=(None,None),initialize=1.31946891450771)
m.x868 = Var(within=Reals,bounds=(None,None),initialize=1.34041286553164)
m.x869 = Var(within=Reals,bounds=(None,None),initialize=1.36135681655558)
m.x870 = Var(within=Reals,bounds=(None,None),initialize=1.38230076757951)
m.x871 = Var(within=Reals,bounds=(None,None),initialize=1.40324471860344)
m.x872 = Var(within=Reals,bounds=(None,None),initialize=1.42418866962737)
m.x873 = Var(within=Reals,bounds=(None,None),initialize=1.4451326206513)
m.x874 = Var(within=Reals,bounds=(None,None),initialize=1.46607657167524)
m.x875 = Var(within=Reals,bounds=(None,None),initialize=1.48702052269917)
m.x876 = Var(within=Reals,bounds=(None,None),initialize=1.5079644737231)
m.x877 = Var(within=Reals,bounds=(None,None),initialize=1.52890842474703)
m.x878 = Var(within=Reals,bounds=(None,None),initialize=1.54985237577096)
m.x879 = Var(within=Reals,bounds=(None,None),initialize=1.5707963267949)
m.x880 = Var(within=Reals,bounds=(None,None),initialize=1.59174027781883)
m.x881 = Var(within=Reals,bounds=(None,None),initialize=1.61268422884276)
m.x882 = Var(within=Reals,bounds=(None,None),initialize=1.63362817986669)
m.x883 = Var(within=Reals,bounds=(None,None),initialize=1.65457213089062)
m.x884 = Var(within=Reals,bounds=(None,None),initialize=1.67551608191456)
m.x885 = Var(within=Reals,bounds=(None,None),initialize=1.69646003293849)
m.x886 = Var(within=Reals,bounds=(None,None),initialize=1.71740398396242)
m.x887 = Var(within=Reals,bounds=(None,None),initialize=1.73834793498635)
m.x888 = Var(within=Reals,bounds=(None,None),initialize=1.75929188601028)
m.x889 = Var(within=Reals,bounds=(None,None),initialize=1.78023583703422)
m.x890 = Var(within=Reals,bounds=(None,None),initialize=1.80117978805815)
m.x891 = Var(within=Reals,bounds=(None,None),initialize=1.82212373908208)
m.x892 = Var(within=Reals,bounds=(None,None),initialize=1.84306769010601)
m.x893 = Var(within=Reals,bounds=(None,None),initialize=1.86401164112994)
m.x894 = Var(within=Reals,bounds=(None,None),initialize=1.88495559215388)
m.x895 = Var(within=Reals,bounds=(None,None),initialize=1.90589954317781)
m.x896 = Var(within=Reals,bounds=(None,None),initialize=1.92684349420174)
m.x897 = Var(within=Reals,bounds=(None,None),initialize=1.94778744522567)
m.x898 = Var(within=Reals,bounds=(None,None),initialize=1.9687313962496)
m.x899 = Var(within=Reals,bounds=(None,None),initialize=1.98967534727354)
m.x900 = Var(within=Reals,bounds=(None,None),initialize=2.01061929829747)
m.x901 = Var(within=Reals,bounds=(None,None),initialize=2.0315632493214)
m.x902 = Var(within=Reals,bounds=(None,None),initialize=2.05250720034533)
m.x903 = Var(within=Reals,bounds=(None,None),initialize=2.07345115136926)
m.x904 = Var(within=Reals,bounds=(None,None),initialize=2.0943951023932)
m.x905 = Var(within=Reals,bounds=(None,None),initialize=2.11533905341713)
m.x906 = Var(within=Reals,bounds=(None,None),initialize=2.13628300444106)
m.x907 = Var(within=Reals,bounds=(None,None),initialize=2.15722695546499)
m.x908 = Var(within=Reals,bounds=(None,None),initialize=2.17817090648892)
m.x909 = Var(within=Reals,bounds=(None,None),initialize=2.19911485751286)
m.x910 = Var(within=Reals,bounds=(None,None),initialize=2.22005880853679)
m.x911 = Var(within=Reals,bounds=(None,None),initialize=2.24100275956072)
m.x912 = Var(within=Reals,bounds=(None,None),initialize=2.26194671058465)
m.x913 = Var(within=Reals,bounds=(None,None),initialize=2.28289066160858)
m.x914 = Var(within=Reals,bounds=(None,None),initialize=2.30383461263252)
m.x915 = Var(within=Reals,bounds=(None,None),initialize=2.32477856365645)
m.x916 = Var(within=Reals,bounds=(None,None),initialize=2.34572251468038)
m.x917 = Var(within=Reals,bounds=(None,None),initialize=2.36666646570431)
m.x918 = Var(within=Reals,bounds=(None,None),initialize=2.38761041672824)
m.x919 = Var(within=Reals,bounds=(None,None),initialize=2.40855436775217)
m.x920 = Var(within=Reals,bounds=(None,None),initialize=2.42949831877611)
m.x921 = Var(within=Reals,bounds=(None,None),initialize=2.45044226980004)
m.x922 = Var(within=Reals,bounds=(None,None),initialize=2.47138622082397)
m.x923 = Var(within=Reals,bounds=(None,None),initialize=2.4923301718479)
m.x924 = Var(within=Reals,bounds=(None,None),initialize=2.51327412287183)
m.x925 = Var(within=Reals,bounds=(None,None),initialize=2.53421807389577)
m.x926 = Var(within=Reals,bounds=(None,None),initialize=2.5551620249197)
m.x927 = Var(within=Reals,bounds=(None,None),initialize=2.57610597594363)
m.x928 = Var(within=Reals,bounds=(None,None),initialize=2.59704992696756)
m.x929 = Var(within=Reals,bounds=(None,None),initialize=2.61799387799149)
m.x930 = Var(within=Reals,bounds=(None,None),initialize=2.63893782901543)
m.x931 = Var(within=Reals,bounds=(None,None),initialize=2.65988178003936)
m.x932 = Var(within=Reals,bounds=(None,None),initialize=2.68082573106329)
m.x933 = Var(within=Reals,bounds=(None,None),initialize=2.70176968208722)
m.x934 = Var(within=Reals,bounds=(None,None),initialize=2.72271363311115)
m.x935 = Var(within=Reals,bounds=(None,None),initialize=2.74365758413509)
m.x936 = Var(within=Reals,bounds=(None,None),initialize=2.76460153515902)
m.x937 = Var(within=Reals,bounds=(None,None),initialize=2.78554548618295)
m.x938 = Var(within=Reals,bounds=(None,None),initialize=2.80648943720688)
m.x939 = Var(within=Reals,bounds=(None,None),initialize=2.82743338823081)
m.x940 = Var(within=Reals,bounds=(None,None),initialize=2.84837733925475)
m.x941 = Var(within=Reals,bounds=(None,None),initialize=2.86932129027868)
m.x942 = Var(within=Reals,bounds=(None,None),initialize=2.89026524130261)
m.x943 = Var(within=Reals,bounds=(None,None),initialize=2.91120919232654)
m.x944 = Var(within=Reals,bounds=(None,None),initialize=2.93215314335047)
m.x945 = Var(within=Reals,bounds=(None,None),initialize=2.95309709437441)
m.x946 = Var(within=Reals,bounds=(None,None),initialize=2.97404104539834)
m.x947 = Var(within=Reals,bounds=(None,None),initialize=2.99498499642227)
m.x948 = Var(within=Reals,bounds=(None,None),initialize=3.0159289474462)
m.x949 = Var(within=Reals,bounds=(None,None),initialize=3.03687289847013)
m.x950 = Var(within=Reals,bounds=(None,None),initialize=3.05781684949407)
m.x951 = Var(within=Reals,bounds=(None,None),initialize=3.078760800518)
m.x952 = Var(within=Reals,bounds=(None,None),initialize=3.09970475154193)
m.x953 = Var(within=Reals,bounds=(None,None),initialize=3.12064870256586)
m.x954 = Var(within=Reals,bounds=(None,None),initialize=3.14159265358979)
m.x955 = Var(within=Reals,bounds=(None,None),initialize=3.16253660461372)
m.x956 = Var(within=Reals,bounds=(None,None),initialize=3.18348055563766)
m.x957 = Var(within=Reals,bounds=(None,None),initialize=3.20442450666159)
m.x958 = Var(within=Reals,bounds=(None,None),initialize=3.22536845768552)
m.x959 = Var(within=Reals,bounds=(None,None),initialize=3.24631240870945)
m.x960 = Var(within=Reals,bounds=(None,None),initialize=3.26725635973338)
m.x961 = Var(within=Reals,bounds=(None,None),initialize=3.28820031075732)
m.x962 = Var(within=Reals,bounds=(None,None),initialize=3.30914426178125)
m.x963 = Var(within=Reals,bounds=(None,None),initialize=3.33008821280518)
m.x964 = Var(within=Reals,bounds=(None,None),initialize=3.35103216382911)
m.x965 = Var(within=Reals,bounds=(None,None),initialize=3.37197611485304)
m.x966 = Var(within=Reals,bounds=(None,None),initialize=3.39292006587698)
m.x967 = Var(within=Reals,bounds=(None,None),initialize=3.41386401690091)
m.x968 = Var(within=Reals,bounds=(None,None),initialize=3.43480796792484)
m.x969 = Var(within=Reals,bounds=(None,None),initialize=3.45575191894877)
m.x970 = Var(within=Reals,bounds=(None,None),initialize=3.4766958699727)
m.x971 = Var(within=Reals,bounds=(None,None),initialize=3.49763982099664)
m.x972 = Var(within=Reals,bounds=(None,None),initialize=3.51858377202057)
m.x973 = Var(within=Reals,bounds=(None,None),initialize=3.5395277230445)
m.x974 = Var(within=Reals,bounds=(None,None),initialize=3.56047167406843)
m.x975 = Var(within=Reals,bounds=(None,None),initialize=3.58141562509236)
m.x976 = Var(within=Reals,bounds=(None,None),initialize=3.6023595761163)
m.x977 = Var(within=Reals,bounds=(None,None),initialize=3.62330352714023)
m.x978 = Var(within=Reals,bounds=(None,None),initialize=3.64424747816416)
m.x979 = Var(within=Reals,bounds=(None,None),initialize=3.66519142918809)
m.x980 = Var(within=Reals,bounds=(None,None),initialize=3.68613538021202)
m.x981 = Var(within=Reals,bounds=(None,None),initialize=3.70707933123596)
m.x982 = Var(within=Reals,bounds=(None,None),initialize=3.72802328225989)
m.x983 = Var(within=Reals,bounds=(None,None),initialize=3.74896723328382)
m.x984 = Var(within=Reals,bounds=(None,None),initialize=3.76991118430775)
m.x985 = Var(within=Reals,bounds=(None,None),initialize=3.79085513533168)
m.x986 = Var(within=Reals,bounds=(None,None),initialize=3.81179908635562)
m.x987 = Var(within=Reals,bounds=(None,None),initialize=3.83274303737955)
m.x988 = Var(within=Reals,bounds=(None,None),initialize=3.85368698840348)
m.x989 = Var(within=Reals,bounds=(None,None),initialize=3.87463093942741)
m.x990 = Var(within=Reals,bounds=(None,None),initialize=3.89557489045134)
m.x991 = Var(within=Reals,bounds=(None,None),initialize=3.91651884147528)
m.x992 = Var(within=Reals,bounds=(None,None),initialize=3.93746279249921)
m.x993 = Var(within=Reals,bounds=(None,None),initialize=3.95840674352314)
m.x994 = Var(within=Reals,bounds=(None,None),initialize=3.97935069454707)
m.x995 = Var(within=Reals,bounds=(None,None),initialize=4.000294645571)
m.x996 = Var(within=Reals,bounds=(None,None),initialize=4.02123859659493)
m.x997 = Var(within=Reals,bounds=(None,None),initialize=4.04218254761887)
m.x998 = Var(within=Reals,bounds=(None,None),initialize=4.0631264986428)
m.x999 = Var(within=Reals,bounds=(None,None),initialize=4.08407044966673)
m.x1000 = Var(within=Reals,bounds=(None,None),initialize=4.10501440069066)
m.x1001 = Var(within=Reals,bounds=(None,None),initialize=4.1259583517146)
m.x1002 = Var(within=Reals,bounds=(None,None),initialize=4.14690230273853)
m.x1003 = Var(within=Reals,bounds=(None,None),initialize=4.16784625376246)
m.x1004 = Var(within=Reals,bounds=(None,None),initialize=4.18879020478639)
m.x1005 = Var(within=Reals,bounds=(0,0),initialize=0)
m.x1006 = Var(within=Reals,bounds=(0,0),initialize=0)
m.x1007 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1008 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1009 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1010 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1011 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1012 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1013 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1014 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1015 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1016 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1017 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1018 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1019 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1020 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1021 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1022 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1023 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1024 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1025 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1026 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1027 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1028 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1029 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1030 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1031 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1032 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1033 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1034 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1035 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1036 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1037 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1038 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1039 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1040 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1041 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1042 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1043 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1044 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1045 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1046 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1047 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1048 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1049 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1050 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1051 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1052 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1053 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1054 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1055 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1056 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1057 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1058 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1059 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1060 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1061 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1062 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1063 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1064 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1065 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1066 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1067 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1068 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1069 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1070 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1071 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1072 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1073 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1074 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1075 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1076 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1077 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1078 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1079 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1080 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1081 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1082 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1083 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1084 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1085 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1086 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1087 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1088 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1089 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1090 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1091 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1092 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1093 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1094 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1095 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1096 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1097 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1098 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1099 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1100 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1101 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1102 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1103 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1104 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1105 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1106 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1107 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1108 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1109 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1110 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1111 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1112 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1113 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1114 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1115 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1116 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1117 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1118 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1119 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1120 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1121 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1122 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1123 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1124 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1125 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1126 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1127 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1128 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1129 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1130 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1131 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1132 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1133 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1134 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1135 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1136 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1137 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1138 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1139 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1140 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1141 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1142 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1143 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1144 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1145 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1146 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1147 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1148 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1149 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1150 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1151 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1152 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1153 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1154 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1155 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1156 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1157 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1158 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1159 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1160 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1161 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1162 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1163 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1164 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1165 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1166 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1167 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1168 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1169 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1170 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1171 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1172 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1173 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1174 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1175 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1176 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1177 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1178 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1179 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1180 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1181 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1182 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1183 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1184 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1185 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1186 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1187 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1188 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1189 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1190 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1191 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1192 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1193 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1194 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1195 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1196 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1197 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1198 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1199 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1200 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1201 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1202 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1203 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1204 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1205 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x1206 = Var(within=Reals,bounds=(0,0),initialize=0)
m.x1207 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1208 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1209 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1210 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1211 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1212 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1213 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1214 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1215 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1216 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1217 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1218 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1219 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1220 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1221 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1222 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1223 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1224 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1225 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1226 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1227 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1228 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1229 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1230 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1231 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1232 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1233 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1234 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1235 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1236 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1237 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1238 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1239 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1240 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1241 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1242 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1243 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1244 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1245 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1246 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1247 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1248 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1249 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1250 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1251 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1252 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1253 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1254 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1255 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1256 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1257 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1258 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1259 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1260 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1261 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1262 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1263 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1264 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1265 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1266 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1267 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1268 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1269 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1270 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1271 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1272 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1273 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1274 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1275 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1276 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1277 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1278 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1279 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1280 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1281 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1282 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1283 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1284 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1285 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1286 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1287 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1288 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1289 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1290 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1291 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1292 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1293 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1294 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1295 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1296 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1297 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1298 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1299 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1300 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1301 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1302 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1303 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1304 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1305 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1306 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1307 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1308 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1309 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1310 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1311 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1312 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1313 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1314 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1315 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1316 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1317 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1318 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1319 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1320 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1321 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1322 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1323 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1324 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1325 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1326 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1327 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1328 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1329 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1330 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1331 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1332 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1333 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1334 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1335 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1336 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1337 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1338 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1339 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1340 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1341 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1342 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1343 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1344 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1345 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1346 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1347 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1348 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1349 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1350 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1351 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1352 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1353 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1354 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1355 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1356 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1357 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1358 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1359 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1360 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1361 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1362 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1363 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1364 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1365 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1366 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1367 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1368 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1369 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1370 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1371 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1372 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1373 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1374 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1375 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1376 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1377 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1378 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1379 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1380 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1381 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1382 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1383 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1384 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1385 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1386 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1387 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1388 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1389 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1390 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1391 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1392 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1393 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1394 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1395 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1396 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1397 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1398 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1399 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1400 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1401 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1402 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1403 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1404 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1405 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1406 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1407 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1408 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1409 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1410 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1411 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1412 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1413 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1414 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1415 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1416 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1417 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1418 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1419 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1420 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1421 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1422 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1423 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1424 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1425 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1426 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1427 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1428 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1429 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1430 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1431 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1432 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1433 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1434 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1435 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1436 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1437 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1438 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1439 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1440 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1441 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1442 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1443 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1444 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1445 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1446 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1447 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1448 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1449 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1450 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1451 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1452 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1453 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1454 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1455 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1456 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1457 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1458 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1459 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1460 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1461 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1462 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1463 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1464 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1465 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1466 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1467 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1468 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1469 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1470 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1471 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1472 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1473 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1474 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1475 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1476 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1477 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1478 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1479 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1480 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1481 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1482 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1483 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1484 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1485 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1486 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1487 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1488 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1489 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1490 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1491 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1492 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1493 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1494 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1495 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1496 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1497 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1498 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1499 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1500 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1501 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1502 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1503 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1504 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1505 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1506 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1507 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1508 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1509 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1510 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1511 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1512 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1513 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1514 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1515 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1516 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1517 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1518 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1519 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1520 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1521 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1522 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1523 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1524 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1525 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1526 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1527 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1528 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1529 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1530 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1531 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1532 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1533 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1534 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1535 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1536 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1537 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1538 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1539 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1540 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1541 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1542 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1543 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1544 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1545 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1546 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1547 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1548 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1549 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1550 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1551 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1552 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1553 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1554 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1555 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1556 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1557 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1558 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1559 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1560 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1561 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1562 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1563 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1564 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1565 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1566 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1567 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1568 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1569 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1570 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1571 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1572 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1573 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1574 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1575 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1576 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1577 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1578 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1579 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1580 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1581 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1582 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1583 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1584 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1585 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1586 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1587 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1588 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1589 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1590 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1591 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1592 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1593 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1594 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1595 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1596 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1597 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1598 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1599 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1600 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1601 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1602 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1603 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1604 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1605 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1606 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1607 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1608 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1609 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1610 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1611 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1612 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1613 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1614 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1615 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1616 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1617 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1618 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1619 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1620 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1621 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1622 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1623 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1624 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1625 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1626 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1627 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1628 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1629 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1630 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1631 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1632 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1633 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1634 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1635 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1636 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1637 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1638 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1639 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1640 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1641 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1642 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1643 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1644 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1645 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1646 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1647 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1648 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1649 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1650 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1651 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1652 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1653 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1654 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1655 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1656 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1657 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1658 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1659 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1660 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1661 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1662 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1663 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1664 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1665 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1666 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1667 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1668 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1669 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1670 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1671 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1672 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1673 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1674 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1675 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1676 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1677 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1678 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1679 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1680 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1681 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1682 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1683 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1684 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1685 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1686 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1687 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1688 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1689 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1690 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1691 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1692 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1693 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1694 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1695 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1696 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1697 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1698 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1699 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1700 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1701 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1702 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1703 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1704 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1705 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1706 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1707 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1708 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1709 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1710 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1711 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1712 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1713 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1714 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1715 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1716 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1717 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1718 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1719 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1720 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1721 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1722 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1723 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1724 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1725 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1726 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1727 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1728 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1729 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1730 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1731 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1732 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1733 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1734 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1735 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1736 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1737 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1738 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1739 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1740 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1741 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1742 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1743 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1744 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1745 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1746 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1747 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1748 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1749 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1750 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1751 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1752 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1753 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1754 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1755 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1756 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1757 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1758 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1759 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1760 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1761 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1762 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1763 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1764 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1765 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1766 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1767 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1768 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1769 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1770 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1771 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1772 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1773 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1774 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1775 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1776 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1777 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1778 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1779 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1780 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1781 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1782 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1783 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1784 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1785 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1786 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1787 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1788 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1789 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1790 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1791 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1792 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1793 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1794 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1795 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1796 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1797 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1798 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1799 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1800 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1801 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1802 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1803 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1804 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1805 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1806 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1807 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1808 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1809 = Var(within=Reals,bounds=(-1,1),initialize=0.001)
m.x1810 = Var(within=Reals,bounds=(None,None),initialize=0.005)
m.x1812 = Var(within=Reals,bounds=(15.2083333333333,15.2083333333333),initialize=15.2083333333333)
m.x1813 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1814 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1815 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1816 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1817 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1818 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1819 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1820 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1821 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1822 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1823 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1824 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1825 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1826 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1827 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1828 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1829 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1830 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1831 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1832 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1833 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1834 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1835 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1836 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1837 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1838 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1839 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1840 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1841 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1842 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1843 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1844 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1845 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1846 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1847 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1848 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1849 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1850 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1851 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1852 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1853 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1854 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1855 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1856 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1857 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1858 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1859 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1860 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1861 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1862 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1863 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1864 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1865 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1866 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1867 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1868 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1869 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1870 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1871 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1872 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1873 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1874 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1875 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1876 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1877 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1878 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1879 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1880 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1881 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1882 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1883 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1884 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1885 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1886 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1887 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1888 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1889 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1890 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1891 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1892 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1893 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1894 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1895 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1896 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1897 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1898 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1899 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1900 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1901 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1902 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1903 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1904 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1905 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1906 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1907 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1908 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1909 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1910 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1911 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1912 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1913 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1914 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1915 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1916 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1917 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1918 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1919 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1920 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1921 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1922 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1923 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1924 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1925 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1926 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1927 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1928 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1929 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1930 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1931 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1932 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1933 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1934 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1935 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1936 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1937 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1938 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1939 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1940 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1941 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1942 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1943 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1944 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1945 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1946 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1947 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1948 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1949 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1950 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1951 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1952 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1953 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1954 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1955 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1956 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1957 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1958 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1959 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1960 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1961 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1962 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1963 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1964 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1965 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1966 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1967 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1968 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1969 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1970 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1971 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1972 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1973 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1974 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1975 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1976 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1977 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1978 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1979 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1980 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1981 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1982 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1983 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1984 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1985 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1986 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1987 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1988 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1989 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1990 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1991 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1992 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1993 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1994 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1995 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1996 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1997 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1998 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x1999 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2000 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2001 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2002 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2003 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2004 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2005 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2006 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2007 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2008 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2009 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2010 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2011 = Var(within=Reals,bounds=(0.0001,None),initialize=15.2083333333333)
m.x2012 = Var(within=Reals,bounds=(15.2083333333333,15.2083333333333),initialize=15.2083333333333)
m.x2013 = Var(within=Reals,bounds=(30.4166666666667,30.4166666666667),initialize=30.4166666666667)
m.x2014 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2015 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2016 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2017 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2018 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2019 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2020 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2021 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2022 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2023 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2024 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2025 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2026 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2027 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2028 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2029 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2030 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2031 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2032 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2033 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2034 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2035 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2036 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2037 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2038 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2039 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2040 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2041 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2042 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2043 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2044 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2045 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2046 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2047 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2048 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2049 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2050 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2051 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2052 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2053 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2054 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2055 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2056 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2057 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2058 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2059 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2060 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2061 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2062 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2063 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2064 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2065 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2066 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2067 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2068 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2069 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2070 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2071 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2072 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2073 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2074 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2075 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2076 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2077 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2078 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2079 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2080 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2081 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2082 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2083 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2084 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2085 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2086 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2087 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2088 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2089 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2090 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2091 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2092 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2093 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2094 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2095 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2096 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2097 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2098 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2099 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2100 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2101 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2102 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2103 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2104 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2105 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2106 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2107 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2108 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2109 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2110 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2111 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2112 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2113 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2114 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2115 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2116 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2117 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2118 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2119 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2120 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2121 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2122 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2123 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2124 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2125 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2126 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2127 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2128 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2129 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2130 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2131 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2132 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2133 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2134 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2135 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2136 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2137 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2138 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2139 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2140 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2141 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2142 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2143 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2144 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2145 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2146 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2147 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2148 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2149 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2150 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2151 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2152 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2153 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2154 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2155 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2156 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2157 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2158 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2159 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2160 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2161 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2162 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2163 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2164 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2165 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2166 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2167 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2168 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2169 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2170 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2171 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2172 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2173 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2174 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2175 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2176 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2177 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2178 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2179 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2180 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2181 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2182 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2183 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2184 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2185 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2186 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2187 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2188 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2189 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2190 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2191 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2192 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2193 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2194 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2195 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2196 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2197 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2198 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2199 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2200 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2201 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2202 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2203 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2204 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2205 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2206 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2207 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2208 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2209 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2210 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2211 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2212 = Var(within=Reals,bounds=(0.0001,None),initialize=30.4166666666667)
m.x2213 = Var(within=Reals,bounds=(30.4166666666667,30.4166666666667),initialize=30.4166666666667)
m.obj = Objective(expr= 200*m.x1810, sense=minimize)
m.c2 = Constraint(expr=-0.5*m.x1810*(m.x604 + m.x605) - m.x1 + m.x2 == 0)
m.c3 = Constraint(expr=-0.5*m.x1810*(m.x605 + m.x606) - m.x2 + m.x3 == 0)
m.c4 = Constraint(expr=-0.5*m.x1810*(m.x606 + m.x607) - m.x3 + m.x4 == 0)
m.c5 = Constraint(expr=-0.5*m.x1810*(m.x607 + m.x608) - m.x4 + m.x5 == 0)
m.c6 = Constraint(expr=-0.5*m.x1810*(m.x608 + m.x609) - m.x5 + m.x6 == 0)
m.c7 = Constraint(expr=-0.5*m.x1810*(m.x609 + m.x610) - m.x6 + m.x7 == 0)
m.c8 = Constraint(expr=-0.5*m.x1810*(m.x610 + m.x611) - m.x7 + m.x8 == 0)
m.c9 = Constraint(expr=-0.5*m.x1810*(m.x611 + m.x612) - m.x8 + m.x9 == 0)
m.c10 = Constraint(expr=-0.5*m.x1810*(m.x612 + m.x613) - m.x9 + m.x10 == 0)
m.c11 = Constraint(expr=-0.5*m.x1810*(m.x613 + m.x614) - m.x10 + m.x11 == 0)
m.c12 = Constraint(expr=-0.5*m.x1810*(m.x614 + m.x615) - m.x11 + m.x12 == 0)
m.c13 = Constraint(expr=-0.5*m.x1810*(m.x615 + m.x616) - m.x12 + m.x13 == 0)
m.c14 = Constraint(expr=-0.5*m.x1810*(m.x616 + m.x617) - m.x13 + m.x14 == 0)
m.c15 = Constraint(expr=-0.5*m.x1810*(m.x617 + m.x618) - m.x14 + m.x15 == 0)
m.c16 = Constraint(expr=-0.5*m.x1810*(m.x618 + m.x619) - m.x15 + m.x16 == 0)
m.c17 = Constraint(expr=-0.5*m.x1810*(m.x619 + m.x620) - m.x16 + m.x17 == 0)
m.c18 = Constraint(expr=-0.5*m.x1810*(m.x620 + m.x621) - m.x17 + m.x18 == 0)
m.c19 = Constraint(expr=-0.5*m.x1810*(m.x621 + m.x622) - m.x18 + m.x19 == 0)
m.c20 = Constraint(expr=-0.5*m.x1810*(m.x622 + m.x623) - m.x19 + m.x20 == 0)
m.c21 = Constraint(expr=-0.5*m.x1810*(m.x623 + m.x624) - m.x20 + m.x21 == 0)
m.c22 = Constraint(expr=-0.5*m.x1810*(m.x624 + m.x625) - m.x21 + m.x22 == 0)
m.c23 = Constraint(expr=-0.5*m.x1810*(m.x625 + m.x626) - m.x22 + m.x23 == 0)
m.c24 = Constraint(expr=-0.5*m.x1810*(m.x626 + m.x627) - m.x23 + m.x24 == 0)
m.c25 = Constraint(expr=-0.5*m.x1810*(m.x627 + m.x628) - m.x24 + m.x25 == 0)
m.c26 = Constraint(expr=-0.5*m.x1810*(m.x628 + m.x629) - m.x25 + m.x26 == 0)
m.c27 = Constraint(expr=-0.5*m.x1810*(m.x629 + m.x630) - m.x26 + m.x27 == 0)
m.c28 = Constraint(expr=-0.5*m.x1810*(m.x630 + m.x631) - m.x27 + m.x28 == 0)
m.c29 = Constraint(expr=-0.5*m.x1810*(m.x631 + m.x632) - m.x28 + m.x29 == 0)
m.c30 = Constraint(expr=-0.5*m.x1810*(m.x632 + m.x633) - m.x29 + m.x30 == 0)
m.c31 = Constraint(expr=-0.5*m.x1810*(m.x633 + m.x634) - m.x30 + m.x31 == 0)
m.c32 = Constraint(expr=-0.5*m.x1810*(m.x634 + m.x635) - m.x31 + m.x32 == 0)
m.c33 = Constraint(expr=-0.5*m.x1810*(m.x635 + m.x636) - m.x32 + m.x33 == 0)
m.c34 = Constraint(expr=-0.5*m.x1810*(m.x636 + m.x637) - m.x33 + m.x34 == 0)
m.c35 = Constraint(expr=-0.5*m.x1810*(m.x637 + m.x638) - m.x34 + m.x35 == 0)
m.c36 = Constraint(expr=-0.5*m.x1810*(m.x638 + m.x639) - m.x35 + m.x36 == 0)
m.c37 = Constraint(expr=-0.5*m.x1810*(m.x639 + m.x640) - m.x36 + m.x37 == 0)
m.c38 = Constraint(expr=-0.5*m.x1810*(m.x640 + m.x641) - m.x37 + m.x38 == 0)
m.c39 = Constraint(expr=-0.5*m.x1810*(m.x641 + m.x642) - m.x38 + m.x39 == 0)
m.c40 = Constraint(expr=-0.5*m.x1810*(m.x642 + m.x643) - m.x39 + m.x40 == 0)
m.c41 = Constraint(expr=-0.5*m.x1810*(m.x643 + m.x644) - m.x40 + m.x41 == 0)
m.c42 = Constraint(expr=-0.5*m.x1810*(m.x644 + m.x645) - m.x41 + m.x42 == 0)
m.c43 = Constraint(expr=-0.5*m.x1810*(m.x645 + m.x646) - m.x42 + m.x43 == 0)
m.c44 = Constraint(expr=-0.5*m.x1810*(m.x646 + m.x647) - m.x43 + m.x44 == 0)
m.c45 = Constraint(expr=-0.5*m.x1810*(m.x647 + m.x648) - m.x44 + m.x45 == 0)
m.c46 = Constraint(expr=-0.5*m.x1810*(m.x648 + m.x649) - m.x45 + m.x46 == 0)
m.c47 = Constraint(expr=-0.5*m.x1810*(m.x649 + m.x650) - m.x46 + m.x47 == 0)
m.c48 = Constraint(expr=-0.5*m.x1810*(m.x650 + m.x651) - m.x47 + m.x48 == 0)
m.c49 = Constraint(expr=-0.5*m.x1810*(m.x651 + m.x652) - m.x48 + m.x49 == 0)
m.c50 = Constraint(expr=-0.5*m.x1810*(m.x652 + m.x653) - m.x49 + m.x50 == 0)
m.c51 = Constraint(expr=-0.5*m.x1810*(m.x653 + m.x654) - m.x50 + m.x51 == 0)
m.c52 = Constraint(expr=-0.5*m.x1810*(m.x654 + m.x655) - m.x51 + m.x52 == 0)
m.c53 = Constraint(expr=-0.5*m.x1810*(m.x655 + m.x656) - m.x52 + m.x53 == 0)
m.c54 = Constraint(expr=-0.5*m.x1810*(m.x656 + m.x657) - m.x53 + m.x54 == 0)
m.c55 = Constraint(expr=-0.5*m.x1810*(m.x657 + m.x658) - m.x54 + m.x55 == 0)
m.c56 = Constraint(expr=-0.5*m.x1810*(m.x658 + m.x659) - m.x55 + m.x56 == 0)
m.c57 = Constraint(expr=-0.5*m.x1810*(m.x659 + m.x660) - m.x56 + m.x57 == 0)
m.c58 = Constraint(expr=-0.5*m.x1810*(m.x660 + m.x661) - m.x57 + m.x58 == 0)
m.c59 = Constraint(expr=-0.5*m.x1810*(m.x661 + m.x662) - m.x58 + m.x59 == 0)
m.c60 = Constraint(expr=-0.5*m.x1810*(m.x662 + m.x663) - m.x59 + m.x60 == 0)
m.c61 = Constraint(expr=-0.5*m.x1810*(m.x663 + m.x664) - m.x60 + m.x61 == 0)
m.c62 = Constraint(expr=-0.5*m.x1810*(m.x664 + m.x665) - m.x61 + m.x62 == 0)
m.c63 = Constraint(expr=-0.5*m.x1810*(m.x665 + m.x666) - m.x62 + m.x63 == 0)
m.c64 = Constraint(expr=-0.5*m.x1810*(m.x666 + m.x667) - m.x63 + m.x64 == 0)
m.c65 = Constraint(expr=-0.5*m.x1810*(m.x667 + m.x668) - m.x64 + m.x65 == 0)
m.c66 = Constraint(expr=-0.5*m.x1810*(m.x668 + m.x669) - m.x65 + m.x66 == 0)
m.c67 = Constraint(expr=-0.5*m.x1810*(m.x669 + m.x670) - m.x66 + m.x67 == 0)
m.c68 = Constraint(expr=-0.5*m.x1810*(m.x670 + m.x671) - m.x67 + m.x68 == 0)
m.c69 = Constraint(expr=-0.5*m.x1810*(m.x671 + m.x672) - m.x68 + m.x69 == 0)
m.c70 = Constraint(expr=-0.5*m.x1810*(m.x672 + m.x673) - m.x69 + m.x70 == 0)
m.c71 = Constraint(expr=-0.5*m.x1810*(m.x673 + m.x674) - m.x70 + m.x71 == 0)
m.c72 = Constraint(expr=-0.5*m.x1810*(m.x674 + m.x675) - m.x71 + m.x72 == 0)
m.c73 = Constraint(expr=-0.5*m.x1810*(m.x675 + m.x676) - m.x72 + m.x73 == 0)
m.c74 = Constraint(expr=-0.5*m.x1810*(m.x676 + m.x677) - m.x73 + m.x74 == 0)
m.c75 = Constraint(expr=-0.5*m.x1810*(m.x677 + m.x678) - m.x74 + m.x75 == 0)
m.c76 = Constraint(expr=-0.5*m.x1810*(m.x678 + m.x679) - m.x75 + m.x76 == 0)
m.c77 = Constraint(expr=-0.5*m.x1810*(m.x679 + m.x680) - m.x76 + m.x77 == 0)
m.c78 = Constraint(expr=-0.5*m.x1810*(m.x680 + m.x681) - m.x77 + m.x78 == 0)
m.c79 = Constraint(expr=-0.5*m.x1810*(m.x681 + m.x682) - m.x78 + m.x79 == 0)
m.c80 = Constraint(expr=-0.5*m.x1810*(m.x682 + m.x683) - m.x79 + m.x80 == 0)
m.c81 = Constraint(expr=-0.5*m.x1810*(m.x683 + m.x684) - m.x80 + m.x81 == 0)
m.c82 = Constraint(expr=-0.5*m.x1810*(m.x684 + m.x685) - m.x81 + m.x82 == 0)
m.c83 = Constraint(expr=-0.5*m.x1810*(m.x685 + m.x686) - m.x82 + m.x83 == 0)
m.c84 = Constraint(expr=-0.5*m.x1810*(m.x686 + m.x687) - m.x83 + m.x84 == 0)
m.c85 = Constraint(expr=-0.5*m.x1810*(m.x687 + m.x688) - m.x84 + m.x85 == 0)
m.c86 = Constraint(expr=-0.5*m.x1810*(m.x688 + m.x689) - m.x85 + m.x86 == 0)
m.c87 = Constraint(expr=-0.5*m.x1810*(m.x689 + m.x690) - m.x86 + m.x87 == 0)
m.c88 = Constraint(expr=-0.5*m.x1810*(m.x690 + m.x691) - m.x87 + m.x88 == 0)
m.c89 = Constraint(expr=-0.5*m.x1810*(m.x691 + m.x692) - m.x88 + m.x89 == 0)
m.c90 = Constraint(expr=-0.5*m.x1810*(m.x692 + m.x693) - m.x89 + m.x90 == 0)
m.c91 = Constraint(expr=-0.5*m.x1810*(m.x693 + m.x694) - m.x90 + m.x91 == 0)
m.c92 = Constraint(expr=-0.5*m.x1810*(m.x694 + m.x695) - m.x91 + m.x92 == 0)
m.c93 = Constraint(expr=-0.5*m.x1810*(m.x695 + m.x696) - m.x92 + m.x93 == 0)
m.c94 = Constraint(expr=-0.5*m.x1810*(m.x696 + m.x697) - m.x93 + m.x94 == 0)
m.c95 = Constraint(expr=-0.5*m.x1810*(m.x697 + m.x698) - m.x94 + m.x95 == 0)
m.c96 = Constraint(expr=-0.5*m.x1810*(m.x698 + m.x699) - m.x95 + m.x96 == 0)
m.c97 = Constraint(expr=-0.5*m.x1810*(m.x699 + m.x700) - m.x96 + m.x97 == 0)
m.c98 = Constraint(expr=-0.5*m.x1810*(m.x700 + m.x701) - m.x97 + m.x98 == 0)
m.c99 = Constraint(expr=-0.5*m.x1810*(m.x701 + m.x702) - m.x98 + m.x99 == 0)
m.c100 = Constraint(expr=-0.5*m.x1810*(m.x702 + m.x703) - m.x99 + m.x100 == 0)
m.c101 = Constraint(expr=-0.5*m.x1810*(m.x703 + m.x704) - m.x100 + m.x101 == 0)
m.c102 = Constraint(expr=-0.5*m.x1810*(m.x704 + m.x705) - m.x101 + m.x102 == 0)
m.c103 = Constraint(expr=-0.5*m.x1810*(m.x705 + m.x706) - m.x102 + m.x103 == 0)
m.c104 = Constraint(expr=-0.5*m.x1810*(m.x706 + m.x707) - m.x103 + m.x104 == 0)
m.c105 = Constraint(expr=-0.5*m.x1810*(m.x707 + m.x708) - m.x104 + m.x105 == 0)
m.c106 = Constraint(expr=-0.5*m.x1810*(m.x708 + m.x709) - m.x105 + m.x106 == 0)
m.c107 = Constraint(expr=-0.5*m.x1810*(m.x709 + m.x710) - m.x106 + m.x107 == 0)
m.c108 = Constraint(expr=-0.5*m.x1810*(m.x710 + m.x711) - m.x107 + m.x108 == 0)
m.c109 = Constraint(expr=-0.5*m.x1810*(m.x711 + m.x712) - m.x108 + m.x109 == 0)
m.c110 = Constraint(expr=-0.5*m.x1810*(m.x712 + m.x713) - m.x109 + m.x110 == 0)
m.c111 = Constraint(expr=-0.5*m.x1810*(m.x713 + m.x714) - m.x110 + m.x111 == 0)
m.c112 = Constraint(expr=-0.5*m.x1810*(m.x714 + m.x715) - m.x111 + m.x112 == 0)
m.c113 = Constraint(expr=-0.5*m.x1810*(m.x715 + m.x716) - m.x112 + m.x113 == 0)
m.c114 = Constraint(expr=-0.5*m.x1810*(m.x716 + m.x717) - m.x113 + m.x114 == 0)
m.c115 = Constraint(expr=-0.5*m.x1810*(m.x717 + m.x718) - m.x114 + m.x115 == 0)
m.c116 = Constraint(expr=-0.5*m.x1810*(m.x718 + m.x719) - m.x115 + m.x116 == 0)
m.c117 = Constraint(expr=-0.5*m.x1810*(m.x719 + m.x720) - m.x116 + m.x117 == 0)
m.c118 = Constraint(expr=-0.5*m.x1810*(m.x720 + m.x721) - m.x117 + m.x118 == 0)
m.c119 = Constraint(expr=-0.5*m.x1810*(m.x721 + m.x722) - m.x118 + m.x119 == 0)
m.c120 = Constraint(expr=-0.5*m.x1810*(m.x722 + m.x723) - m.x119 + m.x120 == 0)
m.c121 = Constraint(expr=-0.5*m.x1810*(m.x723 + m.x724) - m.x120 + m.x121 == 0)
m.c122 = Constraint(expr=-0.5*m.x1810*(m.x724 + m.x725) - m.x121 + m.x122 == 0)
m.c123 = Constraint(expr=-0.5*m.x1810*(m.x725 + m.x726) - m.x122 + m.x123 == 0)
m.c124 = Constraint(expr=-0.5*m.x1810*(m.x726 + m.x727) - m.x123 + m.x124 == 0)
m.c125 = Constraint(expr=-0.5*m.x1810*(m.x727 + m.x728) - m.x124 + m.x125 == 0)
m.c126 = Constraint(expr=-0.5*m.x1810*(m.x728 + m.x729) - m.x125 + m.x126 == 0)
m.c127 = Constraint(expr=-0.5*m.x1810*(m.x729 + m.x730) - m.x126 + m.x127 == 0)
m.c128 = Constraint(expr=-0.5*m.x1810*(m.x730 + m.x731) - m.x127 + m.x128 == 0)
m.c129 = Constraint(expr=-0.5*m.x1810*(m.x731 + m.x732) - m.x128 + m.x129 == 0)
m.c130 = Constraint(expr=-0.5*m.x1810*(m.x732 + m.x733) - m.x129 + m.x130 == 0)
m.c131 = Constraint(expr=-0.5*m.x1810*(m.x733 + m.x734) - m.x130 + m.x131 == 0)
m.c132 = Constraint(expr=-0.5*m.x1810*(m.x734 + m.x735) - m.x131 + m.x132 == 0)
m.c133 = Constraint(expr=-0.5*m.x1810*(m.x735 + m.x736) - m.x132 + m.x133 == 0)
m.c134 = Constraint(expr=-0.5*m.x1810*(m.x736 + m.x737) - m.x133 + m.x134 == 0)
m.c135 = Constraint(expr=-0.5*m.x1810*(m.x737 + m.x738) - m.x134 + m.x135 == 0)
m.c136 = Constraint(expr=-0.5*m.x1810*(m.x738 + m.x739) - m.x135 + m.x136 == 0)
m.c137 = Constraint(expr=-0.5*m.x1810*(m.x739 + m.x740) - m.x136 + m.x137 == 0)
m.c138 = Constraint(expr=-0.5*m.x1810*(m.x740 + m.x741) - m.x137 + m.x138 == 0)
m.c139 = Constraint(expr=-0.5*m.x1810*(m.x741 + m.x742) - m.x138 + m.x139 == 0)
m.c140 = Constraint(expr=-0.5*m.x1810*(m.x742 + m.x743) - m.x139 + m.x140 == 0)
m.c141 = Constraint(expr=-0.5*m.x1810*(m.x743 + m.x744) - m.x140 + m.x141 == 0)
m.c142 = Constraint(expr=-0.5*m.x1810*(m.x744 + m.x745) - m.x141 + m.x142 == 0)
m.c143 = Constraint(expr=-0.5*m.x1810*(m.x745 + m.x746) - m.x142 + m.x143 == 0)
m.c144 = Constraint(expr=-0.5*m.x1810*(m.x746 + m.x747) - m.x143 + m.x144 == 0)
m.c145 = Constraint(expr=-0.5*m.x1810*(m.x747 + m.x748) - m.x144 + m.x145 == 0)
m.c146 = Constraint(expr=-0.5*m.x1810*(m.x748 + m.x749) - m.x145 + m.x146 == 0)
m.c147 = Constraint(expr=-0.5*m.x1810*(m.x749 + m.x750) - m.x146 + m.x147 == 0)
m.c148 = Constraint(expr=-0.5*m.x1810*(m.x750 + m.x751) - m.x147 + m.x148 == 0)
m.c149 = Constraint(expr=-0.5*m.x1810*(m.x751 + m.x752) - m.x148 + m.x149 == 0)
m.c150 = Constraint(expr=-0.5*m.x1810*(m.x752 + m.x753) - m.x149 + m.x150 == 0)
m.c151 = Constraint(expr=-0.5*m.x1810*(m.x753 + m.x754) - m.x150 + m.x151 == 0)
m.c152 = Constraint(expr=-0.5*m.x1810*(m.x754 + m.x755) - m.x151 + m.x152 == 0)
m.c153 = Constraint(expr=-0.5*m.x1810*(m.x755 + m.x756) - m.x152 + m.x153 == 0)
m.c154 = Constraint(expr=-0.5*m.x1810*(m.x756 + m.x757) - m.x153 + m.x154 == 0)
m.c155 = Constraint(expr=-0.5*m.x1810*(m.x757 + m.x758) - m.x154 + m.x155 == 0)
m.c156 = Constraint(expr=-0.5*m.x1810*(m.x758 + m.x759) - m.x155 + m.x156 == 0)
m.c157 = Constraint(expr=-0.5*m.x1810*(m.x759 + m.x760) - m.x156 + m.x157 == 0)
m.c158 = Constraint(expr=-0.5*m.x1810*(m.x760 + m.x761) - m.x157 + m.x158 == 0)
m.c159 = Constraint(expr=-0.5*m.x1810*(m.x761 + m.x762) - m.x158 + m.x159 == 0)
m.c160 = Constraint(expr=-0.5*m.x1810*(m.x762 + m.x763) - m.x159 + m.x160 == 0)
m.c161 = Constraint(expr=-0.5*m.x1810*(m.x763 + m.x764) - m.x160 + m.x161 == 0)
m.c162 = Constraint(expr=-0.5*m.x1810*(m.x764 + m.x765) - m.x161 + m.x162 == 0)
m.c163 = Constraint(expr=-0.5*m.x1810*(m.x765 + m.x766) - m.x162 + m.x163 == 0)
m.c164 = Constraint(expr=-0.5*m.x1810*(m.x766 + m.x767) - m.x163 + m.x164 == 0)
m.c165 = Constraint(expr=-0.5*m.x1810*(m.x767 + m.x768) - m.x164 + m.x165 == 0)
m.c166 = Constraint(expr=-0.5*m.x1810*(m.x768 + m.x769) - m.x165 + m.x166 == 0)
m.c167 = Constraint(expr=-0.5*m.x1810*(m.x769 + m.x770) - m.x166 + m.x167 == 0)
m.c168 = Constraint(expr=-0.5*m.x1810*(m.x770 + m.x771) - m.x167 + m.x168 == 0)
m.c169 = Constraint(expr=-0.5*m.x1810*(m.x771 + m.x772) - m.x168 + m.x169 == 0)
m.c170 = Constraint(expr=-0.5*m.x1810*(m.x772 + m.x773) - m.x169 + m.x170 == 0)
m.c171 = Constraint(expr=-0.5*m.x1810*(m.x773 + m.x774) - m.x170 + m.x171 == 0)
m.c172 = Constraint(expr=-0.5*m.x1810*(m.x774 + m.x775) - m.x171 + m.x172 == 0)
m.c173 = Constraint(expr=-0.5*m.x1810*(m.x775 + m.x776) - m.x172 + m.x173 == 0)
m.c174 = Constraint(expr=-0.5*m.x1810*(m.x776 + m.x777) - m.x173 + m.x174 == 0)
m.c175 = Constraint(expr=-0.5*m.x1810*(m.x777 + m.x778) - m.x174 + m.x175 == 0)
m.c176 = Constraint(expr=-0.5*m.x1810*(m.x778 + m.x779) - m.x175 + m.x176 == 0)
m.c177 = Constraint(expr=-0.5*m.x1810*(m.x779 + m.x780) - m.x176 + m.x177 == 0)
m.c178 = Constraint(expr=-0.5*m.x1810*(m.x780 + m.x781) - m.x177 + m.x178 == 0)
m.c179 = Constraint(expr=-0.5*m.x1810*(m.x781 + m.x782) - m.x178 + m.x179 == 0)
m.c180 = Constraint(expr=-0.5*m.x1810*(m.x782 + m.x783) - m.x179 + m.x180 == 0)
m.c181 = Constraint(expr=-0.5*m.x1810*(m.x783 + m.x784) - m.x180 + m.x181 == 0)
m.c182 = Constraint(expr=-0.5*m.x1810*(m.x784 + m.x785) - m.x181 + m.x182 == 0)
m.c183 = Constraint(expr=-0.5*m.x1810*(m.x785 + m.x786) - m.x182 + m.x183 == 0)
m.c184 = Constraint(expr=-0.5*m.x1810*(m.x786 + m.x787) - m.x183 + m.x184 == 0)
m.c185 = Constraint(expr=-0.5*m.x1810*(m.x787 + m.x788) - m.x184 + m.x185 == 0)
m.c186 = Constraint(expr=-0.5*m.x1810*(m.x788 + m.x789) - m.x185 + m.x186 == 0)
m.c187 = Constraint(expr=-0.5*m.x1810*(m.x789 + m.x790) - m.x186 + m.x187 == 0)
m.c188 = Constraint(expr=-0.5*m.x1810*(m.x790 + m.x791) - m.x187 + m.x188 == 0)
m.c189 = Constraint(expr=-0.5*m.x1810*(m.x791 + m.x792) - m.x188 + m.x189 == 0)
m.c190 = Constraint(expr=-0.5*m.x1810*(m.x792 + m.x793) - m.x189 + m.x190 == 0)
m.c191 = Constraint(expr=-0.5*m.x1810*(m.x793 + m.x794) - m.x190 + m.x191 == 0)
m.c192 = Constraint(expr=-0.5*m.x1810*(m.x794 + m.x795) - m.x191 + m.x192 == 0)
m.c193 = Constraint(expr=-0.5*m.x1810*(m.x795 + m.x796) - m.x192 + m.x193 == 0)
m.c194 = Constraint(expr=-0.5*m.x1810*(m.x796 + m.x797) - m.x193 + m.x194 == 0)
m.c195 = Constraint(expr=-0.5*m.x1810*(m.x797 + m.x798) - m.x194 + m.x195 == 0)
m.c196 = Constraint(expr=-0.5*m.x1810*(m.x798 + m.x799) - m.x195 + m.x196 == 0)
m.c197 = Constraint(expr=-0.5*m.x1810*(m.x799 + m.x800) - m.x196 + m.x197 == 0)
m.c198 = Constraint(expr=-0.5*m.x1810*(m.x800 + m.x801) - m.x197 + m.x198 == 0)
m.c199 = Constraint(expr=-0.5*m.x1810*(m.x801 + m.x802) - m.x198 + m.x199 == 0)
m.c200 = Constraint(expr=-0.5*m.x1810*(m.x802 + m.x803) - m.x199 + m.x200 == 0)
m.c201 = Constraint(expr=-0.5*m.x1810*(m.x803 + m.x804) - m.x200 + m.x201 == 0)
m.c202 = Constraint(expr=-0.5*m.x1810*(m.x805 + m.x806) - m.x202 + m.x203 == 0)
m.c203 = Constraint(expr=-0.5*m.x1810*(m.x806 + m.x807) - m.x203 + m.x204 == 0)
m.c204 = Constraint(expr=-0.5*m.x1810*(m.x807 + m.x808) - m.x204 + m.x205 == 0)
m.c205 = Constraint(expr=-0.5*m.x1810*(m.x808 + m.x809) - m.x205 + m.x206 == 0)
m.c206 = Constraint(expr=-0.5*m.x1810*(m.x809 + m.x810) - m.x206 + m.x207 == 0)
m.c207 = Constraint(expr=-0.5*m.x1810*(m.x810 + m.x811) - m.x207 + m.x208 == 0)
m.c208 = Constraint(expr=-0.5*m.x1810*(m.x811 + m.x812) - m.x208 + m.x209 == 0)
m.c209 = Constraint(expr=-0.5*m.x1810*(m.x812 + m.x813) - m.x209 + m.x210 == 0)
m.c210 = Constraint(expr=-0.5*m.x1810*(m.x813 + m.x814) - m.x210 + m.x211 == 0)
m.c211 = Constraint(expr=-0.5*m.x1810*(m.x814 + m.x815) - m.x211 + m.x212 == 0)
m.c212 = Constraint(expr=-0.5*m.x1810*(m.x815 + m.x816) - m.x212 + m.x213 == 0)
m.c213 = Constraint(expr=-0.5*m.x1810*(m.x816 + m.x817) - m.x213 + m.x214 == 0)
m.c214 = Constraint(expr=-0.5*m.x1810*(m.x817 + m.x818) - m.x214 + m.x215 == 0)
m.c215 = Constraint(expr=-0.5*m.x1810*(m.x818 + m.x819) - m.x215 + m.x216 == 0)
m.c216 = Constraint(expr=-0.5*m.x1810*(m.x819 + m.x820) - m.x216 + m.x217 == 0)
m.c217 = Constraint(expr=-0.5*m.x1810*(m.x820 + m.x821) - m.x217 + m.x218 == 0)
m.c218 = Constraint(expr=-0.5*m.x1810*(m.x821 + m.x822) - m.x218 + m.x219 == 0)
m.c219 = Constraint(expr=-0.5*m.x1810*(m.x822 + m.x823) - m.x219 + m.x220 == 0)
m.c220 = Constraint(expr=-0.5*m.x1810*(m.x823 + m.x824) - m.x220 + m.x221 == 0)
m.c221 = Constraint(expr=-0.5*m.x1810*(m.x824 + m.x825) - m.x221 + m.x222 == 0)
m.c222 = Constraint(expr=-0.5*m.x1810*(m.x825 + m.x826) - m.x222 + m.x223 == 0)
m.c223 = Constraint(expr=-0.5*m.x1810*(m.x826 + m.x827) - m.x223 + m.x224 == 0)
m.c224 = Constraint(expr=-0.5*m.x1810*(m.x827 + m.x828) - m.x224 + m.x225 == 0)
m.c225 = Constraint(expr=-0.5*m.x1810*(m.x828 + m.x829) - m.x225 + m.x226 == 0)
m.c226 = Constraint(expr=-0.5*m.x1810*(m.x829 + m.x830) - m.x226 + m.x227 == 0)
m.c227 = Constraint(expr=-0.5*m.x1810*(m.x830 + m.x831) - m.x227 + m.x228 == 0)
m.c228 = Constraint(expr=-0.5*m.x1810*(m.x831 + m.x832) - m.x228 + m.x229 == 0)
m.c229 = Constraint(expr=-0.5*m.x1810*(m.x832 + m.x833) - m.x229 + m.x230 == 0)
m.c230 = Constraint(expr=-0.5*m.x1810*(m.x833 + m.x834) - m.x230 + m.x231 == 0)
m.c231 = Constraint(expr=-0.5*m.x1810*(m.x834 + m.x835) - m.x231 + m.x232 == 0)
m.c232 = Constraint(expr=-0.5*m.x1810*(m.x835 + m.x836) - m.x232 + m.x233 == 0)
m.c233 = Constraint(expr=-0.5*m.x1810*(m.x836 + m.x837) - m.x233 + m.x234 == 0)
m.c234 = Constraint(expr=-0.5*m.x1810*(m.x837 + m.x838) - m.x234 + m.x235 == 0)
m.c235 = Constraint(expr=-0.5*m.x1810*(m.x838 + m.x839) - m.x235 + m.x236 == 0)
m.c236 = Constraint(expr=-0.5*m.x1810*(m.x839 + m.x840) - m.x236 + m.x237 == 0)
m.c237 = Constraint(expr=-0.5*m.x1810*(m.x840 + m.x841) - m.x237 + m.x238 == 0)
m.c238 = Constraint(expr=-0.5*m.x1810*(m.x841 + m.x842) - m.x238 + m.x239 == 0)
m.c239 = Constraint(expr=-0.5*m.x1810*(m.x842 + m.x843) - m.x239 + m.x240 == 0)
m.c240 = Constraint(expr=-0.5*m.x1810*(m.x843 + m.x844) - m.x240 + m.x241 == 0)
m.c241 = Constraint(expr=-0.5*m.x1810*(m.x844 + m.x845) - m.x241 + m.x242 == 0)
m.c242 = Constraint(expr=-0.5*m.x1810*(m.x845 + m.x846) - m.x242 + m.x243 == 0)
m.c243 = Constraint(expr=-0.5*m.x1810*(m.x846 + m.x847) - m.x243 + m.x244 == 0)
m.c244 = Constraint(expr=-0.5*m.x1810*(m.x847 + m.x848) - m.x244 + m.x245 == 0)
m.c245 = Constraint(expr=-0.5*m.x1810*(m.x848 + m.x849) - m.x245 + m.x246 == 0)
m.c246 = Constraint(expr=-0.5*m.x1810*(m.x849 + m.x850) - m.x246 + m.x247 == 0)
m.c247 = Constraint(expr=-0.5*m.x1810*(m.x850 + m.x851) - m.x247 + m.x248 == 0)
m.c248 = Constraint(expr=-0.5*m.x1810*(m.x851 + m.x852) - m.x248 + m.x249 == 0)
m.c249 = Constraint(expr=-0.5*m.x1810*(m.x852 + m.x853) - m.x249 + m.x250 == 0)
m.c250 = Constraint(expr=-0.5*m.x1810*(m.x853 + m.x854) - m.x250 + m.x251 == 0)
m.c251 = Constraint(expr=-0.5*m.x1810*(m.x854 + m.x855) - m.x251 + m.x252 == 0)
m.c252 = Constraint(expr=-0.5*m.x1810*(m.x855 + m.x856) - m.x252 + m.x253 == 0)
m.c253 = Constraint(expr=-0.5*m.x1810*(m.x856 + m.x857) - m.x253 + m.x254 == 0)
m.c254 = Constraint(expr=-0.5*m.x1810*(m.x857 + m.x858) - m.x254 + m.x255 == 0)
m.c255 = Constraint(expr=-0.5*m.x1810*(m.x858 + m.x859) - m.x255 + m.x256 == 0)
m.c256 = Constraint(expr=-0.5*m.x1810*(m.x859 + m.x860) - m.x256 + m.x257 == 0)
m.c257 = Constraint(expr=-0.5*m.x1810*(m.x860 + m.x861) - m.x257 + m.x258 == 0)
m.c258 = Constraint(expr=-0.5*m.x1810*(m.x861 + m.x862) - m.x258 + m.x259 == 0)
m.c259 = Constraint(expr=-0.5*m.x1810*(m.x862 + m.x863) - m.x259 + m.x260 == 0)
m.c260 = Constraint(expr=-0.5*m.x1810*(m.x863 + m.x864) - m.x260 + m.x261 == 0)
m.c261 = Constraint(expr=-0.5*m.x1810*(m.x864 + m.x865) - m.x261 + m.x262 == 0)
m.c262 = Constraint(expr=-0.5*m.x1810*(m.x865 + m.x866) - m.x262 + m.x263 == 0)
m.c263 = Constraint(expr=-0.5*m.x1810*(m.x866 + m.x867) - m.x263 + m.x264 == 0)
m.c264 = Constraint(expr=-0.5*m.x1810*(m.x867 + m.x868) - m.x264 + m.x265 == 0)
m.c265 = Constraint(expr=-0.5*m.x1810*(m.x868 + m.x869) - m.x265 + m.x266 == 0)
m.c266 = Constraint(expr=-0.5*m.x1810*(m.x869 + m.x870) - m.x266 + m.x267 == 0)
m.c267 = Constraint(expr=-0.5*m.x1810*(m.x870 + m.x871) - m.x267 + m.x268 == 0)
m.c268 = Constraint(expr=-0.5*m.x1810*(m.x871 + m.x872) - m.x268 + m.x269 == 0)
m.c269 = Constraint(expr=-0.5*m.x1810*(m.x872 + m.x873) - m.x269 + m.x270 == 0)
m.c270 = Constraint(expr=-0.5*m.x1810*(m.x873 + m.x874) - m.x270 + m.x271 == 0)
m.c271 = Constraint(expr=-0.5*m.x1810*(m.x874 + m.x875) - m.x271 + m.x272 == 0)
m.c272 = Constraint(expr=-0.5*m.x1810*(m.x875 + m.x876) - m.x272 + m.x273 == 0)
m.c273 = Constraint(expr=-0.5*m.x1810*(m.x876 + m.x877) - m.x273 + m.x274 == 0)
m.c274 = Constraint(expr=-0.5*m.x1810*(m.x877 + m.x878) - m.x274 + m.x275 == 0)
m.c275 = Constraint(expr=-0.5*m.x1810*(m.x878 + m.x879) - m.x275 + m.x276 == 0)
m.c276 = Constraint(expr=-0.5*m.x1810*(m.x879 + m.x880) - m.x276 + m.x277 == 0)
m.c277 = Constraint(expr=-0.5*m.x1810*(m.x880 + m.x881) - m.x277 + m.x278 == 0)
m.c278 = Constraint(expr=-0.5*m.x1810*(m.x881 + m.x882) - m.x278 + m.x279 == 0)
m.c279 = Constraint(expr=-0.5*m.x1810*(m.x882 + m.x883) - m.x279 + m.x280 == 0)
m.c280 = Constraint(expr=-0.5*m.x1810*(m.x883 + m.x884) - m.x280 + m.x281 == 0)
m.c281 = Constraint(expr=-0.5*m.x1810*(m.x884 + m.x885) - m.x281 + m.x282 == 0)
m.c282 = Constraint(expr=-0.5*m.x1810*(m.x885 + m.x886) - m.x282 + m.x283 == 0)
m.c283 = Constraint(expr=-0.5*m.x1810*(m.x886 + m.x887) - m.x283 + m.x284 == 0)
m.c284 = Constraint(expr=-0.5*m.x1810*(m.x887 + m.x888) - m.x284 + m.x285 == 0)
m.c285 = Constraint(expr=-0.5*m.x1810*(m.x888 + m.x889) - m.x285 + m.x286 == 0)
m.c286 = Constraint(expr=-0.5*m.x1810*(m.x889 + m.x890) - m.x286 + m.x287 == 0)
m.c287 = Constraint(expr=-0.5*m.x1810*(m.x890 + m.x891) - m.x287 + m.x288 == 0)
m.c288 = Constraint(expr=-0.5*m.x1810*(m.x891 + m.x892) - m.x288 + m.x289 == 0)
m.c289 = Constraint(expr=-0.5*m.x1810*(m.x892 + m.x893) - m.x289 + m.x290 == 0)
m.c290 = Constraint(expr=-0.5*m.x1810*(m.x893 + m.x894) - m.x290 + m.x291 == 0)
m.c291 = Constraint(expr=-0.5*m.x1810*(m.x894 + m.x895) - m.x291 + m.x292 == 0)
m.c292 = Constraint(expr=-0.5*m.x1810*(m.x895 + m.x896) - m.x292 + m.x293 == 0)
m.c293 = Constraint(expr=-0.5*m.x1810*(m.x896 + m.x897) - m.x293 + m.x294 == 0)
m.c294 = Constraint(expr=-0.5*m.x1810*(m.x897 + m.x898) - m.x294 + m.x295 == 0)
m.c295 = Constraint(expr=-0.5*m.x1810*(m.x898 + m.x899) - m.x295 + m.x296 == 0)
m.c296 = Constraint(expr=-0.5*m.x1810*(m.x899 + m.x900) - m.x296 + m.x297 == 0)
m.c297 = Constraint(expr=-0.5*m.x1810*(m.x900 + m.x901) - m.x297 + m.x298 == 0)
m.c298 = Constraint(expr=-0.5*m.x1810*(m.x901 + m.x902) - m.x298 + m.x299 == 0)
m.c299 = Constraint(expr=-0.5*m.x1810*(m.x902 + m.x903) - m.x299 + m.x300 == 0)
m.c300 = Constraint(expr=-0.5*m.x1810*(m.x903 + m.x904) - m.x300 + m.x301 == 0)
m.c301 = Constraint(expr=-0.5*m.x1810*(m.x904 + m.x905) - m.x301 + m.x302 == 0)
m.c302 = Constraint(expr=-0.5*m.x1810*(m.x905 + m.x906) - m.x302 + m.x303 == 0)
m.c303 = Constraint(expr=-0.5*m.x1810*(m.x906 + m.x907) - m.x303 + m.x304 == 0)
m.c304 = Constraint(expr=-0.5*m.x1810*(m.x907 + m.x908) - m.x304 + m.x305 == 0)
m.c305 = Constraint(expr=-0.5*m.x1810*(m.x908 + m.x909) - m.x305 + m.x306 == 0)
m.c306 = Constraint(expr=-0.5*m.x1810*(m.x909 + m.x910) - m.x306 + m.x307 == 0)
m.c307 = Constraint(expr=-0.5*m.x1810*(m.x910 + m.x911) - m.x307 + m.x308 == 0)
m.c308 = Constraint(expr=-0.5*m.x1810*(m.x911 + m.x912) - m.x308 + m.x309 == 0)
m.c309 = Constraint(expr=-0.5*m.x1810*(m.x912 + m.x913) - m.x309 + m.x310 == 0)
m.c310 = Constraint(expr=-0.5*m.x1810*(m.x913 + m.x914) - m.x310 + m.x311 == 0)
m.c311 = Constraint(expr=-0.5*m.x1810*(m.x914 + m.x915) - m.x311 + m.x312 == 0)
m.c312 = Constraint(expr=-0.5*m.x1810*(m.x915 + m.x916) - m.x312 + m.x313 == 0)
m.c313 = Constraint(expr=-0.5*m.x1810*(m.x916 + m.x917) - m.x313 + m.x314 == 0)
m.c314 = Constraint(expr=-0.5*m.x1810*(m.x917 + m.x918) - m.x314 + m.x315 == 0)
m.c315 = Constraint(expr=-0.5*m.x1810*(m.x918 + m.x919) - m.x315 + m.x316 == 0)
m.c316 = Constraint(expr=-0.5*m.x1810*(m.x919 + m.x920) - m.x316 + m.x317 == 0)
m.c317 = Constraint(expr=-0.5*m.x1810*(m.x920 + m.x921) - m.x317 + m.x318 == 0)
m.c318 = Constraint(expr=-0.5*m.x1810*(m.x921 + m.x922) - m.x318 + m.x319 == 0)
m.c319 = Constraint(expr=-0.5*m.x1810*(m.x922 + m.x923) - m.x319 + m.x320 == 0)
m.c320 = Constraint(expr=-0.5*m.x1810*(m.x923 + m.x924) - m.x320 + m.x321 == 0)
m.c321 = Constraint(expr=-0.5*m.x1810*(m.x924 + m.x925) - m.x321 + m.x322 == 0)
m.c322 = Constraint(expr=-0.5*m.x1810*(m.x925 + m.x926) - m.x322 + m.x323 == 0)
m.c323 = Constraint(expr=-0.5*m.x1810*(m.x926 + m.x927) - m.x323 + m.x324 == 0)
m.c324 = Constraint(expr=-0.5*m.x1810*(m.x927 + m.x928) - m.x324 + m.x325 == 0)
m.c325 = Constraint(expr=-0.5*m.x1810*(m.x928 + m.x929) - m.x325 + m.x326 == 0)
m.c326 = Constraint(expr=-0.5*m.x1810*(m.x929 + m.x930) - m.x326 + m.x327 == 0)
m.c327 = Constraint(expr=-0.5*m.x1810*(m.x930 + m.x931) - m.x327 + m.x328 == 0)
m.c328 = Constraint(expr=-0.5*m.x1810*(m.x931 + m.x932) - m.x328 + m.x329 == 0)
m.c329 = Constraint(expr=-0.5*m.x1810*(m.x932 + m.x933) - m.x329 + m.x330 == 0)
m.c330 = Constraint(expr=-0.5*m.x1810*(m.x933 + m.x934) - m.x330 + m.x331 == 0)
m.c331 = Constraint(expr=-0.5*m.x1810*(m.x934 + m.x935) - m.x331 + m.x332 == 0)
m.c332 = Constraint(expr=-0.5*m.x1810*(m.x935 + m.x936) - m.x332 + m.x333 == 0)
m.c333 = Constraint(expr=-0.5*m.x1810*(m.x936 + m.x937) - m.x333 + m.x334 == 0)
m.c334 = Constraint(expr=-0.5*m.x1810*(m.x937 + m.x938) - m.x334 + m.x335 == 0)
m.c335 = Constraint(expr=-0.5*m.x1810*(m.x938 + m.x939) - m.x335 + m.x336 == 0)
m.c336 = Constraint(expr=-0.5*m.x1810*(m.x939 + m.x940) - m.x336 + m.x337 == 0)
m.c337 = Constraint(expr=-0.5*m.x1810*(m.x940 + m.x941) - m.x337 + m.x338 == 0)
m.c338 = Constraint(expr=-0.5*m.x1810*(m.x941 + m.x942) - m.x338 + m.x339 == 0)
m.c339 = Constraint(expr=-0.5*m.x1810*(m.x942 + m.x943) - m.x339 + m.x340 == 0)
m.c340 = Constraint(expr=-0.5*m.x1810*(m.x943 + m.x944) - m.x340 + m.x341 == 0)
m.c341 = Constraint(expr=-0.5*m.x1810*(m.x944 + m.x945) - m.x341 + m.x342 == 0)
m.c342 = Constraint(expr=-0.5*m.x1810*(m.x945 + m.x946) - m.x342 + m.x343 == 0)
m.c343 = Constraint(expr=-0.5*m.x1810*(m.x946 + m.x947) - m.x343 + m.x344 == 0)
m.c344 = Constraint(expr=-0.5*m.x1810*(m.x947 + m.x948) - m.x344 + m.x345 == 0)
m.c345 = Constraint(expr=-0.5*m.x1810*(m.x948 + m.x949) - m.x345 + m.x346 == 0)
m.c346 = Constraint(expr=-0.5*m.x1810*(m.x949 + m.x950) - m.x346 + m.x347 == 0)
m.c347 = Constraint(expr=-0.5*m.x1810*(m.x950 + m.x951) - m.x347 + m.x348 == 0)
m.c348 = Constraint(expr=-0.5*m.x1810*(m.x951 + m.x952) - m.x348 + m.x349 == 0)
m.c349 = Constraint(expr=-0.5*m.x1810*(m.x952 + m.x953) - m.x349 + m.x350 == 0)
m.c350 = Constraint(expr=-0.5*m.x1810*(m.x953 + m.x954) - m.x350 + m.x351 == 0)
m.c351 = Constraint(expr=-0.5*m.x1810*(m.x954 + m.x955) - m.x351 + m.x352 == 0)
m.c352 = Constraint(expr=-0.5*m.x1810*(m.x955 + m.x956) - m.x352 + m.x353 == 0)
m.c353 = Constraint(expr=-0.5*m.x1810*(m.x956 + m.x957) - m.x353 + m.x354 == 0)
m.c354 = Constraint(expr=-0.5*m.x1810*(m.x957 + m.x958) - m.x354 + m.x355 == 0)
m.c355 = Constraint(expr=-0.5*m.x1810*(m.x958 + m.x959) - m.x355 + m.x356 == 0)
m.c356 = Constraint(expr=-0.5*m.x1810*(m.x959 + m.x960) - m.x356 + m.x357 == 0)
m.c357 = Constraint(expr=-0.5*m.x1810*(m.x960 + m.x961) - m.x357 + m.x358 == 0)
m.c358 = Constraint(expr=-0.5*m.x1810*(m.x961 + m.x962) - m.x358 + m.x359 == 0)
m.c359 = Constraint(expr=-0.5*m.x1810*(m.x962 + m.x963) - m.x359 + m.x360 == 0)
m.c360 = Constraint(expr=-0.5*m.x1810*(m.x963 + m.x964) - m.x360 + m.x361 == 0)
m.c361 = Constraint(expr=-0.5*m.x1810*(m.x964 + m.x965) - m.x361 + m.x362 == 0)
m.c362 = Constraint(expr=-0.5*m.x1810*(m.x965 + m.x966) - m.x362 + m.x363 == 0)
m.c363 = Constraint(expr=-0.5*m.x1810*(m.x966 + m.x967) - m.x363 + m.x364 == 0)
m.c364 = Constraint(expr=-0.5*m.x1810*(m.x967 + m.x968) - m.x364 + m.x365 == 0)
m.c365 = Constraint(expr=-0.5*m.x1810*(m.x968 + m.x969) - m.x365 + m.x366 == 0)
m.c366 = Constraint(expr=-0.5*m.x1810*(m.x969 + m.x970) - m.x366 + m.x367 == 0)
m.c367 = Constraint(expr=-0.5*m.x1810*(m.x970 + m.x971) - m.x367 + m.x368 == 0)
m.c368 = Constraint(expr=-0.5*m.x1810*(m.x971 + m.x972) - m.x368 + m.x369 == 0)
m.c369 = Constraint(expr=-0.5*m.x1810*(m.x972 + m.x973) - m.x369 + m.x370 == 0)
m.c370 = Constraint(expr=-0.5*m.x1810*(m.x973 + m.x974) - m.x370 + m.x371 == 0)
m.c371 = Constraint(expr=-0.5*m.x1810*(m.x974 + m.x975) - m.x371 + m.x372 == 0)
m.c372 = Constraint(expr=-0.5*m.x1810*(m.x975 + m.x976) - m.x372 + m.x373 == 0)
m.c373 = Constraint(expr=-0.5*m.x1810*(m.x976 + m.x977) - m.x373 + m.x374 == 0)
m.c374 = Constraint(expr=-0.5*m.x1810*(m.x977 + m.x978) - m.x374 + m.x375 == 0)
m.c375 = Constraint(expr=-0.5*m.x1810*(m.x978 + m.x979) - m.x375 + m.x376 == 0)
m.c376 = Constraint(expr=-0.5*m.x1810*(m.x979 + m.x980) - m.x376 + m.x377 == 0)
m.c377 = Constraint(expr=-0.5*m.x1810*(m.x980 + m.x981) - m.x377 + m.x378 == 0)
m.c378 = Constraint(expr=-0.5*m.x1810*(m.x981 + m.x982) - m.x378 + m.x379 == 0)
m.c379 = Constraint(expr=-0.5*m.x1810*(m.x982 + m.x983) - m.x379 + m.x380 == 0)
m.c380 = Constraint(expr=-0.5*m.x1810*(m.x983 + m.x984) - m.x380 + m.x381 == 0)
m.c381 = Constraint(expr=-0.5*m.x1810*(m.x984 + m.x985) - m.x381 + m.x382 == 0)
m.c382 = Constraint(expr=-0.5*m.x1810*(m.x985 + m.x986) - m.x382 + m.x383 == 0)
m.c383 = Constraint(expr=-0.5*m.x1810*(m.x986 + m.x987) - m.x383 + m.x384 == 0)
m.c384 = Constraint(expr=-0.5*m.x1810*(m.x987 + m.x988) - m.x384 + m.x385 == 0)
m.c385 = Constraint(expr=-0.5*m.x1810*(m.x988 + m.x989) - m.x385 + m.x386 == 0)
m.c386 = Constraint(expr=-0.5*m.x1810*(m.x989 + m.x990) - m.x386 + m.x387 == 0)
m.c387 = Constraint(expr=-0.5*m.x1810*(m.x990 + m.x991) - m.x387 + m.x388 == 0)
m.c388 = Constraint(expr=-0.5*m.x1810*(m.x991 + m.x992) - m.x388 + m.x389 == 0)
m.c389 = Constraint(expr=-0.5*m.x1810*(m.x992 + m.x993) - m.x389 + m.x390 == 0)
m.c390 = Constraint(expr=-0.5*m.x1810*(m.x993 + m.x994) - m.x390 + m.x391 == 0)
m.c391 = Constraint(expr=-0.5*m.x1810*(m.x994 + m.x995) - m.x391 + m.x392 == 0)
m.c392 = Constraint(expr=-0.5*m.x1810*(m.x995 + m.x996) - m.x392 + m.x393 == 0)
m.c393 = Constraint(expr=-0.5*m.x1810*(m.x996 + m.x997) - m.x393 + m.x394 == 0)
m.c394 = Constraint(expr=-0.5*m.x1810*(m.x997 + m.x998) - m.x394 + m.x395 == 0)
m.c395 = Constraint(expr=-0.5*m.x1810*(m.x998 + m.x999) - m.x395 + m.x396 == 0)
m.c396 = Constraint(expr=-0.5*m.x1810*(m.x999 + m.x1000) - m.x396 + m.x397 == 0)
m.c397 = Constraint(expr=-0.5*m.x1810*(m.x1000 + m.x1001) - m.x397 + m.x398 == 0)
m.c398 = Constraint(expr=-0.5*m.x1810*(m.x1001 + m.x1002) - m.x398 + m.x399 == 0)
m.c399 = Constraint(expr=-0.5*m.x1810*(m.x1002 + m.x1003) - m.x399 + m.x400 == 0)
m.c400 = Constraint(expr=-0.5*m.x1810*(m.x1003 + m.x1004) - m.x400 + m.x401 == 0)
m.c401 = Constraint(expr=-0.5*m.x1810*(m.x1004 + m.x1005) - m.x401 + m.x402 == 0)
m.c402 = Constraint(expr=-0.5*m.x1810*(m.x1006 + m.x1007) - m.x403 + m.x404 == 0)
m.c403 = Constraint(expr=-0.5*m.x1810*(m.x1007 + m.x1008) - m.x404 + m.x405 == 0)
m.c404 = Constraint(expr=-0.5*m.x1810*(m.x1008 + m.x1009) - m.x405 + m.x406 == 0)
m.c405 = Constraint(expr=-0.5*m.x1810*(m.x1009 + m.x1010) - m.x406 + m.x407 == 0)
m.c406 = Constraint(expr=-0.5*m.x1810*(m.x1010 + m.x1011) - m.x407 + m.x408 == 0)
m.c407 = Constraint(expr=-0.5*m.x1810*(m.x1011 + m.x1012) - m.x408 + m.x409 == 0)
m.c408 = Constraint(expr=-0.5*m.x1810*(m.x1012 + m.x1013) - m.x409 + m.x410 == 0)
m.c409 = Constraint(expr=-0.5*m.x1810*(m.x1013 + m.x1014) - m.x410 + m.x411 == 0)
m.c410 = Constraint(expr=-0.5*m.x1810*(m.x1014 + m.x1015) - m.x411 + m.x412 == 0)
m.c411 = Constraint(expr=-0.5*m.x1810*(m.x1015 + m.x1016) - m.x412 + m.x413 == 0)
m.c412 = Constraint(expr=-0.5*m.x1810*(m.x1016 + m.x1017) - m.x413 + m.x414 == 0)
m.c413 = Constraint(expr=-0.5*m.x1810*(m.x1017 + m.x1018) - m.x414 + m.x415 == 0)
m.c414 = Constraint(expr=-0.5*m.x1810*(m.x1018 + m.x1019) - m.x415 + m.x416 == 0)
m.c415 = Constraint(expr=-0.5*m.x1810*(m.x1019 + m.x1020) - m.x416 + m.x417 == 0)
m.c416 = Constraint(expr=-0.5*m.x1810*(m.x1020 + m.x1021) - m.x417 + m.x418 == 0)
m.c417 = Constraint(expr=-0.5*m.x1810*(m.x1021 + m.x1022) - m.x418 + m.x419 == 0)
m.c418 = Constraint(expr=-0.5*m.x1810*(m.x1022 + m.x1023) - m.x419 + m.x420 == 0)
m.c419 = Constraint(expr=-0.5*m.x1810*(m.x1023 + m.x1024) - m.x420 + m.x421 == 0)
m.c420 = Constraint(expr=-0.5*m.x1810*(m.x1024 + m.x1025) - m.x421 + m.x422 == 0)
m.c421 = Constraint(expr=-0.5*m.x1810*(m.x1025 + m.x1026) - m.x422 + m.x423 == 0)
m.c422 = Constraint(expr=-0.5*m.x1810*(m.x1026 + m.x1027) - m.x423 + m.x424 == 0)
m.c423 = Constraint(expr=-0.5*m.x1810*(m.x1027 + m.x1028) - m.x424 + m.x425 == 0)
m.c424 = Constraint(expr=-0.5*m.x1810*(m.x1028 + m.x1029) - m.x425 + m.x426 == 0)
m.c425 = Constraint(expr=-0.5*m.x1810*(m.x1029 + m.x1030) - m.x426 + m.x427 == 0)
m.c426 = Constraint(expr=-0.5*m.x1810*(m.x1030 + m.x1031) - m.x427 + m.x428 == 0)
m.c427 = Constraint(expr=-0.5*m.x1810*(m.x1031 + m.x1032) - m.x428 + m.x429 == 0)
m.c428 = Constraint(expr=-0.5*m.x1810*(m.x1032 + m.x1033) - m.x429 + m.x430 == 0)
m.c429 = Constraint(expr=-0.5*m.x1810*(m.x1033 + m.x1034) - m.x430 + m.x431 == 0)
m.c430 = Constraint(expr=-0.5*m.x1810*(m.x1034 + m.x1035) - m.x431 + m.x432 == 0)
m.c431 = Constraint(expr=-0.5*m.x1810*(m.x1035 + m.x1036) - m.x432 + m.x433 == 0)
m.c432 = Constraint(expr=-0.5*m.x1810*(m.x1036 + m.x1037) - m.x433 + m.x434 == 0)
m.c433 = Constraint(expr=-0.5*m.x1810*(m.x1037 + m.x1038) - m.x434 + m.x435 == 0)
m.c434 = Constraint(expr=-0.5*m.x1810*(m.x1038 + m.x1039) - m.x435 + m.x436 == 0)
m.c435 = Constraint(expr=-0.5*m.x1810*(m.x1039 + m.x1040) - m.x436 + m.x437 == 0)
m.c436 = Constraint(expr=-0.5*m.x1810*(m.x1040 + m.x1041) - m.x437 + m.x438 == 0)
m.c437 = Constraint(expr=-0.5*m.x1810*(m.x1041 + m.x1042) - m.x438 + m.x439 == 0)
m.c438 = Constraint(expr=-0.5*m.x1810*(m.x1042 + m.x1043) - m.x439 + m.x440 == 0)
m.c439 = Constraint(expr=-0.5*m.x1810*(m.x1043 + m.x1044) - m.x440 + m.x441 == 0)
m.c440 = Constraint(expr=-0.5*m.x1810*(m.x1044 + m.x1045) - m.x441 + m.x442 == 0)
m.c441 = Constraint(expr=-0.5*m.x1810*(m.x1045 + m.x1046) - m.x442 + m.x443 == 0)
m.c442 = Constraint(expr=-0.5*m.x1810*(m.x1046 + m.x1047) - m.x443 + m.x444 == 0)
m.c443 = Constraint(expr=-0.5*m.x1810*(m.x1047 + m.x1048) - m.x444 + m.x445 == 0)
m.c444 = Constraint(expr=-0.5*m.x1810*(m.x1048 + m.x1049) - m.x445 + m.x446 == 0)
m.c445 = Constraint(expr=-0.5*m.x1810*(m.x1049 + m.x1050) - m.x446 + m.x447 == 0)
m.c446 = Constraint(expr=-0.5*m.x1810*(m.x1050 + m.x1051) - m.x447 + m.x448 == 0)
m.c447 = Constraint(expr=-0.5*m.x1810*(m.x1051 + m.x1052) - m.x448 + m.x449 == 0)
m.c448 = Constraint(expr=-0.5*m.x1810*(m.x1052 + m.x1053) - m.x449 + m.x450 == 0)
m.c449 = Constraint(expr=-0.5*m.x1810*(m.x1053 + m.x1054) - m.x450 + m.x451 == 0)
m.c450 = Constraint(expr=-0.5*m.x1810*(m.x1054 + m.x1055) - m.x451 + m.x452 == 0)
m.c451 = Constraint(expr=-0.5*m.x1810*(m.x1055 + m.x1056) - m.x452 + m.x453 == 0)
m.c452 = Constraint(expr=-0.5*m.x1810*(m.x1056 + m.x1057) - m.x453 + m.x454 == 0)
m.c453 = Constraint(expr=-0.5*m.x1810*(m.x1057 + m.x1058) - m.x454 + m.x455 == 0)
m.c454 = Constraint(expr=-0.5*m.x1810*(m.x1058 + m.x1059) - m.x455 + m.x456 == 0)
m.c455 = Constraint(expr=-0.5*m.x1810*(m.x1059 + m.x1060) - m.x456 + m.x457 == 0)
m.c456 = Constraint(expr=-0.5*m.x1810*(m.x1060 + m.x1061) - m.x457 + m.x458 == 0)
m.c457 = Constraint(expr=-0.5*m.x1810*(m.x1061 + m.x1062) - m.x458 + m.x459 == 0)
m.c458 = Constraint(expr=-0.5*m.x1810*(m.x1062 + m.x1063) - m.x459 + m.x460 == 0)
m.c459 = Constraint(expr=-0.5*m.x1810*(m.x1063 + m.x1064) - m.x460 + m.x461 == 0)
m.c460 = Constraint(expr=-0.5*m.x1810*(m.x1064 + m.x1065) - m.x461 + m.x462 == 0)
m.c461 = Constraint(expr=-0.5*m.x1810*(m.x1065 + m.x1066) - m.x462 + m.x463 == 0)
m.c462 = Constraint(expr=-0.5*m.x1810*(m.x1066 + m.x1067) - m.x463 + m.x464 == 0)
m.c463 = Constraint(expr=-0.5*m.x1810*(m.x1067 + m.x1068) - m.x464 + m.x465 == 0)
m.c464 = Constraint(expr=-0.5*m.x1810*(m.x1068 + m.x1069) - m.x465 + m.x466 == 0)
m.c465 = Constraint(expr=-0.5*m.x1810*(m.x1069 + m.x1070) - m.x466 + m.x467 == 0)
m.c466 = Constraint(expr=-0.5*m.x1810*(m.x1070 + m.x1071) - m.x467 + m.x468 == 0)
m.c467 = Constraint(expr=-0.5*m.x1810*(m.x1071 + m.x1072) - m.x468 + m.x469 == 0)
m.c468 = Constraint(expr=-0.5*m.x1810*(m.x1072 + m.x1073) - m.x469 + m.x470 == 0)
m.c469 = Constraint(expr=-0.5*m.x1810*(m.x1073 + m.x1074) - m.x470 + m.x471 == 0)
m.c470 = Constraint(expr=-0.5*m.x1810*(m.x1074 + m.x1075) - m.x471 + m.x472 == 0)
m.c471 = Constraint(expr=-0.5*m.x1810*(m.x1075 + m.x1076) - m.x472 + m.x473 == 0)
m.c472 = Constraint(expr=-0.5*m.x1810*(m.x1076 + m.x1077) - m.x473 + m.x474 == 0)
m.c473 = Constraint(expr=-0.5*m.x1810*(m.x1077 + m.x1078) - m.x474 + m.x475 == 0)
m.c474 = Constraint(expr=-0.5*m.x1810*(m.x1078 + m.x1079) - m.x475 + m.x476 == 0)
m.c475 = Constraint(expr=-0.5*m.x1810*(m.x1079 + m.x1080) - m.x476 + m.x477 == 0)
m.c476 = Constraint(expr=-0.5*m.x1810*(m.x1080 + m.x1081) - m.x477 + m.x478 == 0)
m.c477 = Constraint(expr=-0.5*m.x1810*(m.x1081 + m.x1082) - m.x478 + m.x479 == 0)
m.c478 = Constraint(expr=-0.5*m.x1810*(m.x1082 + m.x1083) - m.x479 + m.x480 == 0)
m.c479 = Constraint(expr=-0.5*m.x1810*(m.x1083 + m.x1084) - m.x480 + m.x481 == 0)
m.c480 = Constraint(expr=-0.5*m.x1810*(m.x1084 + m.x1085) - m.x481 + m.x482 == 0)
m.c481 = Constraint(expr=-0.5*m.x1810*(m.x1085 + m.x1086) - m.x482 + m.x483 == 0)
m.c482 = Constraint(expr=-0.5*m.x1810*(m.x1086 + m.x1087) - m.x483 + m.x484 == 0)
m.c483 = Constraint(expr=-0.5*m.x1810*(m.x1087 + m.x1088) - m.x484 + m.x485 == 0)
m.c484 = Constraint(expr=-0.5*m.x1810*(m.x1088 + m.x1089) - m.x485 + m.x486 == 0)
m.c485 = Constraint(expr=-0.5*m.x1810*(m.x1089 + m.x1090) - m.x486 + m.x487 == 0)
m.c486 = Constraint(expr=-0.5*m.x1810*(m.x1090 + m.x1091) - m.x487 + m.x488 == 0)
m.c487 = Constraint(expr=-0.5*m.x1810*(m.x1091 + m.x1092) - m.x488 + m.x489 == 0)
m.c488 = Constraint(expr=-0.5*m.x1810*(m.x1092 + m.x1093) - m.x489 + m.x490 == 0)
m.c489 = Constraint(expr=-0.5*m.x1810*(m.x1093 + m.x1094) - m.x490 + m.x491 == 0)
m.c490 = Constraint(expr=-0.5*m.x1810*(m.x1094 + m.x1095) - m.x491 + m.x492 == 0)
m.c491 = Constraint(expr=-0.5*m.x1810*(m.x1095 + m.x1096) - m.x492 + m.x493 == 0)
m.c492 = Constraint(expr=-0.5*m.x1810*(m.x1096 + m.x1097) - m.x493 + m.x494 == 0)
m.c493 = Constraint(expr=-0.5*m.x1810*(m.x1097 + m.x1098) - m.x494 + m.x495 == 0)
m.c494 = Constraint(expr=-0.5*m.x1810*(m.x1098 + m.x1099) - m.x495 + m.x496 == 0)
m.c495 = Constraint(expr=-0.5*m.x1810*(m.x1099 + m.x1100) - m.x496 + m.x497 == 0)
m.c496 = Constraint(expr=-0.5*m.x1810*(m.x1100 + m.x1101) - m.x497 + m.x498 == 0)
m.c497 = Constraint(expr=-0.5*m.x1810*(m.x1101 + m.x1102) - m.x498 + m.x499 == 0)
m.c498 = Constraint(expr=-0.5*m.x1810*(m.x1102 + m.x1103) - m.x499 + m.x500 == 0)
m.c499 = Constraint(expr=-0.5*m.x1810*(m.x1103 + m.x1104) - m.x500 + m.x501 == 0)
m.c500 = Constraint(expr=-0.5*m.x1810*(m.x1104 + m.x1105) - m.x501 + m.x502 == 0)
m.c501 = Constraint(expr=-0.5*m.x1810*(m.x1105 + m.x1106) - m.x502 + m.x503 == 0)
m.c502 = Constraint(expr=-0.5*m.x1810*(m.x1106 + m.x1107) - m.x503 + m.x504 == 0)
m.c503 = Constraint(expr=-0.5*m.x1810*(m.x1107 + m.x1108) - m.x504 + m.x505 == 0)
m.c504 = Constraint(expr=-0.5*m.x1810*(m.x1108 + m.x1109) - m.x505 + m.x506 == 0)
m.c505 = Constraint(expr=-0.5*m.x1810*(m.x1109 + m.x1110) - m.x506 + m.x507 == 0)
m.c506 = Constraint(expr=-0.5*m.x1810*(m.x1110 + m.x1111) - m.x507 + m.x508 == 0)
m.c507 = Constraint(expr=-0.5*m.x1810*(m.x1111 + m.x1112) - m.x508 + m.x509 == 0)
m.c508 = Constraint(expr=-0.5*m.x1810*(m.x1112 + m.x1113) - m.x509 + m.x510 == 0)
m.c509 = Constraint(expr=-0.5*m.x1810*(m.x1113 + m.x1114) - m.x510 + m.x511 == 0)
m.c510 = Constraint(expr=-0.5*m.x1810*(m.x1114 + m.x1115) - m.x511 + m.x512 == 0)
m.c511 = Constraint(expr=-0.5*m.x1810*(m.x1115 + m.x1116) - m.x512 + m.x513 == 0)
m.c512 = Constraint(expr=-0.5*m.x1810*(m.x1116 + m.x1117) - m.x513 + m.x514 == 0)
m.c513 = Constraint(expr=-0.5*m.x1810*(m.x1117 + m.x1118) - m.x514 + m.x515 == 0)
m.c514 = Constraint(expr=-0.5*m.x1810*(m.x1118 + m.x1119) - m.x515 + m.x516 == 0)
m.c515 = Constraint(expr=-0.5*m.x1810*(m.x1119 + m.x1120) - m.x516 + m.x517 == 0)
m.c516 = Constraint(expr=-0.5*m.x1810*(m.x1120 + m.x1121) - m.x517 + m.x518 == 0)
m.c517 = Constraint(expr=-0.5*m.x1810*(m.x1121 + m.x1122) - m.x518 + m.x519 == 0)
m.c518 = Constraint(expr=-0.5*m.x1810*(m.x1122 + m.x1123) - m.x519 + m.x520 == 0)
m.c519 = Constraint(expr=-0.5*m.x1810*(m.x1123 + m.x1124) - m.x520 + m.x521 == 0)
m.c520 = Constraint(expr=-0.5*m.x1810*(m.x1124 + m.x1125) - m.x521 + m.x522 == 0)
m.c521 = Constraint(expr=-0.5*m.x1810*(m.x1125 + m.x1126) - m.x522 + m.x523 == 0)
m.c522 = Constraint(expr=-0.5*m.x1810*(m.x1126 + m.x1127) - m.x523 + m.x524 == 0)
m.c523 = Constraint(expr=-0.5*m.x1810*(m.x1127 + m.x1128) - m.x524 + m.x525 == 0)
m.c524 = Constraint(expr=-0.5*m.x1810*(m.x1128 + m.x1129) - m.x525 + m.x526 == 0)
m.c525 = Constraint(expr=-0.5*m.x1810*(m.x1129 + m.x1130) - m.x526 + m.x527 == 0)
m.c526 = Constraint(expr=-0.5*m.x1810*(m.x1130 + m.x1131) - m.x527 + m.x528 == 0)
m.c527 = Constraint(expr=-0.5*m.x1810*(m.x1131 + m.x1132) - m.x528 + m.x529 == 0)
m.c528 = Constraint(expr=-0.5*m.x1810*(m.x1132 + m.x1133) - m.x529 + m.x530 == 0)
m.c529 = Constraint(expr=-0.5*m.x1810*(m.x1133 + m.x1134) - m.x530 + m.x531 == 0)
m.c530 = Constraint(expr=-0.5*m.x1810*(m.x1134 + m.x1135) - m.x531 + m.x532 == 0)
m.c531 = Constraint(expr=-0.5*m.x1810*(m.x1135 + m.x1136) - m.x532 + m.x533 == 0)
m.c532 = Constraint(expr=-0.5*m.x1810*(m.x1136 + m.x1137) - m.x533 + m.x534 == 0)
m.c533 = Constraint(expr=-0.5*m.x1810*(m.x1137 + m.x1138) - m.x534 + m.x535 == 0)
m.c534 = Constraint(expr=-0.5*m.x1810*(m.x1138 + m.x1139) - m.x535 + m.x536 == 0)
m.c535 = Constraint(expr=-0.5*m.x1810*(m.x1139 + m.x1140) - m.x536 + m.x537 == 0)
m.c536 = Constraint(expr=-0.5*m.x1810*(m.x1140 + m.x1141) - m.x537 + m.x538 == 0)
m.c537 = Constraint(expr=-0.5*m.x1810*(m.x1141 + m.x1142) - m.x538 + m.x539 == 0)
m.c538 = Constraint(expr=-0.5*m.x1810*(m.x1142 + m.x1143) - m.x539 + m.x540 == 0)
m.c539 = Constraint(expr=-0.5*m.x1810*(m.x1143 + m.x1144) - m.x540 + m.x541 == 0)
m.c540 = Constraint(expr=-0.5*m.x1810*(m.x1144 + m.x1145) - m.x541 + m.x542 == 0)
m.c541 = Constraint(expr=-0.5*m.x1810*(m.x1145 + m.x1146) - m.x542 + m.x543 == 0)
m.c542 = Constraint(expr=-0.5*m.x1810*(m.x1146 + m.x1147) - m.x543 + m.x544 == 0)
m.c543 = Constraint(expr=-0.5*m.x1810*(m.x1147 + m.x1148) - m.x544 + m.x545 == 0)
m.c544 = Constraint(expr=-0.5*m.x1810*(m.x1148 + m.x1149) - m.x545 + m.x546 == 0)
m.c545 = Constraint(expr=-0.5*m.x1810*(m.x1149 + m.x1150) - m.x546 + m.x547 == 0)
m.c546 = Constraint(expr=-0.5*m.x1810*(m.x1150 + m.x1151) - m.x547 + m.x548 == 0)
m.c547 = Constraint(expr=-0.5*m.x1810*(m.x1151 + m.x1152) - m.x548 + m.x549 == 0)
m.c548 = Constraint(expr=-0.5*m.x1810*(m.x1152 + m.x1153) - m.x549 + m.x550 == 0)
m.c549 = Constraint(expr=-0.5*m.x1810*(m.x1153 + m.x1154) - m.x550 + m.x551 == 0)
m.c550 = Constraint(expr=-0.5*m.x1810*(m.x1154 + m.x1155) - m.x551 + m.x552 == 0)
m.c551 = Constraint(expr=-0.5*m.x1810*(m.x1155 + m.x1156) - m.x552 + m.x553 == 0)
m.c552 = Constraint(expr=-0.5*m.x1810*(m.x1156 + m.x1157) - m.x553 + m.x554 == 0)
m.c553 = Constraint(expr=-0.5*m.x1810*(m.x1157 + m.x1158) - m.x554 + m.x555 == 0)
m.c554 = Constraint(expr=-0.5*m.x1810*(m.x1158 + m.x1159) - m.x555 + m.x556 == 0)
m.c555 = Constraint(expr=-0.5*m.x1810*(m.x1159 + m.x1160) - m.x556 + m.x557 == 0)
m.c556 = Constraint(expr=-0.5*m.x1810*(m.x1160 + m.x1161) - m.x557 + m.x558 == 0)
m.c557 = Constraint(expr=-0.5*m.x1810*(m.x1161 + m.x1162) - m.x558 + m.x559 == 0)
m.c558 = Constraint(expr=-0.5*m.x1810*(m.x1162 + m.x1163) - m.x559 + m.x560 == 0)
m.c559 = Constraint(expr=-0.5*m.x1810*(m.x1163 + m.x1164) - m.x560 + m.x561 == 0)
m.c560 = Constraint(expr=-0.5*m.x1810*(m.x1164 + m.x1165) - m.x561 + m.x562 == 0)
m.c561 = Constraint(expr=-0.5*m.x1810*(m.x1165 + m.x1166) - m.x562 + m.x563 == 0)
m.c562 = Constraint(expr=-0.5*m.x1810*(m.x1166 + m.x1167) - m.x563 + m.x564 == 0)
m.c563 = Constraint(expr=-0.5*m.x1810*(m.x1167 + m.x1168) - m.x564 + m.x565 == 0)
m.c564 = Constraint(expr=-0.5*m.x1810*(m.x1168 + m.x1169) - m.x565 + m.x566 == 0)
m.c565 = Constraint(expr=-0.5*m.x1810*(m.x1169 + m.x1170) - m.x566 + m.x567 == 0)
m.c566 = Constraint(expr=-0.5*m.x1810*(m.x1170 + m.x1171) - m.x567 + m.x568 == 0)
m.c567 = Constraint(expr=-0.5*m.x1810*(m.x1171 + m.x1172) - m.x568 + m.x569 == 0)
m.c568 = Constraint(expr=-0.5*m.x1810*(m.x1172 + m.x1173) - m.x569 + m.x570 == 0)
m.c569 = Constraint(expr=-0.5*m.x1810*(m.x1173 + m.x1174) - m.x570 + m.x571 == 0)
m.c570 = Constraint(expr=-0.5*m.x1810*(m.x1174 + m.x1175) - m.x571 + m.x572 == 0)
m.c571 = Constraint(expr=-0.5*m.x1810*(m.x1175 + m.x1176) - m.x572 + m.x573 == 0)
m.c572 = Constraint(expr=-0.5*m.x1810*(m.x1176 + m.x1177) - m.x573 + m.x574 == 0)
m.c573 = Constraint(expr=-0.5*m.x1810*(m.x1177 + m.x1178) - m.x574 + m.x575 == 0)
m.c574 = Constraint(expr=-0.5*m.x1810*(m.x1178 + m.x1179) - m.x575 + m.x576 == 0)
m.c575 = Constraint(expr=-0.5*m.x1810*(m.x1179 + m.x1180) - m.x576 + m.x577 == 0)
m.c576 = Constraint(expr=-0.5*m.x1810*(m.x1180 + m.x1181) - m.x577 + m.x578 == 0)
m.c577 = Constraint(expr=-0.5*m.x1810*(m.x1181 + m.x1182) - m.x578 + m.x579 == 0)
m.c578 = Constraint(expr=-0.5*m.x1810*(m.x1182 + m.x1183) - m.x579 + m.x580 == 0)
m.c579 = Constraint(expr=-0.5*m.x1810*(m.x1183 + m.x1184) - m.x580 + m.x581 == 0)
m.c580 = Constraint(expr=-0.5*m.x1810*(m.x1184 + m.x1185) - m.x581 + m.x582 == 0)
m.c581 = Constraint(expr=-0.5*m.x1810*(m.x1185 + m.x1186) - m.x582 + m.x583 == 0)
m.c582 = Constraint(expr=-0.5*m.x1810*(m.x1186 + m.x1187) - m.x583 + m.x584 == 0)
m.c583 = Constraint(expr=-0.5*m.x1810*(m.x1187 + m.x1188) - m.x584 + m.x585 == 0)
m.c584 = Constraint(expr=-0.5*m.x1810*(m.x1188 + m.x1189) - m.x585 + m.x586 == 0)
m.c585 = Constraint(expr=-0.5*m.x1810*(m.x1189 + m.x1190) - m.x586 + m.x587 == 0)
m.c586 = Constraint(expr=-0.5*m.x1810*(m.x1190 + m.x1191) - m.x587 + m.x588 == 0)
m.c587 = Constraint(expr=-0.5*m.x1810*(m.x1191 + m.x1192) - m.x588 + m.x589 == 0)
m.c588 = Constraint(expr=-0.5*m.x1810*(m.x1192 + m.x1193) - m.x589 + m.x590 == 0)
m.c589 = Constraint(expr=-0.5*m.x1810*(m.x1193 + m.x1194) - m.x590 + m.x591 == 0)
m.c590 = Constraint(expr=-0.5*m.x1810*(m.x1194 + m.x1195) - m.x591 + m.x592 == 0)
m.c591 = Constraint(expr=-0.5*m.x1810*(m.x1195 + m.x1196) - m.x592 + m.x593 == 0)
m.c592 = Constraint(expr=-0.5*m.x1810*(m.x1196 + m.x1197) - m.x593 + m.x594 == 0)
m.c593 = Constraint(expr=-0.5*m.x1810*(m.x1197 + m.x1198) - m.x594 + m.x595 == 0)
m.c594 = Constraint(expr=-0.5*m.x1810*(m.x1198 + m.x1199) - m.x595 + m.x596 == 0)
m.c595 = Constraint(expr=-0.5*m.x1810*(m.x1199 + m.x1200) - m.x596 + m.x597 == 0)
m.c596 = Constraint(expr=-0.5*m.x1810*(m.x1200 + m.x1201) - m.x597 + m.x598 == 0)
m.c597 = Constraint(expr=-0.5*m.x1810*(m.x1201 + m.x1202) - m.x598 + m.x599 == 0)
m.c598 = Constraint(expr=-0.5*m.x1810*(m.x1202 + m.x1203) - m.x599 + m.x600 == 0)
m.c599 = Constraint(expr=-0.5*m.x1810*(m.x1203 + m.x1204) - m.x600 + m.x601 == 0)
m.c600 = Constraint(expr=-0.5*m.x1810*(m.x1204 + m.x1205) - m.x601 + m.x602 == 0)
m.c601 = Constraint(expr=-0.5*m.x1810*(m.x1205 + m.x1206) - m.x602 + m.x603 == 0)
m.c602 = Constraint(expr=-0.1*m.x1810*(m.x1207 + m.x1208) - m.x604 + m.x605 == 0)
m.c603 = Constraint(expr=-0.1*m.x1810*(m.x1208 + m.x1209) - m.x605 + m.x606 == 0)
m.c604 = Constraint(expr=-0.1*m.x1810*(m.x1209 + m.x1210) - m.x606 + m.x607 == 0)
m.c605 = Constraint(expr=-0.1*m.x1810*(m.x1210 + m.x1211) - m.x607 + m.x608 == 0)
m.c606 = Constraint(expr=-0.1*m.x1810*(m.x1211 + m.x1212) - m.x608 + m.x609 == 0)
m.c607 = Constraint(expr=-0.1*m.x1810*(m.x1212 + m.x1213) - m.x609 + m.x610 == 0)
m.c608 = Constraint(expr=-0.1*m.x1810*(m.x1213 + m.x1214) - m.x610 + m.x611 == 0)
m.c609 = Constraint(expr=-0.1*m.x1810*(m.x1214 + m.x1215) - m.x611 + m.x612 == 0)
m.c610 = Constraint(expr=-0.1*m.x1810*(m.x1215 + m.x1216) - m.x612 + m.x613 == 0)
m.c611 = Constraint(expr=-0.1*m.x1810*(m.x1216 + m.x1217) - m.x613 + m.x614 == 0)
m.c612 = Constraint(expr=-0.1*m.x1810*(m.x1217 + m.x1218) - m.x614 + m.x615 == 0)
m.c613 = Constraint(expr=-0.1*m.x1810*(m.x1218 + m.x1219) - m.x615 + m.x616 == 0)
m.c614 = Constraint(expr=-0.1*m.x1810*(m.x1219 + m.x1220) - m.x616 + m.x617 == 0)
m.c615 = Constraint(expr=-0.1*m.x1810*(m.x1220 + m.x1221) - m.x617 + m.x618 == 0)
m.c616 = Constraint(expr=-0.1*m.x1810*(m.x1221 + m.x1222) - m.x618 + m.x619 == 0)
m.c617 = Constraint(expr=-0.1*m.x1810*(m.x1222 + m.x1223) - m.x619 + m.x620 == 0)
m.c618 = Constraint(expr=-0.1*m.x1810*(m.x1223 + m.x1224) - m.x620 + m.x621 == 0)
m.c619 = Constraint(expr=-0.1*m.x1810*(m.x1224 + m.x1225) - m.x621 + m.x622 == 0)
m.c620 = Constraint(expr=-0.1*m.x1810*(m.x1225 + m.x1226) - m.x622 + m.x623 == 0)
m.c621 = Constraint(expr=-0.1*m.x1810*(m.x1226 + m.x1227) - m.x623 + m.x624 == 0)
m.c622 = Constraint(expr=-0.1*m.x1810*(m.x1227 + m.x1228) - m.x624 + m.x625 == 0)
m.c623 = Constraint(expr=-0.1*m.x1810*(m.x1228 + m.x1229) - m.x625 + m.x626 == 0)
m.c624 = Constraint(expr=-0.1*m.x1810*(m.x1229 + m.x1230) - m.x626 + m.x627 == 0)
m.c625 = Constraint(expr=-0.1*m.x1810*(m.x1230 + m.x1231) - m.x627 + m.x628 == 0)
m.c626 = Constraint(expr=-0.1*m.x1810*(m.x1231 + m.x1232) - m.x628 + m.x629 == 0)
m.c627 = Constraint(expr=-0.1*m.x1810*(m.x1232 + m.x1233) - m.x629 + m.x630 == 0)
m.c628 = Constraint(expr=-0.1*m.x1810*(m.x1233 + m.x1234) - m.x630 + m.x631 == 0)
m.c629 = Constraint(expr=-0.1*m.x1810*(m.x1234 + m.x1235) - m.x631 + m.x632 == 0)
m.c630 = Constraint(expr=-0.1*m.x1810*(m.x1235 + m.x1236) - m.x632 + m.x633 == 0)
m.c631 = Constraint(expr=-0.1*m.x1810*(m.x1236 + m.x1237) - m.x633 + m.x634 == 0)
m.c632 = Constraint(expr=-0.1*m.x1810*(m.x1237 + m.x1238) - m.x634 + m.x635 == 0)
m.c633 = Constraint(expr=-0.1*m.x1810*(m.x1238 + m.x1239) - m.x635 + m.x636 == 0)
m.c634 = Constraint(expr=-0.1*m.x1810*(m.x1239 + m.x1240) - m.x636 + m.x637 == 0)
m.c635 = Constraint(expr=-0.1*m.x1810*(m.x1240 + m.x1241) - m.x637 + m.x638 == 0)
m.c636 = Constraint(expr=-0.1*m.x1810*(m.x1241 + m.x1242) - m.x638 + m.x639 == 0)
m.c637 = Constraint(expr=-0.1*m.x1810*(m.x1242 + m.x1243) - m.x639 + m.x640 == 0)
m.c638 = Constraint(expr=-0.1*m.x1810*(m.x1243 + m.x1244) - m.x640 + m.x641 == 0)
m.c639 = Constraint(expr=-0.1*m.x1810*(m.x1244 + m.x1245) - m.x641 + m.x642 == 0)
m.c640 = Constraint(expr=-0.1*m.x1810*(m.x1245 + m.x1246) - m.x642 + m.x643 == 0)
m.c641 = Constraint(expr=-0.1*m.x1810*(m.x1246 + m.x1247) - m.x643 + m.x644 == 0)
m.c642 = Constraint(expr=-0.1*m.x1810*(m.x1247 + m.x1248) - m.x644 + m.x645 == 0)
m.c643 = Constraint(expr=-0.1*m.x1810*(m.x1248 + m.x1249) - m.x645 + m.x646 == 0)
m.c644 = Constraint(expr=-0.1*m.x1810*(m.x1249 + m.x1250) - m.x646 + m.x647 == 0)
m.c645 = Constraint(expr=-0.1*m.x1810*(m.x1250 + m.x1251) - m.x647 + m.x648 == 0)
m.c646 = Constraint(expr=-0.1*m.x1810*(m.x1251 + m.x1252) - m.x648 + m.x649 == 0)
m.c647 = Constraint(expr=-0.1*m.x1810*(m.x1252 + m.x1253) - m.x649 + m.x650 == 0)
m.c648 = Constraint(expr=-0.1*m.x1810*(m.x1253 + m.x1254) - m.x650 + m.x651 == 0)
m.c649 = Constraint(expr=-0.1*m.x1810*(m.x1254 + m.x1255) - m.x651 + m.x652 == 0)
m.c650 = Constraint(expr=-0.1*m.x1810*(m.x1255 + m.x1256) - m.x652 + m.x653 == 0)
m.c651 = Constraint(expr=-0.1*m.x1810*(m.x1256 + m.x1257) - m.x653 + m.x654 == 0)
m.c652 = Constraint(expr=-0.1*m.x1810*(m.x1257 + m.x1258) - m.x654 + m.x655 == 0)
m.c653 = Constraint(expr=-0.1*m.x1810*(m.x1258 + m.x1259) - m.x655 + m.x656 == 0)
m.c654 = Constraint(expr=-0.1*m.x1810*(m.x1259 + m.x1260) - m.x656 + m.x657 == 0)
m.c655 = Constraint(expr=-0.1*m.x1810*(m.x1260 + m.x1261) - m.x657 + m.x658 == 0)
m.c656 = Constraint(expr=-0.1*m.x1810*(m.x1261 + m.x1262) - m.x658 + m.x659 == 0)
m.c657 = Constraint(expr=-0.1*m.x1810*(m.x1262 + m.x1263) - m.x659 + m.x660 == 0)
m.c658 = Constraint(expr=-0.1*m.x1810*(m.x1263 + m.x1264) - m.x660 + m.x661 == 0)
m.c659 = Constraint(expr=-0.1*m.x1810*(m.x1264 + m.x1265) - m.x661 + m.x662 == 0)
m.c660 = Constraint(expr=-0.1*m.x1810*(m.x1265 + m.x1266) - m.x662 + m.x663 == 0)
m.c661 = Constraint(expr=-0.1*m.x1810*(m.x1266 + m.x1267) - m.x663 + m.x664 == 0)
m.c662 = Constraint(expr=-0.1*m.x1810*(m.x1267 + m.x1268) - m.x664 + m.x665 == 0)
m.c663 = Constraint(expr=-0.1*m.x1810*(m.x1268 + m.x1269) - m.x665 + m.x666 == 0)
m.c664 = Constraint(expr=-0.1*m.x1810*(m.x1269 + m.x1270) - m.x666 + m.x667 == 0)
m.c665 = Constraint(expr=-0.1*m.x1810*(m.x1270 + m.x1271) - m.x667 + m.x668 == 0)
m.c666 = Constraint(expr=-0.1*m.x1810*(m.x1271 + m.x1272) - m.x668 + m.x669 == 0)
m.c667 = Constraint(expr=-0.1*m.x1810*(m.x1272 + m.x1273) - m.x669 + m.x670 == 0)
m.c668 = Constraint(expr=-0.1*m.x1810*(m.x1273 + m.x1274) - m.x670 + m.x671 == 0)
m.c669 = Constraint(expr=-0.1*m.x1810*(m.x1274 + m.x1275) - m.x671 + m.x672 == 0)
m.c670 = Constraint(expr=-0.1*m.x1810*(m.x1275 + m.x1276) - m.x672 + m.x673 == 0)
m.c671 = Constraint(expr=-0.1*m.x1810*(m.x1276 + m.x1277) - m.x673 + m.x674 == 0)
m.c672 = Constraint(expr=-0.1*m.x1810*(m.x1277 + m.x1278) - m.x674 + m.x675 == 0)
m.c673 = Constraint(expr=-0.1*m.x1810*(m.x1278 + m.x1279) - m.x675 + m.x676 == 0)
m.c674 = Constraint(expr=-0.1*m.x1810*(m.x1279 + m.x1280) - m.x676 + m.x677 == 0)
m.c675 = Constraint(expr=-0.1*m.x1810*(m.x1280 + m.x1281) - m.x677 + m.x678 == 0)
m.c676 = Constraint(expr=-0.1*m.x1810*(m.x1281 + m.x1282) - m.x678 + m.x679 == 0)
m.c677 = Constraint(expr=-0.1*m.x1810*(m.x1282 + m.x1283) - m.x679 + m.x680 == 0)
m.c678 = Constraint(expr=-0.1*m.x1810*(m.x1283 + m.x1284) - m.x680 + m.x681 == 0)
m.c679 = Constraint(expr=-0.1*m.x1810*(m.x1284 + m.x1285) - m.x681 + m.x682 == 0)
m.c680 = Constraint(expr=-0.1*m.x1810*(m.x1285 + m.x1286) - m.x682 + m.x683 == 0)
m.c681 = Constraint(expr=-0.1*m.x1810*(m.x1286 + m.x1287) - m.x683 + m.x684 == 0)
m.c682 = Constraint(expr=-0.1*m.x1810*(m.x1287 + m.x1288) - m.x684 + m.x685 == 0)
m.c683 = Constraint(expr=-0.1*m.x1810*(m.x1288 + m.x1289) - m.x685 + m.x686 == 0)
m.c684 = Constraint(expr=-0.1*m.x1810*(m.x1289 + m.x1290) - m.x686 + m.x687 == 0)
m.c685 = Constraint(expr=-0.1*m.x1810*(m.x1290 + m.x1291) - m.x687 + m.x688 == 0)
m.c686 = Constraint(expr=-0.1*m.x1810*(m.x1291 + m.x1292) - m.x688 + m.x689 == 0)
m.c687 = Constraint(expr=-0.1*m.x1810*(m.x1292 + m.x1293) - m.x689 + m.x690 == 0)
m.c688 = Constraint(expr=-0.1*m.x1810*(m.x1293 + m.x1294) - m.x690 + m.x691 == 0)
m.c689 = Constraint(expr=-0.1*m.x1810*(m.x1294 + m.x1295) - m.x691 + m.x692 == 0)
m.c690 = Constraint(expr=-0.1*m.x1810*(m.x1295 + m.x1296) - m.x692 + m.x693 == 0)
m.c691 = Constraint(expr=-0.1*m.x1810*(m.x1296 + m.x1297) - m.x693 + m.x694 == 0)
m.c692 = Constraint(expr=-0.1*m.x1810*(m.x1297 + m.x1298) - m.x694 + m.x695 == 0)
m.c693 = Constraint(expr=-0.1*m.x1810*(m.x1298 + m.x1299) - m.x695 + m.x696 == 0)
m.c694 = Constraint(expr=-0.1*m.x1810*(m.x1299 + m.x1300) - m.x696 + m.x697 == 0)
m.c695 = Constraint(expr=-0.1*m.x1810*(m.x1300 + m.x1301) - m.x697 + m.x698 == 0)
m.c696 = Constraint(expr=-0.1*m.x1810*(m.x1301 + m.x1302) - m.x698 + m.x699 == 0)
m.c697 = Constraint(expr=-0.1*m.x1810*(m.x1302 + m.x1303) - m.x699 + m.x700 == 0)
m.c698 = Constraint(expr=-0.1*m.x1810*(m.x1303 + m.x1304) - m.x700 + m.x701 == 0)
m.c699 = Constraint(expr=-0.1*m.x1810*(m.x1304 + m.x1305) - m.x701 + m.x702 == 0)
m.c700 = Constraint(expr=-0.1*m.x1810*(m.x1305 + m.x1306) - m.x702 + m.x703 == 0)
m.c701 = Constraint(expr=-0.1*m.x1810*(m.x1306 + m.x1307) - m.x703 + m.x704 == 0)
m.c702 = Constraint(expr=-0.1*m.x1810*(m.x1307 + m.x1308) - m.x704 + m.x705 == 0)
m.c703 = Constraint(expr=-0.1*m.x1810*(m.x1308 + m.x1309) - m.x705 + m.x706 == 0)
m.c704 = Constraint(expr=-0.1*m.x1810*(m.x1309 + m.x1310) - m.x706 + m.x707 == 0)
m.c705 = Constraint(expr=-0.1*m.x1810*(m.x1310 + m.x1311) - m.x707 + m.x708 == 0)
m.c706 = Constraint(expr=-0.1*m.x1810*(m.x1311 + m.x1312) - m.x708 + m.x709 == 0)
m.c707 = Constraint(expr=-0.1*m.x1810*(m.x1312 + m.x1313) - m.x709 + m.x710 == 0)
m.c708 = Constraint(expr=-0.1*m.x1810*(m.x1313 + m.x1314) - m.x710 + m.x711 == 0)
m.c709 = Constraint(expr=-0.1*m.x1810*(m.x1314 + m.x1315) - m.x711 + m.x712 == 0)
m.c710 = Constraint(expr=-0.1*m.x1810*(m.x1315 + m.x1316) - m.x712 + m.x713 == 0)
m.c711 = Constraint(expr=-0.1*m.x1810*(m.x1316 + m.x1317) - m.x713 + m.x714 == 0)
m.c712 = Constraint(expr=-0.1*m.x1810*(m.x1317 + m.x1318) - m.x714 + m.x715 == 0)
m.c713 = Constraint(expr=-0.1*m.x1810*(m.x1318 + m.x1319) - m.x715 + m.x716 == 0)
m.c714 = Constraint(expr=-0.1*m.x1810*(m.x1319 + m.x1320) - m.x716 + m.x717 == 0)
m.c715 = Constraint(expr=-0.1*m.x1810*(m.x1320 + m.x1321) - m.x717 + m.x718 == 0)
m.c716 = Constraint(expr=-0.1*m.x1810*(m.x1321 + m.x1322) - m.x718 + m.x719 == 0)
m.c717 = Constraint(expr=-0.1*m.x1810*(m.x1322 + m.x1323) - m.x719 + m.x720 == 0)
m.c718 = Constraint(expr=-0.1*m.x1810*(m.x1323 + m.x1324) - m.x720 + m.x721 == 0)
m.c719 = Constraint(expr=-0.1*m.x1810*(m.x1324 + m.x1325) - m.x721 + m.x722 == 0)
m.c720 = Constraint(expr=-0.1*m.x1810*(m.x1325 + m.x1326) - m.x722 + m.x723 == 0)
m.c721 = Constraint(expr=-0.1*m.x1810*(m.x1326 + m.x1327) - m.x723 + m.x724 == 0)
m.c722 = Constraint(expr=-0.1*m.x1810*(m.x1327 + m.x1328) - m.x724 + m.x725 == 0)
m.c723 = Constraint(expr=-0.1*m.x1810*(m.x1328 + m.x1329) - m.x725 + m.x726 == 0)
m.c724 = Constraint(expr=-0.1*m.x1810*(m.x1329 + m.x1330) - m.x726 + m.x727 == 0)
m.c725 = Constraint(expr=-0.1*m.x1810*(m.x1330 + m.x1331) - m.x727 + m.x728 == 0)
m.c726 = Constraint(expr=-0.1*m.x1810*(m.x1331 + m.x1332) - m.x728 + m.x729 == 0)
m.c727 = Constraint(expr=-0.1*m.x1810*(m.x1332 + m.x1333) - m.x729 + m.x730 == 0)
m.c728 = Constraint(expr=-0.1*m.x1810*(m.x1333 + m.x1334) - m.x730 + m.x731 == 0)
m.c729 = Constraint(expr=-0.1*m.x1810*(m.x1334 + m.x1335) - m.x731 + m.x732 == 0)
m.c730 = Constraint(expr=-0.1*m.x1810*(m.x1335 + m.x1336) - m.x732 + m.x733 == 0)
m.c731 = Constraint(expr=-0.1*m.x1810*(m.x1336 + m.x1337) - m.x733 + m.x734 == 0)
m.c732 = Constraint(expr=-0.1*m.x1810*(m.x1337 + m.x1338) - m.x734 + m.x735 == 0)
m.c733 = Constraint(expr=-0.1*m.x1810*(m.x1338 + m.x1339) - m.x735 + m.x736 == 0)
m.c734 = Constraint(expr=-0.1*m.x1810*(m.x1339 + m.x1340) - m.x736 + m.x737 == 0)
m.c735 = Constraint(expr=-0.1*m.x1810*(m.x1340 + m.x1341) - m.x737 + m.x738 == 0)
m.c736 = Constraint(expr=-0.1*m.x1810*(m.x1341 + m.x1342) - m.x738 + m.x739 == 0)
m.c737 = Constraint(expr=-0.1*m.x1810*(m.x1342 + m.x1343) - m.x739 + m.x740 == 0)
m.c738 = Constraint(expr=-0.1*m.x1810*(m.x1343 + m.x1344) - m.x740 + m.x741 == 0)
m.c739 = Constraint(expr=-0.1*m.x1810*(m.x1344 + m.x1345) - m.x741 + m.x742 == 0)
m.c740 = Constraint(expr=-0.1*m.x1810*(m.x1345 + m.x1346) - m.x742 + m.x743 == 0)
m.c741 = Constraint(expr=-0.1*m.x1810*(m.x1346 + m.x1347) - m.x743 + m.x744 == 0)
m.c742 = Constraint(expr=-0.1*m.x1810*(m.x1347 + m.x1348) - m.x744 + m.x745 == 0)
m.c743 = Constraint(expr=-0.1*m.x1810*(m.x1348 + m.x1349) - m.x745 + m.x746 == 0)
m.c744 = Constraint(expr=-0.1*m.x1810*(m.x1349 + m.x1350) - m.x746 + m.x747 == 0)
m.c745 = Constraint(expr=-0.1*m.x1810*(m.x1350 + m.x1351) - m.x747 + m.x748 == 0)
m.c746 = Constraint(expr=-0.1*m.x1810*(m.x1351 + m.x1352) - m.x748 + m.x749 == 0)
m.c747 = Constraint(expr=-0.1*m.x1810*(m.x1352 + m.x1353) - m.x749 + m.x750 == 0)
m.c748 = Constraint(expr=-0.1*m.x1810*(m.x1353 + m.x1354) - m.x750 + m.x751 == 0)
m.c749 = Constraint(expr=-0.1*m.x1810*(m.x1354 + m.x1355) - m.x751 + m.x752 == 0)
m.c750 = Constraint(expr=-0.1*m.x1810*(m.x1355 + m.x1356) - m.x752 + m.x753 == 0)
m.c751 = Constraint(expr=-0.1*m.x1810*(m.x1356 + m.x1357) - m.x753 + m.x754 == 0)
m.c752 = Constraint(expr=-0.1*m.x1810*(m.x1357 + m.x1358) - m.x754 + m.x755 == 0)
m.c753 = Constraint(expr=-0.1*m.x1810*(m.x1358 + m.x1359) - m.x755 + m.x756 == 0)
m.c754 = Constraint(expr=-0.1*m.x1810*(m.x1359 + m.x1360) - m.x756 + m.x757 == 0)
m.c755 = Constraint(expr=-0.1*m.x1810*(m.x1360 + m.x1361) - m.x757 + m.x758 == 0)
m.c756 = Constraint(expr=-0.1*m.x1810*(m.x1361 + m.x1362) - m.x758 + m.x759 == 0)
m.c757 = Constraint(expr=-0.1*m.x1810*(m.x1362 + m.x1363) - m.x759 + m.x760 == 0)
m.c758 = Constraint(expr=-0.1*m.x1810*(m.x1363 + m.x1364) - m.x760 + m.x761 == 0)
m.c759 = Constraint(expr=-0.1*m.x1810*(m.x1364 + m.x1365) - m.x761 + m.x762 == 0)
m.c760 = Constraint(expr=-0.1*m.x1810*(m.x1365 + m.x1366) - m.x762 + m.x763 == 0)
m.c761 = Constraint(expr=-0.1*m.x1810*(m.x1366 + m.x1367) - m.x763 + m.x764 == 0)
m.c762 = Constraint(expr=-0.1*m.x1810*(m.x1367 + m.x1368) - m.x764 + m.x765 == 0)
m.c763 = Constraint(expr=-0.1*m.x1810*(m.x1368 + m.x1369) - m.x765 + m.x766 == 0)
m.c764 = Constraint(expr=-0.1*m.x1810*(m.x1369 + m.x1370) - m.x766 + m.x767 == 0)
m.c765 = Constraint(expr=-0.1*m.x1810*(m.x1370 + m.x1371) - m.x767 + m.x768 == 0)
m.c766 = Constraint(expr=-0.1*m.x1810*(m.x1371 + m.x1372) - m.x768 + m.x769 == 0)
m.c767 = Constraint(expr=-0.1*m.x1810*(m.x1372 + m.x1373) - m.x769 + m.x770 == 0)
m.c768 = Constraint(expr=-0.1*m.x1810*(m.x1373 + m.x1374) - m.x770 + m.x771 == 0)
m.c769 = Constraint(expr=-0.1*m.x1810*(m.x1374 + m.x1375) - m.x771 + m.x772 == 0)
m.c770 = Constraint(expr=-0.1*m.x1810*(m.x1375 + m.x1376) - m.x772 + m.x773 == 0)
m.c771 = Constraint(expr=-0.1*m.x1810*(m.x1376 + m.x1377) - m.x773 + m.x774 == 0)
m.c772 = Constraint(expr=-0.1*m.x1810*(m.x1377 + m.x1378) - m.x774 + m.x775 == 0)
m.c773 = Constraint(expr=-0.1*m.x1810*(m.x1378 + m.x1379) - m.x775 + m.x776 == 0)
m.c774 = Constraint(expr=-0.1*m.x1810*(m.x1379 + m.x1380) - m.x776 + m.x777 == 0)
m.c775 = Constraint(expr=-0.1*m.x1810*(m.x1380 + m.x1381) - m.x777 + m.x778 == 0)
m.c776 = Constraint(expr=-0.1*m.x1810*(m.x1381 + m.x1382) - m.x778 + m.x779 == 0)
m.c777 = Constraint(expr=-0.1*m.x1810*(m.x1382 + m.x1383) - m.x779 + m.x780 == 0)
m.c778 = Constraint(expr=-0.1*m.x1810*(m.x1383 + m.x1384) - m.x780 + m.x781 == 0)
m.c779 = Constraint(expr=-0.1*m.x1810*(m.x1384 + m.x1385) - m.x781 + m.x782 == 0)
m.c780 = Constraint(expr=-0.1*m.x1810*(m.x1385 + m.x1386) - m.x782 + m.x783 == 0)
m.c781 = Constraint(expr=-0.1*m.x1810*(m.x1386 + m.x1387) - m.x783 + m.x784 == 0)
m.c782 = Constraint(expr=-0.1*m.x1810*(m.x1387 + m.x1388) - m.x784 + m.x785 == 0)
m.c783 = Constraint(expr=-0.1*m.x1810*(m.x1388 + m.x1389) - m.x785 + m.x786 == 0)
m.c784 = Constraint(expr=-0.1*m.x1810*(m.x1389 + m.x1390) - m.x786 + m.x787 == 0)
m.c785 = Constraint(expr=-0.1*m.x1810*(m.x1390 + m.x1391) - m.x787 + m.x788 == 0)
m.c786 = Constraint(expr=-0.1*m.x1810*(m.x1391 + m.x1392) - m.x788 + m.x789 == 0)
m.c787 = Constraint(expr=-0.1*m.x1810*(m.x1392 + m.x1393) - m.x789 + m.x790 == 0)
m.c788 = Constraint(expr=-0.1*m.x1810*(m.x1393 + m.x1394) - m.x790 + m.x791 == 0)
m.c789 = Constraint(expr=-0.1*m.x1810*(m.x1394 + m.x1395) - m.x791 + m.x792 == 0)
m.c790 = Constraint(expr=-0.1*m.x1810*(m.x1395 + m.x1396) - m.x792 + m.x793 == 0)
m.c791 = Constraint(expr=-0.1*m.x1810*(m.x1396 + m.x1397) - m.x793 + m.x794 == 0)
m.c792 = Constraint(expr=-0.1*m.x1810*(m.x1397 + m.x1398) - m.x794 + m.x795 == 0)
m.c793 = Constraint(expr=-0.1*m.x1810*(m.x1398 + m.x1399) - m.x795 + m.x796 == 0)
m.c794 = Constraint(expr=-0.1*m.x1810*(m.x1399 + m.x1400) - m.x796 + m.x797 == 0)
m.c795 = Constraint(expr=-0.1*m.x1810*(m.x1400 + m.x1401) - m.x797 + m.x798 == 0)
m.c796 = Constraint(expr=-0.1*m.x1810*(m.x1401 + m.x1402) - m.x798 + m.x799 == 0)
m.c797 = Constraint(expr=-0.1*m.x1810*(m.x1402 + m.x1403) - m.x799 + m.x800 == 0)
m.c798 = Constraint(expr=-0.1*m.x1810*(m.x1403 + m.x1404) - m.x800 + m.x801 == 0)
m.c799 = Constraint(expr=-0.1*m.x1810*(m.x1404 + m.x1405) - m.x801 + m.x802 == 0)
m.c800 = Constraint(expr=-0.1*m.x1810*(m.x1405 + m.x1406) - m.x802 + m.x803 == 0)
m.c801 = Constraint(expr=-0.1*m.x1810*(m.x1406 + m.x1407) - m.x803 + m.x804 == 0)
m.c802 = Constraint(expr=-0.5*(m.x1409/m.x1813 + m.x1408/m.x1812)*m.x1810 - m.x805 + m.x806 == 0)
m.c803 = Constraint(expr=-0.5*(m.x1410/m.x1814 + m.x1409/m.x1813)*m.x1810 - m.x806 + m.x807 == 0)
m.c804 = Constraint(expr=-0.5*(m.x1411/m.x1815 + m.x1410/m.x1814)*m.x1810 - m.x807 + m.x808 == 0)
m.c805 = Constraint(expr=-0.5*(m.x1412/m.x1816 + m.x1411/m.x1815)*m.x1810 - m.x808 + m.x809 == 0)
m.c806 = Constraint(expr=-0.5*(m.x1413/m.x1817 + m.x1412/m.x1816)*m.x1810 - m.x809 + m.x810 == 0)
m.c807 = Constraint(expr=-0.5*(m.x1414/m.x1818 + m.x1413/m.x1817)*m.x1810 - m.x810 + m.x811 == 0)
m.c808 = Constraint(expr=-0.5*(m.x1415/m.x1819 + m.x1414/m.x1818)*m.x1810 - m.x811 + m.x812 == 0)
m.c809 = Constraint(expr=-0.5*(m.x1416/m.x1820 + m.x1415/m.x1819)*m.x1810 - m.x812 + m.x813 == 0)
m.c810 = Constraint(expr=-0.5*(m.x1417/m.x1821 + m.x1416/m.x1820)*m.x1810 - m.x813 + m.x814 == 0)
m.c811 = Constraint(expr=-0.5*(m.x1418/m.x1822 + m.x1417/m.x1821)*m.x1810 - m.x814 + m.x815 == 0)
m.c812 = Constraint(expr=-0.5*(m.x1419/m.x1823 + m.x1418/m.x1822)*m.x1810 - m.x815 + m.x816 == 0)
m.c813 = Constraint(expr=-0.5*(m.x1420/m.x1824 + m.x1419/m.x1823)*m.x1810 - m.x816 + m.x817 == 0)
m.c814 = Constraint(expr=-0.5*(m.x1421/m.x1825 + m.x1420/m.x1824)*m.x1810 - m.x817 + m.x818 == 0)
m.c815 = Constraint(expr=-0.5*(m.x1422/m.x1826 + m.x1421/m.x1825)*m.x1810 - m.x818 + m.x819 == 0)
m.c816 = Constraint(expr=-0.5*(m.x1423/m.x1827 + m.x1422/m.x1826)*m.x1810 - m.x819 + m.x820 == 0)
m.c817 = Constraint(expr=-0.5*(m.x1424/m.x1828 + m.x1423/m.x1827)*m.x1810 - m.x820 + m.x821 == 0)
m.c818 = Constraint(expr=-0.5*(m.x1425/m.x1829 + m.x1424/m.x1828)*m.x1810 - m.x821 + m.x822 == 0)
m.c819 = Constraint(expr=-0.5*(m.x1426/m.x1830 + m.x1425/m.x1829)*m.x1810 - m.x822 + m.x823 == 0)
m.c820 = Constraint(expr=-0.5*(m.x1427/m.x1831 + m.x1426/m.x1830)*m.x1810 - m.x823 + m.x824 == 0)
m.c821 = Constraint(expr=-0.5*(m.x1428/m.x1832 + m.x1427/m.x1831)*m.x1810 - m.x824 + m.x825 == 0)
m.c822 = Constraint(expr=-0.5*(m.x1429/m.x1833 + m.x1428/m.x1832)*m.x1810 - m.x825 + m.x826 == 0)
m.c823 = Constraint(expr=-0.5*(m.x1430/m.x1834 + m.x1429/m.x1833)*m.x1810 - m.x826 + m.x827 == 0)
m.c824 = Constraint(expr=-0.5*(m.x1431/m.x1835 + m.x1430/m.x1834)*m.x1810 - m.x827 + m.x828 == 0)
m.c825 = Constraint(expr=-0.5*(m.x1432/m.x1836 + m.x1431/m.x1835)*m.x1810 - m.x828 + m.x829 == 0)
m.c826 = Constraint(expr=-0.5*(m.x1433/m.x1837 + m.x1432/m.x1836)*m.x1810 - m.x829 + m.x830 == 0)
m.c827 = Constraint(expr=-0.5*(m.x1434/m.x1838 + m.x1433/m.x1837)*m.x1810 - m.x830 + m.x831 == 0)
m.c828 = Constraint(expr=-0.5*(m.x1435/m.x1839 + m.x1434/m.x1838)*m.x1810 - m.x831 + m.x832 == 0)
m.c829 = Constraint(expr=-0.5*(m.x1436/m.x1840 + m.x1435/m.x1839)*m.x1810 - m.x832 + m.x833 == 0)
m.c830 = Constraint(expr=-0.5*(m.x1437/m.x1841 + m.x1436/m.x1840)*m.x1810 - m.x833 + m.x834 == 0)
m.c831 = Constraint(expr=-0.5*(m.x1438/m.x1842 + m.x1437/m.x1841)*m.x1810 - m.x834 + m.x835 == 0)
m.c832 = Constraint(expr=-0.5*(m.x1439/m.x1843 + m.x1438/m.x1842)*m.x1810 - m.x835 + m.x836 == 0)
m.c833 = Constraint(expr=-0.5*(m.x1440/m.x1844 + m.x1439/m.x1843)*m.x1810 - m.x836 + m.x837 == 0)
m.c834 = Constraint(expr=-0.5*(m.x1441/m.x1845 + m.x1440/m.x1844)*m.x1810 - m.x837 + m.x838 == 0)
m.c835 = Constraint(expr=-0.5*(m.x1442/m.x1846 + m.x1441/m.x1845)*m.x1810 - m.x838 + m.x839 == 0)
m.c836 = Constraint(expr=-0.5*(m.x1443/m.x1847 + m.x1442/m.x1846)*m.x1810 - m.x839 + m.x840 == 0)
m.c837 = Constraint(expr=-0.5*(m.x1444/m.x1848 + m.x1443/m.x1847)*m.x1810 - m.x840 + m.x841 == 0)
m.c838 = Constraint(expr=-0.5*(m.x1445/m.x1849 + m.x1444/m.x1848)*m.x1810 - m.x841 + m.x842 == 0)
m.c839 = Constraint(expr=-0.5*(m.x1446/m.x1850 + m.x1445/m.x1849)*m.x1810 - m.x842 + m.x843 == 0)
m.c840 = Constraint(expr=-0.5*(m.x1447/m.x1851 + m.x1446/m.x1850)*m.x1810 - m.x843 + m.x844 == 0)
m.c841 = Constraint(expr=-0.5*(m.x1448/m.x1852 + m.x1447/m.x1851)*m.x1810 - m.x844 + m.x845 == 0)
m.c842 = Constraint(expr=-0.5*(m.x1449/m.x1853 + m.x1448/m.x1852)*m.x1810 - m.x845 + m.x846 == 0)
m.c843 = Constraint(expr=-0.5*(m.x1450/m.x1854 + m.x1449/m.x1853)*m.x1810 - m.x846 + m.x847 == 0)
m.c844 = Constraint(expr=-0.5*(m.x1451/m.x1855 + m.x1450/m.x1854)*m.x1810 - m.x847 + m.x848 == 0)
m.c845 = Constraint(expr=-0.5*(m.x1452/m.x1856 + m.x1451/m.x1855)*m.x1810 - m.x848 + m.x849 == 0)
m.c846 = Constraint(expr=-0.5*(m.x1453/m.x1857 + m.x1452/m.x1856)*m.x1810 - m.x849 + m.x850 == 0)
m.c847 = Constraint(expr=-0.5*(m.x1454/m.x1858 + m.x1453/m.x1857)*m.x1810 - m.x850 + m.x851 == 0)
m.c848 = Constraint(expr=-0.5*(m.x1455/m.x1859 + m.x1454/m.x1858)*m.x1810 - m.x851 + m.x852 == 0)
m.c849 = Constraint(expr=-0.5*(m.x1456/m.x1860 + m.x1455/m.x1859)*m.x1810 - m.x852 + m.x853 == 0)
m.c850 = Constraint(expr=-0.5*(m.x1457/m.x1861 + m.x1456/m.x1860)*m.x1810 - m.x853 + m.x854 == 0)
m.c851 = Constraint(expr=-0.5*(m.x1458/m.x1862 + m.x1457/m.x1861)*m.x1810 - m.x854 + m.x855 == 0)
m.c852 = Constraint(expr=-0.5*(m.x1459/m.x1863 + m.x1458/m.x1862)*m.x1810 - m.x855 + m.x856 == 0)
m.c853 = Constraint(expr=-0.5*(m.x1460/m.x1864 + m.x1459/m.x1863)*m.x1810 - m.x856 + m.x857 == 0)
m.c854 = Constraint(expr=-0.5*(m.x1461/m.x1865 + m.x1460/m.x1864)*m.x1810 - m.x857 + m.x858 == 0)
m.c855 = Constraint(expr=-0.5*(m.x1462/m.x1866 + m.x1461/m.x1865)*m.x1810 - m.x858 + m.x859 == 0)
m.c856 = Constraint(expr=-0.5*(m.x1463/m.x1867 + m.x1462/m.x1866)*m.x1810 - m.x859 + m.x860 == 0)
m.c857 = Constraint(expr=-0.5*(m.x1464/m.x1868 + m.x1463/m.x1867)*m.x1810 - m.x860 + m.x861 == 0)
m.c858 = Constraint(expr=-0.5*(m.x1465/m.x1869 + m.x1464/m.x1868)*m.x1810 - m.x861 + m.x862 == 0)
m.c859 = Constraint(expr=-0.5*(m.x1466/m.x1870 + m.x1465/m.x1869)*m.x1810 - m.x862 + m.x863 == 0)
m.c860 = Constraint(expr=-0.5*(m.x1467/m.x1871 + m.x1466/m.x1870)*m.x1810 - m.x863 + m.x864 == 0)
m.c861 = Constraint(expr=-0.5*(m.x1468/m.x1872 + m.x1467/m.x1871)*m.x1810 - m.x864 + m.x865 == 0)
m.c862 = Constraint(expr=-0.5*(m.x1469/m.x1873 + m.x1468/m.x1872)*m.x1810 - m.x865 + m.x866 == 0)
m.c863 = Constraint(expr=-0.5*(m.x1470/m.x1874 + m.x1469/m.x1873)*m.x1810 - m.x866 + m.x867 == 0)
m.c864 = Constraint(expr=-0.5*(m.x1471/m.x1875 + m.x1470/m.x1874)*m.x1810 - m.x867 + m.x868 == 0)
m.c865 = Constraint(expr=-0.5*(m.x1472/m.x1876 + m.x1471/m.x1875)*m.x1810 - m.x868 + m.x869 == 0)
m.c866 = Constraint(expr=-0.5*(m.x1473/m.x1877 + m.x1472/m.x1876)*m.x1810 - m.x869 + m.x870 == 0)
m.c867 = Constraint(expr=-0.5*(m.x1474/m.x1878 + m.x1473/m.x1877)*m.x1810 - m.x870 + m.x871 == 0)
m.c868 = Constraint(expr=-0.5*(m.x1475/m.x1879 + m.x1474/m.x1878)*m.x1810 - m.x871 + m.x872 == 0)
m.c869 = Constraint(expr=-0.5*(m.x1476/m.x1880 + m.x1475/m.x1879)*m.x1810 - m.x872 + m.x873 == 0)
m.c870 = Constraint(expr=-0.5*(m.x1477/m.x1881 + m.x1476/m.x1880)*m.x1810 - m.x873 + m.x874 == 0)
m.c871 = Constraint(expr=-0.5*(m.x1478/m.x1882 + m.x1477/m.x1881)*m.x1810 - m.x874 + m.x875 == 0)
m.c872 = Constraint(expr=-0.5*(m.x1479/m.x1883 + m.x1478/m.x1882)*m.x1810 - m.x875 + m.x876 == 0)
m.c873 = Constraint(expr=-0.5*(m.x1480/m.x1884 + m.x1479/m.x1883)*m.x1810 - m.x876 + m.x877 == 0)
m.c874 = Constraint(expr=-0.5*(m.x1481/m.x1885 + m.x1480/m.x1884)*m.x1810 - m.x877 + m.x878 == 0)
m.c875 = Constraint(expr=-0.5*(m.x1482/m.x1886 + m.x1481/m.x1885)*m.x1810 - m.x878 + m.x879 == 0)
m.c876 = Constraint(expr=-0.5*(m.x1483/m.x1887 + m.x1482/m.x1886)*m.x1810 - m.x879 + m.x880 == 0)
m.c877 = Constraint(expr=-0.5*(m.x1484/m.x1888 + m.x1483/m.x1887)*m.x1810 - m.x880 + m.x881 == 0)
m.c878 = Constraint(expr=-0.5*(m.x1485/m.x1889 + m.x1484/m.x1888)*m.x1810 - m.x881 + m.x882 == 0)
m.c879 = Constraint(expr=-0.5*(m.x1486/m.x1890 + m.x1485/m.x1889)*m.x1810 - m.x882 + m.x883 == 0)
m.c880 = Constraint(expr=-0.5*(m.x1487/m.x1891 + m.x1486/m.x1890)*m.x1810 - m.x883 + m.x884 == 0)
m.c881 = Constraint(expr=-0.5*(m.x1488/m.x1892 + m.x1487/m.x1891)*m.x1810 - m.x884 + m.x885 == 0)
m.c882 = Constraint(expr=-0.5*(m.x1489/m.x1893 + m.x1488/m.x1892)*m.x1810 - m.x885 + m.x886 == 0)
m.c883 = Constraint(expr=-0.5*(m.x1490/m.x1894 + m.x1489/m.x1893)*m.x1810 - m.x886 + m.x887 == 0)
m.c884 = Constraint(expr=-0.5*(m.x1491/m.x1895 + m.x1490/m.x1894)*m.x1810 - m.x887 + m.x888 == 0)
m.c885 = Constraint(expr=-0.5*(m.x1492/m.x1896 + m.x1491/m.x1895)*m.x1810 - m.x888 + m.x889 == 0)
m.c886 = Constraint(expr=-0.5*(m.x1493/m.x1897 + m.x1492/m.x1896)*m.x1810 - m.x889 + m.x890 == 0)
m.c887 = Constraint(expr=-0.5*(m.x1494/m.x1898 + m.x1493/m.x1897)*m.x1810 - m.x890 + m.x891 == 0)
m.c888 = Constraint(expr=-0.5*(m.x1495/m.x1899 + m.x1494/m.x1898)*m.x1810 - m.x891 + m.x892 == 0)
m.c889 = Constraint(expr=-0.5*(m.x1496/m.x1900 + m.x1495/m.x1899)*m.x1810 - m.x892 + m.x893 == 0)
m.c890 = Constraint(expr=-0.5*(m.x1497/m.x1901 + m.x1496/m.x1900)*m.x1810 - m.x893 + m.x894 == 0)
m.c891 = Constraint(expr=-0.5*(m.x1498/m.x1902 + m.x1497/m.x1901)*m.x1810 - m.x894 + m.x895 == 0)
m.c892 = Constraint(expr=-0.5*(m.x1499/m.x1903 + m.x1498/m.x1902)*m.x1810 - m.x895 + m.x896 == 0)
m.c893 = Constraint(expr=-0.5*(m.x1500/m.x1904 + m.x1499/m.x1903)*m.x1810 - m.x896 + m.x897 == 0)
m.c894 = Constraint(expr=-0.5*(m.x1501/m.x1905 + m.x1500/m.x1904)*m.x1810 - m.x897 + m.x898 == 0)
m.c895 = Constraint(expr=-0.5*(m.x1502/m.x1906 + m.x1501/m.x1905)*m.x1810 - m.x898 + m.x899 == 0)
m.c896 = Constraint(expr=-0.5*(m.x1503/m.x1907 + m.x1502/m.x1906)*m.x1810 - m.x899 + m.x900 == 0)
m.c897 = Constraint(expr=-0.5*(m.x1504/m.x1908 + m.x1503/m.x1907)*m.x1810 - m.x900 + m.x901 == 0)
m.c898 = Constraint(expr=-0.5*(m.x1505/m.x1909 + m.x1504/m.x1908)*m.x1810 - m.x901 + m.x902 == 0)
m.c899 = Constraint(expr=-0.5*(m.x1506/m.x1910 + m.x1505/m.x1909)*m.x1810 - m.x902 + m.x903 == 0)
m.c900 = Constraint(expr=-0.5*(m.x1507/m.x1911 + m.x1506/m.x1910)*m.x1810 - m.x903 + m.x904 == 0)
m.c901 = Constraint(expr=-0.5*(m.x1508/m.x1912 + m.x1507/m.x1911)*m.x1810 - m.x904 + m.x905 == 0)
m.c902 = Constraint(expr=-0.5*(m.x1509/m.x1913 + m.x1508/m.x1912)*m.x1810 - m.x905 + m.x906 == 0)
m.c903 = Constraint(expr=-0.5*(m.x1510/m.x1914 + m.x1509/m.x1913)*m.x1810 - m.x906 + m.x907 == 0)
m.c904 = Constraint(expr=-0.5*(m.x1511/m.x1915 + m.x1510/m.x1914)*m.x1810 - m.x907 + m.x908 == 0)
m.c905 = Constraint(expr=-0.5*(m.x1512/m.x1916 + m.x1511/m.x1915)*m.x1810 - m.x908 + m.x909 == 0)
m.c906 = Constraint(expr=-0.5*(m.x1513/m.x1917 + m.x1512/m.x1916)*m.x1810 - m.x909 + m.x910 == 0)
m.c907 = Constraint(expr=-0.5*(m.x1514/m.x1918 + m.x1513/m.x1917)*m.x1810 - m.x910 + m.x911 == 0)
m.c908 = Constraint(expr=-0.5*(m.x1515/m.x1919 + m.x1514/m.x1918)*m.x1810 - m.x911 + m.x912 == 0)
m.c909 = Constraint(expr=-0.5*(m.x1516/m.x1920 + m.x1515/m.x1919)*m.x1810 - m.x912 + m.x913 == 0)
m.c910 = Constraint(expr=-0.5*(m.x1517/m.x1921 + m.x1516/m.x1920)*m.x1810 - m.x913 + m.x914 == 0)
m.c911 = Constraint(expr=-0.5*(m.x1518/m.x1922 + m.x1517/m.x1921)*m.x1810 - m.x914 + m.x915 == 0)
m.c912 = Constraint(expr=-0.5*(m.x1519/m.x1923 + m.x1518/m.x1922)*m.x1810 - m.x915 + m.x916 == 0)
m.c913 = Constraint(expr=-0.5*(m.x1520/m.x1924 + m.x1519/m.x1923)*m.x1810 - m.x916 + m.x917 == 0)
m.c914 = Constraint(expr=-0.5*(m.x1521/m.x1925 + m.x1520/m.x1924)*m.x1810 - m.x917 + m.x918 == 0)
m.c915 = Constraint(expr=-0.5*(m.x1522/m.x1926 + m.x1521/m.x1925)*m.x1810 - m.x918 + m.x919 == 0)
m.c916 = Constraint(expr=-0.5*(m.x1523/m.x1927 + m.x1522/m.x1926)*m.x1810 - m.x919 + m.x920 == 0)
m.c917 = Constraint(expr=-0.5*(m.x1524/m.x1928 + m.x1523/m.x1927)*m.x1810 - m.x920 + m.x921 == 0)
m.c918 = Constraint(expr=-0.5*(m.x1525/m.x1929 + m.x1524/m.x1928)*m.x1810 - m.x921 + m.x922 == 0)
m.c919 = Constraint(expr=-0.5*(m.x1526/m.x1930 + m.x1525/m.x1929)*m.x1810 - m.x922 + m.x923 == 0)
m.c920 = Constraint(expr=-0.5*(m.x1527/m.x1931 + m.x1526/m.x1930)*m.x1810 - m.x923 + m.x924 == 0)
m.c921 = Constraint(expr=-0.5*(m.x1528/m.x1932 + m.x1527/m.x1931)*m.x1810 - m.x924 + m.x925 == 0)
m.c922 = Constraint(expr=-0.5*(m.x1529/m.x1933 + m.x1528/m.x1932)*m.x1810 - m.x925 + m.x926 == 0)
m.c923 = Constraint(expr=-0.5*(m.x1530/m.x1934 + m.x1529/m.x1933)*m.x1810 - m.x926 + m.x927 == 0)
m.c924 = Constraint(expr=-0.5*(m.x1531/m.x1935 + m.x1530/m.x1934)*m.x1810 - m.x927 + m.x928 == 0)
m.c925 = Constraint(expr=-0.5*(m.x1532/m.x1936 + m.x1531/m.x1935)*m.x1810 - m.x928 + m.x929 == 0)
m.c926 = Constraint(expr=-0.5*(m.x1533/m.x1937 + m.x1532/m.x1936)*m.x1810 - m.x929 + m.x930 == 0)
m.c927 = Constraint(expr=-0.5*(m.x1534/m.x1938 + m.x1533/m.x1937)*m.x1810 - m.x930 + m.x931 == 0)
m.c928 = Constraint(expr=-0.5*(m.x1535/m.x1939 + m.x1534/m.x1938)*m.x1810 - m.x931 + m.x932 == 0)
m.c929 = Constraint(expr=-0.5*(m.x1536/m.x1940 + m.x1535/m.x1939)*m.x1810 - m.x932 + m.x933 == 0)
m.c930 = Constraint(expr=-0.5*(m.x1537/m.x1941 + m.x1536/m.x1940)*m.x1810 - m.x933 + m.x934 == 0)
m.c931 = Constraint(expr=-0.5*(m.x1538/m.x1942 + m.x1537/m.x1941)*m.x1810 - m.x934 + m.x935 == 0)
m.c932 = Constraint(expr=-0.5*(m.x1539/m.x1943 + m.x1538/m.x1942)*m.x1810 - m.x935 + m.x936 == 0)
m.c933 = Constraint(expr=-0.5*(m.x1540/m.x1944 + m.x1539/m.x1943)*m.x1810 - m.x936 + m.x937 == 0)
m.c934 = Constraint(expr=-0.5*(m.x1541/m.x1945 + m.x1540/m.x1944)*m.x1810 - m.x937 + m.x938 == 0)
m.c935 = Constraint(expr=-0.5*(m.x1542/m.x1946 + m.x1541/m.x1945)*m.x1810 - m.x938 + m.x939 == 0)
m.c936 = Constraint(expr=-0.5*(m.x1543/m.x1947 + m.x1542/m.x1946)*m.x1810 - m.x939 + m.x940 == 0)
m.c937 = Constraint(expr=-0.5*(m.x1544/m.x1948 + m.x1543/m.x1947)*m.x1810 - m.x940 + m.x941 == 0)
m.c938 = Constraint(expr=-0.5*(m.x1545/m.x1949 + m.x1544/m.x1948)*m.x1810 - m.x941 + m.x942 == 0)
m.c939 = Constraint(expr=-0.5*(m.x1546/m.x1950 + m.x1545/m.x1949)*m.x1810 - m.x942 + m.x943 == 0)
m.c940 = Constraint(expr=-0.5*(m.x1547/m.x1951 + m.x1546/m.x1950)*m.x1810 - m.x943 + m.x944 == 0)
m.c941 = Constraint(expr=-0.5*(m.x1548/m.x1952 + m.x1547/m.x1951)*m.x1810 - m.x944 + m.x945 == 0)
m.c942 = Constraint(expr=-0.5*(m.x1549/m.x1953 + m.x1548/m.x1952)*m.x1810 - m.x945 + m.x946 == 0)
m.c943 = Constraint(expr=-0.5*(m.x1550/m.x1954 + m.x1549/m.x1953)*m.x1810 - m.x946 + m.x947 == 0)
m.c944 = Constraint(expr=-0.5*(m.x1551/m.x1955 + m.x1550/m.x1954)*m.x1810 - m.x947 + m.x948 == 0)
m.c945 = Constraint(expr=-0.5*(m.x1552/m.x1956 + m.x1551/m.x1955)*m.x1810 - m.x948 + m.x949 == 0)
m.c946 = Constraint(expr=-0.5*(m.x1553/m.x1957 + m.x1552/m.x1956)*m.x1810 - m.x949 + m.x950 == 0)
m.c947 = Constraint(expr=-0.5*(m.x1554/m.x1958 + m.x1553/m.x1957)*m.x1810 - m.x950 + m.x951 == 0)
m.c948 = Constraint(expr=-0.5*(m.x1555/m.x1959 + m.x1554/m.x1958)*m.x1810 - m.x951 + m.x952 == 0)
m.c949 = Constraint(expr=-0.5*(m.x1556/m.x1960 + m.x1555/m.x1959)*m.x1810 - m.x952 + m.x953 == 0)
m.c950 = Constraint(expr=-0.5*(m.x1557/m.x1961 + m.x1556/m.x1960)*m.x1810 - m.x953 + m.x954 == 0)
m.c951 = Constraint(expr=-0.5*(m.x1558/m.x1962 + m.x1557/m.x1961)*m.x1810 - m.x954 + m.x955 == 0)
m.c952 = Constraint(expr=-0.5*(m.x1559/m.x1963 + m.x1558/m.x1962)*m.x1810 - m.x955 + m.x956 == 0)
m.c953 = Constraint(expr=-0.5*(m.x1560/m.x1964 + m.x1559/m.x1963)*m.x1810 - m.x956 + m.x957 == 0)
m.c954 = Constraint(expr=-0.5*(m.x1561/m.x1965 + m.x1560/m.x1964)*m.x1810 - m.x957 + m.x958 == 0)
m.c955 = Constraint(expr=-0.5*(m.x1562/m.x1966 + m.x1561/m.x1965)*m.x1810 - m.x958 + m.x959 == 0)
m.c956 = Constraint(expr=-0.5*(m.x1563/m.x1967 + m.x1562/m.x1966)*m.x1810 - m.x959 + m.x960 == 0)
m.c957 = Constraint(expr=-0.5*(m.x1564/m.x1968 + m.x1563/m.x1967)*m.x1810 - m.x960 + m.x961 == 0)
m.c958 = Constraint(expr=-0.5*(m.x1565/m.x1969 + m.x1564/m.x1968)*m.x1810 - m.x961 + m.x962 == 0)
m.c959 = Constraint(expr=-0.5*(m.x1566/m.x1970 + m.x1565/m.x1969)*m.x1810 - m.x962 + m.x963 == 0)
m.c960 = Constraint(expr=-0.5*(m.x1567/m.x1971 + m.x1566/m.x1970)*m.x1810 - m.x963 + m.x964 == 0)
m.c961 = Constraint(expr=-0.5*(m.x1568/m.x1972 + m.x1567/m.x1971)*m.x1810 - m.x964 + m.x965 == 0)
m.c962 = Constraint(expr=-0.5*(m.x1569/m.x1973 + m.x1568/m.x1972)*m.x1810 - m.x965 + m.x966 == 0)
m.c963 = Constraint(expr=-0.5*(m.x1570/m.x1974 + m.x1569/m.x1973)*m.x1810 - m.x966 + m.x967 == 0)
m.c964 = Constraint(expr=-0.5*(m.x1571/m.x1975 + m.x1570/m.x1974)*m.x1810 - m.x967 + m.x968 == 0)
m.c965 = Constraint(expr=-0.5*(m.x1572/m.x1976 + m.x1571/m.x1975)*m.x1810 - m.x968 + m.x969 == 0)
m.c966 = Constraint(expr=-0.5*(m.x1573/m.x1977 + m.x1572/m.x1976)*m.x1810 - m.x969 + m.x970 == 0)
m.c967 = Constraint(expr=-0.5*(m.x1574/m.x1978 + m.x1573/m.x1977)*m.x1810 - m.x970 + m.x971 == 0)
m.c968 = Constraint(expr=-0.5*(m.x1575/m.x1979 + m.x1574/m.x1978)*m.x1810 - m.x971 + m.x972 == 0)
m.c969 = Constraint(expr=-0.5*(m.x1576/m.x1980 + m.x1575/m.x1979)*m.x1810 - m.x972 + m.x973 == 0)
m.c970 = Constraint(expr=-0.5*(m.x1577/m.x1981 + m.x1576/m.x1980)*m.x1810 - m.x973 + m.x974 == 0)
m.c971 = Constraint(expr=-0.5*(m.x1578/m.x1982 + m.x1577/m.x1981)*m.x1810 - m.x974 + m.x975 == 0)
m.c972 = Constraint(expr=-0.5*(m.x1579/m.x1983 + m.x1578/m.x1982)*m.x1810 - m.x975 + m.x976 == 0)
m.c973 = Constraint(expr=-0.5*(m.x1580/m.x1984 + m.x1579/m.x1983)*m.x1810 - m.x976 + m.x977 == 0)
m.c974 = Constraint(expr=-0.5*(m.x1581/m.x1985 + m.x1580/m.x1984)*m.x1810 - m.x977 + m.x978 == 0)
m.c975 = Constraint(expr=-0.5*(m.x1582/m.x1986 + m.x1581/m.x1985)*m.x1810 - m.x978 + m.x979 == 0)
m.c976 = Constraint(expr=-0.5*(m.x1583/m.x1987 + m.x1582/m.x1986)*m.x1810 - m.x979 + m.x980 == 0)
m.c977 = Constraint(expr=-0.5*(m.x1584/m.x1988 + m.x1583/m.x1987)*m.x1810 - m.x980 + m.x981 == 0)
m.c978 = Constraint(expr=-0.5*(m.x1585/m.x1989 + m.x1584/m.x1988)*m.x1810 - m.x981 + m.x982 == 0)
m.c979 = Constraint(expr=-0.5*(m.x1586/m.x1990 + m.x1585/m.x1989)*m.x1810 - m.x982 + m.x983 == 0)
m.c980 = Constraint(expr=-0.5*(m.x1587/m.x1991 + m.x1586/m.x1990)*m.x1810 - m.x983 + m.x984 == 0)
m.c981 = Constraint(expr=-0.5*(m.x1588/m.x1992 + m.x1587/m.x1991)*m.x1810 - m.x984 + m.x985 == 0)
m.c982 = Constraint(expr=-0.5*(m.x1589/m.x1993 + m.x1588/m.x1992)*m.x1810 - m.x985 + m.x986 == 0)
m.c983 = Constraint(expr=-0.5*(m.x1590/m.x1994 + m.x1589/m.x1993)*m.x1810 - m.x986 + m.x987 == 0)
m.c984 = Constraint(expr=-0.5*(m.x1591/m.x1995 + m.x1590/m.x1994)*m.x1810 - m.x987 + m.x988 == 0)
m.c985 = Constraint(expr=-0.5*(m.x1592/m.x1996 + m.x1591/m.x1995)*m.x1810 - m.x988 + m.x989 == 0)
m.c986 = Constraint(expr=-0.5*(m.x1593/m.x1997 + m.x1592/m.x1996)*m.x1810 - m.x989 + m.x990 == 0)
m.c987 = Constraint(expr=-0.5*(m.x1594/m.x1998 + m.x1593/m.x1997)*m.x1810 - m.x990 + m.x991 == 0)
m.c988 = Constraint(expr=-0.5*(m.x1595/m.x1999 + m.x1594/m.x1998)*m.x1810 - m.x991 + m.x992 == 0)
m.c989 = Constraint(expr=-0.5*(m.x1596/m.x2000 + m.x1595/m.x1999)*m.x1810 - m.x992 + m.x993 == 0)
m.c990 = Constraint(expr=-0.5*(m.x1597/m.x2001 + m.x1596/m.x2000)*m.x1810 - m.x993 + m.x994 == 0)
m.c991 = Constraint(expr=-0.5*(m.x1598/m.x2002 + m.x1597/m.x2001)*m.x1810 - m.x994 + m.x995 == 0)
m.c992 = Constraint(expr=-0.5*(m.x1599/m.x2003 + m.x1598/m.x2002)*m.x1810 - m.x995 + m.x996 == 0)
m.c993 = Constraint(expr=-0.5*(m.x1600/m.x2004 + m.x1599/m.x2003)*m.x1810 - m.x996 + m.x997 == 0)
m.c994 = Constraint(expr=-0.5*(m.x1601/m.x2005 + m.x1600/m.x2004)*m.x1810 - m.x997 + m.x998 == 0)
m.c995 = Constraint(expr=-0.5*(m.x1602/m.x2006 + m.x1601/m.x2005)*m.x1810 - m.x998 + m.x999 == 0)
m.c996 = Constraint(expr=-0.5*(m.x1603/m.x2007 + m.x1602/m.x2006)*m.x1810 - m.x999 + m.x1000 == 0)
m.c997 = Constraint(expr=-0.5*(m.x1604/m.x2008 + m.x1603/m.x2007)*m.x1810 - m.x1000 + m.x1001 == 0)
m.c998 = Constraint(expr=-0.5*(m.x1605/m.x2009 + m.x1604/m.x2008)*m.x1810 - m.x1001 + m.x1002 == 0)
m.c999 = Constraint(expr=-0.5*(m.x1606/m.x2010 + m.x1605/m.x2009)*m.x1810 - m.x1002 + m.x1003 == 0)
m.c1000 = Constraint(expr=-0.5*(m.x1607/m.x2011 + m.x1606/m.x2010)*m.x1810 - m.x1003 + m.x1004 == 0)
m.c1001 = Constraint(expr=-0.5*(m.x1608/m.x2012 + m.x1607/m.x2011)*m.x1810 - m.x1004 + m.x1005 == 0)
m.c1002 = Constraint(expr=-0.5*(m.x1610/m.x2014 + m.x1609/m.x2013)*m.x1810 - m.x1006 + m.x1007 == 0)
m.c1003 = Constraint(expr=-0.5*(m.x1611/m.x2015 + m.x1610/m.x2014)*m.x1810 - m.x1007 + m.x1008 == 0)
m.c1004 = Constraint(expr=-0.5*(m.x1612/m.x2016 + m.x1611/m.x2015)*m.x1810 - m.x1008 + m.x1009 == 0)
m.c1005 = Constraint(expr=-0.5*(m.x1613/m.x2017 + m.x1612/m.x2016)*m.x1810 - m.x1009 + m.x1010 == 0)
m.c1006 = Constraint(expr=-0.5*(m.x1614/m.x2018 + m.x1613/m.x2017)*m.x1810 - m.x1010 + m.x1011 == 0)
m.c1007 = Constraint(expr=-0.5*(m.x1615/m.x2019 + m.x1614/m.x2018)*m.x1810 - m.x1011 + m.x1012 == 0)
m.c1008 = Constraint(expr=-0.5*(m.x1616/m.x2020 + m.x1615/m.x2019)*m.x1810 - m.x1012 + m.x1013 == 0)
m.c1009 = Constraint(expr=-0.5*(m.x1617/m.x2021 + m.x1616/m.x2020)*m.x1810 - m.x1013 + m.x1014 == 0)
m.c1010 = Constraint(expr=-0.5*(m.x1618/m.x2022 + m.x1617/m.x2021)*m.x1810 - m.x1014 + m.x1015 == 0)
m.c1011 = Constraint(expr=-0.5*(m.x1619/m.x2023 + m.x1618/m.x2022)*m.x1810 - m.x1015 + m.x1016 == 0)
m.c1012 = Constraint(expr=-0.5*(m.x1620/m.x2024 + m.x1619/m.x2023)*m.x1810 - m.x1016 + m.x1017 == 0)
m.c1013 = Constraint(expr=-0.5*(m.x1621/m.x2025 + m.x1620/m.x2024)*m.x1810 - m.x1017 + m.x1018 == 0)
m.c1014 = Constraint(expr=-0.5*(m.x1622/m.x2026 + m.x1621/m.x2025)*m.x1810 - m.x1018 + m.x1019 == 0)
m.c1015 = Constraint(expr=-0.5*(m.x1623/m.x2027 + m.x1622/m.x2026)*m.x1810 - m.x1019 + m.x1020 == 0)
m.c1016 = Constraint(expr=-0.5*(m.x1624/m.x2028 + m.x1623/m.x2027)*m.x1810 - m.x1020 + m.x1021 == 0)
m.c1017 = Constraint(expr=-0.5*(m.x1625/m.x2029 + m.x1624/m.x2028)*m.x1810 - m.x1021 + m.x1022 == 0)
m.c1018 = Constraint(expr=-0.5*(m.x1626/m.x2030 + m.x1625/m.x2029)*m.x1810 - m.x1022 + m.x1023 == 0)
m.c1019 = Constraint(expr=-0.5*(m.x1627/m.x2031 + m.x1626/m.x2030)*m.x1810 - m.x1023 + m.x1024 == 0)
m.c1020 = Constraint(expr=-0.5*(m.x1628/m.x2032 + m.x1627/m.x2031)*m.x1810 - m.x1024 + m.x1025 == 0)
m.c1021 = Constraint(expr=-0.5*(m.x1629/m.x2033 + m.x1628/m.x2032)*m.x1810 - m.x1025 + m.x1026 == 0)
m.c1022 = Constraint(expr=-0.5*(m.x1630/m.x2034 + m.x1629/m.x2033)*m.x1810 - m.x1026 + m.x1027 == 0)
m.c1023 = Constraint(expr=-0.5*(m.x1631/m.x2035 + m.x1630/m.x2034)*m.x1810 - m.x1027 + m.x1028 == 0)
m.c1024 = Constraint(expr=-0.5*(m.x1632/m.x2036 + m.x1631/m.x2035)*m.x1810 - m.x1028 + m.x1029 == 0)
m.c1025 = Constraint(expr=-0.5*(m.x1633/m.x2037 + m.x1632/m.x2036)*m.x1810 - m.x1029 + m.x1030 == 0)
m.c1026 = Constraint(expr=-0.5*(m.x1634/m.x2038 + m.x1633/m.x2037)*m.x1810 - m.x1030 + m.x1031 == 0)
m.c1027 = Constraint(expr=-0.5*(m.x1635/m.x2039 + m.x1634/m.x2038)*m.x1810 - m.x1031 + m.x1032 == 0)
m.c1028 = Constraint(expr=-0.5*(m.x1636/m.x2040 + m.x1635/m.x2039)*m.x1810 - m.x1032 + m.x1033 == 0)
m.c1029 = Constraint(expr=-0.5*(m.x1637/m.x2041 + m.x1636/m.x2040)*m.x1810 - m.x1033 + m.x1034 == 0)
m.c1030 = Constraint(expr=-0.5*(m.x1638/m.x2042 + m.x1637/m.x2041)*m.x1810 - m.x1034 + m.x1035 == 0)
m.c1031 = Constraint(expr=-0.5*(m.x1639/m.x2043 + m.x1638/m.x2042)*m.x1810 - m.x1035 + m.x1036 == 0)
m.c1032 = Constraint(expr=-0.5*(m.x1640/m.x2044 + m.x1639/m.x2043)*m.x1810 - m.x1036 + m.x1037 == 0)
m.c1033 = Constraint(expr=-0.5*(m.x1641/m.x2045 + m.x1640/m.x2044)*m.x1810 - m.x1037 + m.x1038 == 0)
m.c1034 = Constraint(expr=-0.5*(m.x1642/m.x2046 + m.x1641/m.x2045)*m.x1810 - m.x1038 + m.x1039 == 0)
m.c1035 = Constraint(expr=-0.5*(m.x1643/m.x2047 + m.x1642/m.x2046)*m.x1810 - m.x1039 + m.x1040 == 0)
m.c1036 = Constraint(expr=-0.5*(m.x1644/m.x2048 + m.x1643/m.x2047)*m.x1810 - m.x1040 + m.x1041 == 0)
m.c1037 = Constraint(expr=-0.5*(m.x1645/m.x2049 + m.x1644/m.x2048)*m.x1810 - m.x1041 + m.x1042 == 0)
m.c1038 = Constraint(expr=-0.5*(m.x1646/m.x2050 + m.x1645/m.x2049)*m.x1810 - m.x1042 + m.x1043 == 0)
m.c1039 = Constraint(expr=-0.5*(m.x1647/m.x2051 + m.x1646/m.x2050)*m.x1810 - m.x1043 + m.x1044 == 0)
m.c1040 = Constraint(expr=-0.5*(m.x1648/m.x2052 + m.x1647/m.x2051)*m.x1810 - m.x1044 + m.x1045 == 0)
m.c1041 = Constraint(expr=-0.5*(m.x1649/m.x2053 + m.x1648/m.x2052)*m.x1810 - m.x1045 + m.x1046 == 0)
m.c1042 = Constraint(expr=-0.5*(m.x1650/m.x2054 + m.x1649/m.x2053)*m.x1810 - m.x1046 + m.x1047 == 0)
m.c1043 = Constraint(expr=-0.5*(m.x1651/m.x2055 + m.x1650/m.x2054)*m.x1810 - m.x1047 + m.x1048 == 0)
m.c1044 = Constraint(expr=-0.5*(m.x1652/m.x2056 + m.x1651/m.x2055)*m.x1810 - m.x1048 + m.x1049 == 0)
m.c1045 = Constraint(expr=-0.5*(m.x1653/m.x2057 + m.x1652/m.x2056)*m.x1810 - m.x1049 + m.x1050 == 0)
m.c1046 = Constraint(expr=-0.5*(m.x1654/m.x2058 + m.x1653/m.x2057)*m.x1810 - m.x1050 + m.x1051 == 0)
m.c1047 = Constraint(expr=-0.5*(m.x1655/m.x2059 + m.x1654/m.x2058)*m.x1810 - m.x1051 + m.x1052 == 0)
m.c1048 = Constraint(expr=-0.5*(m.x1656/m.x2060 + m.x1655/m.x2059)*m.x1810 - m.x1052 + m.x1053 == 0)
m.c1049 = Constraint(expr=-0.5*(m.x1657/m.x2061 + m.x1656/m.x2060)*m.x1810 - m.x1053 + m.x1054 == 0)
m.c1050 = Constraint(expr=-0.5*(m.x1658/m.x2062 + m.x1657/m.x2061)*m.x1810 - m.x1054 + m.x1055 == 0)
m.c1051 = Constraint(expr=-0.5*(m.x1659/m.x2063 + m.x1658/m.x2062)*m.x1810 - m.x1055 + m.x1056 == 0)
m.c1052 = Constraint(expr=-0.5*(m.x1660/m.x2064 + m.x1659/m.x2063)*m.x1810 - m.x1056 + m.x1057 == 0)
m.c1053 = Constraint(expr=-0.5*(m.x1661/m.x2065 + m.x1660/m.x2064)*m.x1810 - m.x1057 + m.x1058 == 0)
m.c1054 = Constraint(expr=-0.5*(m.x1662/m.x2066 + m.x1661/m.x2065)*m.x1810 - m.x1058 + m.x1059 == 0)
m.c1055 = Constraint(expr=-0.5*(m.x1663/m.x2067 + m.x1662/m.x2066)*m.x1810 - m.x1059 + m.x1060 == 0)
m.c1056 = Constraint(expr=-0.5*(m.x1664/m.x2068 + m.x1663/m.x2067)*m.x1810 - m.x1060 + m.x1061 == 0)
m.c1057 = Constraint(expr=-0.5*(m.x1665/m.x2069 + m.x1664/m.x2068)*m.x1810 - m.x1061 + m.x1062 == 0)
m.c1058 = Constraint(expr=-0.5*(m.x1666/m.x2070 + m.x1665/m.x2069)*m.x1810 - m.x1062 + m.x1063 == 0)
m.c1059 = Constraint(expr=-0.5*(m.x1667/m.x2071 + m.x1666/m.x2070)*m.x1810 - m.x1063 + m.x1064 == 0)
m.c1060 = Constraint(expr=-0.5*(m.x1668/m.x2072 + m.x1667/m.x2071)*m.x1810 - m.x1064 + m.x1065 == 0)
m.c1061 = Constraint(expr=-0.5*(m.x1669/m.x2073 + m.x1668/m.x2072)*m.x1810 - m.x1065 + m.x1066 == 0)
m.c1062 = Constraint(expr=-0.5*(m.x1670/m.x2074 + m.x1669/m.x2073)*m.x1810 - m.x1066 + m.x1067 == 0)
m.c1063 = Constraint(expr=-0.5*(m.x1671/m.x2075 + m.x1670/m.x2074)*m.x1810 - m.x1067 + m.x1068 == 0)
m.c1064 = Constraint(expr=-0.5*(m.x1672/m.x2076 + m.x1671/m.x2075)*m.x1810 - m.x1068 + m.x1069 == 0)
m.c1065 = Constraint(expr=-0.5*(m.x1673/m.x2077 + m.x1672/m.x2076)*m.x1810 - m.x1069 + m.x1070 == 0)
m.c1066 = Constraint(expr=-0.5*(m.x1674/m.x2078 + m.x1673/m.x2077)*m.x1810 - m.x1070 + m.x1071 == 0)
m.c1067 = Constraint(expr=-0.5*(m.x1675/m.x2079 + m.x1674/m.x2078)*m.x1810 - m.x1071 + m.x1072 == 0)
m.c1068 = Constraint(expr=-0.5*(m.x1676/m.x2080 + m.x1675/m.x2079)*m.x1810 - m.x1072 + m.x1073 == 0)
m.c1069 = Constraint(expr=-0.5*(m.x1677/m.x2081 + m.x1676/m.x2080)*m.x1810 - m.x1073 + m.x1074 == 0)
m.c1070 = Constraint(expr=-0.5*(m.x1678/m.x2082 + m.x1677/m.x2081)*m.x1810 - m.x1074 + m.x1075 == 0)
m.c1071 = Constraint(expr=-0.5*(m.x1679/m.x2083 + m.x1678/m.x2082)*m.x1810 - m.x1075 + m.x1076 == 0)
m.c1072 = Constraint(expr=-0.5*(m.x1680/m.x2084 + m.x1679/m.x2083)*m.x1810 - m.x1076 + m.x1077 == 0)
m.c1073 = Constraint(expr=-0.5*(m.x1681/m.x2085 + m.x1680/m.x2084)*m.x1810 - m.x1077 + m.x1078 == 0)
m.c1074 = Constraint(expr=-0.5*(m.x1682/m.x2086 + m.x1681/m.x2085)*m.x1810 - m.x1078 + m.x1079 == 0)
m.c1075 = Constraint(expr=-0.5*(m.x1683/m.x2087 + m.x1682/m.x2086)*m.x1810 - m.x1079 + m.x1080 == 0)
m.c1076 = Constraint(expr=-0.5*(m.x1684/m.x2088 + m.x1683/m.x2087)*m.x1810 - m.x1080 + m.x1081 == 0)
m.c1077 = Constraint(expr=-0.5*(m.x1685/m.x2089 + m.x1684/m.x2088)*m.x1810 - m.x1081 + m.x1082 == 0)
m.c1078 = Constraint(expr=-0.5*(m.x1686/m.x2090 + m.x1685/m.x2089)*m.x1810 - m.x1082 + m.x1083 == 0)
m.c1079 = Constraint(expr=-0.5*(m.x1687/m.x2091 + m.x1686/m.x2090)*m.x1810 - m.x1083 + m.x1084 == 0)
m.c1080 = Constraint(expr=-0.5*(m.x1688/m.x2092 + m.x1687/m.x2091)*m.x1810 - m.x1084 + m.x1085 == 0)
m.c1081 = Constraint(expr=-0.5*(m.x1689/m.x2093 + m.x1688/m.x2092)*m.x1810 - m.x1085 + m.x1086 == 0)
m.c1082 = Constraint(expr=-0.5*(m.x1690/m.x2094 + m.x1689/m.x2093)*m.x1810 - m.x1086 + m.x1087 == 0)
m.c1083 = Constraint(expr=-0.5*(m.x1691/m.x2095 + m.x1690/m.x2094)*m.x1810 - m.x1087 + m.x1088 == 0)
m.c1084 = Constraint(expr=-0.5*(m.x1692/m.x2096 + m.x1691/m.x2095)*m.x1810 - m.x1088 + m.x1089 == 0)
m.c1085 = Constraint(expr=-0.5*(m.x1693/m.x2097 + m.x1692/m.x2096)*m.x1810 - m.x1089 + m.x1090 == 0)
m.c1086 = Constraint(expr=-0.5*(m.x1694/m.x2098 + m.x1693/m.x2097)*m.x1810 - m.x1090 + m.x1091 == 0)
m.c1087 = Constraint(expr=-0.5*(m.x1695/m.x2099 + m.x1694/m.x2098)*m.x1810 - m.x1091 + m.x1092 == 0)
m.c1088 = Constraint(expr=-0.5*(m.x1696/m.x2100 + m.x1695/m.x2099)*m.x1810 - m.x1092 + m.x1093 == 0)
m.c1089 = Constraint(expr=-0.5*(m.x1697/m.x2101 + m.x1696/m.x2100)*m.x1810 - m.x1093 + m.x1094 == 0)
m.c1090 = Constraint(expr=-0.5*(m.x1698/m.x2102 + m.x1697/m.x2101)*m.x1810 - m.x1094 + m.x1095 == 0)
m.c1091 = Constraint(expr=-0.5*(m.x1699/m.x2103 + m.x1698/m.x2102)*m.x1810 - m.x1095 + m.x1096 == 0)
m.c1092 = Constraint(expr=-0.5*(m.x1700/m.x2104 + m.x1699/m.x2103)*m.x1810 - m.x1096 + m.x1097 == 0)
m.c1093 = Constraint(expr=-0.5*(m.x1701/m.x2105 + m.x1700/m.x2104)*m.x1810 - m.x1097 + m.x1098 == 0)
m.c1094 = Constraint(expr=-0.5*(m.x1702/m.x2106 + m.x1701/m.x2105)*m.x1810 - m.x1098 + m.x1099 == 0)
m.c1095 = Constraint(expr=-0.5*(m.x1703/m.x2107 + m.x1702/m.x2106)*m.x1810 - m.x1099 + m.x1100 == 0)
m.c1096 = Constraint(expr=-0.5*(m.x1704/m.x2108 + m.x1703/m.x2107)*m.x1810 - m.x1100 + m.x1101 == 0)
m.c1097 = Constraint(expr=-0.5*(m.x1705/m.x2109 + m.x1704/m.x2108)*m.x1810 - m.x1101 + m.x1102 == 0)
m.c1098 = Constraint(expr=-0.5*(m.x1706/m.x2110 + m.x1705/m.x2109)*m.x1810 - m.x1102 + m.x1103 == 0)
m.c1099 = Constraint(expr=-0.5*(m.x1707/m.x2111 + m.x1706/m.x2110)*m.x1810 - m.x1103 + m.x1104 == 0)
m.c1100 = Constraint(expr=-0.5*(m.x1708/m.x2112 + m.x1707/m.x2111)*m.x1810 - m.x1104 + m.x1105 == 0)
m.c1101 = Constraint(expr=-0.5*(m.x1709/m.x2113 + m.x1708/m.x2112)*m.x1810 - m.x1105 + m.x1106 == 0)
m.c1102 = Constraint(expr=-0.5*(m.x1710/m.x2114 + m.x1709/m.x2113)*m.x1810 - m.x1106 + m.x1107 == 0)
m.c1103 = Constraint(expr=-0.5*(m.x1711/m.x2115 + m.x1710/m.x2114)*m.x1810 - m.x1107 + m.x1108 == 0)
m.c1104 = Constraint(expr=-0.5*(m.x1712/m.x2116 + m.x1711/m.x2115)*m.x1810 - m.x1108 + m.x1109 == 0)
m.c1105 = Constraint(expr=-0.5*(m.x1713/m.x2117 + m.x1712/m.x2116)*m.x1810 - m.x1109 + m.x1110 == 0)
m.c1106 = Constraint(expr=-0.5*(m.x1714/m.x2118 + m.x1713/m.x2117)*m.x1810 - m.x1110 + m.x1111 == 0)
m.c1107 = Constraint(expr=-0.5*(m.x1715/m.x2119 + m.x1714/m.x2118)*m.x1810 - m.x1111 + m.x1112 == 0)
m.c1108 = Constraint(expr=-0.5*(m.x1716/m.x2120 + m.x1715/m.x2119)*m.x1810 - m.x1112 + m.x1113 == 0)
m.c1109 = Constraint(expr=-0.5*(m.x1717/m.x2121 + m.x1716/m.x2120)*m.x1810 - m.x1113 + m.x1114 == 0)
m.c1110 = Constraint(expr=-0.5*(m.x1718/m.x2122 + m.x1717/m.x2121)*m.x1810 - m.x1114 + m.x1115 == 0)
m.c1111 = Constraint(expr=-0.5*(m.x1719/m.x2123 + m.x1718/m.x2122)*m.x1810 - m.x1115 + m.x1116 == 0)
m.c1112 = Constraint(expr=-0.5*(m.x1720/m.x2124 + m.x1719/m.x2123)*m.x1810 - m.x1116 + m.x1117 == 0)
m.c1113 = Constraint(expr=-0.5*(m.x1721/m.x2125 + m.x1720/m.x2124)*m.x1810 - m.x1117 + m.x1118 == 0)
m.c1114 = Constraint(expr=-0.5*(m.x1722/m.x2126 + m.x1721/m.x2125)*m.x1810 - m.x1118 + m.x1119 == 0)
m.c1115 = Constraint(expr=-0.5*(m.x1723/m.x2127 + m.x1722/m.x2126)*m.x1810 - m.x1119 + m.x1120 == 0)
m.c1116 = Constraint(expr=-0.5*(m.x1724/m.x2128 + m.x1723/m.x2127)*m.x1810 - m.x1120 + m.x1121 == 0)
m.c1117 = Constraint(expr=-0.5*(m.x1725/m.x2129 + m.x1724/m.x2128)*m.x1810 - m.x1121 + m.x1122 == 0)
m.c1118 = Constraint(expr=-0.5*(m.x1726/m.x2130 + m.x1725/m.x2129)*m.x1810 - m.x1122 + m.x1123 == 0)
m.c1119 = Constraint(expr=-0.5*(m.x1727/m.x2131 + m.x1726/m.x2130)*m.x1810 - m.x1123 + m.x1124 == 0)
m.c1120 = Constraint(expr=-0.5*(m.x1728/m.x2132 + m.x1727/m.x2131)*m.x1810 - m.x1124 + m.x1125 == 0)
m.c1121 = Constraint(expr=-0.5*(m.x1729/m.x2133 + m.x1728/m.x2132)*m.x1810 - m.x1125 + m.x1126 == 0)
m.c1122 = Constraint(expr=-0.5*(m.x1730/m.x2134 + m.x1729/m.x2133)*m.x1810 - m.x1126 + m.x1127 == 0)
m.c1123 = Constraint(expr=-0.5*(m.x1731/m.x2135 + m.x1730/m.x2134)*m.x1810 - m.x1127 + m.x1128 == 0)
m.c1124 = Constraint(expr=-0.5*(m.x1732/m.x2136 + m.x1731/m.x2135)*m.x1810 - m.x1128 + m.x1129 == 0)
m.c1125 = Constraint(expr=-0.5*(m.x1733/m.x2137 + m.x1732/m.x2136)*m.x1810 - m.x1129 + m.x1130 == 0)
m.c1126 = Constraint(expr=-0.5*(m.x1734/m.x2138 + m.x1733/m.x2137)*m.x1810 - m.x1130 + m.x1131 == 0)
m.c1127 = Constraint(expr=-0.5*(m.x1735/m.x2139 + m.x1734/m.x2138)*m.x1810 - m.x1131 + m.x1132 == 0)
m.c1128 = Constraint(expr=-0.5*(m.x1736/m.x2140 + m.x1735/m.x2139)*m.x1810 - m.x1132 + m.x1133 == 0)
m.c1129 = Constraint(expr=-0.5*(m.x1737/m.x2141 + m.x1736/m.x2140)*m.x1810 - m.x1133 + m.x1134 == 0)
m.c1130 = Constraint(expr=-0.5*(m.x1738/m.x2142 + m.x1737/m.x2141)*m.x1810 - m.x1134 + m.x1135 == 0)
m.c1131 = Constraint(expr=-0.5*(m.x1739/m.x2143 + m.x1738/m.x2142)*m.x1810 - m.x1135 + m.x1136 == 0)
m.c1132 = Constraint(expr=-0.5*(m.x1740/m.x2144 + m.x1739/m.x2143)*m.x1810 - m.x1136 + m.x1137 == 0)
m.c1133 = Constraint(expr=-0.5*(m.x1741/m.x2145 + m.x1740/m.x2144)*m.x1810 - m.x1137 + m.x1138 == 0)
m.c1134 = Constraint(expr=-0.5*(m.x1742/m.x2146 + m.x1741/m.x2145)*m.x1810 - m.x1138 + m.x1139 == 0)
m.c1135 = Constraint(expr=-0.5*(m.x1743/m.x2147 + m.x1742/m.x2146)*m.x1810 - m.x1139 + m.x1140 == 0)
m.c1136 = Constraint(expr=-0.5*(m.x1744/m.x2148 + m.x1743/m.x2147)*m.x1810 - m.x1140 + m.x1141 == 0)
m.c1137 = Constraint(expr=-0.5*(m.x1745/m.x2149 + m.x1744/m.x2148)*m.x1810 - m.x1141 + m.x1142 == 0)
m.c1138 = Constraint(expr=-0.5*(m.x1746/m.x2150 + m.x1745/m.x2149)*m.x1810 - m.x1142 + m.x1143 == 0)
m.c1139 = Constraint(expr=-0.5*(m.x1747/m.x2151 + m.x1746/m.x2150)*m.x1810 - m.x1143 + m.x1144 == 0)
m.c1140 = Constraint(expr=-0.5*(m.x1748/m.x2152 + m.x1747/m.x2151)*m.x1810 - m.x1144 + m.x1145 == 0)
m.c1141 = Constraint(expr=-0.5*(m.x1749/m.x2153 + m.x1748/m.x2152)*m.x1810 - m.x1145 + m.x1146 == 0)
m.c1142 = Constraint(expr=-0.5*(m.x1750/m.x2154 + m.x1749/m.x2153)*m.x1810 - m.x1146 + m.x1147 == 0)
m.c1143 = Constraint(expr=-0.5*(m.x1751/m.x2155 + m.x1750/m.x2154)*m.x1810 - m.x1147 + m.x1148 == 0)
m.c1144 = Constraint(expr=-0.5*(m.x1752/m.x2156 + m.x1751/m.x2155)*m.x1810 - m.x1148 + m.x1149 == 0)
m.c1145 = Constraint(expr=-0.5*(m.x1753/m.x2157 + m.x1752/m.x2156)*m.x1810 - m.x1149 + m.x1150 == 0)
m.c1146 = Constraint(expr=-0.5*(m.x1754/m.x2158 + m.x1753/m.x2157)*m.x1810 - m.x1150 + m.x1151 == 0)
m.c1147 = Constraint(expr=-0.5*(m.x1755/m.x2159 + m.x1754/m.x2158)*m.x1810 - m.x1151 + m.x1152 == 0)
m.c1148 = Constraint(expr=-0.5*(m.x1756/m.x2160 + m.x1755/m.x2159)*m.x1810 - m.x1152 + m.x1153 == 0)
m.c1149 = Constraint(expr=-0.5*(m.x1757/m.x2161 + m.x1756/m.x2160)*m.x1810 - m.x1153 + m.x1154 == 0)
m.c1150 = Constraint(expr=-0.5*(m.x1758/m.x2162 + m.x1757/m.x2161)*m.x1810 - m.x1154 + m.x1155 == 0)
m.c1151 = Constraint(expr=-0.5*(m.x1759/m.x2163 + m.x1758/m.x2162)*m.x1810 - m.x1155 + m.x1156 == 0)
m.c1152 = Constraint(expr=-0.5*(m.x1760/m.x2164 + m.x1759/m.x2163)*m.x1810 - m.x1156 + m.x1157 == 0)
m.c1153 = Constraint(expr=-0.5*(m.x1761/m.x2165 + m.x1760/m.x2164)*m.x1810 - m.x1157 + m.x1158 == 0)
m.c1154 = Constraint(expr=-0.5*(m.x1762/m.x2166 + m.x1761/m.x2165)*m.x1810 - m.x1158 + m.x1159 == 0)
m.c1155 = Constraint(expr=-0.5*(m.x1763/m.x2167 + m.x1762/m.x2166)*m.x1810 - m.x1159 + m.x1160 == 0)
m.c1156 = Constraint(expr=-0.5*(m.x1764/m.x2168 + m.x1763/m.x2167)*m.x1810 - m.x1160 + m.x1161 == 0)
m.c1157 = Constraint(expr=-0.5*(m.x1765/m.x2169 + m.x1764/m.x2168)*m.x1810 - m.x1161 + m.x1162 == 0)
m.c1158 = Constraint(expr=-0.5*(m.x1766/m.x2170 + m.x1765/m.x2169)*m.x1810 - m.x1162 + m.x1163 == 0)
m.c1159 = Constraint(expr=-0.5*(m.x1767/m.x2171 + m.x1766/m.x2170)*m.x1810 - m.x1163 + m.x1164 == 0)
m.c1160 = Constraint(expr=-0.5*(m.x1768/m.x2172 + m.x1767/m.x2171)*m.x1810 - m.x1164 + m.x1165 == 0)
m.c1161 = Constraint(expr=-0.5*(m.x1769/m.x2173 + m.x1768/m.x2172)*m.x1810 - m.x1165 + m.x1166 == 0)
m.c1162 = Constraint(expr=-0.5*(m.x1770/m.x2174 + m.x1769/m.x2173)*m.x1810 - m.x1166 + m.x1167 == 0)
m.c1163 = Constraint(expr=-0.5*(m.x1771/m.x2175 + m.x1770/m.x2174)*m.x1810 - m.x1167 + m.x1168 == 0)
m.c1164 = Constraint(expr=-0.5*(m.x1772/m.x2176 + m.x1771/m.x2175)*m.x1810 - m.x1168 + m.x1169 == 0)
m.c1165 = Constraint(expr=-0.5*(m.x1773/m.x2177 + m.x1772/m.x2176)*m.x1810 - m.x1169 + m.x1170 == 0)
m.c1166 = Constraint(expr=-0.5*(m.x1774/m.x2178 + m.x1773/m.x2177)*m.x1810 - m.x1170 + m.x1171 == 0)
m.c1167 = Constraint(expr=-0.5*(m.x1775/m.x2179 + m.x1774/m.x2178)*m.x1810 - m.x1171 + m.x1172 == 0)
m.c1168 = Constraint(expr=-0.5*(m.x1776/m.x2180 + m.x1775/m.x2179)*m.x1810 - m.x1172 + m.x1173 == 0)
m.c1169 = Constraint(expr=-0.5*(m.x1777/m.x2181 + m.x1776/m.x2180)*m.x1810 - m.x1173 + m.x1174 == 0)
m.c1170 = Constraint(expr=-0.5*(m.x1778/m.x2182 + m.x1777/m.x2181)*m.x1810 - m.x1174 + m.x1175 == 0)
m.c1171 = Constraint(expr=-0.5*(m.x1779/m.x2183 + m.x1778/m.x2182)*m.x1810 - m.x1175 + m.x1176 == 0)
m.c1172 = Constraint(expr=-0.5*(m.x1780/m.x2184 + m.x1779/m.x2183)*m.x1810 - m.x1176 + m.x1177 == 0)
m.c1173 = Constraint(expr=-0.5*(m.x1781/m.x2185 + m.x1780/m.x2184)*m.x1810 - m.x1177 + m.x1178 == 0)
m.c1174 = Constraint(expr=-0.5*(m.x1782/m.x2186 + m.x1781/m.x2185)*m.x1810 - m.x1178 + m.x1179 == 0)
m.c1175 = Constraint(expr=-0.5*(m.x1783/m.x2187 + m.x1782/m.x2186)*m.x1810 - m.x1179 + m.x1180 == 0)
m.c1176 = Constraint(expr=-0.5*(m.x1784/m.x2188 + m.x1783/m.x2187)*m.x1810 - m.x1180 + m.x1181 == 0)
m.c1177 = Constraint(expr=-0.5*(m.x1785/m.x2189 + m.x1784/m.x2188)*m.x1810 - m.x1181 + m.x1182 == 0)
m.c1178 = Constraint(expr=-0.5*(m.x1786/m.x2190 + m.x1785/m.x2189)*m.x1810 - m.x1182 + m.x1183 == 0)
m.c1179 = Constraint(expr=-0.5*(m.x1787/m.x2191 + m.x1786/m.x2190)*m.x1810 - m.x1183 + m.x1184 == 0)
m.c1180 = Constraint(expr=-0.5*(m.x1788/m.x2192 + m.x1787/m.x2191)*m.x1810 - m.x1184 + m.x1185 == 0)
m.c1181 = Constraint(expr=-0.5*(m.x1789/m.x2193 + m.x1788/m.x2192)*m.x1810 - m.x1185 + m.x1186 == 0)
m.c1182 = Constraint(expr=-0.5*(m.x1790/m.x2194 + m.x1789/m.x2193)*m.x1810 - m.x1186 + m.x1187 == 0)
m.c1183 = Constraint(expr=-0.5*(m.x1791/m.x2195 + m.x1790/m.x2194)*m.x1810 - m.x1187 + m.x1188 == 0)
m.c1184 = Constraint(expr=-0.5*(m.x1792/m.x2196 + m.x1791/m.x2195)*m.x1810 - m.x1188 + m.x1189 == 0)
m.c1185 = Constraint(expr=-0.5*(m.x1793/m.x2197 + m.x1792/m.x2196)*m.x1810 - m.x1189 + m.x1190 == 0)
m.c1186 = Constraint(expr=-0.5*(m.x1794/m.x2198 + m.x1793/m.x2197)*m.x1810 - m.x1190 + m.x1191 == 0)
m.c1187 = Constraint(expr=-0.5*(m.x1795/m.x2199 + m.x1794/m.x2198)*m.x1810 - m.x1191 + m.x1192 == 0)
m.c1188 = Constraint(expr=-0.5*(m.x1796/m.x2200 + m.x1795/m.x2199)*m.x1810 - m.x1192 + m.x1193 == 0)
m.c1189 = Constraint(expr=-0.5*(m.x1797/m.x2201 + m.x1796/m.x2200)*m.x1810 - m.x1193 + m.x1194 == 0)
m.c1190 = Constraint(expr=-0.5*(m.x1798/m.x2202 + m.x1797/m.x2201)*m.x1810 - m.x1194 + m.x1195 == 0)
m.c1191 = Constraint(expr=-0.5*(m.x1799/m.x2203 + m.x1798/m.x2202)*m.x1810 - m.x1195 + m.x1196 == 0)
m.c1192 = Constraint(expr=-0.5*(m.x1800/m.x2204 + m.x1799/m.x2203)*m.x1810 - m.x1196 + m.x1197 == 0)
m.c1193 = Constraint(expr=-0.5*(m.x1801/m.x2205 + m.x1800/m.x2204)*m.x1810 - m.x1197 + m.x1198 == 0)
m.c1194 = Constraint(expr=-0.5*(m.x1802/m.x2206 + m.x1801/m.x2205)*m.x1810 - m.x1198 + m.x1199 == 0)
m.c1195 = Constraint(expr=-0.5*(m.x1803/m.x2207 + m.x1802/m.x2206)*m.x1810 - m.x1199 + m.x1200 == 0)
m.c1196 = Constraint(expr=-0.5*(m.x1804/m.x2208 + m.x1803/m.x2207)*m.x1810 - m.x1200 + m.x1201 == 0)
m.c1197 = Constraint(expr=-0.5*(m.x1805/m.x2209 + m.x1804/m.x2208)*m.x1810 - m.x1201 + m.x1202 == 0)
m.c1198 = Constraint(expr=-0.5*(m.x1806/m.x2210 + m.x1805/m.x2209)*m.x1810 - m.x1202 + m.x1203 == 0)
m.c1199 = Constraint(expr=-0.5*(m.x1807/m.x2211 + m.x1806/m.x2210)*m.x1810 - m.x1203 + m.x1204 == 0)
m.c1200 = Constraint(expr=-0.5*(m.x1808/m.x2212 + m.x1807/m.x2211)*m.x1810 - m.x1204 + m.x1205 == 0)
m.c1201 = Constraint(expr=-0.5*(m.x1809/m.x2213 + m.x1808/m.x2212)*m.x1810 - m.x1205 + m.x1206 == 0)
m.c1202 = Constraint(expr=-sin(m.x403)**2*m.x2013 + m.x1812 == 0)
m.c1203 = Constraint(expr=-sin(m.x404)**2*m.x2014 + m.x1813 == 0)
m.c1204 = Constraint(expr=-sin(m.x405)**2*m.x2015 + m.x1814 == 0)
m.c1205 = Constraint(expr=-sin(m.x406)**2*m.x2016 + m.x1815 == 0)
m.c1206 = Constraint(expr=-sin(m.x407)**2*m.x2017 + m.x1816 == 0)
m.c1207 = Constraint(expr=-sin(m.x408)**2*m.x2018 + m.x1817 == 0)
m.c1208 = Constraint(expr=-sin(m.x409)**2*m.x2019 + m.x1818 == 0)
m.c1209 = Constraint(expr=-sin(m.x410)**2*m.x2020 + m.x1819 == 0)
m.c1210 = Constraint(expr=-sin(m.x411)**2*m.x2021 + m.x1820 == 0)
m.c1211 = Constraint(expr=-sin(m.x412)**2*m.x2022 + m.x1821 == 0)
m.c1212 = Constraint(expr=-sin(m.x413)**2*m.x2023 + m.x1822 == 0)
m.c1213 = Constraint(expr=-sin(m.x414)**2*m.x2024 + m.x1823 == 0)
m.c1214 = Constraint(expr=-sin(m.x415)**2*m.x2025 + m.x1824 == 0)
m.c1215 = Constraint(expr=-sin(m.x416)**2*m.x2026 + m.x1825 == 0)
m.c1216 = Constraint(expr=-sin(m.x417)**2*m.x2027 + m.x1826 == 0)
m.c1217 = Constraint(expr=-sin(m.x418)**2*m.x2028 + m.x1827 == 0)
m.c1218 = Constraint(expr=-sin(m.x419)**2*m.x2029 + m.x1828 == 0)
m.c1219 = Constraint(expr=-sin(m.x420)**2*m.x2030 + m.x1829 == 0)
m.c1220 = Constraint(expr=-sin(m.x421)**2*m.x2031 + m.x1830 == 0)
m.c1221 = Constraint(expr=-sin(m.x422)**2*m.x2032 + m.x1831 == 0)
m.c1222 = Constraint(expr=-sin(m.x423)**2*m.x2033 + m.x1832 == 0)
m.c1223 = Constraint(expr=-sin(m.x424)**2*m.x2034 + m.x1833 == 0)
m.c1224 = Constraint(expr=-sin(m.x425)**2*m.x2035 + m.x1834 == 0)
m.c1225 = Constraint(expr=-sin(m.x426)**2*m.x2036 + m.x1835 == 0)
m.c1226 = Constraint(expr=-sin(m.x427)**2*m.x2037 + m.x1836 == 0)
m.c1227 = Constraint(expr=-sin(m.x428)**2*m.x2038 + m.x1837 == 0)
m.c1228 = Constraint(expr=-sin(m.x429)**2*m.x2039 + m.x1838 == 0)
m.c1229 = Constraint(expr=-sin(m.x430)**2*m.x2040 + m.x1839 == 0)
m.c1230 = Constraint(expr=-sin(m.x431)**2*m.x2041 + m.x1840 == 0)
m.c1231 = Constraint(expr=-sin(m.x432)**2*m.x2042 + m.x1841 == 0)
m.c1232 = Constraint(expr=-sin(m.x433)**2*m.x2043 + m.x1842 == 0)
m.c1233 = Constraint(expr=-sin(m.x434)**2*m.x2044 + m.x1843 == 0)
m.c1234 = Constraint(expr=-sin(m.x435)**2*m.x2045 + m.x1844 == 0)
m.c1235 = Constraint(expr=-sin(m.x436)**2*m.x2046 + m.x1845 == 0)
m.c1236 = Constraint(expr=-sin(m.x437)**2*m.x2047 + m.x1846 == 0)
m.c1237 = Constraint(expr=-sin(m.x438)**2*m.x2048 + m.x1847 == 0)
m.c1238 = Constraint(expr=-sin(m.x439)**2*m.x2049 + m.x1848 == 0)
m.c1239 = Constraint(expr=-sin(m.x440)**2*m.x2050 + m.x1849 == 0)
m.c1240 = Constraint(expr=-sin(m.x441)**2*m.x2051 + m.x1850 == 0)
m.c1241 = Constraint(expr=-sin(m.x442)**2*m.x2052 + m.x1851 == 0)
m.c1242 = Constraint(expr=-sin(m.x443)**2*m.x2053 + m.x1852 == 0)
m.c1243 = Constraint(expr=-sin(m.x444)**2*m.x2054 + m.x1853 == 0)
m.c1244 = Constraint(expr=-sin(m.x445)**2*m.x2055 + m.x1854 == 0)
m.c1245 = Constraint(expr=-sin(m.x446)**2*m.x2056 + m.x1855 == 0)
m.c1246 = Constraint(expr=-sin(m.x447)**2*m.x2057 + m.x1856 == 0)
m.c1247 = Constraint(expr=-sin(m.x448)**2*m.x2058 + m.x1857 == 0)
m.c1248 = Constraint(expr=-sin(m.x449)**2*m.x2059 + m.x1858 == 0)
m.c1249 = Constraint(expr=-sin(m.x450)**2*m.x2060 + m.x1859 == 0)
m.c1250 = Constraint(expr=-sin(m.x451)**2*m.x2061 + m.x1860 == 0)
m.c1251 = Constraint(expr=-sin(m.x452)**2*m.x2062 + m.x1861 == 0)
m.c1252 = Constraint(expr=-sin(m.x453)**2*m.x2063 + m.x1862 == 0)
m.c1253 = Constraint(expr=-sin(m.x454)**2*m.x2064 + m.x1863 == 0)
m.c1254 = Constraint(expr=-sin(m.x455)**2*m.x2065 + m.x1864 == 0)
m.c1255 = Constraint(expr=-sin(m.x456)**2*m.x2066 + m.x1865 == 0)
m.c1256 = Constraint(expr=-sin(m.x457)**2*m.x2067 + m.x1866 == 0)
m.c1257 = Constraint(expr=-sin(m.x458)**2*m.x2068 + m.x1867 == 0)
m.c1258 = Constraint(expr=-sin(m.x459)**2*m.x2069 + m.x1868 == 0)
m.c1259 = Constraint(expr=-sin(m.x460)**2*m.x2070 + m.x1869 == 0)
m.c1260 = Constraint(expr=-sin(m.x461)**2*m.x2071 + m.x1870 == 0)
m.c1261 = Constraint(expr=-sin(m.x462)**2*m.x2072 + m.x1871 == 0)
m.c1262 = Constraint(expr=-sin(m.x463)**2*m.x2073 + m.x1872 == 0)
m.c1263 = Constraint(expr=-sin(m.x464)**2*m.x2074 + m.x1873 == 0)
m.c1264 = Constraint(expr=-sin(m.x465)**2*m.x2075 + m.x1874 == 0)
m.c1265 = Constraint(expr=-sin(m.x466)**2*m.x2076 + m.x1875 == 0)
m.c1266 = Constraint(expr=-sin(m.x467)**2*m.x2077 + m.x1876 == 0)
m.c1267 = Constraint(expr=-sin(m.x468)**2*m.x2078 + m.x1877 == 0)
m.c1268 = Constraint(expr=-sin(m.x469)**2*m.x2079 + m.x1878 == 0)
m.c1269 = Constraint(expr=-sin(m.x470)**2*m.x2080 + m.x1879 == 0)
m.c1270 = Constraint(expr=-sin(m.x471)**2*m.x2081 + m.x1880 == 0)
m.c1271 = Constraint(expr=-sin(m.x472)**2*m.x2082 + m.x1881 == 0)
m.c1272 = Constraint(expr=-sin(m.x473)**2*m.x2083 + m.x1882 == 0)
m.c1273 = Constraint(expr=-sin(m.x474)**2*m.x2084 + m.x1883 == 0)
m.c1274 = Constraint(expr=-sin(m.x475)**2*m.x2085 + m.x1884 == 0)
m.c1275 = Constraint(expr=-sin(m.x476)**2*m.x2086 + m.x1885 == 0)
m.c1276 = Constraint(expr=-sin(m.x477)**2*m.x2087 + m.x1886 == 0)
m.c1277 = Constraint(expr=-sin(m.x478)**2*m.x2088 + m.x1887 == 0)
m.c1278 = Constraint(expr=-sin(m.x479)**2*m.x2089 + m.x1888 == 0)
m.c1279 = Constraint(expr=-sin(m.x480)**2*m.x2090 + m.x1889 == 0)
m.c1280 = Constraint(expr=-sin(m.x481)**2*m.x2091 + m.x1890 == 0)
m.c1281 = Constraint(expr=-sin(m.x482)**2*m.x2092 + m.x1891 == 0)
m.c1282 = Constraint(expr=-sin(m.x483)**2*m.x2093 + m.x1892 == 0)
m.c1283 = Constraint(expr=-sin(m.x484)**2*m.x2094 + m.x1893 == 0)
m.c1284 = Constraint(expr=-sin(m.x485)**2*m.x2095 + m.x1894 == 0)
m.c1285 = Constraint(expr=-sin(m.x486)**2*m.x2096 + m.x1895 == 0)
m.c1286 = Constraint(expr=-sin(m.x487)**2*m.x2097 + m.x1896 == 0)
m.c1287 = Constraint(expr=-sin(m.x488)**2*m.x2098 + m.x1897 == 0)
m.c1288 = Constraint(expr=-sin(m.x489)**2*m.x2099 + m.x1898 == 0)
m.c1289 = Constraint(expr=-sin(m.x490)**2*m.x2100 + m.x1899 == 0)
m.c1290 = Constraint(expr=-sin(m.x491)**2*m.x2101 + m.x1900 == 0)
m.c1291 = Constraint(expr=-sin(m.x492)**2*m.x2102 + m.x1901 == 0)
m.c1292 = Constraint(expr=-sin(m.x493)**2*m.x2103 + m.x1902 == 0)
m.c1293 = Constraint(expr=-sin(m.x494)**2*m.x2104 + m.x1903 == 0)
m.c1294 = Constraint(expr=-sin(m.x495)**2*m.x2105 + m.x1904 == 0)
m.c1295 = Constraint(expr=-sin(m.x496)**2*m.x2106 + m.x1905 == 0)
m.c1296 = Constraint(expr=-sin(m.x497)**2*m.x2107 + m.x1906 == 0)
m.c1297 = Constraint(expr=-sin(m.x498)**2*m.x2108 + m.x1907 == 0)
m.c1298 = Constraint(expr=-sin(m.x499)**2*m.x2109 + m.x1908 == 0)
m.c1299 = Constraint(expr=-sin(m.x500)**2*m.x2110 + m.x1909 == 0)
m.c1300 = Constraint(expr=-sin(m.x501)**2*m.x2111 + m.x1910 == 0)
m.c1301 = Constraint(expr=-sin(m.x502)**2*m.x2112 + m.x1911 == 0)
m.c1302 = Constraint(expr=-sin(m.x503)**2*m.x2113 + m.x1912 == 0)
m.c1303 = Constraint(expr=-sin(m.x504)**2*m.x2114 + m.x1913 == 0)
m.c1304 = Constraint(expr=-sin(m.x505)**2*m.x2115 + m.x1914 == 0)
m.c1305 = Constraint(expr=-sin(m.x506)**2*m.x2116 + m.x1915 == 0)
m.c1306 = Constraint(expr=-sin(m.x507)**2*m.x2117 + m.x1916 == 0)
m.c1307 = Constraint(expr=-sin(m.x508)**2*m.x2118 + m.x1917 == 0)
m.c1308 = Constraint(expr=-sin(m.x509)**2*m.x2119 + m.x1918 == 0)
m.c1309 = Constraint(expr=-sin(m.x510)**2*m.x2120 + m.x1919 == 0)
m.c1310 = Constraint(expr=-sin(m.x511)**2*m.x2121 + m.x1920 == 0)
m.c1311 = Constraint(expr=-sin(m.x512)**2*m.x2122 + m.x1921 == 0)
m.c1312 = Constraint(expr=-sin(m.x513)**2*m.x2123 + m.x1922 == 0)
m.c1313 = Constraint(expr=-sin(m.x514)**2*m.x2124 + m.x1923 == 0)
m.c1314 = Constraint(expr=-sin(m.x515)**2*m.x2125 + m.x1924 == 0)
m.c1315 = Constraint(expr=-sin(m.x516)**2*m.x2126 + m.x1925 == 0)
m.c1316 = Constraint(expr=-sin(m.x517)**2*m.x2127 + m.x1926 == 0)
m.c1317 = Constraint(expr=-sin(m.x518)**2*m.x2128 + m.x1927 == 0)
m.c1318 = Constraint(expr=-sin(m.x519)**2*m.x2129 + m.x1928 == 0)
m.c1319 = Constraint(expr=-sin(m.x520)**2*m.x2130 + m.x1929 == 0)
m.c1320 = Constraint(expr=-sin(m.x521)**2*m.x2131 + m.x1930 == 0)
m.c1321 = Constraint(expr=-sin(m.x522)**2*m.x2132 + m.x1931 == 0)
m.c1322 = Constraint(expr=-sin(m.x523)**2*m.x2133 + m.x1932 == 0)
m.c1323 = Constraint(expr=-sin(m.x524)**2*m.x2134 + m.x1933 == 0)
m.c1324 = Constraint(expr=-sin(m.x525)**2*m.x2135 + m.x1934 == 0)
m.c1325 = Constraint(expr=-sin(m.x526)**2*m.x2136 + m.x1935 == 0)
m.c1326 = Constraint(expr=-sin(m.x527)**2*m.x2137 + m.x1936 == 0)
m.c1327 = Constraint(expr=-sin(m.x528)**2*m.x2138 + m.x1937 == 0)
m.c1328 = Constraint(expr=-sin(m.x529)**2*m.x2139 + m.x1938 == 0)
m.c1329 = Constraint(expr=-sin(m.x530)**2*m.x2140 + m.x1939 == 0)
m.c1330 = Constraint(expr=-sin(m.x531)**2*m.x2141 + m.x1940 == 0)
m.c1331 = Constraint(expr=-sin(m.x532)**2*m.x2142 + m.x1941 == 0)
m.c1332 = Constraint(expr=-sin(m.x533)**2*m.x2143 + m.x1942 == 0)
m.c1333 = Constraint(expr=-sin(m.x534)**2*m.x2144 + m.x1943 == 0)
m.c1334 = Constraint(expr=-sin(m.x535)**2*m.x2145 + m.x1944 == 0)
m.c1335 = Constraint(expr=-sin(m.x536)**2*m.x2146 + m.x1945 == 0)
m.c1336 = Constraint(expr=-sin(m.x537)**2*m.x2147 + m.x1946 == 0)
m.c1337 = Constraint(expr=-sin(m.x538)**2*m.x2148 + m.x1947 == 0)
m.c1338 = Constraint(expr=-sin(m.x539)**2*m.x2149 + m.x1948 == 0)
m.c1339 = Constraint(expr=-sin(m.x540)**2*m.x2150 + m.x1949 == 0)
m.c1340 = Constraint(expr=-sin(m.x541)**2*m.x2151 + m.x1950 == 0)
m.c1341 = Constraint(expr=-sin(m.x542)**2*m.x2152 + m.x1951 == 0)
m.c1342 = Constraint(expr=-sin(m.x543)**2*m.x2153 + m.x1952 == 0)
m.c1343 = Constraint(expr=-sin(m.x544)**2*m.x2154 + m.x1953 == 0)
m.c1344 = Constraint(expr=-sin(m.x545)**2*m.x2155 + m.x1954 == 0)
m.c1345 = Constraint(expr=-sin(m.x546)**2*m.x2156 + m.x1955 == 0)
m.c1346 = Constraint(expr=-sin(m.x547)**2*m.x2157 + m.x1956 == 0)
m.c1347 = Constraint(expr=-sin(m.x548)**2*m.x2158 + m.x1957 == 0)
m.c1348 = Constraint(expr=-sin(m.x549)**2*m.x2159 + m.x1958 == 0)
m.c1349 = Constraint(expr=-sin(m.x550)**2*m.x2160 + m.x1959 == 0)
m.c1350 = Constraint(expr=-sin(m.x551)**2*m.x2161 + m.x1960 == 0)
m.c1351 = Constraint(expr=-sin(m.x552)**2*m.x2162 + m.x1961 == 0)
m.c1352 = Constraint(expr=-sin(m.x553)**2*m.x2163 + m.x1962 == 0)
m.c1353 = Constraint(expr=-sin(m.x554)**2*m.x2164 + m.x1963 == 0)
m.c1354 = Constraint(expr=-sin(m.x555)**2*m.x2165 + m.x1964 == 0)
m.c1355 = Constraint(expr=-sin(m.x556)**2*m.x2166 + m.x1965 == 0)
m.c1356 = Constraint(expr=-sin(m.x557)**2*m.x2167 + m.x1966 == 0)
m.c1357 = Constraint(expr=-sin(m.x558)**2*m.x2168 + m.x1967 == 0)
m.c1358 = Constraint(expr=-sin(m.x559)**2*m.x2169 + m.x1968 == 0)
m.c1359 = Constraint(expr=-sin(m.x560)**2*m.x2170 + m.x1969 == 0)
m.c1360 = Constraint(expr=-sin(m.x561)**2*m.x2171 + m.x1970 == 0)
m.c1361 = Constraint(expr=-sin(m.x562)**2*m.x2172 + m.x1971 == 0)
m.c1362 = Constraint(expr=-sin(m.x563)**2*m.x2173 + m.x1972 == 0)
m.c1363 = Constraint(expr=-sin(m.x564)**2*m.x2174 + m.x1973 == 0)
m.c1364 = Constraint(expr=-sin(m.x565)**2*m.x2175 + m.x1974 == 0)
m.c1365 = Constraint(expr=-sin(m.x566)**2*m.x2176 + m.x1975 == 0)
m.c1366 = Constraint(expr=-sin(m.x567)**2*m.x2177 + m.x1976 == 0)
m.c1367 = Constraint(expr=-sin(m.x568)**2*m.x2178 + m.x1977 == 0)
m.c1368 = Constraint(expr=-sin(m.x569)**2*m.x2179 + m.x1978 == 0)
m.c1369 = Constraint(expr=-sin(m.x570)**2*m.x2180 + m.x1979 == 0)
m.c1370 = Constraint(expr=-sin(m.x571)**2*m.x2181 + m.x1980 == 0)
m.c1371 = Constraint(expr=-sin(m.x572)**2*m.x2182 + m.x1981 == 0)
m.c1372 = Constraint(expr=-sin(m.x573)**2*m.x2183 + m.x1982 == 0)
m.c1373 = Constraint(expr=-sin(m.x574)**2*m.x2184 + m.x1983 == 0)
m.c1374 = Constraint(expr=-sin(m.x575)**2*m.x2185 + m.x1984 == 0)
m.c1375 = Constraint(expr=-sin(m.x576)**2*m.x2186 + m.x1985 == 0)
m.c1376 = Constraint(expr=-sin(m.x577)**2*m.x2187 + m.x1986 == 0)
m.c1377 = Constraint(expr=-sin(m.x578)**2*m.x2188 + m.x1987 == 0)
m.c1378 = Constraint(expr=-sin(m.x579)**2*m.x2189 + m.x1988 == 0)
m.c1379 = Constraint(expr=-sin(m.x580)**2*m.x2190 + m.x1989 == 0)
m.c1380 = Constraint(expr=-sin(m.x581)**2*m.x2191 + m.x1990 == 0)
m.c1381 = Constraint(expr=-sin(m.x582)**2*m.x2192 + m.x1991 == 0)
m.c1382 = Constraint(expr=-sin(m.x583)**2*m.x2193 + m.x1992 == 0)
m.c1383 = Constraint(expr=-sin(m.x584)**2*m.x2194 + m.x1993 == 0)
m.c1384 = Constraint(expr=-sin(m.x585)**2*m.x2195 + m.x1994 == 0)
m.c1385 = Constraint(expr=-sin(m.x586)**2*m.x2196 + m.x1995 == 0)
m.c1386 = Constraint(expr=-sin(m.x587)**2*m.x2197 + m.x1996 == 0)
m.c1387 = Constraint(expr=-sin(m.x588)**2*m.x2198 + m.x1997 == 0)
m.c1388 = Constraint(expr=-sin(m.x589)**2*m.x2199 + m.x1998 == 0)
m.c1389 = Constraint(expr=-sin(m.x590)**2*m.x2200 + m.x1999 == 0)
m.c1390 = Constraint(expr=-sin(m.x591)**2*m.x2201 + m.x2000 == 0)
m.c1391 = Constraint(expr=-sin(m.x592)**2*m.x2202 + m.x2001 == 0)
m.c1392 = Constraint(expr=-sin(m.x593)**2*m.x2203 + m.x2002 == 0)
m.c1393 = Constraint(expr=-sin(m.x594)**2*m.x2204 + m.x2003 == 0)
m.c1394 = Constraint(expr=-sin(m.x595)**2*m.x2205 + m.x2004 == 0)
m.c1395 = Constraint(expr=-sin(m.x596)**2*m.x2206 + m.x2005 == 0)
m.c1396 = Constraint(expr=-sin(m.x597)**2*m.x2207 + m.x2006 == 0)
m.c1397 = Constraint(expr=-sin(m.x598)**2*m.x2208 + m.x2007 == 0)
m.c1398 = Constraint(expr=-sin(m.x599)**2*m.x2209 + m.x2008 == 0)
m.c1399 = Constraint(expr=-sin(m.x600)**2*m.x2210 + m.x2009 == 0)
m.c1400 = Constraint(expr=-sin(m.x601)**2*m.x2211 + m.x2010 == 0)
m.c1401 = Constraint(expr=-sin(m.x602)**2*m.x2212 + m.x2011 == 0)
m.c1402 = Constraint(expr=-sin(m.x603)**2*m.x2213 + m.x2012 == 0)
m.c1403 = Constraint(expr=-0.333333333333333*((5 - m.x1)**3 + m.x1**3) + m.x2013 == 0)
m.c1404 = Constraint(expr=-0.333333333333333*((5 - m.x2)**3 + m.x2**3) + m.x2014 == 0)
m.c1405 = Constraint(expr=-0.333333333333333*((5 - m.x3)**3 + m.x3**3) + m.x2015 == 0)
m.c1406 = Constraint(expr=-0.333333333333333*((5 - m.x4)**3 + m.x4**3) + m.x2016 == 0)
m.c1407 = Constraint(expr=-0.333333333333333*((5 - m.x5)**3 + m.x5**3) + m.x2017 == 0)
m.c1408 = Constraint(expr=-0.333333333333333*((5 - m.x6)**3 + m.x6**3) + m.x2018 == 0)
m.c1409 = Constraint(expr=-0.333333333333333*((5 - m.x7)**3 + m.x7**3) + m.x2019 == 0)
m.c1410 = Constraint(expr=-0.333333333333333*((5 - m.x8)**3 + m.x8**3) + m.x2020 == 0)
m.c1411 = Constraint(expr=-0.333333333333333*((5 - m.x9)**3 + m.x9**3) + m.x2021 == 0)
m.c1412 = Constraint(expr=-0.333333333333333*((5 - m.x10)**3 + m.x10**3) + m.x2022 == 0)
m.c1413 = Constraint(expr=-0.333333333333333*((5 - m.x11)**3 + m.x11**3) + m.x2023 == 0)
m.c1414 = Constraint(expr=-0.333333333333333*((5 - m.x12)**3 + m.x12**3) + m.x2024 == 0)
m.c1415 = Constraint(expr=-0.333333333333333*((5 - m.x13)**3 + m.x13**3) + m.x2025 == 0)
m.c1416 = Constraint(expr=-0.333333333333333*((5 - m.x14)**3 + m.x14**3) + m.x2026 == 0)
m.c1417 = Constraint(expr=-0.333333333333333*((5 - m.x15)**3 + m.x15**3) + m.x2027 == 0)
m.c1418 = Constraint(expr=-0.333333333333333*((5 - m.x16)**3 + m.x16**3) + m.x2028 == 0)
m.c1419 = Constraint(expr=-0.333333333333333*((5 - m.x17)**3 + m.x17**3) + m.x2029 == 0)
m.c1420 = Constraint(expr=-0.333333333333333*((5 - m.x18)**3 + m.x18**3) + m.x2030 == 0)
m.c1421 = Constraint(expr=-0.333333333333333*((5 - m.x19)**3 + m.x19**3) + m.x2031 == 0)
m.c1422 = Constraint(expr=-0.333333333333333*((5 - m.x20)**3 + m.x20**3) + m.x2032 == 0)
m.c1423 = Constraint(expr=-0.333333333333333*((5 - m.x21)**3 + m.x21**3) + m.x2033 == 0)
m.c1424 = Constraint(expr=-0.333333333333333*((5 - m.x22)**3 + m.x22**3) + m.x2034 == 0)
m.c1425 = Constraint(expr=-0.333333333333333*((5 - m.x23)**3 + m.x23**3) + m.x2035 == 0)
m.c1426 = Constraint(expr=-0.333333333333333*((5 - m.x24)**3 + m.x24**3) + m.x2036 == 0)
m.c1427 = Constraint(expr=-0.333333333333333*((5 - m.x25)**3 + m.x25**3) + m.x2037 == 0)
m.c1428 = Constraint(expr=-0.333333333333333*((5 - m.x26)**3 + m.x26**3) + m.x2038 == 0)
m.c1429 = Constraint(expr=-0.333333333333333*((5 - m.x27)**3 + m.x27**3) + m.x2039 == 0)
m.c1430 = Constraint(expr=-0.333333333333333*((5 - m.x28)**3 + m.x28**3) + m.x2040 == 0)
m.c1431 = Constraint(expr=-0.333333333333333*((5 - m.x29)**3 + m.x29**3) + m.x2041 == 0)
m.c1432 = Constraint(expr=-0.333333333333333*((5 - m.x30)**3 + m.x30**3) + m.x2042 == 0)
m.c1433 = Constraint(expr=-0.333333333333333*((5 - m.x31)**3 + m.x31**3) + m.x2043 == 0)
m.c1434 = Constraint(expr=-0.333333333333333*((5 - m.x32)**3 + m.x32**3) + m.x2044 == 0)
m.c1435 = Constraint(expr=-0.333333333333333*((5 - m.x33)**3 + m.x33**3) + m.x2045 == 0)
m.c1436 = Constraint(expr=-0.333333333333333*((5 - m.x34)**3 + m.x34**3) + m.x2046 == 0)
m.c1437 = Constraint(expr=-0.333333333333333*((5 - m.x35)**3 + m.x35**3) + m.x2047 == 0)
m.c1438 = Constraint(expr=-0.333333333333333*((5 - m.x36)**3 + m.x36**3) + m.x2048 == 0)
m.c1439 = Constraint(expr=-0.333333333333333*((5 - m.x37)**3 + m.x37**3) + m.x2049 == 0)
m.c1440 = Constraint(expr=-0.333333333333333*((5 - m.x38)**3 + m.x38**3) + m.x2050 == 0)
m.c1441 = Constraint(expr=-0.333333333333333*((5 - m.x39)**3 + m.x39**3) + m.x2051 == 0)
m.c1442 = Constraint(expr=-0.333333333333333*((5 - m.x40)**3 + m.x40**3) + m.x2052 == 0)
m.c1443 = Constraint(expr=-0.333333333333333*((5 - m.x41)**3 + m.x41**3) + m.x2053 == 0)
m.c1444 = Constraint(expr=-0.333333333333333*((5 - m.x42)**3 + m.x42**3) + m.x2054 == 0)
m.c1445 = Constraint(expr=-0.333333333333333*((5 - m.x43)**3 + m.x43**3) + m.x2055 == 0)
m.c1446 = Constraint(expr=-0.333333333333333*((5 - m.x44)**3 + m.x44**3) + m.x2056 == 0)
m.c1447 = Constraint(expr=-0.333333333333333*((5 - m.x45)**3 + m.x45**3) + m.x2057 == 0)
m.c1448 = Constraint(expr=-0.333333333333333*((5 - m.x46)**3 + m.x46**3) + m.x2058 == 0)
m.c1449 = Constraint(expr=-0.333333333333333*((5 - m.x47)**3 + m.x47**3) + m.x2059 == 0)
m.c1450 = Constraint(expr=-0.333333333333333*((5 - m.x48)**3 + m.x48**3) + m.x2060 == 0)
m.c1451 = Constraint(expr=-0.333333333333333*((5 - m.x49)**3 + m.x49**3) + m.x2061 == 0)
m.c1452 = Constraint(expr=-0.333333333333333*((5 - m.x50)**3 + m.x50**3) + m.x2062 == 0)
m.c1453 = Constraint(expr=-0.333333333333333*((5 - m.x51)**3 + m.x51**3) + m.x2063 == 0)
m.c1454 = Constraint(expr=-0.333333333333333*((5 - m.x52)**3 + m.x52**3) + m.x2064 == 0)
m.c1455 = Constraint(expr=-0.333333333333333*((5 - m.x53)**3 + m.x53**3) + m.x2065 == 0)
m.c1456 = Constraint(expr=-0.333333333333333*((5 - m.x54)**3 + m.x54**3) + m.x2066 == 0)
m.c1457 = Constraint(expr=-0.333333333333333*((5 - m.x55)**3 + m.x55**3) + m.x2067 == 0)
m.c1458 = Constraint(expr=-0.333333333333333*((5 - m.x56)**3 + m.x56**3) + m.x2068 == 0)
m.c1459 = Constraint(expr=-0.333333333333333*((5 - m.x57)**3 + m.x57**3) + m.x2069 == 0)
m.c1460 = Constraint(expr=-0.333333333333333*((5 - m.x58)**3 + m.x58**3) + m.x2070 == 0)
m.c1461 = Constraint(expr=-0.333333333333333*((5 - m.x59)**3 + m.x59**3) + m.x2071 == 0)
m.c1462 = Constraint(expr=-0.333333333333333*((5 - m.x60)**3 + m.x60**3) + m.x2072 == 0)
m.c1463 = Constraint(expr=-0.333333333333333*((5 - m.x61)**3 + m.x61**3) + m.x2073 == 0)
m.c1464 = Constraint(expr=-0.333333333333333*((5 - m.x62)**3 + m.x62**3) + m.x2074 == 0)
m.c1465 = Constraint(expr=-0.333333333333333*((5 - m.x63)**3 + m.x63**3) + m.x2075 == 0)
m.c1466 = Constraint(expr=-0.333333333333333*((5 - m.x64)**3 + m.x64**3) + m.x2076 == 0)
m.c1467 = Constraint(expr=-0.333333333333333*((5 - m.x65)**3 + m.x65**3) + m.x2077 == 0)
m.c1468 = Constraint(expr=-0.333333333333333*((5 - m.x66)**3 + m.x66**3) + m.x2078 == 0)
m.c1469 = Constraint(expr=-0.333333333333333*((5 - m.x67)**3 + m.x67**3) + m.x2079 == 0)
m.c1470 = Constraint(expr=-0.333333333333333*((5 - m.x68)**3 + m.x68**3) + m.x2080 == 0)
m.c1471 = Constraint(expr=-0.333333333333333*((5 - m.x69)**3 + m.x69**3) + m.x2081 == 0)
m.c1472 = Constraint(expr=-0.333333333333333*((5 - m.x70)**3 + m.x70**3) + m.x2082 == 0)
m.c1473 = Constraint(expr=-0.333333333333333*((5 - m.x71)**3 + m.x71**3) + m.x2083 == 0)
m.c1474 = Constraint(expr=-0.333333333333333*((5 - m.x72)**3 + m.x72**3) + m.x2084 == 0)
m.c1475 = Constraint(expr=-0.333333333333333*((5 - m.x73)**3 + m.x73**3) + m.x2085 == 0)
m.c1476 = Constraint(expr=-0.333333333333333*((5 - m.x74)**3 + m.x74**3) + m.x2086 == 0)
m.c1477 = Constraint(expr=-0.333333333333333*((5 - m.x75)**3 + m.x75**3) + m.x2087 == 0)
m.c1478 = Constraint(expr=-0.333333333333333*((5 - m.x76)**3 + m.x76**3) + m.x2088 == 0)
m.c1479 = Constraint(expr=-0.333333333333333*((5 - m.x77)**3 + m.x77**3) + m.x2089 == 0)
m.c1480 = Constraint(expr=-0.333333333333333*((5 - m.x78)**3 + m.x78**3) + m.x2090 == 0)
m.c1481 = Constraint(expr=-0.333333333333333*((5 - m.x79)**3 + m.x79**3) + m.x2091 == 0)
m.c1482 = Constraint(expr=-0.333333333333333*((5 - m.x80)**3 + m.x80**3) + m.x2092 == 0)
m.c1483 = Constraint(expr=-0.333333333333333*((5 - m.x81)**3 + m.x81**3) + m.x2093 == 0)
m.c1484 = Constraint(expr=-0.333333333333333*((5 - m.x82)**3 + m.x82**3) + m.x2094 == 0)
m.c1485 = Constraint(expr=-0.333333333333333*((5 - m.x83)**3 + m.x83**3) + m.x2095 == 0)
m.c1486 = Constraint(expr=-0.333333333333333*((5 - m.x84)**3 + m.x84**3) + m.x2096 == 0)
m.c1487 = Constraint(expr=-0.333333333333333*((5 - m.x85)**3 + m.x85**3) + m.x2097 == 0)
m.c1488 = Constraint(expr=-0.333333333333333*((5 - m.x86)**3 + m.x86**3) + m.x2098 == 0)
m.c1489 = Constraint(expr=-0.333333333333333*((5 - m.x87)**3 + m.x87**3) + m.x2099 == 0)
m.c1490 = Constraint(expr=-0.333333333333333*((5 - m.x88)**3 + m.x88**3) + m.x2100 == 0)
m.c1491 = Constraint(expr=-0.333333333333333*((5 - m.x89)**3 + m.x89**3) + m.x2101 == 0)
m.c1492 = Constraint(expr=-0.333333333333333*((5 - m.x90)**3 + m.x90**3) + m.x2102 == 0)
m.c1493 = Constraint(expr=-0.333333333333333*((5 - m.x91)**3 + m.x91**3) + m.x2103 == 0)
m.c1494 = Constraint(expr=-0.333333333333333*((5 - m.x92)**3 + m.x92**3) + m.x2104 == 0)
m.c1495 = Constraint(expr=-0.333333333333333*((5 - m.x93)**3 + m.x93**3) + m.x2105 == 0)
m.c1496 = Constraint(expr=-0.333333333333333*((5 - m.x94)**3 + m.x94**3) + m.x2106 == 0)
m.c1497 = Constraint(expr=-0.333333333333333*((5 - m.x95)**3 + m.x95**3) + m.x2107 == 0)
m.c1498 = Constraint(expr=-0.333333333333333*((5 - m.x96)**3 + m.x96**3) + m.x2108 == 0)
m.c1499 = Constraint(expr=-0.333333333333333*((5 - m.x97)**3 + m.x97**3) + m.x2109 == 0)
m.c1500 = Constraint(expr=-0.333333333333333*((5 - m.x98)**3 + m.x98**3) + m.x2110 == 0)
m.c1501 = Constraint(expr=-0.333333333333333*((5 - m.x99)**3 + m.x99**3) + m.x2111 == 0)
m.c1502 = Constraint(expr=-0.333333333333333*((5 - m.x100)**3 + m.x100**3) + m.x2112 == 0)
m.c1503 = Constraint(expr=-0.333333333333333*((5 - m.x101)**3 + m.x101**3) + m.x2113 == 0)
m.c1504 = Constraint(expr=-0.333333333333333*((5 - m.x102)**3 + m.x102**3) + m.x2114 == 0)
m.c1505 = Constraint(expr=-0.333333333333333*((5 - m.x103)**3 + m.x103**3) + m.x2115 == 0)
m.c1506 = Constraint(expr=-0.333333333333333*((5 - m.x104)**3 + m.x104**3) + m.x2116 == 0)
m.c1507 = Constraint(expr=-0.333333333333333*((5 - m.x105)**3 + m.x105**3) + m.x2117 == 0)
m.c1508 = Constraint(expr=-0.333333333333333*((5 - m.x106)**3 + m.x106**3) + m.x2118 == 0)
m.c1509 = Constraint(expr=-0.333333333333333*((5 - m.x107)**3 + m.x107**3) + m.x2119 == 0)
m.c1510 = Constraint(expr=-0.333333333333333*((5 - m.x108)**3 + m.x108**3) + m.x2120 == 0)
m.c1511 = Constraint(expr=-0.333333333333333*((5 - m.x109)**3 + m.x109**3) + m.x2121 == 0)
m.c1512 = Constraint(expr=-0.333333333333333*((5 - m.x110)**3 + m.x110**3) + m.x2122 == 0)
m.c1513 = Constraint(expr=-0.333333333333333*((5 - m.x111)**3 + m.x111**3) + m.x2123 == 0)
m.c1514 = Constraint(expr=-0.333333333333333*((5 - m.x112)**3 + m.x112**3) + m.x2124 == 0)
m.c1515 = Constraint(expr=-0.333333333333333*((5 - m.x113)**3 + m.x113**3) + m.x2125 == 0)
m.c1516 = Constraint(expr=-0.333333333333333*((5 - m.x114)**3 + m.x114**3) + m.x2126 == 0)
m.c1517 = Constraint(expr=-0.333333333333333*((5 - m.x115)**3 + m.x115**3) + m.x2127 == 0)
m.c1518 = Constraint(expr=-0.333333333333333*((5 - m.x116)**3 + m.x116**3) + m.x2128 == 0)
m.c1519 = Constraint(expr=-0.333333333333333*((5 - m.x117)**3 + m.x117**3) + m.x2129 == 0)
m.c1520 = Constraint(expr=-0.333333333333333*((5 - m.x118)**3 + m.x118**3) + m.x2130 == 0)
m.c1521 = Constraint(expr=-0.333333333333333*((5 - m.x119)**3 + m.x119**3) + m.x2131 == 0)
m.c1522 = Constraint(expr=-0.333333333333333*((5 - m.x120)**3 + m.x120**3) + m.x2132 == 0)
m.c1523 = Constraint(expr=-0.333333333333333*((5 - m.x121)**3 + m.x121**3) + m.x2133 == 0)
m.c1524 = Constraint(expr=-0.333333333333333*((5 - m.x122)**3 + m.x122**3) + m.x2134 == 0)
m.c1525 = Constraint(expr=-0.333333333333333*((5 - m.x123)**3 + m.x123**3) + m.x2135 == 0)
m.c1526 = Constraint(expr=-0.333333333333333*((5 - m.x124)**3 + m.x124**3) + m.x2136 == 0)
m.c1527 = Constraint(expr=-0.333333333333333*((5 - m.x125)**3 + m.x125**3) + m.x2137 == 0)
m.c1528 = Constraint(expr=-0.333333333333333*((5 - m.x126)**3 + m.x126**3) + m.x2138 == 0)
m.c1529 = Constraint(expr=-0.333333333333333*((5 - m.x127)**3 + m.x127**3) + m.x2139 == 0)
m.c1530 = Constraint(expr=-0.333333333333333*((5 - m.x128)**3 + m.x128**3) + m.x2140 == 0)
m.c1531 = Constraint(expr=-0.333333333333333*((5 - m.x129)**3 + m.x129**3) + m.x2141 == 0)
m.c1532 = Constraint(expr=-0.333333333333333*((5 - m.x130)**3 + m.x130**3) + m.x2142 == 0)
m.c1533 = Constraint(expr=-0.333333333333333*((5 - m.x131)**3 + m.x131**3) + m.x2143 == 0)
m.c1534 = Constraint(expr=-0.333333333333333*((5 - m.x132)**3 + m.x132**3) + m.x2144 == 0)
m.c1535 = Constraint(expr=-0.333333333333333*((5 - m.x133)**3 + m.x133**3) + m.x2145 == 0)
m.c1536 = Constraint(expr=-0.333333333333333*((5 - m.x134)**3 + m.x134**3) + m.x2146 == 0)
m.c1537 = Constraint(expr=-0.333333333333333*((5 - m.x135)**3 + m.x135**3) + m.x2147 == 0)
m.c1538 = Constraint(expr=-0.333333333333333*((5 - m.x136)**3 + m.x136**3) + m.x2148 == 0)
m.c1539 = Constraint(expr=-0.333333333333333*((5 - m.x137)**3 + m.x137**3) + m.x2149 == 0)
m.c1540 = Constraint(expr=-0.333333333333333*((5 - m.x138)**3 + m.x138**3) + m.x2150 == 0)
m.c1541 = Constraint(expr=-0.333333333333333*((5 - m.x139)**3 + m.x139**3) + m.x2151 == 0)
m.c1542 = Constraint(expr=-0.333333333333333*((5 - m.x140)**3 + m.x140**3) + m.x2152 == 0)
m.c1543 = Constraint(expr=-0.333333333333333*((5 - m.x141)**3 + m.x141**3) + m.x2153 == 0)
m.c1544 = Constraint(expr=-0.333333333333333*((5 - m.x142)**3 + m.x142**3) + m.x2154 == 0)
m.c1545 = Constraint(expr=-0.333333333333333*((5 - m.x143)**3 + m.x143**3) + m.x2155 == 0)
m.c1546 = Constraint(expr=-0.333333333333333*((5 - m.x144)**3 + m.x144**3) + m.x2156 == 0)
m.c1547 = Constraint(expr=-0.333333333333333*((5 - m.x145)**3 + m.x145**3) + m.x2157 == 0)
m.c1548 = Constraint(expr=-0.333333333333333*((5 - m.x146)**3 + m.x146**3) + m.x2158 == 0)
m.c1549 = Constraint(expr=-0.333333333333333*((5 - m.x147)**3 + m.x147**3) + m.x2159 == 0)
m.c1550 = Constraint(expr=-0.333333333333333*((5 - m.x148)**3 + m.x148**3) + m.x2160 == 0)
m.c1551 = Constraint(expr=-0.333333333333333*((5 - m.x149)**3 + m.x149**3) + m.x2161 == 0)
m.c1552 = Constraint(expr=-0.333333333333333*((5 - m.x150)**3 + m.x150**3) + m.x2162 == 0)
m.c1553 = Constraint(expr=-0.333333333333333*((5 - m.x151)**3 + m.x151**3) + m.x2163 == 0)
m.c1554 = Constraint(expr=-0.333333333333333*((5 - m.x152)**3 + m.x152**3) + m.x2164 == 0)
m.c1555 = Constraint(expr=-0.333333333333333*((5 - m.x153)**3 + m.x153**3) + m.x2165 == 0)
m.c1556 = Constraint(expr=-0.333333333333333*((5 - m.x154)**3 + m.x154**3) + m.x2166 == 0)
m.c1557 = Constraint(expr=-0.333333333333333*((5 - m.x155)**3 + m.x155**3) + m.x2167 == 0)
m.c1558 = Constraint(expr=-0.333333333333333*((5 - m.x156)**3 + m.x156**3) + m.x2168 == 0)
m.c1559 = Constraint(expr=-0.333333333333333*((5 - m.x157)**3 + m.x157**3) + m.x2169 == 0)
m.c1560 = Constraint(expr=-0.333333333333333*((5 - m.x158)**3 + m.x158**3) + m.x2170 == 0)
m.c1561 = Constraint(expr=-0.333333333333333*((5 - m.x159)**3 + m.x159**3) + m.x2171 == 0)
m.c1562 = Constraint(expr=-0.333333333333333*((5 - m.x160)**3 + m.x160**3) + m.x2172 == 0)
m.c1563 = Constraint(expr=-0.333333333333333*((5 - m.x161)**3 + m.x161**3) + m.x2173 == 0)
m.c1564 = Constraint(expr=-0.333333333333333*((5 - m.x162)**3 + m.x162**3) + m.x2174 == 0)
m.c1565 = Constraint(expr=-0.333333333333333*((5 - m.x163)**3 + m.x163**3) + m.x2175 == 0)
m.c1566 = Constraint(expr=-0.333333333333333*((5 - m.x164)**3 + m.x164**3) + m.x2176 == 0)
m.c1567 = Constraint(expr=-0.333333333333333*((5 - m.x165)**3 + m.x165**3) + m.x2177 == 0)
m.c1568 = Constraint(expr=-0.333333333333333*((5 - m.x166)**3 + m.x166**3) + m.x2178 == 0)
m.c1569 = Constraint(expr=-0.333333333333333*((5 - m.x167)**3 + m.x167**3) + m.x2179 == 0)
m.c1570 = Constraint(expr=-0.333333333333333*((5 - m.x168)**3 + m.x168**3) + m.x2180 == 0)
m.c1571 = Constraint(expr=-0.333333333333333*((5 - m.x169)**3 + m.x169**3) + m.x2181 == 0)
m.c1572 = Constraint(expr=-0.333333333333333*((5 - m.x170)**3 + m.x170**3) + m.x2182 == 0)
m.c1573 = Constraint(expr=-0.333333333333333*((5 - m.x171)**3 + m.x171**3) + m.x2183 == 0)
m.c1574 = Constraint(expr=-0.333333333333333*((5 - m.x172)**3 + m.x172**3) + m.x2184 == 0)
m.c1575 = Constraint(expr=-0.333333333333333*((5 - m.x173)**3 + m.x173**3) + m.x2185 == 0)
m.c1576 = Constraint(expr=-0.333333333333333*((5 - m.x174)**3 + m.x174**3) + m.x2186 == 0)
m.c1577 = Constraint(expr=-0.333333333333333*((5 - m.x175)**3 + m.x175**3) + m.x2187 == 0)
m.c1578 = Constraint(expr=-0.333333333333333*((5 - m.x176)**3 + m.x176**3) + m.x2188 == 0)
m.c1579 = Constraint(expr=-0.333333333333333*((5 - m.x177)**3 + m.x177**3) + m.x2189 == 0)
m.c1580 = Constraint(expr=-0.333333333333333*((5 - m.x178)**3 + m.x178**3) + m.x2190 == 0)
m.c1581 = Constraint(expr=-0.333333333333333*((5 - m.x179)**3 + m.x179**3) + m.x2191 == 0)
m.c1582 = Constraint(expr=-0.333333333333333*((5 - m.x180)**3 + m.x180**3) + m.x2192 == 0)
m.c1583 = Constraint(expr=-0.333333333333333*((5 - m.x181)**3 + m.x181**3) + m.x2193 == 0)
m.c1584 = Constraint(expr=-0.333333333333333*((5 - m.x182)**3 + m.x182**3) + m.x2194 == 0)
m.c1585 = Constraint(expr=-0.333333333333333*((5 - m.x183)**3 + m.x183**3) + m.x2195 == 0)
m.c1586 = Constraint(expr=-0.333333333333333*((5 - m.x184)**3 + m.x184**3) + m.x2196 == 0)
m.c1587 = Constraint(expr=-0.333333333333333*((5 - m.x185)**3 + m.x185**3) + m.x2197 == 0)
m.c1588 = Constraint(expr=-0.333333333333333*((5 - m.x186)**3 + m.x186**3) + m.x2198 == 0)
m.c1589 = Constraint(expr=-0.333333333333333*((5 - m.x187)**3 + m.x187**3) + m.x2199 == 0)
m.c1590 = Constraint(expr=-0.333333333333333*((5 - m.x188)**3 + m.x188**3) + m.x2200 == 0)
m.c1591 = Constraint(expr=-0.333333333333333*((5 - m.x189)**3 + m.x189**3) + m.x2201 == 0)
m.c1592 = Constraint(expr=-0.333333333333333*((5 - m.x190)**3 + m.x190**3) + m.x2202 == 0)
m.c1593 = Constraint(expr=-0.333333333333333*((5 - m.x191)**3 + m.x191**3) + m.x2203 == 0)
m.c1594 = Constraint(expr=-0.333333333333333*((5 - m.x192)**3 + m.x192**3) + m.x2204 == 0)
m.c1595 = Constraint(expr=-0.333333333333333*((5 - m.x193)**3 + m.x193**3) + m.x2205 == 0)
m.c1596 = Constraint(expr=-0.333333333333333*((5 - m.x194)**3 + m.x194**3) + m.x2206 == 0)
m.c1597 = Constraint(expr=-0.333333333333333*((5 - m.x195)**3 + m.x195**3) + m.x2207 == 0)
m.c1598 = Constraint(expr=-0.333333333333333*((5 - m.x196)**3 + m.x196**3) + m.x2208 == 0)
m.c1599 = Constraint(expr=-0.333333333333333*((5 - m.x197)**3 + m.x197**3) + m.x2209 == 0)
m.c1600 = Constraint(expr=-0.333333333333333*((5 - m.x198)**3 + m.x198**3) + m.x2210 == 0)
m.c1601 = Constraint(expr=-0.333333333333333*((5 - m.x199)**3 + m.x199**3) + m.x2211 == 0)
m.c1602 = Constraint(expr=-0.333333333333333*((5 - m.x200)**3 + m.x200**3) + m.x2212 == 0)
m.c1603 = Constraint(expr=-0.333333333333333*((5 - m.x201)**3 + m.x201**3) + m.x2213 == 0)
| 53.537387 | 102 | 0.688542 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 697 | 0.002392 |
8994560794eac403f32c84dae0fea83d1c5d480e | 3,379 | py | Python | nonconformist/base.py | smazzanti/nonconformist | 5ed072c82ae6d923eb6063a6a5c8fa664fbf729c | [
"MIT"
] | 301 | 2015-03-18T01:47:37.000Z | 2022-03-11T14:50:55.000Z | nonconformist/base.py | smazzanti/nonconformist | 5ed072c82ae6d923eb6063a6a5c8fa664fbf729c | [
"MIT"
] | 25 | 2016-07-25T21:36:26.000Z | 2022-02-23T00:39:07.000Z | nonconformist/base.py | smazzanti/nonconformist | 5ed072c82ae6d923eb6063a6a5c8fa664fbf729c | [
"MIT"
] | 91 | 2015-03-19T08:25:16.000Z | 2022-03-08T08:31:38.000Z | #!/usr/bin/env python
"""
docstring
"""
# Authors: Henrik Linusson
import abc
import numpy as np
from sklearn.base import BaseEstimator
class RegressorMixin(object):
def __init__(self):
super(RegressorMixin, self).__init__()
@classmethod
def get_problem_type(cls):
return 'regression'
class ClassifierMixin(object):
def __init__(self):
super(ClassifierMixin, self).__init__()
@classmethod
def get_problem_type(cls):
return 'classification'
class BaseModelAdapter(BaseEstimator):
__metaclass__ = abc.ABCMeta
def __init__(self, model, fit_params=None):
super(BaseModelAdapter, self).__init__()
self.model = model
self.last_x, self.last_y = None, None
self.clean = False
self.fit_params = {} if fit_params is None else fit_params
def fit(self, x, y):
"""Fits the model.
Parameters
----------
x : numpy array of shape [n_samples, n_features]
Inputs of examples for fitting the model.
y : numpy array of shape [n_samples]
Outputs of examples for fitting the model.
Returns
-------
None
"""
self.model.fit(x, y, **self.fit_params)
self.clean = False
def predict(self, x):
"""Returns the prediction made by the underlying model.
Parameters
----------
x : numpy array of shape [n_samples, n_features]
Inputs of test examples.
Returns
-------
y : numpy array of shape [n_samples]
Predicted outputs of test examples.
"""
if (
not self.clean or
self.last_x is None or
self.last_y is None or
not np.array_equal(self.last_x, x)
):
self.last_x = x
self.last_y = self._underlying_predict(x)
self.clean = True
return self.last_y.copy()
@abc.abstractmethod
def _underlying_predict(self, x):
"""Produces a prediction using the encapsulated model.
Parameters
----------
x : numpy array of shape [n_samples, n_features]
Inputs of test examples.
Returns
-------
y : numpy array of shape [n_samples]
Predicted outputs of test examples.
"""
pass
class ClassifierAdapter(BaseModelAdapter):
def __init__(self, model, fit_params=None):
super(ClassifierAdapter, self).__init__(model, fit_params)
def _underlying_predict(self, x):
return self.model.predict_proba(x)
class RegressorAdapter(BaseModelAdapter):
def __init__(self, model, fit_params=None):
super(RegressorAdapter, self).__init__(model, fit_params)
def _underlying_predict(self, x):
return self.model.predict(x)
class OobMixin(object):
def __init__(self, model, fit_params=None):
super(OobMixin, self).__init__(model, fit_params)
self.train_x = None
def fit(self, x, y):
super(OobMixin, self).fit(x, y)
self.train_x = x
def _underlying_predict(self, x):
# TODO: sub-sampling of ensemble for test patterns
oob = x == self.train_x
if hasattr(oob, 'all'):
oob = oob.all()
if oob:
return self._oob_prediction()
else:
return super(OobMixin, self)._underlying_predict(x)
class OobClassifierAdapter(OobMixin, ClassifierAdapter):
def __init__(self, model, fit_params=None):
super(OobClassifierAdapter, self).__init__(model, fit_params)
def _oob_prediction(self):
return self.model.oob_decision_function_
class OobRegressorAdapter(OobMixin, RegressorAdapter):
def __init__(self, model, fit_params=None):
super(OobRegressorAdapter, self).__init__(model, fit_params)
def _oob_prediction(self):
return self.model.oob_prediction_
| 21.522293 | 63 | 0.718556 | 3,215 | 0.951465 | 0 | 0 | 457 | 0.135247 | 0 | 0 | 939 | 0.277893 |
8995599b49ae65bec50e95a8d6ce10788f734c9e | 1,890 | py | Python | corehq/apps/receiverwrapper/rate_limiter.py | dborowiecki/commcare-hq | f2f4fa67faec09040a98502f5657444075b63f2e | [
"BSD-3-Clause"
] | null | null | null | corehq/apps/receiverwrapper/rate_limiter.py | dborowiecki/commcare-hq | f2f4fa67faec09040a98502f5657444075b63f2e | [
"BSD-3-Clause"
] | null | null | null | corehq/apps/receiverwrapper/rate_limiter.py | dborowiecki/commcare-hq | f2f4fa67faec09040a98502f5657444075b63f2e | [
"BSD-3-Clause"
] | null | null | null | from corehq.project_limits.rate_limiter import RateDefinition, RateLimiter, \
PerUserRateDefinition
from corehq.util.datadog.gauges import datadog_counter
from corehq.util.datadog.utils import bucket_value
from corehq.util.decorators import silence_and_report_error, enterprise_skip
from corehq.util.timer import TimingContext
# Danny promised in an Aug 2019 email not to enforce limits that were lower than this.
# If we as a team end up regretting this decision, we'll have to reset expectations
# with the Dimagi NDoH team.
rates_promised_not_to_go_lower_than = RateDefinition(
per_week=115,
per_day=23,
per_hour=3,
per_minute=0.07,
per_second=0.005,
)
floor_for_small_domain = RateDefinition(
per_week=100,
per_day=50,
per_hour=30,
per_minute=10,
per_second=1,
)
test_rates = PerUserRateDefinition(
per_user_rate_definition=rates_promised_not_to_go_lower_than.times(2.0),
constant_rate_definition=floor_for_small_domain,
)
submission_rate_limiter = RateLimiter(
feature_key='submissions',
get_rate_limits=test_rates.get_rate_limits
)
@enterprise_skip
@silence_and_report_error("Exception raised in the submission rate limiter",
'commcare.xform_submissions.rate_limiter_errors')
def rate_limit_submission_by_delaying(domain, max_wait):
if not submission_rate_limiter.allow_usage(domain):
with TimingContext() as timer:
acquired = submission_rate_limiter.wait(domain, timeout=max_wait)
if acquired:
duration_tag = bucket_value(timer.duration, [1, 5, 10, 15, 20], unit='s')
else:
duration_tag = 'timeout'
datadog_counter('commcare.xform_submissions.rate_limited.test', tags=[
'domain:{}'.format(domain),
'duration:{}'.format(duration_tag)
])
submission_rate_limiter.report_usage(domain)
| 33.75 | 86 | 0.74127 | 0 | 0 | 0 | 0 | 783 | 0.414286 | 0 | 0 | 389 | 0.20582 |
89970080ba2f0570c2f1e353abfb492b88c1cf1e | 2,263 | py | Python | ShareSpace/views.py | BNordstrom16/ShareSpaceWeb | 676ddbc52f745d4b8a17f18f26a15329ad91ebfa | [
"MIT"
] | null | null | null | ShareSpace/views.py | BNordstrom16/ShareSpaceWeb | 676ddbc52f745d4b8a17f18f26a15329ad91ebfa | [
"MIT"
] | null | null | null | ShareSpace/views.py | BNordstrom16/ShareSpaceWeb | 676ddbc52f745d4b8a17f18f26a15329ad91ebfa | [
"MIT"
] | null | null | null | from django.shortcuts import render, redirect
from django.views.generic import UpdateView, DeleteView
from .models import Storage
from django_tables2 import RequestConfig
from .tables import StorageTable
from django.contrib.auth.decorators import login_required
from .forms import StorageForm, QuestionForm
def index(request):
table = Storage.objects.reverse()[0:3]
return render(request, '../templates/index.html', {'storages': table})
def about(request):
if request.method == "POST":
form = QuestionForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return '/about'
else:
form = QuestionForm()
return render(request, '../templates/about.html', {'form': form})
def current_storages(request):
table = StorageTable(Storage.objects.all())
RequestConfig(request).configure(table)
return render(request, '../templates/current_storages.html', {'table': table})
@login_required(login_url='/accounts/login')
def create_storage(request):
if request.method == "POST":
form = StorageForm(request.POST, request.FILES)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.user_id = request.user
model_instance.save()
return redirect('/current_storages')
else:
form = StorageForm()
return render(request, '../templates/create_storage.html', {'form': form})
def storage(request, storage_id):
storage_request = Storage.objects.get(pk=storage_id)
return render(request, '../templates/storage.html', {'storage': storage_request})
class EditStorage(UpdateView):
model = Storage
form_class = StorageForm
template_name = 'storage_update_form.html'
success_url = '/current_storages'
class DeleteStorage(DeleteView):
model = Storage
template_name = 'storage_confirm_delete.html'
success_url = '/current_storages'
def show_image(request, storage_id):
photo_request = Storage.objects.get(pk=storage_id)
return render(request, '../templates/show_image.html', {'storage': photo_request})
def logout(request):
return render(request, '../templates/registration/logout.html', {})
| 28.2875 | 86 | 0.696421 | 304 | 0.134335 | 0 | 0 | 495 | 0.218736 | 0 | 0 | 412 | 0.182059 |
899a40a76b3d46b1165d8bfc6e8d1efe16d93e6b | 1,282 | py | Python | rest_framework_security/deny_repeat_password/signals.py | RubenEu/django-rest-framework-security | 638cf271c51a5bafd434a6b6a9c25a7c4849b485 | [
"MIT"
] | 7 | 2020-09-01T09:55:25.000Z | 2021-11-04T06:59:04.000Z | rest_framework_security/deny_repeat_password/signals.py | RubenEu/django-rest-framework-security | 638cf271c51a5bafd434a6b6a9c25a7c4849b485 | [
"MIT"
] | 32 | 2020-10-28T17:09:18.000Z | 2022-03-12T00:55:09.000Z | rest_framework_security/deny_repeat_password/signals.py | RubenEu/django-rest-framework-security | 638cf271c51a5bafd434a6b6a9c25a7c4849b485 | [
"MIT"
] | 2 | 2020-12-18T01:26:53.000Z | 2021-11-04T06:59:07.000Z | from django.apps import apps
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver, Signal
from rest_framework_security.deny_repeat_password import config
from rest_framework_security.deny_repeat_password.emails import ChangedPasswordEmail
from rest_framework_security.deny_repeat_password.models import UserPassword
password_changed = Signal(providing_args=["user"])
@receiver(post_save, sender=get_user_model())
def set_user_password_receiver(sender, instance, **kwargs):
if instance._password is None:
return
user_password, created = UserPassword.objects.get_or_create(
user=instance, password=instance.password
)
UserPassword.objects.remove_old_passwords(instance)
if (
created
and config.DENY_REPEAT_PASSWORD_CLOSE_SESSIONS
and apps.is_installed("rest_framework_security.authentication")
):
from rest_framework_security.authentication.models import UserSession
UserSession.objects.filter(user=instance).clean_and_delete()
if created:
password_changed.send(None, user=instance)
@receiver(password_changed)
def send_password_changed_email(sender, user, **kwargs):
ChangedPasswordEmail(user).send()
| 34.648649 | 84 | 0.789392 | 0 | 0 | 0 | 0 | 828 | 0.645866 | 0 | 0 | 46 | 0.035881 |