blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
721
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
5
91
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
321 values
visit_date
timestamp[ns]date
2016-08-12 09:31:09
2023-09-06 10:45:07
revision_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
committer_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
github_id
int64
426
681M
star_events_count
int64
101
243k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[ns]date
2012-06-28 18:51:49
2023-09-14 21:59:16
gha_created_at
timestamp[ns]date
2008-02-11 22:55:26
2023-08-10 11:14:58
gha_language
stringclasses
147 values
src_encoding
stringclasses
26 values
language
stringclasses
2 values
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
6
10.2M
extension
stringclasses
115 values
filename
stringlengths
3
113
content
stringlengths
6
10.2M
79334c1b3de67a9558cd1c4488e11dc968109696
0d4e2ba5b8a137be3e865302b1d4c86eb63402b9
/ogb/version.py
2fa2618d418d115065d53375ab166e1e12ca12f4
[ "MIT" ]
permissive
snap-stanford/ogb
bdedd2e58e45658b1db12d88157d5793b161c558
745531be13c5403a93c80e21a41848e38ea7637c
refs/heads/master
2023-08-29T13:47:29.491563
2023-06-10T14:30:23
2023-06-10T14:30:23
223,495,162
1,805
437
MIT
2023-06-24T05:35:39
2019-11-22T22:13:57
Python
UTF-8
Python
false
false
621
py
version.py
import os import logging from threading import Thread __version__ = '1.3.6' try: os.environ['OUTDATED_IGNORE'] = '1' from outdated import check_outdated # noqa except ImportError: check_outdated = None def check(): try: is_outdated, latest = check_outdated('ogb', __version__) if is_outdated: logging.warning( f'The OGB package is out of date. Your version is ' f'{__version__}, while the latest version is {latest}.') except Exception: pass if check_outdated is not None: thread = Thread(target=check) thread.start()
97b9cd5584c6e0ebbe6cb940bf9bc30b4d0c10d3
0009c76a25c89a0d61d3bc9e10071da58bdfaa5a
/py/ztools/lib/python_pick.py
5135b8ef7d9281263bc28783970c7ee0a0f972ad
[ "MIT" ]
permissive
julesontheroad/NSC_BUILDER
84054e70a80b572088b0806a47ceb398302451b5
e9083e83383281bdd9e167d3141163dcc56b6710
refs/heads/master
2023-07-05T05:23:17.114363
2021-11-15T19:34:47
2021-11-15T19:34:47
149,040,416
1,249
143
MIT
2022-12-15T03:19:33
2018-09-16T22:18:01
Python
UTF-8
Python
false
false
7,032
py
python_pick.py
#-*-coding:utf-8-*- ''' Based on python-pick python-pick - Library Data: * Name: python-pick * Author: wong2 * License: MIT -> https://github.com/wong2/pick/blob/master/LICENSE * Modifications by julesontheroad for: https://github.com/julesontheroad/NSC_BUILDER/ Currently the only modification was to add intro (459) to the selector, more things may be added on the future. ''' import curses __all__ = ['Picker', 'pick'] KEYS_ENTER = (curses.KEY_ENTER, ord('\n'), ord('\r'),459) KEYS_UP = (curses.KEY_UP, ord('k')) KEYS_DOWN = (curses.KEY_DOWN, ord('j')) KEYS_SELECT = (curses.KEY_RIGHT, ord(' ')) class Picker(object): """The :class:`Picker <Picker>` object :param options: a list of options to choose from :param title: (optional) a title above options list :param multi_select: (optional) if true its possible to select multiple values by hitting SPACE, defaults to False :param indicator: (optional) custom the selection indicator :param default_index: (optional) set this if the default selected option is not the first one :param options_map_func: (optional) a mapping function to pass each option through before displaying """ def __init__(self, options, title=None, indicator='*', default_index=0, multi_select=False, min_selection_count=0, options_map_func=None): if len(options) == 0: raise ValueError('options should not be an empty list') self.options = options self.title = title self.indicator = indicator self.multi_select = multi_select self.min_selection_count = min_selection_count self.options_map_func = options_map_func self.all_selected = [] if default_index >= len(options): raise ValueError('default_index should be less than the length of options') if multi_select and min_selection_count > len(options): raise ValueError('min_selection_count is bigger than the available options, you will not be able to make any selection') if options_map_func is not None and not callable(options_map_func): raise ValueError('options_map_func must be a callable function') self.index = default_index self.custom_handlers = {} def register_custom_handler(self, key, func): self.custom_handlers[key] = func def move_up(self): self.index -= 1 if self.index < 0: self.index = len(self.options) - 1 def move_down(self): self.index += 1 if self.index >= len(self.options): self.index = 0 def mark_index(self): if self.multi_select: if self.index in self.all_selected: self.all_selected.remove(self.index) else: self.all_selected.append(self.index) def get_selected(self): """return the current selected option as a tuple: (option, index) or as a list of tuples (in case multi_select==True) """ if self.multi_select: return_tuples = [] for selected in self.all_selected: return_tuples.append((self.options[selected], selected)) return return_tuples else: return self.options[self.index], self.index def get_title_lines(self): if self.title: return self.title.split('\n') + [''] return [] def get_option_lines(self): lines = [] for index, option in enumerate(self.options): # pass the option through the options map of one was passed in if self.options_map_func: option = self.options_map_func(option) if index == self.index: prefix = self.indicator else: prefix = len(self.indicator) * ' ' if self.multi_select and index in self.all_selected: format = curses.color_pair(1) line = ('{0} {1}'.format(prefix, option), format) else: line = '{0} {1}'.format(prefix, option) lines.append(line) return lines def get_lines(self): title_lines = self.get_title_lines() option_lines = self.get_option_lines() lines = title_lines + option_lines current_line = self.index + len(title_lines) + 1 return lines, current_line def draw(self): """draw the curses ui on the screen, handle scroll if needed""" self.screen.clear() x, y = 1, 1 # start point max_y, max_x = self.screen.getmaxyx() max_rows = max_y - y # the max rows we can draw lines, current_line = self.get_lines() # calculate how many lines we should scroll, relative to the top scroll_top = getattr(self, 'scroll_top', 0) if current_line <= scroll_top: scroll_top = 0 elif current_line - scroll_top > max_rows: scroll_top = current_line - max_rows self.scroll_top = scroll_top lines_to_draw = lines[scroll_top:scroll_top+max_rows] for line in lines_to_draw: if type(line) is tuple: self.screen.addnstr(y, x, line[0], max_x-2, line[1]) else: self.screen.addnstr(y, x, line, max_x-2) y += 1 self.screen.refresh() def run_loop(self): while True: self.draw() c = self.screen.getch() if c in KEYS_UP: self.move_up() elif c in KEYS_DOWN: self.move_down() elif c in KEYS_ENTER: if self.multi_select and len(self.all_selected) < self.min_selection_count: continue return self.get_selected() elif c in KEYS_SELECT and self.multi_select: self.mark_index() elif c in self.custom_handlers: ret = self.custom_handlers[c](self) if ret: return ret def config_curses(self): # use the default colors of the terminal curses.use_default_colors() # hide the cursor curses.curs_set(0) #add some color for multi_select #@todo make colors configurable curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_WHITE) def _start(self, screen): self.screen = screen self.config_curses() return self.run_loop() def start(self): return curses.wrapper(self._start) def pick(options, title=None, indicator='*', default_index=0, multi_select=False, min_selection_count=0, options_map_func=None): """Construct and start a :class:`Picker <Picker>`. Usage:: >>> from pick import pick >>> title = 'Please choose an option: ' >>> options = ['option1', 'option2', 'option3'] >>> option, index = pick(options, title) """ picker = Picker(options, title, indicator, default_index, multi_select, min_selection_count, options_map_func) return picker.start()
4e878655cd6a84768e378d89f49b7c80ec2744d7
5e9576c368e98927e2965bd2fb23bd35d9993d69
/featuretools/primitives/standard/transform/binary/or_primitive.py
e426a1544e3386d82336a3c95b037befe3afcc76
[ "BSD-3-Clause" ]
permissive
alteryx/featuretools
c6e319e063e8e84e7684bf232376f95dc5272160
c284c2d27a95b81e0bae913ac90df2b02c8f3b37
refs/heads/main
2023-08-25T12:21:33.945418
2023-08-23T16:30:25
2023-08-23T16:30:25
102,908,804
1,783
201
BSD-3-Clause
2023-09-07T18:53:19
2017-09-08T22:15:17
Python
UTF-8
Python
false
false
1,586
py
or_primitive.py
import numpy as np from woodwork.column_schema import ColumnSchema from woodwork.logical_types import Boolean, BooleanNullable from featuretools.primitives.base.transform_primitive_base import TransformPrimitive from featuretools.utils.gen_utils import Library class Or(TransformPrimitive): """Performs element-wise logical OR of two lists. Description: Given a list of booleans X and a list of booleans Y, determine whether each value in X is `True`, or whether its corresponding value in Y is `True`. Examples: >>> _or = Or() >>> _or([False, True, False], [True, True, False]).tolist() [True, True, False] """ name = "or" input_types = [ [ ColumnSchema(logical_type=BooleanNullable), ColumnSchema(logical_type=BooleanNullable), ], [ColumnSchema(logical_type=Boolean), ColumnSchema(logical_type=Boolean)], [ ColumnSchema(logical_type=Boolean), ColumnSchema(logical_type=BooleanNullable), ], [ ColumnSchema(logical_type=BooleanNullable), ColumnSchema(logical_type=Boolean), ], ] return_type = ColumnSchema(logical_type=BooleanNullable) commutative = True compatibility = [Library.PANDAS, Library.DASK, Library.SPARK] description_template = "whether {} is true or {} is true" def get_function(self): return np.logical_or def generate_name(self, base_feature_names): return "OR(%s, %s)" % (base_feature_names[0], base_feature_names[1])
1f56c89db61c094add76cd2bb78062bf275d07a4
fc8ffd2f74d63024145e0628c700461765797c1c
/custom_components/edgeos/select.py
facfc33a1205ea2c9756cf885c4f2f1e9665890f
[]
no_license
elad-bar/ha-edgeos
a22edeb4429c2bd581e74cc535ce5ce3583ce84f
62e66ac5d67d2704cd8d602db9b5f1f490ed8f1f
refs/heads/master
2023-08-23T17:57:52.953761
2023-03-30T07:58:02
2023-03-30T07:58:02
169,467,285
129
31
null
2023-08-13T08:46:35
2019-02-06T19:53:18
Python
UTF-8
Python
false
false
792
py
select.py
""" Support for select. """ from __future__ import annotations import logging from .core.components.select import CoreSelect from .core.helpers.setup_base_entry import async_setup_base_entry _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry, async_add_devices): """Set up the component.""" await async_setup_base_entry( hass, config_entry, async_add_devices, CoreSelect.get_domain(), CoreSelect.get_component, ) async def async_unload_entry(hass, config_entry): _LOGGER.info(f"Unload entry for {CoreSelect.get_domain()} domain: {config_entry}") return True async def async_remove_entry(hass, entry) -> None: _LOGGER.info(f"Remove entry for {CoreSelect.get_domain()} entry: {entry}")
0fc9aa514856079a6a22481541f4c26964f0996b
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/Configuration/DataProcessing/python/Impl/cosmicsEra_Run2_2017.py
9946b56997b79d97fa1892c082c92295916af233
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
Python
false
false
499
py
cosmicsEra_Run2_2017.py
#!/usr/bin/env python3 """ _cosmicsEra_Run2_2017_ Scenario supporting cosmic data taking """ import os import sys from Configuration.Eras.Era_Run2_2017_cff import Run2_2017 from Configuration.DataProcessing.Impl.cosmics import cosmics class cosmicsEra_Run2_2017(cosmics): def __init__(self): cosmics.__init__(self) self.eras = Run2_2017 """ _cosmicsEra_Run2_2017_ Implement configuration building for data processing for cosmic data taking in Run2 """
73963577c9c9a5f9442a82c05be020280cacc839
1180c0bfe29959d95f3c131e6e839950e528d4ee
/03/d3prof3t/tags.py
424fbe29155c4a1c2a557a3f6d7945e28fe8ddf6
[]
no_license
pybites/challenges
e3e461accd8e7f890aee8007ba5070086ef983fc
02b77652d0901e6e06cb9b1e7cb3e59c675445c2
refs/heads/community
2023-08-20T18:19:02.982214
2022-11-17T09:23:31
2022-11-17T09:23:31
78,264,928
764
3,115
null
2023-07-21T05:58:19
2017-01-07T07:17:50
Jupyter Notebook
UTF-8
Python
false
false
1,892
py
tags.py
from collections import Counter from difflib import SequenceMatcher from itertools import product import re import string IDENTICAL = 1.0 TOP_NUMBER = 10 RSS_FEED = 'rss.xml' SIMILAR = 0.87 TAG_HTML = re.compile(r'<category>([^<]+)</category>') def get_tags(): """Find all tags (TAG_HTML) in RSS_FEED. Replace dash with whitespace. Hint: use TAG_HTML.findall""" tags = None with open(RSS_FEED) as fp: for line in fp: tags = TAG_HTML.findall(line.lower()) return [tag.translate(string.maketrans('-', ' ')) for tag in tags if tag] def get_top_tags(tags): """Get the TOP_NUMBER of most common tags Hint: use most_common method of Counter (already imported)""" if tags: return Counter(tags).most_common(10) def get_similarities(tags): """Find set of tags pairs with similarity ratio of > SIMILAR Hint 1: compare each tag, use for in for, or product from itertools (already imported) Hint 2: use SequenceMatcher (imported) to calculate the similarity ratio Bonus: for performance gain compare the first char of each tag in pair and continue if not the same""" tag_pairs = product(tags, tags) all_tag_pairs = [sorted(tag) for tag in list(tag_pairs)] for tag_pair in all_tag_pairs: if tag_pair[0] != tag_pair[1]: match_ratio = SequenceMatcher(a=tag_pair[0], b=tag_pair[1]).ratio() if match_ratio > SIMILAR and match_ratio < IDENTICAL: yield tag_pair if __name__ == "__main__": tags = get_tags() top_tags = get_top_tags(tags) print('* Top {} tags:'.format(TOP_NUMBER)) for tag, count in top_tags: print('{:<20} {}'.format(tag, count)) similar_tags = dict(get_similarities(tags)) print() print('* Similar tags:') for singular, plural in similar_tags.items(): print('{:<20} {}'.format(singular, plural))
c6b603b69a6093c8521a6525791a4906c6818729
f305f84ea6f721c2391300f0a60e21d2ce14f2a5
/11_动态规划/经典题/dfs+cache/1575. 统计所有可行路径.py
9c846a43fbbe7a698a622109d0c37f004add9a8a
[]
no_license
981377660LMT/algorithm-study
f2ada3e6959338ae1bc21934a84f7314a8ecff82
7e79e26bb8f641868561b186e34c1127ed63c9e0
refs/heads/master
2023-09-01T18:26:16.525579
2023-09-01T12:21:58
2023-09-01T12:21:58
385,861,235
225
24
null
null
null
null
UTF-8
Python
false
false
1,748
py
1575. 统计所有可行路径.py
from typing import List from functools import lru_cache # 2 <= locations.length <= 100 # locations[i] 表示第 i 个城市的位置 # 给你 start,finish 和 fuel 分别表示出发城市、目的地城市和你初始拥有的汽油总量 # 每一步中,如果你在城市 i ,你可以选择任意一个城市 j ,满足 j != i 且 0 <= j < locations.length ,并移动到城市 j # 从城市 i 移动到 j 消耗的汽油量为 |locations[i] - locations[j]| # 请注意, fuel 任何时刻都 不能 为负,且你 `可以 经过任意城市超过一次`(包括 start 和 finish )。 # 请你返回从 start 到 finish 所有可能路径的数目。 MOD = int(1e9 + 7) class Solution: def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int: weight = lambda i, j: abs(locations[i] - locations[j]) @lru_cache(None) def dfs(cur: int, remain: int) -> int: # if remain < 0: # return 0 if remain < weight(cur, finish): return 0 res = 0 if cur == finish: res += 1 for next in range(len(locations)): if cur == next: continue res += dfs(next, remain - weight(cur, next)) return res return dfs(start, fuel) % MOD print(Solution().countRoutes(locations=[2, 3, 6, 8, 4], start=1, finish=3, fuel=5)) # 输出:4 # 解释:以下为所有可能路径,每一条都用了 5 单位的汽油: # 1 -> 3 # 1 -> 2 -> 3 # 1 -> 4 -> 3 # 1 -> 4 -> 2 -> 3 print(Solution().countRoutes(locations=[4, 3, 1], start=1, finish=0, fuel=6))
2bdb85e001ab74bb690d4b2664719924a760d60f
d09a90f5b62c28bfe363e66ef6195f8313933d50
/utility/models_util.py
94ff2623240b89ae907a4217931d67b6719c64dd
[ "BSD-2-Clause", "Python-2.0" ]
permissive
borzacchiello/seninja
1caaa6088050b6d6c2a4869f1830be29da0ea016
7a0d939d9e58bed832b88da1e75546f4f2d11868
refs/heads/master
2023-06-09T12:46:22.695364
2023-06-01T18:02:04
2023-06-01T18:02:04
195,441,771
202
18
BSD-2-Clause
2023-05-27T18:35:03
2019-07-05T16:50:03
Python
UTF-8
Python
false
false
669
py
models_util.py
from ..arch.arch_x86 import x86Arch from .expr_wrap_util import symbolic from .bninja_util import get_function def get_arg_k(state, k, size, view): ip = state.get_ip() func = get_function(view, ip) calling_convention = func.calling_convention.name args = state.arch.get_argument_regs(calling_convention) if k-1 < len(args): res = getattr(state.regs, args[k-1]) return res.Extract(8*size-1, 0) else: stack_pointer = getattr(state.regs, state.arch.get_stack_pointer_reg()) assert not symbolic(stack_pointer) return state.mem.load(stack_pointer + (state.arch.bits() // 8)*k, size, state.arch.endness())
dc5400a5712c8c8b35e662243f1e0e7d3046b27a
e22eeb5256e17a96a98b3ff25433aec2d641cd2c
/openstack/network/v2/firewall_rule.py
04a84eadb93be4e0b725d7b47634cf0d45d9b0a0
[ "Apache-2.0" ]
permissive
openstack/openstacksdk
b4b95fd7869653feea5a3b783e9a5c588235c039
d474eb84c605c429bb9cccb166cabbdd1654d73c
refs/heads/master
2023-09-03T22:50:03.398512
2023-07-27T14:09:35
2023-08-29T16:28:46
16,223,378
124
130
Apache-2.0
2023-09-06T02:52:47
2014-01-25T02:48:00
Python
UTF-8
Python
false
false
3,157
py
firewall_rule.py
# Copyright (c) 2018 China Telecom Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack import resource class FirewallRule(resource.Resource): resource_key = 'firewall_rule' resources_key = 'firewall_rules' base_path = '/fwaas/firewall_rules' _allow_unknown_attrs_in_body = True # capabilities allow_create = True allow_fetch = True allow_commit = True allow_delete = True allow_list = True _query_mapping = resource.QueryParameters( 'action', 'description', 'destination_ip_address', 'name', 'destination_port', 'enabled', 'ip_version', 'project_id', 'protocol', 'shared', 'source_ip_address', 'source_port', 'firewall_policy_id', ) # Properties #: The action that the API performs on traffic that matches the firewall #: rule. Valid values are allow or deny. Default is deny. action = resource.Body('action') #: The description of the firewall rule description = resource.Body('description') #: The destination IPv4 or IPv6 address or CIDR for the firewall rule. destination_ip_address = resource.Body('destination_ip_address') #: The destination port or port range for the firewall rule. destination_port = resource.Body('destination_port') #: Facilitates selectively turning off rules without having to disassociate #: the rule from the firewall policy enabled = resource.Body('enabled') #: The IP protocol version for the firewall rule. Valid values are 4 or 6. ip_version = resource.Body('ip_version') #: The name of the firewall rule. name = resource.Body('name') #: The ID of the project that owns the resource. project_id = resource.Body('project_id') #: The IP protocol for the firewall rule. protocol = resource.Body('protocol') #: Indicates whether this firewall rule is shared across all projects. shared = resource.Body('shared') #: The source IPv4 or IPv6 address or CIDR for the firewall rule. source_ip_address = resource.Body('source_ip_address') #: The source port or port range for the firewall rule. source_port = resource.Body('source_port') #: Summary field of a FirewallRule, composed of the protocol, #: source_ip_address:source_port, #: destination_ip_address:destination_port and action. summary = resource.Computed('summary', default='') #: The ID of the firewall policy. firewall_policy_id = resource.Body('firewall_policy_id') #: The ID of the firewall rule. id = resource.Body('id')
6d76584c6234c68520e7f2c8b024674cbe103832
fb5c5d50d87a6861393d31911b9fae39bdc3cc62
/Scripts/sims4communitylib/enums/common_currency_modify_reasons.py
f973802af6154d3962d738e07b43b017665bdd38
[ "CC-BY-4.0" ]
permissive
ColonolNutty/Sims4CommunityLibrary
ee26126375f2f59e5567b72f6eb4fe9737a61df3
58e7beb30b9c818b294d35abd2436a0192cd3e82
refs/heads/master
2023-08-31T06:04:09.223005
2023-08-22T19:57:42
2023-08-22T19:57:42
205,197,959
183
38
null
2023-05-28T16:17:53
2019-08-29T15:48:35
Python
UTF-8
Python
false
false
3,673
py
common_currency_modify_reasons.py
""" The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY """ from protocolbuffers import Consts_pb2 from sims4communitylib.enums.enumtypes.common_int import CommonInt class CommonCurrencyModifyReason(CommonInt): """Various reasons for currencies to be modified.""" # Change reasons CHEAT: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_MONEY_CHEAT SPLIT_HOUSEHOLD: 'CommonCurrencyModifyReason' = Consts_pb2.FUNDS_SPLIT_HOUSEHOLD # Add reasons INTERACTION_REWARD: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_INTERACTION_REWARD EVENT_REWARD: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_EVENET_REWARD OBJECT_SELL: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_OBJECT_SELL STRUCTURE_SELL: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_STRUCTURE_SELL LOT_SELL: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_LOT_SELL HOUSEHOLD_TRANSFER_GAIN: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_HOUSEHOLD_TRANSFER_GAIN SIM_POINTS_EXCHANGED: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_SIM_POINTS_EXCHANGED SIM_WALLET_FUNDED: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_SIM_WALLET_FUNDED CAREER: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_MONEY_CAREER ASPIRATION_REWARD: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_MONEY_ASPIRATION_REWARD ROYALTY: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_MONEY_ROYALTY FIRE_INSURANCE: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_MONEY_FIREINSURANCE RETAIL_PROFITS: 'CommonCurrencyModifyReason' = Consts_pb2.FUNDS_RETAIL_PROFITS RETAIL_TRANSFER_GAIN: 'CommonCurrencyModifyReason' = Consts_pb2.FUNDS_RETAIL_TRANSFER_GAIN HOLIDAY_LOTTERY: 'CommonCurrencyModifyReason' = Consts_pb2.FUNDS_HOLIDAY_LOTTERY LIFESTYLE_BRAND: 'CommonCurrencyModifyReason' = Consts_pb2.FUNDS_LIFESTYLE_BRAND ROOMMATE_RENT: 'CommonCurrencyModifyReason' = Consts_pb2.FUNDS_ROOMMATE_RENT SCHOLARSHIP_SURPLUS: 'CommonCurrencyModifyReason' = Consts_pb2.FUNDS_SCHOLARSHIP_SURPLUS MARKETPLACE_OBJECT_SALE: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_MONEY_OBJECT_MARKETPLACE_SALE # Remove reasons INTERACTION_COST: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_INTERACTION_COST EVENT_COST: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_EVENT_COST OBJECT_BUY: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_OBJECT_BUY STRUCTURE_BUY: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_STRUCTURE_BUY CAS_ITEM_BUY: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_CAS_BUY BLUEPRINT_CONSTRUCTED: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_LOT_BUY LOT_BUY: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_LOT_BUY HOUSEHOLD_TRANSFER_LOSS: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_HOUSEHOLD_TRANSFER_LOSS SIM_WALLET_EMPTIED: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_SIM_WALLET_EMPTIED CRAFTING_COST: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_CRAFTING_COST VACATION: 'CommonCurrencyModifyReason' = Consts_pb2.FUNDS_MONEY_VACATION RETAIL_ITEM_BUY: 'CommonCurrencyModifyReason' = Consts_pb2.FUNDS_RETAIL_ITEM_BUY RETAIL_TRANSFER_LOSS: 'CommonCurrencyModifyReason' = Consts_pb2.FUNDS_RETAIL_TRANSFER_LOSS TUITION_COST: 'CommonCurrencyModifyReason' = Consts_pb2.FUNDS_TUITION_COST SIM_DEATH_COST: 'CommonCurrencyModifyReason' = Consts_pb2.TELEMETRY_LOANS_SIM_DEATH
f7a3dde2744e80d2e27cf95fb889c5466acce303
cd2a10f149babe29d2d3c3199ce5e6c14c906440
/testing/testone.py
2436b69f34366eef80eb33561c7326b29184ae53
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
parrt/dtreeviz
afcad7c1f09108df7d16742f2354cc4dd22f0477
a3d02a5fd382bb8e70af92cc9110d9ef73bc86a0
refs/heads/master
2023-07-24T12:49:08.622792
2023-07-13T17:20:36
2023-07-13T17:20:36
144,636,984
2,505
322
MIT
2023-09-13T00:27:33
2018-08-13T21:45:15
Jupyter Notebook
UTF-8
Python
false
false
7,207
py
testone.py
import graphviz from dtreeviz.shadow import * from gen_samples import * import tempfile from sklearn.tree import export_graphviz def viz_iris(orientation="TD", max_depth=5, random_state=666, fancy=True): clf = tree.DecisionTreeClassifier(max_depth=max_depth, random_state=random_state) iris = load_iris() data = pd.DataFrame(iris.data) data.columns = iris.feature_names clf = clf.fit(data, iris.target) # for i in range(len(iris.data)): for i in [60]: x = data.iloc[i] pred = clf.predict([x.values]) shadow_tree = ShadowDecTree(clf, iris.data, iris.target, feature_names=iris.feature_names, class_names=["setosa", "versicolor", "virginica"]) pred2 = shadow_tree.predict(x.values) print(f'{x} -> {pred[0]} vs mine {pred2[0]}, path = {[f"node{p.feature_name()}" for p in pred2[1]]}') path = [n.id for n in pred2[1]] if pred[0]!=pred2[0]: print("MISMATCH!") features = list(data.columns) features = np.array(['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']) st = dtreeviz(clf, iris.data, iris.target, target_name='variety', feature_names=features, orientation=orientation, class_names=["setosa", "versicolor", "virginica"], # 0,1,2 targets #histtype='strip', fancy=fancy, X=x) return st def viz_boston(orientation="TD", max_depth=3, random_state=666, fancy=True): regr = tree.DecisionTreeRegressor(max_depth=max_depth, random_state=random_state) boston = load_boston() regr = regr.fit(boston.data, boston.target) X = boston.data[np.random.randint(0, len(boston.data)),:] print(boston.feature_names) features = np.array(['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT']) viz = dtreeviz(regr, boston.data, boston.target, target_name='price', feature_names=features, orientation=orientation, fancy=fancy, X=X) export_graphviz(regr, out_file="/tmp/boston-scikit-tree.dot", filled=True, rounded=True, special_characters=True) return viz def viz_knowledge(orientation="TD", max_depth=3, random_state=666, fancy=True): # data from https://archive.ics.uci.edu/ml/datasets/User+Knowledge+Modeling clf = tree.DecisionTreeClassifier(max_depth=max_depth, random_state=random_state) know = pd.read_csv("data/knowledge.csv") target_names = ['very_low', 'Low', 'Middle', 'High'] know['UNS'] = know['UNS'].map({n: i for i, n in enumerate(target_names)}) X_train, y_train = know.drop('UNS', axis=1), know['UNS'] clf = clf.fit(X_train[['PEG','LPR']], y_train) X = X_train.iloc[np.random.randint(0, len(know))] viz = dtreeviz(clf, X_train[['PEG','LPR']], y_train, target_name='UNS', feature_names=['PEG','LPR'], orientation=orientation, class_names=target_names, # show_node_labels=True, histtype='strip', fancy=fancy) return viz def viz_diabetes(orientation="TD", max_depth=3, random_state=666, fancy=True, pickX=False): diabetes = load_diabetes() regr = tree.DecisionTreeRegressor(max_depth=max_depth, random_state=random_state) regr.fit(diabetes.data, diabetes.target) X = None if pickX: X = diabetes.data[np.random.randint(0, len(diabetes.data)),:] viz = dtreeviz(regr, diabetes.data, diabetes.target, target_name='progr', feature_names=diabetes.feature_names, orientation=orientation, fancy=fancy, X=X) return viz # # def viz_knowledge(orientation="TD", max_depth=3, random_state=666, fancy=True, pickX=False): # # data from https://archive.ics.uci.edu/ml/datasets/User+Knowledge+Modeling # clf = tree.DecisionTreeClassifier(max_depth=max_depth, random_state=random_state) # know = pd.read_csv("data/knowledge.csv") # target_names = ['very_low', 'Low', 'Middle', 'High'] # know['UNS'] = know['UNS'].map({n: i for i, n in enumerate(target_names)}) # # X_train, y_train = know.drop('UNS', axis=1), know['UNS'] # clf = clf.fit(X_train, y_train) # # st = dtreeviz(clf, X_train, y_train, target_name='UNS', # feature_names=X_train.columns.values, orientation=orientation, # class_names=target_names, # fancy=fancy, # X=X_train.iloc[3,:]) # return st def viz_digits(orientation="TD", max_depth=3, random_state=666, fancy=True, pickX=False): clf = tree.DecisionTreeClassifier(max_depth=max_depth, random_state=random_state) digits = load_digits() # "8x8 image of integer pixels in the range 0..16." columns = [f'pixel[{i},{j}]' for i in range(8) for j in range(8)] clf.fit(digits.data, digits.target) X = None if pickX: X = digits.data[np.random.randint(0, len(digits.data)),:] viz = dtreeviz(clf, digits.data, digits.target, target_name='number', feature_names=columns, orientation=orientation, class_names=[chr(c) for c in range(ord('0'),ord('9')+1)], fancy=fancy, histtype='bar', X=X) return viz def viz_wine(orientation="TD", max_depth=3, random_state=666, fancy=True, pickX=False): clf = tree.DecisionTreeClassifier(max_depth=max_depth) wine = load_wine() X_train = wine.data y_train = wine.target clf.fit(X_train, y_train) X = None if pickX: X = X_train[np.random.randint(0, len(X_train.data)),:] viz = dtreeviz(clf, wine.data, wine.target, target_name='wine', feature_names=wine.feature_names, class_names=list(wine.target_names), X=X) # pass the test observation return viz def weird_binary_case(): # See bug https://github.com/parrt/dtreeviz/issues/17 import numpy as np from sklearn.tree import DecisionTreeClassifier from dtreeviz.trees import dtreeviz x = np.random.choice([-1,1], size=(100, 2)) y = np.random.choice([0, 1], size=100) viz = dtreeviz( tree_model=DecisionTreeClassifier(max_depth=1).fit(x, y), X_train=x, y_train=y, feature_names=['a', 'b'], target_name='y', class_names=[1, 0] ) return viz viz = weird_binary_case() # viz = viz_wine(pickX=False, orientation='TD', max_depth=4, fancy=True) # viz = viz_diabetes(pickX=True) # viz = viz_boston(fancy=True, max_depth=4, orientation='TD') # viz = viz_iris(fancy=True, orientation='TD', max_depth=3) # viz = viz_digits(fancy=True, max_depth=3, orientation='TD') # viz = viz_knowledge(fancy=True, orientation='TD', max_depth=2) #g = graphviz.Source(st) # tmp = tempfile.gettempdir() # print(f"Tmp dir is {tmp}") # with open("/tmp/t3.dot", "w") as f: # f.write(st+"\n") # #print(viz.dot) # viz.save("/tmp/t.pdf") # viz.save("/tmp/t.png") # viz.save("/tmp/t.svg") viz.view()
82c5c855af6e6998d0d1159ed51b80fe3441cd5f
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/RecoBTag/SecondaryVertex/python/pfInclusiveSecondaryVertexFinderAK8TagInfos_cfi.py
8c6136b17b9be62cf914e49f0850373acac20e23
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
Python
false
false
442
py
pfInclusiveSecondaryVertexFinderAK8TagInfos_cfi.py
import FWCore.ParameterSet.Config as cms from RecoBTag.SecondaryVertex.pfInclusiveSecondaryVertexFinderTagInfos_cfi import * pfInclusiveSecondaryVertexFinderAK8TagInfos = pfInclusiveSecondaryVertexFinderTagInfos.clone( trackIPTagInfos = "pfImpactParameterAK8TagInfos", extSVDeltaRToJet = 0.8, trackSelection = dict(jetDeltaRMax = 0.8), # plays no role since using IVF vertices vertexCuts = dict(maxDeltaRToJetAxis = 0.8) )
98ddb51e9062b6f6fb9be6a79ce3c73f86303349
4bc83047ebef789d46f948eb07b8b771a9eab996
/httpx/_transports/base.py
f6fdfe694340ab00e0759c2cfb1a2ea53ed65736
[ "BSD-3-Clause" ]
permissive
encode/httpx
3d227e56cdf9141dec60a4222b3f954da25758dd
053bc57c3799801ff11273dd393cb0715e63ecf9
refs/heads/master
2023-08-31T00:42:31.360625
2023-08-29T09:27:23
2023-08-29T09:27:23
179,492,861
11,116
931
BSD-3-Clause
2023-09-13T19:49:01
2019-04-04T12:27:00
Python
UTF-8
Python
false
false
2,510
py
base.py
import typing from types import TracebackType from .._models import Request, Response T = typing.TypeVar("T", bound="BaseTransport") A = typing.TypeVar("A", bound="AsyncBaseTransport") class BaseTransport: def __enter__(self: T) -> T: return self def __exit__( self, exc_type: typing.Optional[typing.Type[BaseException]] = None, exc_value: typing.Optional[BaseException] = None, traceback: typing.Optional[TracebackType] = None, ) -> None: self.close() def handle_request(self, request: Request) -> Response: """ Send a single HTTP request and return a response. Developers shouldn't typically ever need to call into this API directly, since the Client class provides all the higher level user-facing API niceties. In order to properly release any network resources, the response stream should *either* be consumed immediately, with a call to `response.stream.read()`, or else the `handle_request` call should be followed with a try/finally block to ensuring the stream is always closed. Example usage: with httpx.HTTPTransport() as transport: req = httpx.Request( method=b"GET", url=(b"https", b"www.example.com", 443, b"/"), headers=[(b"Host", b"www.example.com")], ) resp = transport.handle_request(req) body = resp.stream.read() print(resp.status_code, resp.headers, body) Takes a `Request` instance as the only argument. Returns a `Response` instance. """ raise NotImplementedError( "The 'handle_request' method must be implemented." ) # pragma: no cover def close(self) -> None: pass class AsyncBaseTransport: async def __aenter__(self: A) -> A: return self async def __aexit__( self, exc_type: typing.Optional[typing.Type[BaseException]] = None, exc_value: typing.Optional[BaseException] = None, traceback: typing.Optional[TracebackType] = None, ) -> None: await self.aclose() async def handle_async_request( self, request: Request, ) -> Response: raise NotImplementedError( "The 'handle_async_request' method must be implemented." ) # pragma: no cover async def aclose(self) -> None: pass
ed79f55a3ffc95e30365879465205da58cc85de8
53da5088e9856600eea25dc82e62a062e86e8719
/tests/test_tools.py
20985d39e9f1c5a2c3e60c77442ba83bb27fdf44
[ "Apache-2.0" ]
permissive
NLeSC/mcfly
0d84731282b24b7e08908e2331b950ab3f6224e8
958aa1c115ca55a50272e39f3855086a8fb59309
refs/heads/main
2023-08-30T01:15:41.822669
2023-05-30T07:39:57
2023-05-30T07:39:57
59,207,352
377
99
Apache-2.0
2023-02-08T13:03:22
2016-05-19T13:09:26
JavaScript
UTF-8
Python
false
false
111
py
test_tools.py
import os def safe_remove(path): try: os.remove(path) except FileNotFoundError: pass
597f6ca8ebca41d9c35a298d1c4b65806f63b4c9
10ddfb2d43a8ec5d47ce35dc0b8acf4fd58dea94
/Python/making-a-large-island.py
1156ca1d2c5dbf1fb71263aa936b007999f262a0
[ "MIT" ]
permissive
kamyu104/LeetCode-Solutions
f54822059405ef4df737d2e9898b024f051fd525
4dc4e6642dc92f1983c13564cc0fd99917cab358
refs/heads/master
2023-09-02T13:48:26.830566
2023-08-28T10:11:12
2023-08-28T10:11:12
152,631,182
4,549
1,651
MIT
2023-05-31T06:10:33
2018-10-11T17:38:35
C++
UTF-8
Python
false
false
1,457
py
making-a-large-island.py
# Time: O(n^2) # Space: O(n^2) class Solution(object): def largestIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] def dfs(r, c, index, grid): if not (0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == 1): return 0 result = 1 grid[r][c] = index for d in directions: result += dfs(r+d[0], c+d[1], index, grid) return result area = {} index = 2 for r in xrange(len(grid)): for c in xrange(len(grid[r])): if grid[r][c] == 1: area[index] = dfs(r, c, index, grid) index += 1 result = max(area.values() or [0]) for r in xrange(len(grid)): for c in xrange(len(grid[r])): if grid[r][c] == 0: seen = set() for d in directions: nr, nc = r+d[0], c+d[1] if not (0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] > 1): continue seen.add(grid[nr][nc]) result = max(result, 1 + sum(area[i] for i in seen)) return result
c0181a608520efedfcd545dcb3664dc19dbfdfdb
9b1a345a2377bbac949856f2aac8947ab2e26205
/pwndbg/commands/ipython_interactive.py
d73fa02fc2fb93089a99a3aa1ccab7b93ec3de0b
[ "MIT" ]
permissive
pwndbg/pwndbg
4577c02d213fa347891d7e0f5415beb2a497c002
f642efbd92e30c7b892b5e816d353cc5a03e5cb5
refs/heads/dev
2023-08-31T10:48:45.172197
2023-08-27T09:55:46
2023-08-27T10:12:02
31,181,767
5,954
1,080
MIT
2023-09-11T11:03:02
2015-02-22T21:35:19
Python
UTF-8
Python
false
false
1,532
py
ipython_interactive.py
""" Command to start an interactive IPython prompt. """ from __future__ import annotations import sys from contextlib import contextmanager import gdb import pwndbg.color.message as M import pwndbg.commands import pwndbg.lib.stdio @contextmanager def switch_to_ipython_env(): """We need to change stdout/stderr to the default ones, otherwise we can't use tab or autocomplete""" # Save GDB's excepthook saved_excepthook = sys.excepthook # Switch to default stdout/stderr with pwndbg.lib.stdio.stdio: yield # Restore Python's default ps1, ps2, and excepthook for GDB's `pi` command sys.ps1 = ">>> " sys.ps2 = "... " sys.excepthook = saved_excepthook @pwndbg.commands.ArgparsedCommand("Start an interactive IPython prompt.") def ipi() -> None: with switch_to_ipython_env(): # Use `gdb.execute` to embed IPython into GDB's variable scope try: gdb.execute("pi import IPython") except gdb.error: print( M.warn( "Cannot import IPython.\n" "You need to install IPython if you want to use this command.\n" "Maybe you can try `pip install ipython` first." ) ) return code4ipython = """import jedi import pwn jedi.Interpreter._allow_descriptor_getattr_default = False IPython.embed(colors='neutral',banner1='',confirm_exit=False,simple_prompt=False, user_ns=globals()) """ gdb.execute(f"py\n{code4ipython}")
08e69ac861832a1b9c26c6da01d0c8108c442b00
0fa67bbf0a669ea3e68cc2e8d474ff2b1c9d8641
/train.py
4e8659b6a3c9244302847e4327392782e041e0f6
[ "MIT" ]
permissive
SeanNaren/deepspeech.pytorch
90bc4c17282937f2edd5b35ddd1d2ab5de968fc8
b88a631ef6b96553e16bbaa5bd6a621435bed278
refs/heads/master
2023-08-20T08:38:23.593110
2022-10-24T12:11:50
2022-10-24T12:11:50
78,508,757
2,193
747
MIT
2022-12-13T15:02:28
2017-01-10T07:28:18
Python
UTF-8
Python
false
false
878
py
train.py
import hydra from hydra.core.config_store import ConfigStore from deepspeech_pytorch.configs.lightning_config import ModelCheckpointConf from deepspeech_pytorch.configs.train_config import DeepSpeechConfig, AdamConfig, SGDConfig, BiDirectionalConfig, \ UniDirectionalConfig from deepspeech_pytorch.training import train cs = ConfigStore.instance() cs.store(name="config", node=DeepSpeechConfig) cs.store(group="optim", name="sgd", node=SGDConfig) cs.store(group="optim", name="adam", node=AdamConfig) cs.store(group="checkpoint", name="file", node=ModelCheckpointConf) cs.store(group="model", name="bidirectional", node=BiDirectionalConfig) cs.store(group="model", name="unidirectional", node=UniDirectionalConfig) @hydra.main(config_path='.', config_name="config") def hydra_main(cfg: DeepSpeechConfig): train(cfg=cfg) if __name__ == '__main__': hydra_main()
3a715a053064e5408d8b152e9e803d474de644aa
5a361fd402b330189792b592465c1fc48c6a5fb4
/application/flicket/scripts/flicket_user_details.py
5e0177f9db6ba299ec03ee216bcee29256c54373
[ "MIT" ]
permissive
evereux/flicket
a807e4a3cabce45b42cf02acceee1deb023b0487
ef1330dca9bcc75cedd9fb68a0ecb4de67f2e6cc
refs/heads/master
2023-05-10T17:14:05.116769
2023-05-01T11:20:23
2023-05-01T11:20:23
74,390,774
120
64
MIT
2023-05-02T00:13:00
2016-11-21T17:58:26
Python
UTF-8
Python
false
false
1,023
py
flicket_user_details.py
#! usr/bin/python3 # -*- coding: utf-8 -*- # # Flicket - copyright Paul Bourne: evereux@gmail.com from application.flicket.models.flicket_models import FlicketTicket, FlicketPost class FlicketUserDetails: """ class returns various details about user from user object input. """ def __init__(self, user_obj): self.user = user_obj self.id = user_obj.id @property def num_assigned(self): """ return number of tickers assigned to user """ return FlicketTicket.query.filter_by(assigned=self.user).count() @property def num_posts(self): """ return number of post made by user """ return FlicketTicket.query.filter_by(started_id=self.id).count() + FlicketPost.query.filter_by( user_id=self.id).count() def __repr__(self): return "<FlicketUserDetails: id={}, num_assigned={}, num_posts>".format(self.id, self.num_assigned, self.num_posts)
eb0267923849d6eef2e52797e352d5b987ac3688
c4a119311ac01bbe7d5ab81b1d3d663ad0900ab6
/python3-alpha/python-libs/gdata/tlslite/VerifierDB.py
792bd5d6d1531b05f68bf678838e039c0a7a8d92
[ "Apache-2.0" ]
permissive
kuri65536/python-for-android
1d8d99e81e64bc87805c2c58ee0dcf43d413e72e
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
refs/heads/master
2021-06-02T01:17:29.685199
2018-05-05T00:12:13
2018-05-05T01:36:22
32,235,625
280
122
Apache-2.0
2020-05-15T06:47:36
2015-03-14T22:44:36
Python
UTF-8
Python
false
false
3,114
py
VerifierDB.py
"""Class for storing SRP password verifiers.""" from .utils.cryptomath import * from .utils.compat import * from . import mathtls from .BaseDB import BaseDB class VerifierDB(BaseDB): """This class represent an in-memory or on-disk database of SRP password verifiers. A VerifierDB can be passed to a server handshake to authenticate a client based on one of the verifiers. This class is thread-safe. """ def __init__(self, filename=None): """Create a new VerifierDB instance. @type filename: str @param filename: Filename for an on-disk database, or None for an in-memory database. If the filename already exists, follow this with a call to open(). To create a new on-disk database, follow this with a call to create(). """ BaseDB.__init__(self, filename, "verifier") def _getItem(self, username, valueStr): (N, g, salt, verifier) = valueStr.split(" ") N = base64ToNumber(N) g = base64ToNumber(g) salt = base64ToString(salt) verifier = base64ToNumber(verifier) return (N, g, salt, verifier) def __setitem__(self, username, verifierEntry): """Add a verifier entry to the database. @type username: str @param username: The username to associate the verifier with. Must be less than 256 characters in length. Must not already be in the database. @type verifierEntry: tuple @param verifierEntry: The verifier entry to add. Use L{tlslite.VerifierDB.VerifierDB.makeVerifier} to create a verifier entry. """ BaseDB.__setitem__(self, username, verifierEntry) def _setItem(self, username, value): if len(username)>=256: raise ValueError("username too long") N, g, salt, verifier = value N = numberToBase64(N) g = numberToBase64(g) salt = stringToBase64(salt) verifier = numberToBase64(verifier) valueStr = " ".join( (N, g, salt, verifier) ) return valueStr def _checkItem(self, value, username, param): (N, g, salt, verifier) = value x = mathtls.makeX(salt, username, param) v = powMod(g, x, N) return (verifier == v) def makeVerifier(username, password, bits): """Create a verifier entry which can be stored in a VerifierDB. @type username: str @param username: The username for this verifier. Must be less than 256 characters in length. @type password: str @param password: The password for this verifier. @type bits: int @param bits: This values specifies which SRP group parameters to use. It must be one of (1024, 1536, 2048, 3072, 4096, 6144, 8192). Larger values are more secure but slower. 2048 is a good compromise between safety and speed. @rtype: tuple @return: A tuple which may be stored in a VerifierDB. """ return mathtls.makeVerifier(username, password, bits) makeVerifier = staticmethod(makeVerifier)
4f9035d32883cdea1feaf540ed58f36d44c6d16d
753cd066a9bd26b6c37c8d53a86c7a9c659ec18c
/vision/swin/pytorch/swin_test.py
c67601aca5ff80c10b6c43c7b54cfb0fc43e82e4
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
graphcore/examples
ac872015808ed2a913d4d7bf0d63202ce15ebbae
e2f834dd60e7939672c1795b4ac62e89ad0bca49
refs/heads/master
2023-08-05T02:08:12.341836
2023-07-27T11:13:10
2023-07-27T11:13:10
143,977,106
311
80
MIT
2023-09-11T16:42:56
2018-08-08T07:29:17
Python
UTF-8
Python
false
false
7,134
py
swin_test.py
# Copyright (c) 2022 Graphcore Ltd. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import time import argparse import datetime import numpy as np import torch import torch.nn as nn from config import get_config from models.build import build_pipeline as build_model from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy from optimizer import build_optimizer from options import get_options import poptorch from collections import OrderedDict from torchvision import datasets, transforms from torch.utils.data import Dataset from lr_scheduler import build_scheduler from timm.models import resume_checkpoint from dataset.ipu_mixup import Mixup from pathlib import Path import unittest import pytest import ctypes import subprocess swin_root_path = str(Path(__file__).parent) sys.path.append(swin_root_path) class ReturnIndexDataset(datasets.ImageFolder): def __getitem__(self, idx): img, lab = super(ReturnIndexDataset, self).__getitem__(idx) return img, lab def parse_option(): parser = argparse.ArgumentParser("Swin Transformer training and evaluation script", add_help=False) parser.add_argument( "--cfg", default="SWIN_LARGE_224_22K_FINETUNE_1K_FP16_POD16", type=str, metavar="PATH", help="path to config file", ) parser.add_argument("--batch-size", type=int, help="batch size for single GPU") parser.add_argument("--num-workers", type=int, default=8, help="batch size for single GPU") parser.add_argument("--weights", type=str, help="weights for model") parser.add_argument("--device", type=str, default="", choices=["cpu", "ipu", "gpu"]) parser.add_argument("--alignment", action="store_true", help="if alignment fwd or bwd") parser.add_argument("--half", default=True, action="store_true", help="use half") parser.add_argument( "--resume", default="", type=str, metavar="PATH", help="Resume full model and optimizer state from checkpoint (default: none)", ) parser.add_argument("--data-path", type=str, metavar="FILE", help="path to dataset") parser.add_argument("--checkpoint-output-dir", type=str, metavar="FILE", help="path to save output files") parser.add_argument("--pretrained-model", type=str, help="path to init checkpoint when fine tune models") parser.add_argument("--ga", type=int, help="Gradient Accumulations Steps") parser.add_argument("--amp", type=float, help="Available memory proportion") parser.add_argument("--rts", action="store_true", help="Replicated tensor sharding") parser.add_argument("--compile-only", action="store_true", help="Compile only") args, unparsed = parser.parse_known_args() config = get_config(args) return args, config def get_random_datum(config): result = [] batch_size = config.DATA.BATCH_SIZE * config.IPU.NUM_LOCALREPLICA * config.IPU.GRADIENT_ACCUMULATION_STEPS if config.PRECISION[0] == "half": use_half = True else: use_half = False dataset = GeneratedDataset( shape=[3, config.DATA.IMG_SIZE[0], config.DATA.IMG_SIZE[0]], size=batch_size, half_precision=use_half ) data = (dataset[i] for i in range(batch_size)) for batches in zip(*data): result.append(torch.stack(batches)) return result class GeneratedDataset(Dataset): """ Generated dataset creates a random dataset with the given shape and precision. The size determines the number of items in the dataset. """ def __init__(self, shape, size=60000, half_precision=True): # use_half self.size = size self.half_precision = half_precision self.data_shape = shape def __len__(self): return self.size def __getitem__(self, index): synthetic_data = torch.rand(self.data_shape) synthetic_label = torch.randint(0, 2, [1], dtype=torch.long) if self.half_precision: synthetic_data = synthetic_data.half() return synthetic_data, synthetic_label def compile_model(poptorch_model, config): datum = get_random_datum(config) (pre_input, pre_label) = datum mixup_fn = Mixup( mixup_alpha=config.AUG.MIXUP, cutmix_alpha=config.AUG.CUTMIX, cutmix_minmax=config.AUG.CUTMIX_MINMAX, prob=config.AUG.MIXUP_PROB, switch_prob=config.AUG.MIXUP_SWITCH_PROB, mode=config.AUG.MIXUP_MODE, label_smoothing=config.MODEL.LABEL_SMOOTHING, num_classes=config.MODEL.NUM_CLASSES, ) pre_input, pre_label = mixup_fn(pre_input, pre_label) poptorch_model.compile(pre_input, pre_label) return pre_input, pre_label class TestSWIN(unittest.TestCase): @pytest.mark.ipus(8) def test_swin_model(self): cmd = "make" ret = subprocess.check_call(cmd, shell=True, cwd=swin_root_path) assert os.path.exists(os.path.join(swin_root_path, "custom_ops.so")), "please compile custom op" ctypes.cdll.LoadLibrary(os.path.join(swin_root_path, "custom_ops.so")) args, config = parse_option() config.defrost() config.IPU.NUM_LOCALREPLICA = 1 config.IPU.GRADIENT_ACCUMULATION_STEPS = 16 config.freeze() seed = config.SEED torch.manual_seed(seed) np.random.seed(seed) opts = get_options(config) self.train(args, opts, config) def train(self, args, opts, config): if config.AUG.MIXUP > 0.0: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif config.MODEL.LABEL_SMOOTHING > 0.0: criterion = LabelSmoothingCrossEntropy(smoothing=config.MODEL.LABEL_SMOOTHING) else: criterion = torch.nn.CrossEntropyLoss() model = build_model(config=config, train_loss_fn=criterion) if args.half: print("use half") model.half() optimizer = build_optimizer(config, model) model = poptorch.trainingModel(model.train(), opts, optimizer=optimizer) data, targets = compile_model(model, config) lr_scheduler = build_scheduler(config, optimizer, 10008) start_epoch = 0 if lr_scheduler is not None and start_epoch > 0: lr_scheduler.step(start_epoch) for step in range(0, 100): time_s = time.time() model.setOptimizer(lr_scheduler.optimizer) _, loss = model(data, targets) time_e = time.time() print("batch time:", time_e - time_s) assert loss.mean() <= 10.0, "loss error"
99f13d8f00c0b4fbb9f6805e21e0c27d5274fbbd
e228abda54dc7ab992ba634997b0d21b7200d091
/dynamic_rest/__init__.py
4366be935b7d5c08739d5d1f9f89ee4ac71acb19
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
AltSchool/dynamic-rest
3fd2456d72fdf84e75556bc0fea7303e496b7ec7
ed69e5af4ddf153e6eb304b7db80cc6adbf4d654
refs/heads/master
2023-09-06T01:57:47.555537
2023-03-27T16:15:22
2023-03-27T16:15:22
31,736,312
812
131
MIT
2023-05-28T09:15:45
2015-03-05T21:05:17
Python
UTF-8
Python
false
false
363
py
__init__.py
"""Dynamic REST (or DREST) is an extension of Django REST Framework. DREST offers the following features on top of the standard DRF kit: - Linked/embedded/sideloaded relationships - Field inclusions/exlusions - Field-based filtering/sorting - Directory panel for the browsable API - Optimizations """ default_app_config = "dynamic_rest.apps.DynamicRestConfig"
e5558f2a8220dc75ec5b191d8ab1348e83e13004
10ddfb2d43a8ec5d47ce35dc0b8acf4fd58dea94
/Python/minimum-adjacent-swaps-to-reach-the-kth-smallest-number.py
7b8bb0085f73d3df25f0029198db6ba37074bc41
[ "MIT" ]
permissive
kamyu104/LeetCode-Solutions
f54822059405ef4df737d2e9898b024f051fd525
4dc4e6642dc92f1983c13564cc0fd99917cab358
refs/heads/master
2023-09-02T13:48:26.830566
2023-08-28T10:11:12
2023-08-28T10:11:12
152,631,182
4,549
1,651
MIT
2023-05-31T06:10:33
2018-10-11T17:38:35
C++
UTF-8
Python
false
false
1,641
py
minimum-adjacent-swaps-to-reach-the-kth-smallest-number.py
# Time: O((k + n) * n) # Space: O(n) class Solution(object): def getMinSwaps(self, num, k): """ :type num: str :type k: int :rtype: int """ def next_permutation(nums, begin, end): def reverse(nums, begin, end): left, right = begin, end-1 while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 k, l = begin-1, begin for i in reversed(xrange(begin, end-1)): if nums[i] < nums[i+1]: k = i break else: reverse(nums, begin, end) return False for i in reversed(xrange(k+1, end)): if nums[i] > nums[k]: l = i break nums[k], nums[l] = nums[l], nums[k] reverse(nums, k+1, end) return True new_num = list(num) while k: next_permutation(new_num, 0, len(new_num)) k -= 1 result = 0 for i in xrange(len(new_num)): if new_num[i] == num[i]: continue # // greedily move the one with the least cost from new_num to num without missing optimal cost for j in xrange(i+1, len(new_num)): if new_num[j] == num[i]: break result += j-i for j in reversed(xrange(i+1, j+1)): new_num[j], new_num[j-1] = new_num[j-1], new_num[j] return result
634fafc11b8770030093ca1854275bfb9b1a32ea
15eb68a30bd1bcd8c153ce3c8774e09ef3f4135d
/Docs/torch_code_examples/quant_analyzer_code_example.py
803f43dff282d2539437d991186382e3b421b7f8
[ "BSD-3-Clause" ]
permissive
quic/aimet
77a984af68fc3c46d98c707d18a14c95a3efdacf
5a406e657082b6a4f6e4bf48f0e46e085cb1e351
refs/heads/develop
2023-08-21T12:51:10.500286
2023-08-18T18:35:39
2023-08-18T18:35:39
257,688,216
1,676
339
NOASSERTION
2023-09-08T06:59:39
2020-04-21T18:57:10
Python
UTF-8
Python
false
false
6,557
py
quant_analyzer_code_example.py
# /usr/bin/env python3.6 # -*- mode: python -*- # ============================================================================= # @@-COPYRIGHT-START-@@ # # Copyright (c) 2022, Qualcomm Innovation Center, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # SPDX-License-Identifier: BSD-3-Clause # # @@-COPYRIGHT-END-@@ # ============================================================================= # pylint: skip-file """ Quant Analyzer code example """ # Step 0. Import statements from typing import Any import torch from torchvision import models from aimet_common.defs import QuantScheme from aimet_torch.model_preparer import prepare_model from aimet_torch.quant_analyzer import QuantAnalyzer, CallbackFunc # End step 0 # Step 1. Prepare forward pass callback # NOTE: In the actual use cases, the users should implement this part to serve # their own goals if necessary. def forward_pass_callback(model: torch.nn.Module, _: Any = None) -> None: """ NOTE: This is intended to be the user-defined model calibration function. AIMET requires the above signature. So if the user's calibration function does not match this signature, please create a simple wrapper around this callback function. A callback function for model calibration that simply runs forward passes on the model to compute encoding (delta/offset). This callback function should use representative data and should be subset of entire train/validation dataset (~1000 images/samples). :param model: PyTorch model. :param _: Argument(s) of this callback function. Up to the user to determine the type of this parameter. E.g. could be simply an integer representing the number of data samples to use. Or could be a tuple of parameters or an object representing something more complex. """ # User action required # User should create data loader/iterable using representative dataset and simply run # forward passes on the model. # End step 1 # Step 2. Prepare eval callback # NOTE: In the actual use cases, the users should implement this part to serve # their own goals if necessary. def eval_callback(model: torch.nn.Module, _: Any = None) -> float: """ NOTE: This is intended to be the user-defined model evaluation function. AIMET requires the above signature. So if the user's calibration function does not match this signature, please create a simple wrapper around this callback function. A callback function for model evaluation that determines model performance. This callback function is expected to return scalar value representing the model performance evaluated against entire test/evaluation dataset. :param model: PyTorch model. :param _: Argument(s) of this callback function. Up to the user to determine the type of this parameter. E.g. could be simply an integer representing the number of data samples to use. Or could be a tuple of parameters or an object representing something more complex. :return: Scalar value representing the model performance. """ # User action required # User should create data loader/iterable using entire test/evaluation dataset, perform forward passes on # the model and return single scalar value representing the model performance. return .8 # End step 2 def quant_analyzer_example(): # Step 3. Prepare model model = models.resnet18(pretrained=True).cuda().eval() input_shape = (1, 3, 224, 224) dummy_input = torch.randn(*input_shape).cuda() prepared_model = prepare_model(model) # End step 3 # User action required # User should pass actual argument(s) of the callback functions. forward_pass_callback_fn = CallbackFunc(forward_pass_callback, func_callback_args=None) eval_callback_fn = CallbackFunc(eval_callback, func_callback_args=None) # User action required # User should use unlabeled dataloader, so if the dataloader yields labels as well user should use discard them. unlabeled_data_loader = _get_unlabled_data_loader() # Step 4. Create QuantAnalyzer object quant_analyzer = QuantAnalyzer(model=prepared_model, dummy_input=dummy_input, forward_pass_callback=forward_pass_callback_fn, eval_callback=eval_callback_fn) # Approximately 256 images/samples are recommended for MSE loss analysis. So, if the dataloader # has batch_size of 64, then 4 number of batches leads to 256 images/samples. quant_analyzer.enable_per_layer_mse_loss(unlabeled_dataset_iterable=unlabeled_data_loader, num_batches=4) # End step 4 # Step 5. Run QuantAnalyzer quant_analyzer.analyze(quant_scheme=QuantScheme.post_training_tf_enhanced, default_param_bw=8, default_output_bw=8, config_file=None, results_dir="./quant_analyzer_results/") # End step 5 if __name__ == '__main__': quant_analyzer_example()
ba4f9f4c6234d1f3818d8cbbee6c0013764db4b6
c50e7eb190802d7849c0d0cea02fb4d2f0021777
/src/connection-monitor-preview/azext_connection_monitor_preview/custom.py
61afca26e02187dc861d04a60df2193c69231b45
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
Azure/azure-cli-extensions
c1615b19930bba7166c282918f166cd40ff6609c
b8c2cf97e991adf0c0a207d810316b8f4686dc29
refs/heads/main
2023-08-24T12:40:15.528432
2023-08-24T09:17:25
2023-08-24T09:17:25
106,580,024
336
1,226
MIT
2023-09-14T10:48:57
2017-10-11T16:27:31
Python
UTF-8
Python
false
false
40,175
py
custom.py
# pylint: disable=unused-argument,too-many-locals # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from knack.util import CLIError def create_nw_connection_monitor(cmd, client, connection_monitor_name, watcher_rg, watcher_name, resource_group_name=None, location=None, source_resource=None, source_port=None, dest_resource=None, dest_port=None, dest_address=None, tags=None, do_not_start=None, monitoring_interval=None, endpoint_source_name=None, endpoint_source_resource_id=None, endpoint_source_address=None, endpoint_dest_name=None, endpoint_dest_resource_id=None, endpoint_dest_address=None, test_config_name=None, test_config_frequency=None, test_config_protocol=None, test_config_preferred_ip_version=None, test_config_threshold_failed_percent=None, test_config_threshold_round_trip_time=None, test_config_tcp_disable_trace_route=None, test_config_tcp_port=None, test_config_icmp_disable_trace_route=None, test_config_http_port=None, test_config_http_method=None, test_config_http_path=None, test_config_http_valid_status_codes=None, test_config_http_prefer_https=None, test_group_name=None, test_group_disable=None, output_type=None, workspace_ids=None, notes=None): v1_required_parameter_set = [ source_resource, source_port, dest_resource, dest_address, dest_port ] v2_required_parameter_set = [ endpoint_source_name, endpoint_source_resource_id, endpoint_dest_name, endpoint_dest_address, test_config_name, test_config_protocol, output_type, workspace_ids, ] if any(v1_required_parameter_set): # V1 creation connection_monitor = _create_nw_connection_monitor_v1(cmd, connection_monitor_name, watcher_rg, watcher_name, source_resource, resource_group_name, source_port, location, dest_resource, dest_port, dest_address, tags, do_not_start, monitoring_interval) from ._client_factory import cf_nw_connection_monitor_v1 client = cf_nw_connection_monitor_v1(cmd.cli_ctx).connection_monitors # overwrite to use 2019-06-01 API elif any(v2_required_parameter_set): # V2 creation connection_monitor = _create_nw_connection_monitor_v2(cmd, location, tags, endpoint_source_name, endpoint_source_resource_id, endpoint_source_address, endpoint_dest_name, endpoint_dest_resource_id, endpoint_dest_address, test_config_name, test_config_frequency, test_config_protocol, test_config_preferred_ip_version, test_config_threshold_failed_percent, test_config_threshold_round_trip_time, test_config_tcp_port, test_config_tcp_disable_trace_route, test_config_icmp_disable_trace_route, test_config_http_port, test_config_http_method, test_config_http_path, test_config_http_valid_status_codes, test_config_http_prefer_https, test_group_name, test_group_disable, output_type, workspace_ids, notes) else: raise CLIError('Unknown operation') return client.create_or_update(watcher_rg, watcher_name, connection_monitor_name, connection_monitor) def _create_nw_connection_monitor_v1(cmd, connection_monitor_name, watcher_rg, watcher_name, source_resource, resource_group_name=None, source_port=None, location=None, dest_resource=None, dest_port=None, dest_address=None, tags=None, do_not_start=None, monitoring_interval=60): ConnectionMonitor, ConnectionMonitorSource, ConnectionMonitorDestination = cmd.get_models( 'ConnectionMonitor', 'ConnectionMonitorSource', 'ConnectionMonitorDestination') cmv1 = ConnectionMonitor( location=location, tags=tags, source=ConnectionMonitorSource( resource_id=source_resource, port=source_port ), destination=ConnectionMonitorDestination( resource_id=dest_resource, port=dest_port, address=dest_address ), auto_start=not do_not_start, monitoring_interval_in_seconds=monitoring_interval, endpoints=None, test_configurations=None, test_groups=None, outputs=None, nots=None ) return cmv1 def _create_nw_connection_monitor_v2(cmd, location=None, tags=None, endpoint_source_name=None, endpoint_source_resource_id=None, endpoint_source_address=None, endpoint_dest_name=None, endpoint_dest_resource_id=None, endpoint_dest_address=None, test_config_name=None, test_config_frequency=None, test_config_protocol=None, test_config_preferred_ip_version=None, test_config_threshold_failed_percent=None, test_config_threshold_round_trip_time=None, test_config_tcp_port=None, test_config_tcp_disable_trace_route=False, test_config_icmp_disable_trace_route=False, test_config_http_port=None, test_config_http_method=None, test_config_http_path=None, test_config_http_valid_status_codes=None, test_config_http_prefer_https=None, test_group_name=None, test_group_disable=False, output_type=None, workspace_ids=None, notes=None): src_endpoint = _create_nw_connection_monitor_v2_endpoint(cmd, endpoint_source_name, endpoint_source_resource_id, endpoint_source_address) dst_endpoint = _create_nw_connection_monitor_v2_endpoint(cmd, endpoint_dest_name, endpoint_dest_resource_id, endpoint_dest_address) test_config = _create_nw_connection_monitor_v2_test_configuration(cmd, test_config_name, test_config_frequency, test_config_protocol, test_config_threshold_failed_percent, test_config_threshold_round_trip_time, test_config_preferred_ip_version, test_config_tcp_port, test_config_tcp_disable_trace_route, test_config_icmp_disable_trace_route, test_config_http_port, test_config_http_method, test_config_http_path, test_config_http_valid_status_codes, test_config_http_prefer_https) test_group = _create_nw_connection_monitor_v2_test_group(cmd, test_group_name, test_group_disable, [test_config], [src_endpoint], [dst_endpoint]) if output_type: outputs = [] if workspace_ids: for workspace_id in workspace_ids: output = _create_nw_connection_monitor_v2_output(cmd, output_type, workspace_id) outputs.append(output) else: outputs = [] ConnectionMonitor = cmd.get_models('ConnectionMonitor') cmv2 = ConnectionMonitor(location=location, tags=tags, auto_start=None, monitoring_interval_in_seconds=None, endpoints=[src_endpoint, dst_endpoint], test_configurations=[test_config], test_groups=[test_group], outputs=outputs, notes=notes) return cmv2 def _create_nw_connection_monitor_v2_endpoint(cmd, name, resource_id=None, address=None, filter_type=None, filter_items=None): if (filter_type and not filter_items) or (not filter_type and filter_items): raise CLIError('usage error: ' '--filter-type and --filter-item for endpoint filter must be present at the same time.') ConnectionMonitorEndpoint, ConnectionMonitorEndpointFilter = cmd.get_models( 'ConnectionMonitorEndpoint', 'ConnectionMonitorEndpointFilter') endpoint = ConnectionMonitorEndpoint(name=name, resource_id=resource_id, address=address) if filter_type and filter_items: endpoint_filter = ConnectionMonitorEndpointFilter(type=filter_type, items=filter_items) endpoint.filter = endpoint_filter return endpoint def _create_nw_connection_monitor_v2_test_configuration(cmd, name, test_frequency, protocol, threshold_failed_percent, threshold_round_trip_time, preferred_ip_version, tcp_port=None, tcp_disable_trace_route=None, icmp_disable_trace_route=None, http_port=None, http_method=None, http_path=None, http_valid_status_codes=None, http_prefer_https=None, http_request_headers=None): (ConnectionMonitorTestConfigurationProtocol, ConnectionMonitorTestConfiguration, ConnectionMonitorSuccessThreshold) = cmd.get_models( 'ConnectionMonitorTestConfigurationProtocol', 'ConnectionMonitorTestConfiguration', 'ConnectionMonitorSuccessThreshold') test_config = ConnectionMonitorTestConfiguration(name=name, test_frequency_sec=test_frequency, protocol=protocol, preferred_ip_version=preferred_ip_version) if threshold_failed_percent or threshold_round_trip_time: threshold = ConnectionMonitorSuccessThreshold(checks_failed_percent=threshold_failed_percent, round_trip_time_ms=threshold_round_trip_time) test_config.success_threshold = threshold if protocol == ConnectionMonitorTestConfigurationProtocol.tcp: ConnectionMonitorTcpConfiguration = cmd.get_models('ConnectionMonitorTcpConfiguration') tcp_config = ConnectionMonitorTcpConfiguration( port=tcp_port, tcp_disable_trace_route=tcp_disable_trace_route ) test_config.tcp_configuration = tcp_config elif protocol == ConnectionMonitorTestConfigurationProtocol.icmp: ConnectionMonitorIcmpConfiguration = cmd.get_models('ConnectionMonitorIcmpConfiguration') icmp_config = ConnectionMonitorIcmpConfiguration(disable_trace_route=icmp_disable_trace_route) test_config.icmp_configuration = icmp_config elif protocol == ConnectionMonitorTestConfigurationProtocol.http: ConnectionMonitorHttpConfiguration = cmd.get_models('ConnectionMonitorHttpConfiguration') http_config = ConnectionMonitorHttpConfiguration( port=http_port, method=http_method, path=http_path, request_headers=http_request_headers, valid_status_code_ranges=http_valid_status_codes, prefer_https=http_prefer_https) test_config.http_configuration = http_config else: raise CLIError('Unsupported protocol: "{}" for test configuration'.format(protocol)) return test_config def _create_nw_connection_monitor_v2_test_group(cmd, name, disable, test_configurations, source_endpoints, destination_endpoints): ConnectionMonitorTestGroup = cmd.get_models('ConnectionMonitorTestGroup') test_group = ConnectionMonitorTestGroup(name=name, disable=disable, test_configurations=[tc.name for tc in test_configurations], sources=[e.name for e in source_endpoints], destinations=[e.name for e in destination_endpoints]) return test_group def _create_nw_connection_monitor_v2_output(cmd, output_type, workspace_id=None): ConnectionMonitorOutput, OutputType = cmd.get_models('ConnectionMonitorOutput', 'OutputType') output = ConnectionMonitorOutput(type=output_type) if output_type == OutputType.workspace: ConnectionMonitorWorkspaceSettings = cmd.get_models('ConnectionMonitorWorkspaceSettings') workspace = ConnectionMonitorWorkspaceSettings(workspace_resource_id=workspace_id) output.workspace_settings = workspace else: raise CLIError('Unsupported output type: "{}"'.format(output_type)) return output def add_nw_connection_monitor_v2_endpoint(cmd, client, watcher_rg, watcher_name, connection_monitor_name, location, name, source_test_groups=None, dest_test_groups=None, resource_id=None, address=None, filter_type=None, filter_items=None): ConnectionMonitorEndpoint, ConnectionMonitorEndpointFilter = cmd.get_models( 'ConnectionMonitorEndpoint', 'ConnectionMonitorEndpointFilter') endpoint = ConnectionMonitorEndpoint(name=name, resource_id=resource_id, address=address) if filter_type and filter_items: endpoint_filter = ConnectionMonitorEndpointFilter(type=filter_type, items=filter_items) endpoint.filter = endpoint_filter connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) connection_monitor.endpoints.append(endpoint) src_test_groups, dst_test_groups = set(source_test_groups or []), set(dest_test_groups or []) for test_group in connection_monitor.test_groups: if test_group.name in src_test_groups: test_group.sources.append(endpoint.name) if test_group.name in dst_test_groups: test_group.destinations.append(endpoint.name) return client.create_or_update(watcher_rg, watcher_name, connection_monitor_name, connection_monitor) def remove_nw_connection_monitor_v2_endpoint(client, watcher_rg, watcher_name, connection_monitor_name, location, name, test_groups=None): connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) # refresh endpoints new_endpoints = [endpoint for endpoint in connection_monitor.endpoints if endpoint.name != name] connection_monitor.endpoints = new_endpoints # refresh test groups if test_groups is not None: temp_test_groups = [t for t in connection_monitor.test_groups if t.name in test_groups] else: temp_test_groups = connection_monitor.test_groups for test_group in temp_test_groups: if name in test_group.sources: test_group.sources.remove(name) if name in test_group.destinations: test_group.destinations.remove(name) return client.create_or_update(watcher_rg, watcher_name, connection_monitor_name, connection_monitor) def show_nw_connection_monitor_v2_endpoint(client, watcher_rg, watcher_name, connection_monitor_name, location, name): connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) for endpoint in connection_monitor.endpoints: if endpoint.name == name: return endpoint raise CLIError('unknown endpoint: {}'.format(name)) def list_nw_connection_monitor_v2_endpoint(client, watcher_rg, watcher_name, connection_monitor_name, location): connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) return connection_monitor.endpoints def add_nw_connection_monitor_v2_test_configuration(cmd, client, watcher_rg, watcher_name, connection_monitor_name, location, name, protocol, test_groups, frequency=None, threshold_failed_percent=None, threshold_round_trip_time=None, preferred_ip_version=None, tcp_port=None, tcp_disable_trace_route=None, icmp_disable_trace_route=None, http_port=None, http_method=None, http_path=None, http_valid_status_codes=None, http_prefer_https=None, http_request_headers=None): new_test_config = _create_nw_connection_monitor_v2_test_configuration(cmd, name, frequency, protocol, threshold_failed_percent, threshold_round_trip_time, preferred_ip_version, tcp_port, tcp_disable_trace_route, icmp_disable_trace_route, http_port, http_method, http_path, http_valid_status_codes, http_prefer_https, http_request_headers) connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) connection_monitor.test_configurations.append(new_test_config) for test_group in connection_monitor.test_groups: if test_group.name in test_groups: test_group.test_configurations.append(new_test_config.name) return client.create_or_update(watcher_rg, watcher_name, connection_monitor_name, connection_monitor) def remove_nw_connection_monitor_v2_test_configuration(client, watcher_rg, watcher_name, connection_monitor_name, location, name, test_groups=None): connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) # refresh test configurations new_test_configurations = [t for t in connection_monitor.test_configurations if t.name != name] connection_monitor.test_configurations = new_test_configurations if test_groups is not None: temp_test_groups = [t for t in connection_monitor.test_groups if t.name in test_groups] else: temp_test_groups = connection_monitor.test_groups # refresh test groups for test_group in temp_test_groups: test_group.test_configurations.remove(name) return client.create_or_update(watcher_rg, watcher_name, connection_monitor_name, connection_monitor) def show_nw_connection_monitor_v2_test_configuration(client, watcher_rg, watcher_name, connection_monitor_name, location, name): connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) for test_config in connection_monitor.test_configurations: if test_config.name == name: return test_config raise CLIError('unknown test configuration: {}'.format(name)) def list_nw_connection_monitor_v2_test_configuration(client, watcher_rg, watcher_name, connection_monitor_name, location): connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) return connection_monitor.test_configurations def add_nw_connection_monitor_v2_test_group(cmd, client, connection_monitor_name, watcher_rg, watcher_name, location, name, endpoint_source_name, endpoint_dest_name, test_config_name, disable=False, endpoint_source_resource_id=None, endpoint_source_address=None, endpoint_dest_resource_id=None, endpoint_dest_address=None, test_config_frequency=None, test_config_protocol=None, test_config_preferred_ip_version=None, test_config_threshold_failed_percent=None, test_config_threshold_round_trip_time=None, test_config_tcp_disable_trace_route=None, test_config_tcp_port=None, test_config_icmp_disable_trace_route=None, test_config_http_port=None, test_config_http_method=None, test_config_http_path=None, test_config_http_valid_status_codes=None, test_config_http_prefer_https=None): new_test_configuration_creation_requirements = [ test_config_protocol, test_config_preferred_ip_version, test_config_threshold_failed_percent, test_config_threshold_round_trip_time, test_config_tcp_disable_trace_route, test_config_tcp_port, test_config_icmp_disable_trace_route, test_config_http_port, test_config_http_method, test_config_http_path, test_config_http_valid_status_codes, test_config_http_prefer_https ] connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) new_test_group = _create_nw_connection_monitor_v2_test_group(cmd, name, disable, [], [], []) # deal with endpoint if any([endpoint_source_address, endpoint_source_resource_id]): src_endpoint = _create_nw_connection_monitor_v2_endpoint(cmd, endpoint_source_name, endpoint_source_resource_id, endpoint_source_address) connection_monitor.endpoints.append(src_endpoint) if any([endpoint_dest_address, endpoint_dest_resource_id]): dst_endpoint = _create_nw_connection_monitor_v2_endpoint(cmd, endpoint_dest_name, endpoint_dest_resource_id, endpoint_dest_address) connection_monitor.endpoints.append(dst_endpoint) new_test_group.sources.append(endpoint_source_name) new_test_group.destinations.append(endpoint_dest_name) # deal with test configuration if any(new_test_configuration_creation_requirements): test_config = _create_nw_connection_monitor_v2_test_configuration(cmd, test_config_name, test_config_frequency, test_config_protocol, test_config_threshold_failed_percent, test_config_threshold_round_trip_time, test_config_preferred_ip_version, test_config_tcp_port, test_config_tcp_disable_trace_route, test_config_icmp_disable_trace_route, test_config_http_port, test_config_http_method, test_config_http_path, test_config_http_valid_status_codes, test_config_http_prefer_https) connection_monitor.test_configurations.append(test_config) new_test_group.test_configurations.append(test_config_name) connection_monitor.test_groups.append(new_test_group) return client.create_or_update(watcher_rg, watcher_name, connection_monitor_name, connection_monitor) def remove_nw_connection_monitor_v2_test_group(client, watcher_rg, watcher_name, connection_monitor_name, location, name): connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) new_test_groups, removed_test_group = [], None for t in connection_monitor.test_groups: if t.name == name: removed_test_group = t else: new_test_groups.append(t) if removed_test_group is None: raise CLIError('test group: "{}" not exist'.format(name)) connection_monitor.test_groups = new_test_groups # deal with endpoints which are only referenced by this removed test group removed_endpoints = [] for e in removed_test_group.sources + removed_test_group.destinations: tmp = [t for t in connection_monitor.test_groups if (e in t.sources or e in t.destinations)] if not tmp: removed_endpoints.append(e) connection_monitor.endpoints = [e for e in connection_monitor.endpoints if e.name not in removed_endpoints] # deal with test configurations which are only referenced by this remove test group removed_test_configurations = [] for c in removed_test_group.test_configurations: tmp = [t for t in connection_monitor.test_groups if c in t.test_configurations] if not tmp: removed_test_configurations.append(c) connection_monitor.test_configurations = [c for c in connection_monitor.test_configurations if c.name not in removed_test_configurations] return client.create_or_update(watcher_rg, watcher_name, connection_monitor_name, connection_monitor) def show_nw_connection_monitor_v2_test_group(client, watcher_rg, watcher_name, connection_monitor_name, location, name): connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) for t in connection_monitor.test_groups: if t.name == name: return t raise CLIError('unknown test group: {}'.format(name)) def list_nw_connection_monitor_v2_test_group(client, watcher_rg, watcher_name, connection_monitor_name, location): connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) return connection_monitor.test_groups def add_nw_connection_monitor_v2_output(cmd, client, watcher_rg, watcher_name, connection_monitor_name, location, out_type, workspace_id=None): output = _create_nw_connection_monitor_v2_output(cmd, out_type, workspace_id) connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) if connection_monitor.outputs is None: connection_monitor.outputs = [] connection_monitor.outputs.append(output) return client.create_or_update(watcher_rg, watcher_name, connection_monitor_name, connection_monitor) def remove_nw_connection_monitor_v2_output(client, watcher_rg, watcher_name, connection_monitor_name, location): connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) connection_monitor.outputs = [] return client.create_or_update(watcher_rg, watcher_name, connection_monitor_name, connection_monitor) def list_nw_connection_monitor_v2_output(client, watcher_rg, watcher_name, connection_monitor_name, location): connection_monitor = client.get(watcher_rg, watcher_name, connection_monitor_name) return connection_monitor.outputs
fb81989702b68a6eb56a8cc96c87650c7b38bfe2
79914e3d51c52fce1b9638c5b15e77b8769aaa01
/bull/__init__.py
91032385649a4d7f9a654d45d1eeab35494459bc
[]
no_license
jeffknupp/bull
aaf1ab62842fcce2a62936d3e8e0b5c2744c8ebc
f3c5f33ec59810d4ee8febf7f9bd769541527f49
refs/heads/develop
2021-03-12T20:00:27.328797
2015-08-20T22:50:04
2015-08-20T22:50:04
16,057,005
105
38
null
2019-10-22T23:52:22
2014-01-19T23:50:53
Python
UTF-8
Python
false
false
716
py
__init__.py
"""Bull library, used for selling digital goods.""" import os from flask import Flask from jinja2 import Environment, FileSystemLoader, ChoiceLoader, PackageLoader import stripe from .bull import bull, mail, login_manager, bcrypt from .models import Product, Purchase, db app = Flask(__name__) app.config['SECRET_KEY'] = 'foo' app.config['WTF_CSRF_KEY'] = 'foo' app.config.from_object('config') app.jinja_loader = ChoiceLoader([ FileSystemLoader(os.path.join(os.getcwd(), 'templates')), PackageLoader('bull'), ]) stripe.api_key = app.config['STRIPE_SECRET_KEY'] db.init_app(app) mail.init_app(app) bcrypt.init_app(app) login_manager.init_app(app) app.register_blueprint(bull) __version__ = '0.4.1'
605b47932d315340ae7f49db429ab575e113d663
1f61e06271f8e9582669686457c40336235d1eee
/Module 1/Chapter 10/face_recognizer.py
e37aac64d21e0515991ce725a652afc9942fb643
[ "MIT" ]
permissive
PacktPublishing/Python-Real-World-Machine-Learning
f1747fdd73937544a243059ac7476bfbfac6d113
669e793cf80c35b6d2028f74bff2cd87b9458791
refs/heads/master
2023-04-13T11:48:13.459731
2023-01-30T09:21:10
2023-01-30T09:21:10
70,907,139
108
111
MIT
2023-04-04T14:38:41
2016-10-14T12:13:47
Jupyter Notebook
UTF-8
Python
false
false
3,759
py
face_recognizer.py
import os import cv2 import numpy as np from sklearn import preprocessing # Class to handle tasks related to label encoding class LabelEncoder(object): # Method to encode labels from words to numbers def encode_labels(self, label_words): self.le = preprocessing.LabelEncoder() self.le.fit(label_words) # Convert input label from word to number def word_to_num(self, label_word): return int(self.le.transform([label_word])[0]) # Convert input label from number to word def num_to_word(self, label_num): return self.le.inverse_transform([label_num])[0] # Extract images and labels from input path def get_images_and_labels(input_path): label_words = [] # Iterate through the input path and append files for root, dirs, files in os.walk(input_path): for filename in (x for x in files if x.endswith('.jpg')): filepath = os.path.join(root, filename) label_words.append(filepath.split('/')[-2]) # Initialize variables images = [] le = LabelEncoder() le.encode_labels(label_words) labels = [] # Parse the input directory for root, dirs, files in os.walk(input_path): for filename in (x for x in files if x.endswith('.jpg')): filepath = os.path.join(root, filename) # Read the image in grayscale format image = cv2.imread(filepath, 0) # Extract the label name = filepath.split('/')[-2] # Perform face detection faces = faceCascade.detectMultiScale(image, 1.1, 2, minSize=(100,100)) # Iterate through face rectangles for (x, y, w, h) in faces: images.append(image[y:y+h, x:x+w]) labels.append(le.word_to_num(name)) return images, labels, le if __name__=='__main__': cascade_path = "cascade_files/haarcascade_frontalface_alt.xml" path_train = 'faces_dataset/train' path_test = 'faces_dataset/test' # Load face cascade file faceCascade = cv2.CascadeClassifier(cascade_path) # Initialize Local Binary Patterns Histogram face recognizer recognizer = cv2.face.createLBPHFaceRecognizer() # Extract images, labels, and label encoder from training dataset images, labels, le = get_images_and_labels(path_train) # Train the face recognizer print "\nTraining..." recognizer.train(images, np.array(labels)) # Test the recognizer on unknown images print '\nPerforming prediction on test images...' stop_flag = False for root, dirs, files in os.walk(path_test): for filename in (x for x in files if x.endswith('.jpg')): filepath = os.path.join(root, filename) # Read the image predict_image = cv2.imread(filepath, 0) # Detect faces faces = faceCascade.detectMultiScale(predict_image, 1.1, 2, minSize=(100,100)) # Iterate through face rectangles for (x, y, w, h) in faces: # Predict the output predicted_index, conf = recognizer.predict( predict_image[y:y+h, x:x+w]) # Convert to word label predicted_person = le.num_to_word(predicted_index) # Overlay text on the output image and display it cv2.putText(predict_image, 'Prediction: ' + predicted_person, (10,60), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 6) cv2.imshow("Recognizing face", predict_image) c = cv2.waitKey(0) if c == 27: stop_flag = True break if stop_flag: break
c3c3d0a31bfe8bd8fc57f357bb86e42242835741
6958f617af0c5a76304ceb1006c77bc70ca0e195
/python/taichi/tools/video.py
70f734efe9cafe726b0792b74b2f84b915c5bb83
[ "Apache-2.0" ]
permissive
taichi-dev/taichi
3fae315a494f1c97392d5b931c939abbbfba1bdc
b30b511f55e3d0ebff765ee048d0aaa4ba9e7667
refs/heads/master
2023-09-02T13:28:18.208792
2023-08-23T23:22:43
2023-08-23T23:22:43
74,660,642
17,231
1,841
Apache-2.0
2023-09-14T11:29:32
2016-11-24T10:00:05
C++
UTF-8
Python
false
false
9,296
py
video.py
import os import shutil from taichi._lib.utils import get_os_name from taichi.tools.image import imwrite FRAME_FN_TEMPLATE = "%06d.png" FRAME_DIR = "frames" # Write the frames to the disk and then make videos (mp4 or gif) if necessary def scale_video(input_fn, output_fn, ratiow, ratioh): os.system(f'ffmpeg -i {input_fn} -vf "scale=iw*{ratiow:.4f}:ih*{ratioh:.4f}" {output_fn}') def crop_video(input_fn, output_fn, x_begin, x_end, y_begin, y_end): os.system( f'ffmpeg -i {input_fn} -filter:v "crop=iw*{x_end - x_begin:.4f}:ih*{y_end - y_begin:.4f}:iw*{x_begin:0.4f}:ih*{1 - y_end:0.4f}" {output_fn}' ) def accelerate_video(input_fn, output_fn, speed): os.system(f'ffmpeg -i {input_fn} -filter:v "setpts={1 / speed:.4f}*PTS" {output_fn}') def get_ffmpeg_path(): return "ffmpeg" def mp4_to_gif(input_fn, output_fn, framerate): # Generate the palette palette_name = "palette.png" if get_os_name() == "win": command = get_ffmpeg_path() + f" -loglevel panic -i {input_fn} -vf 'palettegen' -y {palette_name}" else: command = ( get_ffmpeg_path() + f" -loglevel panic -i {input_fn} -vf 'fps={framerate}," f"scale=320:640:flags=lanczos,palettegen' -y {palette_name}" ) # print command os.system(command) # Generate the GIF command = get_ffmpeg_path() + f" -loglevel panic -i {input_fn} -i {palette_name} -lavfi paletteuse -y {output_fn}" # print command os.system(command) os.remove(palette_name) class VideoManager: """Utility class for exporting results to `mp4` and `gif` formats. This class relies on `ffmpeg`. Args: output_dir (str): directory to save the frames. video_filename (str): filename for the video. default filename is video.mp4. width, height (int): resolution of the video. post_processor (object): any object that implements the `process(img)` method, which accepts an image as a `numpy.ndarray` and returns the process image. framerate (int): frame rate of the video. automatic_build (bool): automatically generate the resulting video or not. Example:: >>> video_manager = ti.tools.VideoManager(output_dir="./output", framerate=24, automatic_build=False) >>> for i in range(50): >>> render() >>> img = pixels.to_numpy() >>> video_manager.write_frame(img) >>> >>> video_manager.make_video(gif=True, mp4=True) Returns: An instance of :class:`taichi.tools.VideoManager` class. """ def __init__( self, output_dir, video_filename=None, width=None, height=None, post_processor=None, framerate=24, automatic_build=True, ): assert (width is None) == (height is None) self.width = width self.height = height self.directory = output_dir self.frame_directory = os.path.join(self.directory, FRAME_DIR) try: os.makedirs(self.frame_directory) except: pass self.video_filename = video_filename self.next_video_checkpoint = 4 self.framerate = framerate self.post_processor = post_processor self.frame_counter = 0 self.frame_fns = [] self.automatic_build = automatic_build def get_output_filename(self, suffix): if not self.video_filename: return os.path.join(self.directory, "video" + suffix) filename, extension = os.path.splitext(self.video_filename) if extension is not None: print(f"Warning: file extension {extension} will be disregarded!") return os.path.join(self.directory, filename + suffix) def write_frame(self, img): """Write an `numpy.ndarray` `img` to an image file. The filename will be automatically determined by this manager and the frame counter. """ if img.shape[0] % 2 != 0: print("Warning: height is not divisible by 2! Dropping last row") img = img[:-1] if img.shape[1] % 2 != 0: print("Warning: width is not divisible by 2! Dropping last column") img = img[:, :-1] if self.post_processor: img = self.post_processor.process(img) if self.width is None: self.width = img.shape[0] self.height = img.shape[1] assert os.path.exists(self.directory) fn = FRAME_FN_TEMPLATE % self.frame_counter self.frame_fns.append(fn) imwrite(img, os.path.join(self.frame_directory, fn)) self.frame_counter += 1 if self.frame_counter % self.next_video_checkpoint == 0: if self.automatic_build: self.make_video() self.next_video_checkpoint *= 2 def get_frame_directory(self): """Returns path to the directory where the image files are located in.""" return self.frame_directory def write_frames(self, images): """Write a list of `numpy.ndarray` `images` to image files.""" for img in images: self.write_frame(img) def clean_frames(self): """Delete all previous image files in the saved directory.""" for fn in os.listdir(self.frame_directory): if fn.endswith(".png") and fn in self.frame_fns: os.remove(fn) def make_video(self, mp4=True, gif=True): """Convert the image files to a `mp4` or `gif` animation.""" fn = self.get_output_filename(".mp4") command = ( (get_ffmpeg_path() + f" -loglevel panic -framerate {self.framerate} -i ") + os.path.join(self.frame_directory, FRAME_FN_TEMPLATE) + " -s:v " + str(self.width) + "x" + str(self.height) + " -c:v libx264 -profile:v high -crf 1 -pix_fmt yuv420p -y " + fn ) os.system(command) if gif: mp4_to_gif( self.get_output_filename(".mp4"), self.get_output_filename(".gif"), self.framerate, ) if not mp4: os.remove(fn) def interpolate_frames(frame_dir, mul=4): # TODO: remove dependency on cv2 here import cv2 # pylint: disable=C0415 files = os.listdir(frame_dir) images = [] images_interpolated = [] for f in sorted(files): if f.endswith("png"): images.append(cv2.imread(f) / 255.0) # pylint: disable=E1101 for i in range(len(images) - 1): images_interpolated.append(images[i]) for j in range(mul - 1): alpha = 1 - j / mul images_interpolated.append(images[i] * alpha + images[i + 1] * (1 - alpha)) images_interpolated.append(images[-1]) os.makedirs("interpolated", exist_ok=True) for i, img in enumerate(images_interpolated): cv2.imwrite(f"interpolated/{i:05d}.png", img * 255.0) # pylint: disable=E1101 def ffmpeg_common_args(frame_rate, input_fn, width, height, crf, output_path): return ( f"{get_ffmpeg_path()} -y -loglevel panic -framerate {frame_rate} -i {input_fn} -s:v {width}x{height} " + f"-c:v libx264 -profile:v high -crf {crf} -pix_fmt yuv420p {output_path}" ) def make_video(input_files, width=0, height=0, frame_rate=24, crf=20, output_path="video.mp4"): """Convert a list of image files to a `gif` or `mp4` animation. Args: input_files (list[str]): the list of image file names. width (int): output video width. height (int): output video height. frame_rate (int): framerate of the output video. crf (int): quality of the output video, the lower the better quality, but also larger file size. output_path (str): path to the output video. """ if isinstance(input_files, list): from PIL import Image # pylint: disable=C0415 with Image.open(input_files[0]) as img: width, height = img.size tmp_dir = "tmp_ffmpeg_dir" os.mkdir(tmp_dir) if width % 2 != 0: print(f"Width ({width}) not divisible by 2") width -= 1 if height % 2 != 0: print(f"Height ({width}) not divisible by 2") height -= 1 for i, inp in enumerate(input_files): shutil.copy(inp, os.path.join(tmp_dir, f"{i:06d}.png")) inputs = f"{tmp_dir}/%06d.png" command = ffmpeg_common_args(frame_rate, inputs, width, height, crf, output_path) ret = os.system(command) assert ret == 0, "ffmpeg failed to generate video file." for i in range(len(input_files)): os.remove(os.path.join(tmp_dir, f"{i:06d}.png")) os.rmdir(tmp_dir) elif isinstance(input_files, str): assert width != 0 and height != 0 command = ffmpeg_common_args(frame_rate, input_files, width, height, crf, output_path) ret = os.system(command) assert ret == 0, "ffmpeg failed to generate video file." else: assert ( False ), f'input_files should be list (of files) or str (of file template, e.g., "%04d.png") instead of {type(input_files)}' __all__ = ["VideoManager"]
2e036da25f32c58a0fd6082232d8cb8a769348fc
607dc8df19fc5248f6289cdda97857b5d58ca16f
/benchmark/src/wrappers/wrapper.py
fe325ca4edf9a1300ff61e3c12a1c9e50d5bac41
[ "BSD-3-Clause", "LicenseRef-scancode-philippe-de-muyter", "LicenseRef-scancode-unknown-license-reference" ]
permissive
automl/SMAC3
7dce243a33023c52d6819deff966f7b502e90ed0
541ee7e0383b491b86d1a23dcff669f2efad616d
refs/heads/main
2023-08-31T17:36:06.067579
2023-08-01T13:02:51
2023-08-01T13:02:51
65,900,469
943
259
NOASSERTION
2023-09-11T02:36:57
2016-08-17T10:58:05
Python
UTF-8
Python
false
false
1,179
py
wrapper.py
from __future__ import annotations from abc import abstractmethod from src.datasets.dataset import Dataset from src.models.model import Model from src.tasks.task import Task class Wrapper: supported_versions: list[str] = [] def __init__(self, task: Task, seed: int = 0) -> None: if len(task.objectives) > 2: raise RuntimeError("Not supported yet.") self._seed = seed self._task = task @property def seed(self) -> int: return self._seed @property def task(self) -> Task: return self._task @property def model(self) -> Model: return self._task.model @property def dataset(self) -> Dataset: return self._task.model.dataset @abstractmethod def run(self) -> None: raise NotImplementedError @abstractmethod def get_trajectory(self, sort_by: str = "trials") -> tuple[list[float], list[float]]: """List of x and y values of the incumbents over time. x depends on ``sort_by``.""" raise NotImplementedError @abstractmethod def get_samples(self) -> tuple[list["Configuration"]]: raise NotImplementedError
c9fe96e7b19d99bc8625cbd6fd2d949c1e0ef805
855b013907d33b7e1bb74f688e5314b0e9bae510
/python-package/setup.py
60a27cdb14da93218bfd1405a5fcc757936fbab2
[ "Apache-2.0" ]
permissive
aksnzhy/xlearn
5b3f3aa29b31c7080a3e0835f073d34157878c44
4c240aa0aa63c1d105fb9aec583adc2ad2840368
refs/heads/master
2023-09-01T08:44:21.447056
2022-06-05T10:44:18
2022-06-05T10:44:18
93,925,242
3,261
624
Apache-2.0
2023-08-28T05:18:27
2017-06-10T08:09:31
C++
UTF-8
Python
false
false
1,903
py
setup.py
# Copyright (c) 2018 by contributors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8 """Setup xlearn package.""" from __future__ import absolute_import import sys import os from setuptools import setup, find_packages sys.path.insert(0, '.') CURRENT_DIR = os.path.dirname(__file__) libpath_py = os.path.join(CURRENT_DIR, 'xlearn/libpath.py') libpath = {'__file__': libpath_py} exec(compile(open(libpath_py, "rb").read(), libpath_py, 'exec'), libpath, libpath) LIB_PATH = [os.path.relpath(libfile, CURRENT_DIR) for libfile in libpath['find_lib_path']()] print("Install libxlearn_api from: %s" % LIB_PATH) setup(name='xlearn', version=open(os.path.join(CURRENT_DIR, 'xlearn/VERSION')).read().strip(), description="xLearn Python Package", maintainer='Chao Ma', maintainer_email='mctt90@gmail.com', zip_safe=False, packages=find_packages(), # this will use MANIFEST.in during install where we specify additional files, # this is the golden line include_package_data=True, install_requires=[ 'numpy', 'scipy<1.3.0; python_version<"3"', 'scipy>=1.3.0; python_version>="3"' ], data_files=[('xlearn', LIB_PATH)], license='Apache-2.0', classifiers=['License :: OSI Approved :: Apache Software License'], url='https://github.com/aksnzhy/xlearn')
6da6ff743f45435342065a6bdc080cf9a6b2906f
fac6bd9d5ca6b068e9ec5ce8a6e703c9261476a3
/roletools/menus.py
8826146a5cb41a24a5de6168e822fa9f661db164
[ "MIT" ]
permissive
TrustyJAID/Trusty-cogs
b72b48a7da37d6985cfc7924dae3a2ff4fcbb39f
5b4c87d461065ef55af4f012a89501925a34a8d5
refs/heads/master
2023-09-04T22:55:34.235209
2023-09-04T22:52:25
2023-09-04T22:52:25
160,604,179
170
252
MIT
2023-06-10T17:01:00
2018-12-06T02:02:25
Python
UTF-8
Python
false
false
23,704
py
menus.py
from __future__ import annotations from typing import Any, List, Optional import discord from red_commons.logging import getLogger # from discord.ext.commands.errors import BadArgument from redbot.core import bank from redbot.core.commands import commands from redbot.core.i18n import Translator from redbot.core.utils.chat_formatting import humanize_list, pagify from redbot.vendored.discord.ext import menus log = getLogger("red.Trusty-cogs.RoleTools") _ = Translator("RoleTools", __file__) class StopButton(discord.ui.Button): def __init__( self, style: discord.ButtonStyle, row: Optional[int], ): super().__init__(style=style, row=row) self.style = style self.emoji = "\N{HEAVY MULTIPLICATION X}\N{VARIATION SELECTOR-16}" async def callback(self, interaction: discord.Interaction): self.view.stop() if interaction.message.flags.ephemeral: await interaction.response.edit_message(view=None) return await interaction.message.delete() class ForwardButton(discord.ui.Button): def __init__( self, style: discord.ButtonStyle, row: Optional[int], ): super().__init__(style=style, row=row) self.style = style self.emoji = "\N{BLACK RIGHT-POINTING TRIANGLE}\N{VARIATION SELECTOR-16}" async def callback(self, interaction: discord.Interaction): await self.view.show_checked_page(self.view.current_page + 1, interaction) class BackButton(discord.ui.Button): def __init__( self, style: discord.ButtonStyle, row: Optional[int], ): super().__init__(style=style, row=row) self.style = style self.emoji = "\N{BLACK LEFT-POINTING TRIANGLE}\N{VARIATION SELECTOR-16}" async def callback(self, interaction: discord.Interaction): await self.view.show_checked_page(self.view.current_page - 1, interaction) class LastItemButton(discord.ui.Button): def __init__( self, style: discord.ButtonStyle, row: Optional[int], ): super().__init__(style=style, row=row) self.style = style self.emoji = ( "\N{BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}\N{VARIATION SELECTOR-16}" ) async def callback(self, interaction: discord.Interaction): await self.view.show_page(self.view._source.get_max_pages() - 1, interaction) class FirstItemButton(discord.ui.Button): def __init__( self, style: discord.ButtonStyle, row: Optional[int], ): super().__init__(style=style, row=row) self.style = style self.emoji = ( "\N{BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}\N{VARIATION SELECTOR-16}" ) async def callback(self, interaction: discord.Interaction): await self.view.show_page(0, interaction) class ReactRolePages(menus.ListPageSource): def __init__(self, pages: list): super().__init__(pages, per_page=1) def is_paginating(self): return True async def format_page(self, menu: menus.MenuPages, page): if menu.ctx.channel.permissions_for(menu.ctx.guild.me).embed_links: em = discord.Embed(description=page, colour=await menu.bot.get_embed_colour(menu.ctx)) em.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}") return em else: return page class ButtonRolePages(menus.ListPageSource): def __init__(self, pages: list): super().__init__(pages, per_page=1) def is_paginating(self): return True async def format_page(self, menu: menus.MenuPages, page): if menu.ctx.channel.permissions_for(menu.ctx.guild.me).embed_links: if len(page) > 4000: em = discord.Embed(colour=await menu.bot.get_embed_colour(menu.ctx)) count = 0 for pages in pagify(page, page_length=1024): if count < 4: em.description += pages else: em.add_field(name=_("Button Role Info Continued"), value=pages) em.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}") else: em = discord.Embed( description=page, colour=await menu.bot.get_embed_colour(menu.ctx) ) em.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}") return em else: return page class SelectOptionPages(menus.ListPageSource): def __init__(self, pages: list): super().__init__(pages, per_page=1) def is_paginating(self): return True async def format_page(self, menu: menus.MenuPages, page): if menu.ctx.channel.permissions_for(menu.ctx.guild.me).embed_links: if len(page) > 4000: em = discord.Embed(colour=await menu.bot.get_embed_colour(menu.ctx)) count = 0 for pages in pagify(page, page_length=1024): if count < 4: em.description += pages else: em.add_field(name=_("Select Option Info Continued"), value=pages) em.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}") else: em = discord.Embed( description=page, colour=await menu.bot.get_embed_colour(menu.ctx) ) em.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}") return em else: return page class SelectMenuPages(menus.ListPageSource): def __init__(self, pages: list): super().__init__(pages, per_page=1) def is_paginating(self): return True async def format_page(self, menu: menus.MenuPages, page): if menu.ctx.channel.permissions_for(menu.ctx.guild.me).embed_links: if len(page) > 4000: em = discord.Embed(colour=await menu.bot.get_embed_colour(menu.ctx)) count = 0 for pages in pagify(page, page_length=1024): if count < 4: em.description += pages else: em.add_field(name=_("Select Menu Info Continued"), value=pages) em.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}") else: em = discord.Embed( description=page, colour=await menu.bot.get_embed_colour(menu.ctx) ) em.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}") return em else: return page class RoleToolsSelectOption(discord.ui.RoleSelect): def __init__(self, placeholder: str = _("Select a role")): super().__init__(min_values=1, max_values=1, placeholder=placeholder) self.current_role: discord.Role async def callback(self, interaction: discord.Interaction): index = interaction.guild.roles.index(self.values[0]) await self.view.show_checked_page(index, interaction) class StickyToggleButton(discord.ui.Button): def __init__( self, ): super().__init__(style=discord.ButtonStyle.green, label=_("Sticky")) self.view: BaseMenu async def callback(self, interaction: discord.Interaction): cog = interaction.client.get_cog("RoleTools") current = await cog.config.role(self.view._source.current_role).sticky() await cog.config.role(self.view._source.current_role).sticky.set(not current) await self.view.show_page(self.view.current_page, interaction) class AutoToggleButton(discord.ui.Button): def __init__( self, ): super().__init__(style=discord.ButtonStyle.green, label=_("Auto")) self.view: BaseMenu async def callback(self, interaction: discord.Interaction): cog = interaction.client.get_cog("RoleTools") current = await cog.config.role(self.view._source.current_role).auto() await cog.config.role(self.view._source.current_role).auto.set(not current) await self.view.show_page(self.view.current_page, interaction) class SelfAddToggleButton(discord.ui.Button): def __init__( self, ): super().__init__(style=discord.ButtonStyle.green, label=_("Selfassignable")) self.view: BaseMenu async def callback(self, interaction: discord.Interaction): cog = interaction.client.get_cog("RoleTools") current = await cog.config.role(self.view._source.current_role).selfassignable() await cog.config.role(self.view._source.current_role).selfassignable.set(not current) await self.view.show_page(self.view.current_page, interaction) class SelfRemToggleButton(discord.ui.Button): def __init__( self, ): super().__init__(style=discord.ButtonStyle.green, label=_("Selfremovable")) self.view: BaseMenu async def callback(self, interaction: discord.Interaction): cog = interaction.client.get_cog("RoleTools") current = await cog.config.role(self.view._source.current_role).selfremovable() await cog.config.role(self.view._source.current_role).selfremovable.set(not current) await self.view.show_page(self.view.current_page, interaction) class RolePages(menus.ListPageSource): def __init__(self, roles: List[discord.Role]): super().__init__(roles, per_page=1) def is_paginating(self): return True async def format_page(self, menu: BaseMenu, role: discord.Role): self.current_role = role role_settings = await menu.cog.config.role(role).all() menu.update_buttons(role_settings) msg = _("Role Settings for {role}\n".format(role=role.name)) jump_url = "https://discord.com/channels/{guild}/{channel}/{message}" em = discord.Embed(title=msg, colour=role.colour) mod_roles = await menu.bot.get_mod_roles(menu.ctx.guild) admin_roles = await menu.bot.get_admin_roles(menu.ctx.guild) required_roles = [menu.ctx.guild.get_role(i) for i in role_settings["required"]] exclusive_roles = [menu.ctx.guild.get_role(i) for i in role_settings["exclusive_to"]] inclusive_roles = [menu.ctx.guild.get_role(i) for i in role_settings["inclusive_with"]] permissions = humanize_list( [perm.replace("_", " ").title() for perm, value in role.permissions if value] ) buttons = humanize_list(role_settings["buttons"]) select_options = humanize_list(role_settings["select_options"]) require_any = role_settings["require_any"] settings = _( "{role}\n```md\n" "# ID: {role_id}\n" "Colour {colour}\n" "Members {members}\n" "Assignable {assignable}\n" "Mentionable {mentionable}\n" "Position {position}\n" "Hoisted {hoisted}\n" "# RoleTools settings\n" "Sticky {sticky}\n" "Auto {auto}\n" "Selfassignable {selfassign}\n" "Selfremovable {selfrem}\n" "# Core Bot settings\n" "Mod {mod}\n" "Admin {admin}\n\n" "```" ).format( role=role.mention, role_id=role.id, members=len(role.members), assignable=role.is_assignable(), mentionable=role.mentionable, position=role.position, hoisted=role.hoist, sticky=role_settings["sticky"], auto=role_settings["auto"], selfassign=role_settings["selfassignable"], selfrem=role_settings["selfremovable"], colour=str(role.colour), mod=role in mod_roles, admin=role in admin_roles, ) settings += _("**Created:** {created_at}\n").format( created_at=discord.utils.format_dt(role.created_at) ) if cost := role_settings.get("cost"): currency_name = await bank.get_currency_name(menu.ctx.guild) settings += _("**Cost:** {cost} {currency_name}\n").format( cost=cost, currency_name=currency_name ) if buttons: settings += _("**Buttons:** {button_names}\n").format(button_names=buttons) if select_options: settings += _("**Select Options:** {select_names}\n").format( select_names=select_options ) if permissions: settings += _("**Permissions:** {permissions}\n").format(permissions=permissions) if role.managed: if getattr(role, "is_bot_managed", lambda: False)(): bot = role.guild.get_member(role.tags.bot_id) settings += _("Bot Role: {bot}").format(bot=bot.mention) elif getattr(role, "is_premium_subscriber", lambda: False)(): settings += _("**Premium Role:** True\n") else: settings += _("**Managed Role:** True\n") if inclusive_roles: settings += _("**Inclusive with:** {inclusive}\n").format( inclusive=humanize_list([r.mention for r in inclusive_roles if r]) ) if exclusive_roles: settings += _("**Exclusive to:** {inclusive}\n").format( inclusive=humanize_list([r.mention for r in exclusive_roles if r]) ) if required_roles: settings += _("**Requires{any_of}:** {inclusive}\n").format( inclusive=humanize_list([r.mention for r in required_roles if r]), any_of="" if not require_any else _(" any of"), ) if role_settings["reactions"]: settings += _("**Reaction Roles**\n") for reaction in role_settings["reactions"]: channel, message, emoji = reaction.split("-") if emoji.isdigit(): emoji = menu.bot.get_emoji(int(emoji)) if not emoji: emoji = _("Emoji from another server") link = jump_url.format(guild=menu.ctx.guild.id, channel=channel, message=message) settings += _("{emoji} on [message]({link})\n").format(emoji=emoji, link=link) embeds = [e for e in pagify(settings, page_length=5500)] if len(embeds) > 1: command = f"`{menu.ctx.clean_prefix}roletools reactionroles`" settings = _("{settings}\nPlease see {command} to see full details").format( settings=embeds[0], command=command ) pages = pagify(settings, page_length=1024) em.description = "" for index, page in enumerate(pages): if index < 2: # em.add_field(name=_("Role settings for {role}".format(role=role.name)), value=page) em.description += page else: em.add_field( name=_("Role settings for {role} (continued)").format(role=role.name), value=page, ) if role.display_icon: if isinstance(role.display_icon, discord.Asset): em.set_thumbnail(url=role.display_icon) else: cdn_fmt = " https://cdnjs.cloudflare.com/ajax/libs/twemoji/14.0.2/72x72/{codepoint:x}.png" url = cdn_fmt.format(codepoint=ord(str(role.display_icon))) log.verbose("RolePages role.display_icon: %s", role.display_icon) em.set_thumbnail(url=url) em.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}") return em class BaseMenu(discord.ui.View): def __init__( self, source: menus.PageSource, cog: commands.Cog, timeout: int = 60, message: discord.Message = None, **kwargs: Any, ) -> None: super().__init__( timeout=timeout, ) self.cog = cog self.bot = None self.message = message self._source = source self.ctx = None self.author: Optional[discord.Member] = None self.current_page = kwargs.get("page_start", 0) self.forward_button = ForwardButton(discord.ButtonStyle.grey, 0) self.back_button = BackButton(discord.ButtonStyle.grey, 0) self.first_item = FirstItemButton(discord.ButtonStyle.grey, 0) self.last_item = LastItemButton(discord.ButtonStyle.grey, 0) self.stop_button = StopButton(discord.ButtonStyle.red, 0) self.add_item(self.stop_button) self.add_item(self.first_item) self.add_item(self.back_button) self.add_item(self.forward_button) self.add_item(self.last_item) if isinstance(source, RolePages): self.select_view = RoleToolsSelectOption() self.add_item(self.select_view) self.auto = AutoToggleButton() self.add_item(self.auto) self.sticky = StickyToggleButton() self.add_item(self.sticky) self.selfassignable = SelfAddToggleButton() self.add_item(self.selfassignable) self.selfremovable = SelfRemToggleButton() self.add_item(self.selfremovable) @property def source(self): return self._source async def on_timeout(self): await self.message.edit(view=None) def update_buttons(self, data: dict): buttons = { "sticky": self.sticky, "auto": self.auto, "selfassignable": self.selfassignable, "selfremovable": self.selfremovable, } for key, button in buttons.items(): if key in data: if data[key]: button.style = discord.ButtonStyle.green else: button.style = discord.ButtonStyle.red if self.author is not None: if self.author.id == self.ctx.guild.owner_id: button.disabled = False else: button.disabled = ( self.author.guild_permissions.manage_roles and self.source.current_role >= self.author.top_role ) button.disabled |= not self.source.current_role.is_assignable() async def start(self, ctx: commands.Context): self.ctx = ctx self.bot = self.cog.bot self.author = ctx.author # await self.source._prepare_once() self.message = await self.send_initial_message(ctx) async def _get_kwargs_from_page(self, page): value = await discord.utils.maybe_coroutine(self._source.format_page, self, page) if isinstance(value, dict): return value elif isinstance(value, str): return {"content": value, "embed": None} elif isinstance(value, discord.Embed): return {"embed": value, "content": None} async def send_initial_message(self, ctx: commands.Context): """|coro| The default implementation of :meth:`Menu.send_initial_message` for the interactive pagination session. This implementation shows the first page of the source. """ self.ctx = ctx page = await self._source.get_page(self.current_page) kwargs = await self._get_kwargs_from_page(page) self.message = await ctx.send(**kwargs, view=self) return self.message async def show_page(self, page_number: int, interaction: discord.Interaction): page = await self._source.get_page(page_number) self.current_page = page_number kwargs = await self._get_kwargs_from_page(page) await interaction.response.edit_message(**kwargs, view=self) async def show_checked_page(self, page_number: int, interaction: discord.Interaction) -> None: max_pages = self._source.get_max_pages() try: if max_pages is None: # If it doesn't give maximum pages, it cannot be checked await self.show_page(page_number, interaction) elif page_number >= max_pages: await self.show_page(0, interaction) elif page_number < 0: await self.show_page(max_pages - 1, interaction) elif max_pages > page_number >= 0: await self.show_page(page_number, interaction) except IndexError: # An error happened that can be handled, so ignore it. pass async def interaction_check(self, interaction: discord.Interaction): """Just extends the default reaction_check to use owner_ids""" if interaction.user.id not in ( *interaction.client.owner_ids, getattr(self.author, "id", None), ): await interaction.response.send_message( content=_("You are not authorized to interact with this."), ephemeral=True ) return False return True class ConfirmView(discord.ui.View): """ This is just a copy of my version from Red to be removed later possibly https://github.com/Cog-Creators/Red-DiscordBot/pull/6176 """ def __init__( self, author: Optional[discord.abc.User] = None, *, timeout: float = 180.0, disable_buttons: bool = False, ): if timeout is None: raise TypeError("This view should not be used as a persistent view.") super().__init__(timeout=timeout) self.result: Optional[bool] = None self.author: Optional[discord.abc.User] = author self.message: Optional[discord.Message] = None self.disable_buttons = disable_buttons async def on_timeout(self): if self.message is None: # we can't do anything here if message is none return if self.disable_buttons: self.confirm_button.disabled = True self.dismiss_button.disabled = True await self.message.edit(view=self) else: await self.message.edit(view=None) @discord.ui.button(label=_("Yes"), style=discord.ButtonStyle.green) async def confirm_button(self, interaction: discord.Interaction, button: discord.ui.Button): self.result = True self.stop() # respond to the interaction so the user does not see "interaction failed". await interaction.response.defer() # call `on_timeout` explicitly here since it's not called when `stop()` is called. await self.on_timeout() @discord.ui.button(label=_("No"), style=discord.ButtonStyle.secondary) async def dismiss_button(self, interaction: discord.Interaction, button: discord.ui.Button): self.result = False self.stop() # respond to the interaction so the user does not see "interaction failed". await interaction.response.defer() # call `on_timeout` explicitly here since it's not called when `stop()` is called. await self.on_timeout() async def interaction_check(self, interaction: discord.Interaction): if self.message is None: self.message = interaction.message if self.author and interaction.user.id != self.author.id: await interaction.response.send_message( content=_("You are not authorized to interact with this."), ephemeral=True ) return False return True
784e4be2f03edda6a3302d4925ba59f0b5bb56a3
f576f0ea3725d54bd2551883901b25b863fe6688
/sdk/maps/azure-maps-search/azure/maps/search/models/_models.py
f2808ee58e393e03152235b8f2999a675807f65e
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
permissive
Azure/azure-sdk-for-python
02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c
c2ca191e736bb06bfbbbc9493e8325763ba990bb
refs/heads/main
2023-09-06T09:30:13.135012
2023-09-06T01:08:06
2023-09-06T01:08:06
4,127,088
4,046
2,755
MIT
2023-09-14T21:48:49
2012-04-24T16:46:12
Python
UTF-8
Python
false
false
46,889
py
_models.py
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ # pylint: disable=unused-import,ungrouped-imports, C0302, C0203 from typing import List, Optional, Union, NamedTuple import msrest.serialization from .._generated.models import ( PointOfInterest, DataSource, SearchAddressBatchItem as _SearchAddressBatchItem, SearchAddressBatchItemResponse, ReverseSearchAddressBatchItem as _ReverseSearchAddressBatchItem, BatchResultSummary, GeoJsonObjectType ) class LatLon(NamedTuple): """Represents coordinate latitude and longitude :keyword lat: The coordinate as latitude. :paramtype lat: float :keyword lon: The coordinate as longitude. :paramtype lon: float """ lat: float = 0 lon: float = 0 class BoundingBox(NamedTuple): """Represents information about the coordinate range :keyword west: The westmost value of coordinates. :paramtype west: float :keyword south: The southmost value of coordinates. :paramtype south: float :keyword east: The eastmost value of coordinates. :paramtype east: float :keyword north: The northmost value of coordinates. :paramtype north: float """ west: float = 0.0 south: float = 0.0 east: float = 0.0 north: float = 0.0 # pylint: disable=too-many-instance-attributes class StructuredAddress(object): """The Structured address as the search input. :param country_code: Country (Note: This is a two-letter code, not a country name.). :type country_code: str :keyword cross_street: The name of the street being crossed. :paramtype cross_street: str :keyword street_number: The building number on the street. :paramtype street_number: str :keyword street_name: The street name. :paramtype street_name: str :keyword municipality: City / Town. :paramtype municipality: str :keyword municipality_subdivision: Sub / Super City. :paramtype municipality_subdivision: str :keyword country_tertiary_subdivision: Named Area. :paramtype country_tertiary_subdivision: str :keyword country_secondary_subdivision: County. :paramtype country_secondary_subdivision: str :keyword country_subdivision: State or Province. :paramtype country_subdivision: str :keyword postal_code: Postal Code / Zip Code. :paramtype postal_code: str """ def __init__( self, country_code: str, *, cross_street: Optional[str] = None, street_number: Optional[str] = None, street_name: Optional[str] = None, municipality: Optional[str] = None, municipality_subdivision: Optional[str] = None, country_tertiary_subdivision: Optional[str] = None, country_secondary_subdivision: Optional[str] = None, country_subdivision: Optional[str] = None, postal_code: Optional[str] = None ): self.country_code = country_code self.cross_street = cross_street self.street_number = street_number self.street_name = street_name self.municipality = municipality self.municipality_subdivision = municipality_subdivision self.country_tertiary_subdivision = country_tertiary_subdivision self.country_secondary_subdivision = country_secondary_subdivision self.country_subdivision = country_subdivision self.postal_code = postal_code class SearchSummary(object): """Summary object for a Search API response. :keyword query: The query parameter that was used to produce these search results. :paramtype query: str :keyword query_type: The type of query being returned: NEARBY or NON_NEAR. Possible values include: "NEARBY", "NON_NEAR". :paramtype query_type: str or ~azure.maps.search.models.QueryType :keyword query_time: Time spent resolving the query, in milliseconds. :paramtype query_time: int :keyword num_results: Number of results in the response. :paramtype num_results: int :keyword top: Maximum number of responses that will be returned. :paramtype top: int :keyword skip: The starting offset of the returned Results within the full Result set. :paramtype skip: int :keyword total_results: The total number of Results found. :paramtype total_results: int :keyword fuzzy_level: The maximum fuzzy level required to provide Results. :paramtype fuzzy_level: int :keyword geo_bias: Indication when the internal search engine has applied a geospatial bias to improve the ranking of results. :paramtype geo_bias: ~azure.maps.search.models.LatLongPairAbbreviated """ def __init__( self, *, query: str = None, query_type: str = None, query_time: int = None, num_results: int = None, top: int = None, skip: int = None, total_results: int = None, fuzzy_level: int = None, geo_bias: LatLon = None ): self.query = query self.query_type = query_type self.query_time = query_time self.num_results = num_results self.top = top self.skip = skip self.total_results = total_results self.fuzzy_level = fuzzy_level self.geo_bias = geo_bias class AddressRanges(object): """Describes the address range on both sides of the street for a search result. Coordinates for the start and end locations of the address range are included. :keyword range_start: Address range on the left(start) side of the street. :paramtype range_start: str :keyword range_end: Address range on the right(end) side of the street. :paramtype range_end: str :keyword range_from: A location represented as a latitude and longitude using short names 'lat' & 'lon'. :paramtype range_from: ~azure.maps.search.models.LatLon :keyword range_to: A location represented as a latitude and longitude using short names 'lat' & 'lon'. :paramtype range_to: ~azure.maps.search.models.LatLon """ def __init__( self, *, range_start: str = None, range_end: str = None, range_from: LatLon = None, range_to: LatLon = None ): self.range_left = range_start self.range_right = range_end self.from_property = None if not range_from else LatLon( range_from.lat, range_from.lon ) self.to = None if not range_to else LatLon( range_to.lat, range_to.lon ) class EntryPoint(object): """The entry point for the POI being returned. :keyword entry_point_type: The type of entry point. :paramtype entry_point_type: str or ~azure.maps.search.models.EntryPointType :keyword position: A location represented as a latitude and longitude using short names 'lat' & 'lon'. :paramtype position: ~azure.maps.search.models.LatLon """ def __init__( self, entry_point_type: str = None, position: LatLon = None ): self.type = entry_point_type self.position = None if not position else LatLon( position.lat, position.lon ) # pylint: disable=too-many-instance-attributes class Address(object): """The address of the result. :keyword building_number: The building number on the street. :paramtype building_number: str :keyword street: The street name. :paramtype street: str :keyword cross_street: The name of the street being crossed. :paramtype cross_street: str :keyword street_number: The building number on the street. :paramtype street_number: str :keyword route_numbers: The codes used to unambiguously identify the street. :paramtype route_numbers: list[int] :keyword street_name: The street name. :paramtype street_name: str :keyword street_name_and_number: The street name and number. :paramtype street_name_and_number: str :keyword municipality: City / Town. :paramtype municipality: str :keyword municipality_subdivision: Sub / Super City. :paramtype municipality_subdivision: str :keyword country_tertiary_subdivision: Named Area. :paramtype country_tertiary_subdivision: str :keyword country_secondary_subdivision: County. :paramtype country_secondary_subdivision: str :keyword country_subdivision: State or Province. :paramtype country_subdivision: str :keyword postal_code: Postal Code / Zip Code. :paramtype postal_code: str :keyword extended_postal_code: Extended postal code (availability is dependent on the region). :paramtype extended_postal_code: str :keyword country_code: Country (Note: This is a two-letter code, not a country name.). :paramtype country_code: str :keyword country: Country name. :paramtype country: str :keyword country_code_iso3: ISO alpha-3 country code. :paramtype country_code_iso3: str :keyword freeform_address: An address line formatted according to the formatting rules of a Result's country of origin, or in the case of a country, its full country name. :paramtype freeform_address: str :keyword country_subdivision_name: The full name of a first level of country administrative hierarchy. This field appears only in case countrySubdivision is presented in an abbreviated form. Only supported for USA, Canada, and Great Britain. :paramtype country_subdivision_name: str :keyword local_name: An address component which represents the name of a geographic area or locality that groups a number of addressable objects for addressing purposes, without being an administrative unit. This field is used to build the ``freeformAddress`` property. :paramtype local_name: str :keyword bounding_box: Bounding box coordinates. :paramtype bounding_box: ~azure.maps.search.models.BoundingBox """ def __init__( self, *, building_number: str = None, street: str = None, cross_street: str = None, street_number: str = None, route_numbers: List[int] = None, street_name: str = None, street_name_and_number: str = None, municipality: str = None, municipality_subdivision: str = None, country_tertiary_subdivision: str = None, country_secondary_subdivision: str = None, country_subdivision: str = None, postal_code: str = None, extended_postal_code: str = None, country_code: str = None, country: str = None, country_code_iso3: str = None, freeform_address: str = None, country_subdivision_name: str = None, local_name: str = None, bounding_box: BoundingBox = None, ): self.building_number = building_number self.street = street self.cross_street = cross_street self.street_number = street_number self.route_numbers = route_numbers self.street_name = street_name self.street_name_and_number = street_name_and_number self.municipality = municipality self.municipality_subdivision = municipality_subdivision self.country_tertiary_subdivision = country_tertiary_subdivision self.country_secondary_subdivision = country_secondary_subdivision self.country_subdivision = country_subdivision self.postal_code = postal_code self.extended_postal_code = extended_postal_code self.country_code = country_code self.country = country self.country_code_iso3 = country_code_iso3 self.freeform_address = freeform_address self.country_subdivision_name = country_subdivision_name self.local_name = local_name self.bounding_box = bounding_box # pylint: disable=too-many-instance-attributes class SearchAddressResultItem(object): """Result object for a Search API response.. :keyword type: Possible values include: "POI", "Street", "Geography", "Point Address", "Address Range", "Cross Street". :paramtype type: str or ~azure.maps.search.models.SearchAddressResultType :keyword id: Id property. :paramtype id: str :keyword score: The value within a result set to indicate the relative matching score between results. :paramtype score: float :keyword distance_in_meters: Straight line distance between the result and geobias location in meters. :paramtype distance_in_meters: float :keyword info: Information about the original data source of the Result. Used for support requests. :paramtype info: str :param entity_type: Possible values include: "Country", "CountrySubdivision", "CountrySecondarySubdivision", "CountryTertiarySubdivision", "Municipality", "MunicipalitySubdivision", "Neighbourhood", "PostalCodeArea". :type entity_type: str or ~azure.maps.search.models.GeographicEntityType :keyword point_of_interest: Details of the returned POI including information such as the name, phone, url address, and classifications. :paramtype point_of_interest: ~azure.maps.search.models.PointOfInterest :keyword address: The address of the result. :paramtype address: ~azure.maps.search.models.Address :param position: A location represented as a latitude and longitude using short names 'lat' & 'lon'. :type position: ~azure.maps.search.models.LatLon :keyword viewport: The viewport that covers the result represented by the top-left and bottom- right coordinates as BoundingBox. :paramtype viewport: ~azure.maps.search.models.BoundingBox :keyword entry_points: Array of EntryPoints. Those describe the types of entrances available at the location. The type can be "main" for main entrances such as a front door, or a lobby, and "minor", for side and back doors. :paramtype entry_points: list[~azure.maps.search.models.EntryPoint] :keyword address_ranges: Describes the address range on both sides of the street for a search result. Coordinates for the start and end locations of the address range are included. :paramtype address_ranges: ~azure.maps.search.models.AddressRanges :keyword data_sources: Optional section. Reference geometry id. :paramtype data_sources: ~azure.maps.search.models.DataSource :keyword match_type: Information on the type of match. :paramtype match_type: str or ~azure.maps.search.models.MatchType :keyword detour_time: Detour time in seconds. :paramtype detour_time: int """ def __init__( self, *, type_: str = None, id_: str = None, score: float = None, distance_in_meters: float = None, info: str = None, entity_type: str = None, point_of_interest: PointOfInterest = None, address: Address = None, position: LatLon = None, viewport: BoundingBox = None, entry_points: EntryPoint = None, address_ranges: AddressRanges = None, data_sources: DataSource = None, match_type: str = None, detour_time: int = None ): self.type = type_ self.id = id_ self.score = score self.distance_in_meters = distance_in_meters self.info = info self.entity_type = entity_type self.point_of_interest = point_of_interest self.address = address self.position = None if not position else LatLon( position.lat, position.lon ) self.viewport = viewport self.entry_points = entry_points self.address_ranges = None if not position else LatLon( address_ranges.range_left, address_ranges.range_right ) self.data_sources = data_sources self.match_type = match_type self.detour_time = detour_time class SearchAddressResult(object): """This object is returned from a successful Search calls. Variables are only populated by the server, and will be ignored when sending a request. :keyword summary: Summary object for a Search API response. :paramtype summary: ~azure.maps.search.models.SearchSummary :keyword results: A list of Search API results. :paramtype results: list[~azure.maps.search.models.SearchAddressResultItem] """ def __init__( self, summary: SearchSummary = None, results: List[SearchAddressResultItem] = None ): self.query = summary.query self.query_type = summary.query_type self.query_time = summary.query_time self.num_results = summary.num_results self.top = summary.top self.skip = summary.skip self.total_results = summary.total_results self.fuzzy_level = summary.fuzzy_level self.geo_bias = None if not summary.geo_bias else LatLon( summary.geo_bias.lat, summary.geo_bias.lon ) self.results = results class ReverseSearchAddressResultItem(object): """Result object for a Search Address Reverse response. Variables are only populated by the server, and will be ignored when sending a request. :keyword address: The address of the result. :paramtype address: ~azure.maps.search.models.Address :keyword position: Position property in the form of "latitude,longitude". :paramtype position: ~azure.maps.search.models.LatLon :keyword road_use: :paramtype road_use: list[str] :keyword match_type: Information on the type of match. :paramtype match_type: str or ~azure.maps.search.models.MatchType """ def __init__( self, *, address: Address = None, position: LatLon = None, road_use: List[str] = None, match_type: str = None ): self.address = address self.position = None if not position else LatLon( float(position.split(',')[0]), float(position.split(',')[1]) ) self.road_use = road_use self.match_type = match_type class ReverseSearchAddressResult(object): """This object is returned from a successful Search Address Reverse call. Variables are only populated by the server, and will be ignored when sending a request. :keyword summary: Summary object for a Search Address Reverse response. :paramtype summary: ~azure.maps.search.models.SearchSummary :keyword results: Addresses array. :paramtype results: list[~azure.maps.search.models.ReverseSearchAddressResultItem] """ def __init__( self, *, summary: SearchSummary = None, results: List[ReverseSearchAddressResultItem] = None ): self.query_type = summary.query_type self.query_time = summary.query_time self.results = results class ReverseSearchAddressBatchItem(_ReverseSearchAddressBatchItem): """An item returned from Search Address Reverse Batch service call. Variables are only populated by the server, and will be ignored when sending a request. :keyword response: The result of the query. SearchAddressReverseResponse if the query completed successfully, ErrorResponse otherwise. :paramtype response: ~azure.maps.search.models.ReverseSearchAddressBatchItemResponse """ def __init__( self, **kwargs ): super(ReverseSearchAddressBatchItem, self).__init__(**kwargs) self.response = None class ReverseSearchAddressBatchProcessResult(object): """This object is returned from a successful Search Address Reverse Batch service call. Variables are only populated by the server, and will be ignored when sending a request. :keyword summary: Summary of the results for the batch request. :paramtype summary: ~azure.maps.search._generated.models.BatchResultSummary :keyword items: Array containing the batch results. :paramtype items: list[ReverseSearchAddressBatchItem] """ def __init__( self, *, summary: BatchResultSummary = None, items: List[ReverseSearchAddressBatchItem] = None ): self.summary = summary self.items = items class GeoJsonObject(msrest.serialization.Model): """A valid ``GeoJSON`` object. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3>`_ for details. You probably want to use the sub-classes and not this class directly. Known sub-classes are: GeoJsonFeature, GeoJsonFeatureCollection, GeoJsonGeometry, GeoJsonGeometryCollection, GeoJsonLineString, GeoJsonMultiLineString, GeoJsonMultiPoint, GeoJsonMultiPolygon, GeoJsonPoint, GeoJsonPolygon. All required parameters must be populated in order to send to Azure. :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection". :type type: str or ~azure.maps.search._generated.models.GeoJsonObjectType """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, } _subtype_map = { 'type': {'Feature': 'GeoJsonFeature', 'FeatureCollection': 'GeoJsonFeatureCollection', 'GeoJsonGeometry': 'GeoJsonGeometry', 'GeometryCollection': 'GeoJsonGeometryCollection', 'LineString': 'GeoJsonLineString', 'MultiLineString': 'GeoJsonMultiLineString', 'MultiPoint': 'GeoJsonMultiPoint', 'MultiPolygon': 'GeoJsonMultiPolygon', 'Point': 'GeoJsonPoint', 'Polygon': 'GeoJsonPolygon' } } def __init__( self, type_: Union[str, GeoJsonObjectType] = None, **kwargs ): super(GeoJsonObject, self).__init__(**kwargs) self.type = type_ # type: Optional[Union[str, GeoJsonObjectType]] class GeoJsonFeatureData(msrest.serialization.Model): """GeoJsonFeatureData. All required parameters must be populated in order to send to Azure. :param geometry: Required. A valid ``GeoJSON`` object. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3>`_ for details. :type geometry: ~azure.maps.search.models.GeoJsonObject :param properties: Properties can contain any additional metadata about the ``Feature``. Value can be any JSON object or a JSON null value. :type properties: object :param feature_type: The type of the feature. The value depends on the data model the current feature is part of. Some data models may have an empty value. :type feature_type: str """ _validation = { 'geometry': {'required': True}, } _attribute_map = { 'geometry': {'key': 'geometry', 'type': 'GeoJsonObject'}, 'properties': {'key': 'properties', 'type': 'object'}, 'feature_type': {'key': 'featureType', 'type': 'str'}, } def __init__( self, geometry: "GeoJsonObject", *, properties: Optional[object] = None, feature_type: Optional[str] = None, **kwargs ): super(GeoJsonFeatureData, self).__init__(**kwargs) self.geometry = geometry self.properties = properties self.feature_type = feature_type class GeoJsonFeature(GeoJsonObject, GeoJsonFeatureData): """A valid ``GeoJSON Feature`` object type. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.2>`_ for details. All required parameters must be populated in order to send to Azure. :param geometry: Required. A valid ``GeoJSON`` object. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3>`_ for details. :type geometry: ~azure.maps.search.models.GeoJsonObject :param properties: Properties can contain any additional metadata about the ``Feature``. Value can be any JSON object or a JSON null value. :type properties: object :param feature_type: The type of the feature. The value depends on the data model the current feature is part of. Some data models may have an empty value. :type feature_type: str :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection". :type type: str or ~azure.maps.search._generated.models.GeoJsonObjectType """ def __init__( self, geometry: GeoJsonObject, *, properties: Optional[object] = None, feature_type: Optional[str] = None, **kwargs ): super(GeoJsonFeature, self).__init__( geometry=geometry, properties=properties, feature_type=feature_type, **kwargs ) self.geometry = geometry self.properties = properties self.feature_type = feature_type self.type = 'Feature' # type: str class GeoJsonFeatureCollectionData(msrest.serialization.Model): """GeoJsonFeatureCollectionData. All required parameters must be populated in order to send to Azure. :param features: Required. Contains a list of valid ``GeoJSON Feature`` objects. :type features: list[~azure.maps.search.models.GeoJsonFeature] """ _validation = { 'features': {'required': True}, } _attribute_map = { 'features': {'key': 'features', 'type': '[GeoJsonFeature]'}, } def __init__( self, *, features: List["GeoJsonFeature"], **kwargs ): super(GeoJsonFeatureCollectionData, self).__init__(**kwargs) self.features = features class GeoJsonFeatureCollection(GeoJsonObject, GeoJsonFeatureCollectionData): """A valid ``GeoJSON FeatureCollection`` object type. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.3>`_ for details. All required parameters must be populated in order to send to Azure. :param features: Required. Contains a list of valid ``GeoJSON Feature`` objects. :type features: list[~azure.maps.search.models.GeoJsonFeature] :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection". :type type: str or ~azure.maps.search._generated.models.GeoJsonObjectType """ _validation = { 'features': {'required': True}, 'type': {'required': True}, } _attribute_map = { 'features': {'key': 'features', 'type': '[GeoJsonFeature]'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, *, features: List["GeoJsonFeature"], **kwargs ): super(GeoJsonFeatureCollection, self).__init__(features=features, **kwargs) self.features = features self.type = 'FeatureCollection' # type: str self.type = 'FeatureCollection' # type: str class GeoJsonGeometry(GeoJsonObject): """A valid ``GeoJSON`` geometry object. The type must be one of the seven valid GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.1>`_ for details. All required parameters must be populated in order to send to Azure. :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection". :type type: str or ~azure.maps.search._generated.models.GeoJsonObjectType """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, **kwargs ): super(GeoJsonGeometry, self).__init__(**kwargs) self.type = 'GeoJsonGeometry' # type: str class GeoJsonGeometryCollectionData(msrest.serialization.Model): """GeoJsonGeometryCollectionData. All required parameters must be populated in order to send to Azure. :param geometries: Required. Contains a list of valid ``GeoJSON`` geometry objects. **Note** that coordinates in GeoJSON are in x, y order (longitude, latitude). :type geometries: list[~azure.maps.search.models.GeoJsonObject] """ _validation = { 'geometries': {'required': True}, } _attribute_map = { 'geometries': {'key': 'geometries', 'type': '[GeoJsonObject]'}, } def __init__( self, *, geometries: List["GeoJsonObject"], **kwargs ): super(GeoJsonGeometryCollectionData, self).__init__(**kwargs) self.geometries = geometries class GeoJsonGeometryCollection(GeoJsonObject, GeoJsonGeometryCollectionData): """A valid ``GeoJSON GeometryCollection`` object type. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.1.8>`_ for details. All required parameters must be populated in order to send to Azure. :param geometries: Required. Contains a list of valid ``GeoJSON`` geometry objects. **Note** that coordinates in GeoJSON are in x, y order (longitude, latitude). :type geometries: list[~azure.maps.search.models.GeoJsonObject] :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection". :type type: str or ~azure.maps.search._generated.models.GeoJsonObjectType """ _validation = { 'geometries': {'required': True}, 'type': {'required': True}, } _attribute_map = { 'geometries': {'key': 'geometries', 'type': '[GeoJsonObject]'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, *, geometries: List["GeoJsonObject"], **kwargs ): super(GeoJsonGeometryCollection, self).__init__(geometries=geometries, **kwargs) self.geometries = geometries self.type = 'GeometryCollection' # type: str self.type = 'GeometryCollection' # type: str class GeoJsonLineStringData(msrest.serialization.Model): """GeoJsonLineStringData. All required parameters must be populated in order to send to Azure. :param coordinates: Required. Coordinates for the ``GeoJson LineString`` geometry. :type coordinates: list[LatLon] """ _validation = { 'coordinates': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': '[LatLon]'}, } def __init__( self, *, coordinates: List[LatLon], **kwargs ): super(GeoJsonLineStringData, self).__init__(**kwargs) self.coordinates = coordinates class GeoJsonLineString(GeoJsonObject, GeoJsonLineStringData): """A valid ``GeoJSON LineString`` geometry type. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.1.4>`_ for details. All required parameters must be populated in order to send to Azure. :param coordinates: Required. Coordinates for the ``GeoJson LineString`` geometry. :type coordinates: list[LatLon] :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection". :type type: str or ~azure.maps.search._generated.models.GeoJsonObjectType """ _validation = { 'coordinates': {'required': True}, 'type': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': '[LatLon]'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, *, coordinates: List[LatLon], **kwargs ): super(GeoJsonLineString, self).__init__(coordinates=coordinates, **kwargs) self.coordinates = coordinates self.type = 'LineString' # type: str self.type = 'LineString' # type: str class GeoJsonMultiLineStringData(msrest.serialization.Model): """GeoJsonMultiLineStringData. All required parameters must be populated in order to send to Azure. :param coordinates: Required. Coordinates for the ``GeoJson MultiLineString`` geometry. :type coordinates: list[list[LatLon]] """ _validation = { 'coordinates': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': '[[LatLon]]'}, } def __init__( self, *, coordinates: List[List[LatLon]], **kwargs ): super(GeoJsonMultiLineStringData, self).__init__(**kwargs) self.coordinates = coordinates class GeoJsonMultiLineString(GeoJsonObject, GeoJsonMultiLineStringData): """A valid ``GeoJSON MultiLineString`` geometry type. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.1.5>`_ for details. All required parameters must be populated in order to send to Azure. :param coordinates: Required. Coordinates for the ``GeoJson MultiLineString`` geometry. :type coordinates: list[list[LatLon]] :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection". :type type: str or ~azure.maps.search._generated.models.GeoJsonObjectType """ _validation = { 'coordinates': {'required': True}, 'type': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': '[[LatLon]]'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, *, coordinates: List[List[LatLon]], **kwargs ): super(GeoJsonMultiLineString, self).__init__(coordinates=coordinates, **kwargs) self.coordinates = coordinates self.type = 'MultiLineString' # type: str self.type = 'MultiLineString' # type: str class GeoJsonMultiPointData(msrest.serialization.Model): """Data contained by a ``GeoJson MultiPoint``. All required parameters must be populated in order to send to Azure. :param coordinates: Required. Coordinates for the ``GeoJson MultiPoint`` geometry. :type coordinates: list[LatLon] """ _validation = { 'coordinates': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': '[LatLon]'}, } def __init__( self, *, coordinates: List[LatLon], **kwargs ): super(GeoJsonMultiPointData, self).__init__(**kwargs) self.coordinates = coordinates class GeoJsonMultiPoint(GeoJsonObject, GeoJsonMultiPointData): """A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.1.3>`_ for details. All required parameters must be populated in order to send to Azure. :param coordinates: Required. Coordinates for the ``GeoJson MultiPoint`` geometry. :type coordinates: list[LatLon] :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection". :type type: str or ~azure.maps.search._generated.models.GeoJsonObjectType """ _validation = { 'coordinates': {'required': True}, 'type': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': '[LatLon]'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, *, coordinates: List[LatLon], **kwargs ): super(GeoJsonMultiPoint, self).__init__(coordinates=coordinates, **kwargs) self.coordinates = coordinates self.type = 'MultiPoint' # type: str self.type = 'MultiPoint' # type: str class GeoJsonMultiPolygonData(msrest.serialization.Model): """GeoJsonMultiPolygonData. All required parameters must be populated in order to send to Azure. :param coordinates: Required. Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that coordinates in GeoJSON are in x, y order (longitude, latitude). :type coordinates: list[list[list[LatLon]]] """ _validation = { 'coordinates': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': '[[[LatLon]]]'}, } def __init__( self, *, coordinates: List[List[List[LatLon]]], **kwargs ): super(GeoJsonMultiPolygonData, self).__init__(**kwargs) self.coordinates = coordinates class GeoJsonMultiPolygon(GeoJsonObject, GeoJsonMultiPolygonData): """A valid ``GeoJSON MultiPolygon`` object type. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.1.7>`_ for details. All required parameters must be populated in order to send to Azure. :param coordinates: Required. Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that coordinates in GeoJSON are in x, y order (longitude, latitude). :type coordinates: list[list[list[LatLon]]] :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection". :type type: str or ~azure.maps.search._generated.models.GeoJsonObjectType """ _validation = { 'coordinates': {'required': True}, 'type': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': '[[[LatLon]]]'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, *, coordinates: List[List[List[LatLon]]], **kwargs ): super(GeoJsonMultiPolygon, self).__init__(coordinates=coordinates, **kwargs) self.coordinates = coordinates self.type = 'MultiPolygon' # type: str self.type = 'MultiPolygon' # type: str class GeoJsonPointData(msrest.serialization.Model): """Data contained by a ``GeoJson Point``. All required parameters must be populated in order to send to Azure. :param coordinates: Required. A ``Position`` is an array of numbers with two or more elements. The first two elements are *longitude* and *latitude*, precisely in that order. *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.1.1>`_ for details. :type coordinates: LatLon """ _validation = { 'coordinates': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': 'LatLon'}, } def __init__( self, *, coordinates: LatLon, **kwargs ): super(GeoJsonPointData, self).__init__(**kwargs) self.coordinates = coordinates class GeoJsonPoint(GeoJsonObject, GeoJsonPointData): """A valid ``GeoJSON Point`` geometry type. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.1.2>`_ for details. All required parameters must be populated in order to send to Azure. :param coordinates: Required. A ``Position`` is an array of numbers with two or more elements. The first two elements are *longitude* and *latitude*, precisely in that order. *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.1.1>`_ for details. :type coordinates: LatLon :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection". :type type: str or ~azure.maps.search._models.GeoJsonObjectType """ _validation = { 'coordinates': {'required': True}, 'type': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': 'LatLon'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, *, coordinates: LatLon, **kwargs ): super(GeoJsonPoint, self).__init__(coordinates=coordinates, **kwargs) self.coordinates = coordinates self.type = 'Point' # type: str class GeoJsonPolygonData(msrest.serialization.Model): """GeoJsonPolygonData. All required parameters must be populated in order to send to Azure. :param coordinates: Required. Coordinates for the ``GeoJson Polygon`` geometry type. :type coordinates: list[list[LatLon]] """ _validation = { 'coordinates': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': '[[LatLon]]'}, } def __init__( self, *, coordinates: List[List[LatLon]], **kwargs ): super(GeoJsonPolygonData, self).__init__(**kwargs) self.coordinates = coordinates class GeoJsonPolygon(GeoJsonObject, GeoJsonPolygonData): """A valid ``GeoJSON Polygon`` geometry type. Please refer to `RFC 7946 <https://tools.ietf.org/html/rfc7946#section-3.1.6>`_ for details. All required parameters must be populated in order to send to Azure. :param coordinates: Required. Coordinates for the ``GeoJson Polygon`` geometry type. :type coordinates: list[list[LatLon]] :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection". :type type: str or ~azure.maps.search._generated.models.GeoJsonObjectType """ _validation = { 'coordinates': {'required': True}, 'type': {'required': True}, } _attribute_map = { 'coordinates': {'key': 'coordinates', 'type': '[[LatLon]]'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, *, coordinates: List[List[LatLon]], **kwargs ): super(GeoJsonPolygon, self).__init__(coordinates=coordinates, **kwargs) self.coordinates = coordinates self.type = 'Polygon' # type: str class SearchAlongRouteOptions(object): def __init__( self, *, route: Optional["GeoJsonLineString"] = None, **kwargs ): super(SearchAlongRouteOptions, self).__init__(**kwargs) self.route = route class SearchAddressBatchItem(_SearchAddressBatchItem): """An item returned from Search Address Batch service call. Variables are only populated by the server, and will be ignored when sending a request. :keyword status_code: HTTP request status code. :paramtype status_code: int :keyword response: The result of the query. SearchAddressResponse if the query completed successfully, ErrorResponse otherwise. :paramtype response: ~azure.maps.search.models.SearchAddressBatchItemResponse """ def __init__( self, response: SearchAddressBatchItemResponse = None, **kwargs ): super(SearchAddressBatchItem, self).__init__(**kwargs) self.response = response class SearchAddressBatchResult(object): """This object is returned from a successful Search Address Batch service call. Variables are only populated by the server, and will be ignored when sending a request. :keyword summary: Summary of the results for the batch request. :paramtype summary: ~azure.maps.search._generated.models.BatchResultSummary :keyword items: Array containing the batch results. :paramtype items: list[~azure.maps.search._generated.models.SearchAddressBatchItem] """ def __init__( self, summary: BatchResultSummary = None, items: List[SearchAddressBatchItem] = None ): self.summary = summary self.items = items
9ab84dcae54eab8f6fa95e817d36f6f98380fed5
1534531d248728e583310214c84cd329cfeb243b
/accelerator/standard_methods/a_dataset_filter_columns.py
5412a85706ddd22d8abad31b272501109784a9f8
[ "Apache-2.0" ]
permissive
eBay/accelerator
415a006d18283940661c0f3cbae2c311acc1ffaa
8376d289e39cd90562de7dc2e3cdaa0bf080587b
refs/heads/master
2023-03-10T11:08:58.828517
2022-07-14T19:15:46
2022-07-14T19:15:46
130,265,539
146
30
null
null
null
null
UTF-8
Python
false
false
2,318
py
a_dataset_filter_columns.py
############################################################################ # # # Copyright (c) 2017 eBay Inc. # # Modifications copyright (c) 2018-2020 Carl Drougge # # Modifications copyright (c) 2020 Anders Berkeman # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################ from __future__ import absolute_import description = r"""Make only some columns from a dataset visible.""" from accelerator.extras import OptionDefault options = dict( # Specify only one of these options discard_columns = OptionDefault(["colname1", "colname2", "..."]), keep_columns = OptionDefault(["colname1", "colname2", "..."]), ) datasets = ("source", "previous",) def synthesis(): if options.keep_columns: assert not options.discard_columns, "Only specify one of keep_columns and discard_columns" keep = set(options.keep_columns) else: assert options.discard_columns, "Specify either keep_columns or discard_columns" discard = set(options.discard_columns) keep = set(datasets.source.columns) - discard assert keep, "All columns discarded" datasets.source.link_to_here(column_filter=keep, override_previous=datasets.previous)
220c12d959032fda6f135ccf9c5d9e96e0d21972
0cd893fddf3a43459030292dad953c3810713513
/clif/testing/python/non_raising_test.py
7f6a1f010e2c6b89450d1613545964b3724e0ebe
[ "Apache-2.0" ]
permissive
google/clif
8fc6d75f7e4a1a443f9bd596d05ea3e4c820e1c4
7501b3ca70a92a7a15022b3035bc4b1706f7569a
refs/heads/main
2023-08-19T06:26:17.321706
2023-08-18T23:18:45
2023-08-18T23:20:30
88,560,371
1,026
146
Apache-2.0
2023-08-31T23:41:41
2017-04-17T23:36:06
C++
UTF-8
Python
false
false
1,692
py
non_raising_test.py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from absl.testing import absltest from clif.testing.python import non_raising class NonRaisingTest(absltest.TestCase): def testReturnTestNonRaisingPlain(self): num = non_raising.ReturnTestNonRaisingPlain() self.assertEqual(num, 1) def testReturnTestNonRaisingMarked(self): num = non_raising.ReturnTestNonRaisingMarked() self.assertEqual(num, -1) def testReturnTestNonRaisingAndIvalPlain(self): num, ival = non_raising.ReturnTestNonRaisingAndIvalPlain() self.assertEqual(num, 1) self.assertEqual(ival, 3) def testReturnTestNonRaisingAndIvalMarked(self): num, ival = non_raising.ReturnTestNonRaisingAndIvalMarked() self.assertEqual(num, -1) self.assertEqual(ival, 3) def testReturnIvalAndTestNonRaisingPlain(self): ival, num = non_raising.ReturnIvalAndTestNonRaisingPlain() self.assertEqual(ival, 5) self.assertEqual(num, 1) def testReturnIvalAndTestNonRaisingMarked(self): ival, num = non_raising.ReturnIvalAndTestNonRaisingMarked() self.assertEqual(ival, 5) self.assertEqual(num, -1) if __name__ == '__main__': absltest.main()
14a3f9d929b5c875808b1df24fcdeb708a7192dc
7eb606a7957e5500f163c93dc4b19418cf9cf335
/ludwig/utils/structural_warning.py
c8702a0d501afe952bcdb1b1d298840ea0fb515c
[ "Apache-2.0", "MIT" ]
permissive
ludwig-ai/ludwig
024f74da86567a57ec8e30efcb4600f0c52333a1
e1d023e41606c9b76b35e1d231c2f13368a30eca
refs/heads/master
2023-09-03T08:07:32.978301
2023-09-01T19:39:32
2023-09-01T19:39:32
163,346,054
2,567
285
Apache-2.0
2023-09-14T20:34:52
2018-12-27T23:58:12
Python
UTF-8
Python
false
false
1,107
py
structural_warning.py
import warnings from ludwig.utils.logging_utils import log_once def warn_structure_refactor(old_module: str, new_module: str, direct: bool = True) -> None: """Create structure refactor warning to indicate modules new location post. Only creates a warning once per module. """ old_module = old_module.replace(".py", "") if log_once(old_module): warning = ( f"The module `{old_module}` has been moved to `{new_module}` and the old " f"location will be deprecated soon. Please adjust your imports to point " f"to the new location." ) if direct: warning += f" Example: Do a global search and " f"replace `{old_module}` with `{new_module}`." else: warning += ( f"\nATTENTION: This module may have been split or refactored. Please " f"check the contents of `{new_module}` before making changes." ) with warnings.catch_warnings(): warnings.simplefilter("always") warnings.warn(warning, DeprecationWarning, stacklevel=3)
fde06aa8ae49416670f0bc2985745ce8ced45593
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
/scripts/toolbox/modules/ArangodEnvironment/Agent.py
63e46c2b4b06b7640bfe489060848c8d50ae9c91
[ "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "BSL-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode-public-domain", "JSON", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSD-4-Clause", "Python-2.0", "LGPL-2.1-or-later" ]
permissive
arangodb/arangodb
0980625e76c56a2449d90dcb8d8f2c485e28a83b
43c40535cee37fc7349a21793dc33b1833735af5
refs/heads/devel
2023-08-31T09:34:47.451950
2023-08-31T07:25:02
2023-08-31T07:25:02
2,649,214
13,385
982
Apache-2.0
2023-09-14T17:02:16
2011-10-26T06:42:00
C++
UTF-8
Python
false
false
549
py
Agent.py
from .ArangodServer import ArangodServer class Agent(ArangodServer): def __init__(self, environment): super().__init__(environment) environment.register_agent(self) def collect_parameters(self, param): param["--agency.activate"] = "true" param["--agency.my-address"] = self.get_endpoint() param["--agency.pool-size"] = "1" param["--agency.size"] = "1" param["--agency.supervision"] = "true" param["--agency.wait-for-sync"] = "false" super().collect_parameters(param)
9aad7b61d307d435f5934743a861dc7378cf85d4
7bb974bb16651a2749282c5bae7016ea4f72be63
/sudoku_solver/sudoku_solve_backtrace_recursive.py
8b2aa9895131e7ed4ded2d113628d21580ab1705
[]
no_license
jadijadi/programming_class_cheats
9736225b23b3c09de7241c3fd2f14f33739b3079
1e9b943b3cad15e5ef7bf6d2f270cb1f6a3f0aa3
refs/heads/master
2023-01-08T14:37:56.085140
2022-01-11T12:35:58
2022-01-11T12:35:58
46,111,971
166
108
null
2023-06-25T06:20:24
2015-11-13T09:15:07
Jupyter Notebook
UTF-8
Python
false
false
1,649
py
sudoku_solve_backtrace_recursive.py
puzzle = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 0, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9] ] guess = [ [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0] ] def draw(): for j in puzzle: for i in j: print(i, end=" ") print("\n") def find_free(): for i in range(9): for j in range(9): if (puzzle[i][j] == 0): l = [i, j] guess[i][j] = 1 return l return False def is_valid(n, x, y): for i in range(9): if (puzzle[x][i] == n or puzzle[i][y] == n): return False x_square = (x // 3) * 3 y_square = (y // 3) * 3 for i in range(x_square, x_square + 3): for j in range(y_square, y_square + 3): if (puzzle[i][j] == n): return False return True def solve(): l = find_free() if (l == False): return True x = l[0] y = l[1] for i in range(1, 10): if (is_valid(i, x, y)): puzzle[x][y] = i if (solve()): return True puzzle[x][y] = 0 return False if (solve()): draw() else: print("I can not solve it! wow....\n")
3ee72f3a2d7e4f3d131fb94aa783101cdceb8e03
bed34365a9dab825fd9f4a4ff1b0863f441266ac
/neutron/tests/unit/objects/test_securitygroup.py
53a7901d3ac3adf8746b110fc536babf03ce6d06
[ "Apache-2.0" ]
permissive
openstack/neutron
0913ee3cd69d5bdb9c10aa084d4e1803abee320c
dde31aae392b80341f6440eb38db1583563d7d1f
refs/heads/master
2023-08-31T13:09:41.831598
2023-08-31T11:37:30
2023-08-31T11:37:30
2,400,289
1,174
1,325
Apache-2.0
2022-06-29T08:00:05
2011-09-16T16:04:08
Python
UTF-8
Python
false
false
11,784
py
test_securitygroup.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import collections import itertools import netaddr from oslo_utils import uuidutils from neutron.objects import securitygroup from neutron.tests.unit.objects import test_base from neutron.tests.unit.objects import test_rbac from neutron.tests.unit import testlib_api class SecurityGroupRBACDbObjectTestCase(test_rbac.TestRBACObjectMixin, test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = securitygroup.SecurityGroupRBAC _parent_class = securitygroup.SecurityGroup def setUp(self): super(SecurityGroupRBACDbObjectTestCase, self).setUp() for obj in self.db_objs: sg_obj = securitygroup.SecurityGroup(self.context, id=obj['object_id'], project_id=obj['project_id']) sg_obj.create() def _create_test_security_group_rbac(self): self.objs[0].create() return self.objs[0] def test_object_version_degradation_1_1_to_1_0_no_shared(self): security_group_rbac_obj = self._create_test_security_group_rbac() x = security_group_rbac_obj.obj_to_primitive('1.0') security_group_rbac_dict = x self.assertNotIn('shared', security_group_rbac_dict['versioned_object.data']) class SecurityGroupRBACIfaceObjectTestCase(test_rbac.TestRBACObjectMixin, test_base.BaseObjectIfaceTestCase): _test_class = securitygroup.SecurityGroupRBAC class SecurityGroupIfaceObjTestCase(test_rbac.RBACBaseObjectIfaceTestCase): _test_class = securitygroup.SecurityGroup class SecurityGroupDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = securitygroup.SecurityGroup def setUp(self): super(SecurityGroupDbObjTestCase, self).setUp() # TODO(ihrachys): consider refactoring base test class to set None for # all nullable fields for db_obj in self.db_objs: for rule in db_obj['rules']: # we either make it null, or create remote groups for each rule # generated; we picked the former here rule['remote_group_id'] = None sg_rule = self.get_random_db_fields(securitygroup.SecurityGroupRule) self.model_map.update({ self._test_class.db_model: self.db_objs, securitygroup.SecurityGroupRule.db_model: sg_rule}) def _create_test_security_group(self): self.objs[0].create() return self.objs[0] def _create_test_security_group_with_rule(self): sg_obj = self._create_test_security_group() rule_params = { 'project_id': sg_obj.project_id, 'security_group_id': sg_obj.id, 'remote_address_group_id': None, 'remote_ip_prefix': netaddr.IPNetwork('10.0.0.120/24')} sg_rule = securitygroup.SecurityGroupRule( self.context, **rule_params) sg_obj.rules = [sg_rule] return sg_obj def test_object_version_degradation_1_3_to_1_2_no_remote_ag(self): sg_obj = self._create_test_security_group_with_rule() sg_obj_1_2 = sg_obj.obj_to_primitive('1.2') for rule in sg_obj_1_2['versioned_object.data']['rules']: self.assertEqual('1.0', rule['versioned_object.version']) self.assertNotIn('remote_address_group_id', rule['versioned_object.data']) def test_object_version_degradation_1_4_to_1_3_no_normalized_cidr(self): sg_obj = self._create_test_security_group_with_rule() sg_obj_1_3 = sg_obj.obj_to_primitive('1.3') for rule in sg_obj_1_3['versioned_object.data']['rules']: self.assertEqual('1.1', rule['versioned_object.version']) self.assertNotIn('normalized_cidr', rule['versioned_object.data']) def test_object_version_degradation_1_2_to_1_1_no_stateful(self): sg_stateful_obj = self._create_test_security_group() sg_no_stateful_obj = sg_stateful_obj.obj_to_primitive('1.1') self.assertNotIn('stateful', sg_no_stateful_obj['versioned_object.data']) def test_is_default_True(self): fields = self.obj_fields[0].copy() sg_obj = self._make_object(fields) sg_obj.is_default = True sg_obj.create() default_sg_obj = securitygroup.DefaultSecurityGroup.get_object( self.context, project_id=sg_obj.project_id, security_group_id=sg_obj.id) self.assertIsNotNone(default_sg_obj) sg_obj = securitygroup.SecurityGroup.get_object( self.context, id=sg_obj.id, project_id=sg_obj.project_id ) self.assertTrue(sg_obj.is_default) def test_is_default_False(self): fields = self.obj_fields[0].copy() sg_obj = self._make_object(fields) sg_obj.is_default = False sg_obj.create() default_sg_obj = securitygroup.DefaultSecurityGroup.get_object( self.context, project_id=sg_obj.project_id, security_group_id=sg_obj.id) self.assertIsNone(default_sg_obj) sg_obj = securitygroup.SecurityGroup.get_object( self.context, id=sg_obj.id, project_id=sg_obj.project_id ) self.assertFalse(sg_obj.is_default) def test_get_object_filter_by_is_default(self): fields = self.obj_fields[0].copy() sg_obj = self._make_object(fields) sg_obj.is_default = True sg_obj.create() listed_obj = securitygroup.SecurityGroup.get_object( self.context, id=sg_obj.id, project_id=sg_obj.project_id, is_default=True ) self.assertIsNotNone(listed_obj) self.assertEqual(sg_obj, listed_obj) def test_get_objects_queries_constant(self): # TODO(electrocucaracha) SecurityGroup is using SecurityGroupRule # object to reload rules, which costs extra SQL query each time # is_default field is loaded as part of get_object(s). SecurityGroup # has defined relationship for SecurityGroupRules, so it should be # possible to reuse side loaded values fo this. To be reworked in # follow-up patch. pass def test_get_object_no_synth(self): fields = self.obj_fields[0].copy() sg_obj = self._make_object(fields) sg_obj.is_default = True sg_obj.create() listed_obj = securitygroup.SecurityGroup.get_object( self.context, fields=['id', 'name'], id=sg_obj.id, project_id=sg_obj.project_id ) self.assertIsNotNone(listed_obj) self.assertEqual(len(sg_obj.rules), 0) self.assertIsNone(listed_obj.rules) def test_get_objects_no_synth(self): fields = self.obj_fields[0].copy() sg_obj = self._make_object(fields) sg_obj.is_default = True sg_obj.create() listed_objs = securitygroup.SecurityGroup.get_objects( self.context, fields=['id', 'name'], id=sg_obj.id, project_id=sg_obj.project_id ) self.assertEqual(len(listed_objs), 1) self.assertEqual(len(sg_obj.rules), 0) self.assertIsNone(listed_objs[0].rules) class DefaultSecurityGroupIfaceObjTestCase(test_base.BaseObjectIfaceTestCase): _test_class = securitygroup.DefaultSecurityGroup class DefaultSecurityGroupDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = securitygroup.DefaultSecurityGroup def setUp(self): super(DefaultSecurityGroupDbObjTestCase, self).setUp() self.update_obj_fields( { 'security_group_id': lambda: self._create_test_security_group_id() }) class SecurityGroupRuleIfaceObjTestCase(test_base.BaseObjectIfaceTestCase): _test_class = securitygroup.SecurityGroupRule class SecurityGroupRuleDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = securitygroup.SecurityGroupRule def setUp(self): super(SecurityGroupRuleDbObjTestCase, self).setUp() self.update_obj_fields( { 'security_group_id': lambda: self._create_test_security_group_id(), 'remote_group_id': lambda: self._create_test_security_group_id(), 'remote_address_group_id': lambda: self._create_test_address_group_id() }) def _create_test_security_group_rule(self): self.objs[0].create() return self.objs[0] def test_get_security_group_rule_ids(self): """Retrieve the SG rules associated to a project (see method desc.) SG1 (PROJECT1) SG2 (PROJECT2) rule1a (PROJECT1) rule2a (PROJECT1) rule1b (PROJECT2) rule2b (PROJECT2) query PROJECT1: rule1a, rule1b, rule2a query PROJECT2: rule1b, rule2a, rule2b """ projects = [uuidutils.generate_uuid(), uuidutils.generate_uuid()] sgs = [ self._create_test_security_group_id({'project_id': projects[0]}), self._create_test_security_group_id({'project_id': projects[1]})] rules_per_project = collections.defaultdict(list) rules_per_sg = collections.defaultdict(list) for project, sg in itertools.product(projects, sgs): sgrule_fields = self.get_random_object_fields( securitygroup.SecurityGroupRule) sgrule_fields['project_id'] = project sgrule_fields['security_group_id'] = sg rule = securitygroup.SecurityGroupRule(self.context, **sgrule_fields) rule.create() rules_per_project[project].append(rule.id) rules_per_sg[sg].append(rule.id) for idx in range(2): rule_ids = securitygroup.SecurityGroupRule.\ get_security_group_rule_ids(projects[idx]) rule_ids_ref = set(rules_per_project[projects[idx]]) rule_ids_ref.update(set(rules_per_sg[sgs[idx]])) self.assertEqual(rule_ids_ref, set(rule_ids)) def test_object_version_degradation_1_1_to_1_0_no_remote_ag(self): rule_remote_ag_obj = self._create_test_security_group_rule() rule_no_remote_ag_obj = rule_remote_ag_obj.obj_to_primitive('1.0') self.assertNotIn('remote_address_group_id', rule_no_remote_ag_obj['versioned_object.data']) def test_object_version_degradation_1_2_to_1_1_no_normalized_cidr(self): sg_rule_obj = self._create_test_security_group_rule() sg_rule_10_obj = sg_rule_obj.obj_to_primitive('1.0') self.assertNotIn('normalized_cidr', sg_rule_10_obj['versioned_object.data'])
8fd16b7cc9182a31c16934a8ee1bb7111db13fb2
a5d20c1d3d0f402b34f15081c8d41ec7291f292d
/src/demos/python/vehicle/demo_VEH_SuspensionTestRig.py
d8812d05de606c7b9d8ef32c94798bf46c83ee9a
[ "BSD-3-Clause" ]
permissive
projectchrono/chrono
3535b1a22b3f9ac55cd3bb6c3015f1ee7c78308e
6a96ca61e232088d9eb5a286e5a12f5b7747ac16
refs/heads/main
2023-09-03T21:00:45.434375
2023-09-02T13:41:05
2023-09-02T13:41:05
12,567,717
1,874
460
BSD-3-Clause
2023-09-10T10:30:18
2013-09-03T15:34:23
C++
UTF-8
Python
false
false
4,975
py
demo_VEH_SuspensionTestRig.py
# ============================================================================= # PROJECT CHRONO - http://projectchrono.org # # Copyright (c) 2022 projectchrono.org # All rights reserved. # # Use of this source code is governed by a BSD-style license that can be found # in the LICENSE file at the top level of the distribution and at # http://projectchrono.org/license-chrono.txt. # # ============================================================================= # Authors: Radu Serban # ============================================================================= # # Demonstration program for a suspension test rig. # # Driver inputs for a suspension test rig include left/right post displacements # and steering input (the latter being ignored if the tested suspension is not # attached to a steering mechanism). These driver inputs can be obtained from # an interactive driver system (of type ChSuspensionTestRigInteractiveDriverIRR) or from a data file # (using a driver system of type ChSuspensionTestRigDataDriver). # # See the description of ChSuspensionTestRig::PlotOutput for details on data # collected (if output is enabled). # # ============================================================================= import pychrono as chrono import pychrono.vehicle as veh import pychrono.irrlicht as irr import errno import os import math as m # ============================================================================= def main() : #print("Copyright (c) 2017 projectchrono.org\nChrono version: ", CHRONO_VERSION , "\n\n") # Create the rig from a JSON specification file rig = veh.ChSuspensionTestRigPushrod(str_file) # Create and initialize the tires # (not needed if the vehicle's suspension JSON specification files include tire data) for ia in test_axles: axle = rig.GetVehicle().GetAxle(ia) for wheel in axle.GetWheels(): tire = veh.ReadTireJSON(tire_file) rig.GetVehicle().InitializeTire(tire, wheel, veh.VisualizationType_NONE) # Optional rig settings rig.SetSuspensionVisualizationType(veh.VisualizationType_PRIMITIVES) rig.SetSteeringVisualizationType(veh.VisualizationType_PRIMITIVES) rig.SetSubchassisVisualizationType(veh.VisualizationType_PRIMITIVES) rig.SetWheelVisualizationType(veh.VisualizationType_NONE); rig.SetTireVisualizationType(veh.VisualizationType_MESH) # Create the vehicle Irrlicht application cam_loc = (rig.GetSpindlePos(0, veh.LEFT) + rig.GetSpindlePos(0, veh.RIGHT)) * 0.5 vis = veh.ChWheeledVehicleVisualSystemIrrlicht() vis.SetWindowTitle('Suspension Test Rig') vis.SetWindowSize(1280, 1024) vis.Initialize() vis.AddTypicalLights() vis.AddLogo(chrono.GetChronoDataFile('logo_pychrono_alpha.png')) vis.SetChaseCamera(cam_loc, 4.0, 0.5) vis.AddSkyBox() vis.AttachVehicle(rig.GetVehicle()) # Create and attach an STR driver driver = veh.ChSuspensionTestRigDataDriver(driver_file) rig.SetDriver(driver) # Initialize suspension test rig rig.Initialize() vis.BindAll() # Set output try: os.mkdir(out_dir) except OSError as exc: if exc.errno != errno.EEXIST: print("Error creating output directory " ) if output: rig.SetOutput(veh.ChVehicleOutput.ASCII, out_dir, 'output', out_step_size) if plot: rig.SetPlotOutput(out_step_size) # Simulation loop while vis.Run() : time = rig.GetVehicle().GetChTime() # Render scene vis.BeginScene() vis.Render() vis.EndScene() # Advance simulation of the rig rig.Advance(step_size) # Update visualization app driver_inputs = veh.DriverInputs() driver_inputs.m_steering = rig.GetSteeringInput() driver_inputs.m_throttle = 0.0 driver_inputs.m_braking = 0.0 vis.Synchronize(time, driver_inputs) vis.Advance(step_size) if rig.DriverEnded(): break rig.PlotOutput(out_dir, 'output_plot') # ============================================================================= # The path to the Chrono data directory containing various assets (meshes, textures, data files) # is automatically set, relative to the default location of this demo. # If running from a different directory, you must change the path to the data directory with: #chrono.SetChronoDataPath('path/to/data') veh.SetDataPath(chrono.GetChronoDataPath() + 'vehicle/') # JSON file for suspension test rig str_file = veh.GetDataFile('mtv/suspensionTest/MTV_ST_rear.json') # JSON file for tire tire_file = veh.GetDataFile('mtv/tire/FMTV_TMeasyTire.json') # Driver data file driver_file = veh.GetDataFile('mtv/suspensionTest/ST_inputs.dat') # Vehicle axles included in test rig test_axles = [1, 2] # Simulation step size step_size = 1e-3 # Output collection output = True plot = True out_dir = './SUSPENSION_TEST_RIG' out_step_size = 1e-2 main()
2ce1eb70bf422d81b567989ad9887f8463486de2
f425ebe567930eda1bea606eb1b5149611f825fd
/scripts/so6_clip_sector.py
8471df648578288a67c0ef8ed52924446b102f0f
[ "MIT" ]
permissive
xoolive/traffic
4f479dcdac86b7850d68e01f6f09ce60e1a69295
e64fe6dbd205c2b56d4ec1f1fada5e524e73982e
refs/heads/master
2023-09-04T10:54:03.122322
2023-09-02T08:45:31
2023-09-02T08:45:31
127,042,768
319
87
MIT
2023-09-02T08:46:31
2018-03-27T20:32:46
Python
UTF-8
Python
false
false
2,299
py
so6_clip_sector.py
import argparse from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path from tqdm import tqdm from traffic.core import Airspace from traffic.data import SO6, nm_airspaces def clip(so6: SO6, airspace: Airspace) -> SO6: return so6.inside_bbox(airspace).intersects(airspace) def unpack_and_clip(filename: str, sectorname: str) -> SO6: so6 = SO6.from_file(filename) sector = nm_airspaces[sectorname] if sector is None: raise ValueError("Airspace not found") if so6 is None: raise RuntimeError return clip(so6, sector) def prepare_all(filename: Path, output_dir: Path, sectorname: str) -> None: so6 = unpack_and_clip(filename.as_posix(), sectorname) output_name = filename.with_suffix(".pkl").name so6.to_pickle((output_dir / output_name).as_posix()) def glob_all( directory: Path, output_dir: Path, sectorname: str, max_workers: int = 4 ) -> None: if not directory.is_dir(): raise ValueError(f"Directory {directory} does not exist") if not output_dir.is_dir(): output_dir.mkdir(parents=True) with ProcessPoolExecutor(max_workers=max_workers) as executor: tasks = { executor.submit( prepare_all, filename, output_dir, sectorname ): filename for filename in directory.glob("**/*.so6") } for future in tqdm(as_completed(tasks), total=len(tasks)): try: future.result() except Exception as e: print(f"Exception {e} occurred on file {tasks[future]}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Clip SO6 on sector") parser.add_argument( "-d", dest="directory", type=Path, help="directory containing so6 files" ) parser.add_argument( "-o", dest="output_dir", type=Path, help="output directory for pkl files", ) parser.add_argument( "-s", dest="sector_name", help="name of the sector to pick in AIRAC files", ) parser.add_argument( "-t", dest="max_workers", default=4, type=int, help="number of parallel processes", ) args = parser.parse_args() glob_all(**vars(args))
c064a5b523afca6934f921c15f5ae7d323c23bc2
771c1e2011a85a287c766b1a3d299ced2e6f799f
/src/electionguard_cli/encrypt_ballots/encrypt_ballots_input_retrieval_step.py
a62952316215ae1e9703296f77828175ed57e4f8
[ "MIT" ]
permissive
microsoft/electionguard-python
f50f64a473a8d77984a2faf4aa8db40cebb5c201
b3ddc2a732f6c5f078a3afbe05b00d632a2ff5e0
refs/heads/main
2023-08-03T12:44:35.322716
2022-10-28T12:47:18
2022-10-28T12:47:18
246,392,956
143
117
MIT
2023-08-02T00:24:32
2020-03-10T19:46:06
Python
UTF-8
Python
false
false
992
py
encrypt_ballots_input_retrieval_step.py
from io import TextIOWrapper from electionguard.ballot import PlaintextBallot from electionguard.manifest import Manifest from .encrypt_ballot_inputs import EncryptBallotInputs from ..cli_steps import ( InputRetrievalStepBase, ) class EncryptBallotsInputRetrievalStep(InputRetrievalStepBase): """Responsible for retrieving and parsing user provided inputs for the CLI's encrypt ballots command.""" def get_inputs( self, manifest_file: TextIOWrapper, context_file: TextIOWrapper, ballots_dir: str, ) -> EncryptBallotInputs: self.print_header("Retrieving Inputs") manifest: Manifest = self._get_manifest(manifest_file) context = InputRetrievalStepBase._get_context(context_file) plaintext_ballots = InputRetrievalStepBase._get_ballots( ballots_dir, PlaintextBallot ) return EncryptBallotInputs( manifest, context, plaintext_ballots, )
9fdf54049e7d624aec1d6e12196e94a04d116287
486fa0a987ab1648de91efeb4b7ba8be3dd6b016
/tests/test.generic.007.timer.py
720af1e9253d57aba256ce20a76fda1b9537e3da
[ "MIT" ]
permissive
ceccopierangiolieugenio/pyTermTk
9f5103d6af9e93fe2572b61486919020d2007550
f9c2a4d97f2cd04f0b86cf10661f63a61edae48e
refs/heads/main
2023-08-30T20:58:39.239718
2023-08-02T22:51:02
2023-08-02T22:51:02
339,475,110
414
16
MIT
2023-08-31T23:16:10
2021-02-16T17:23:36
Python
UTF-8
Python
false
false
4,434
py
test.generic.007.timer.py
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2023 Eugenio Parodi <ceccopierangiolieugenio AT googlemail DOT com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import sys, os import threading sys.path.append(os.path.join(sys.path[0],'..')) import TermTk as ttk root = ttk.TTk(title="pyTermTk Timer Test") class TimerV2(): __slots__ = ('timeout', '_timer') def __init__(self): # Define Signals self.timeout = ttk.pyTTkSignal() self._timer = None def quit(self): if self._timer: self._timer.cancel() @ttk.pyTTkSlot(float) def start(self, sec=0.0): if self._timer: self._timer.cancel() self._timer = threading.Timer(sec, self.timeout.emit) self._timer.start() @ttk.pyTTkSlot() def stop(self): if self._timer: self._timer.cancel() class TimerV3(threading.Thread): __slots__ = ('timeout', '_timer', '_quit', '_delay') def __init__(self): self.timeout = ttk.pyTTkSignal() self._delay = 0 self._quit = threading.Event() self._start = threading.Event() self._timer = threading.Event() super().__init__() super().start() def quit(self): self._quit.set() self._timer.set() self._start.set() def run(self): while not self._quit.is_set(): # ttk.TTkLog.info(f"t3-2 _start.wait") self._start.wait() self._start.clear() # ttk.TTkLog.info(f"t3-3 _timer.wait {self._delay=}") if not self._timer.wait(self._delay): # ttk.TTkLog.info(f"t3-5 (EMIT)") self.timeout.emit() #ttk.TTkLog.info(f"t3-6") self._quit.set() #ttk.TTkLog.info(f"t3-7") # def run(self): # self.finished.wait(self.interval) # if not self.finished.is_set(): # self.function(*self.args, **self.kwargs) # self.finished.set() @ttk.pyTTkSlot(float) def start(self, sec=0.0): self._delay = sec self._timer.set() self._timer.clear() self._start.set() @ttk.pyTTkSlot() def stop(self): self._timer.set() sb = ttk.TTkSpinBox(parent=root, pos=(0,1), size=(10,1), value=2) bStart = ttk.TTkButton(parent=root, text="Start", pos=(0,2), size=(10,3), border=True) bStop = ttk.TTkButton(parent=root, text="Stop", pos=(0,5), size=(10,3), border=True) # ttk.TTkButton(parent=root, text="Button 2", pos=(0,2), size=(10,3), toolTip="TT Button 2", border=True) # ttk.TTkButton(parent=root, text="Button 2", pos=(0,2), size=(10,3), toolTip="TT Button 2", border=True) w1 = ttk.TTkWindow(parent=root, title="LOG", pos=(0,10), size=(90,20), layout=ttk.TTkGridLayout(), toolTip="TT Log Window\n With\nLogDump") ttk.TTkLogViewer(parent=w1) t2 = TimerV2() t2.timeout.connect(lambda : ttk.TTkLog.debug(f"timeout (t2)")) t3 = TimerV3() t3.timeout.connect(lambda : ttk.TTkLog.debug(f"timeout (t3)")) t3_loop = TimerV3() @ttk.pyTTkSlot() def _loop(): ttk.TTkLog.debug(f"timeout (t3) LOOP") t3_loop.start(1) t3_loop.timeout.connect(_loop) t3_loop.start(1) @ttk.pyTTkSlot() def _start(): v = sb.value() ttk.TTkLog.debug(f"start : {v=}") t2.start(v) t3.start(v) @ttk.pyTTkSlot() def _stop(): t2.stop() t3.stop() bStart.clicked.connect(_start) bStop.clicked.connect(_stop) root.mainloop()
a22e3e714119c93887c9f1af9d8b861b6282a5ff
af395c3cb83dfd489565c1f516743b8eec0b547c
/appendix_argparse/choices.py
b7450096a303e850f6e9b04bba1a4172ad1c8186
[ "MIT" ]
permissive
kyclark/tiny_python_projects
0b2b15a78daa4c1d42f3804840592c5ca4a287fb
0e73a0d1d9301ffd5179d895baf60d8899bf2d34
refs/heads/master
2023-01-12T11:02:30.077085
2021-12-08T02:10:02
2021-12-08T02:10:02
187,108,291
1,221
2,393
MIT
2023-01-02T13:44:03
2019-05-16T22:15:27
Python
UTF-8
Python
false
false
953
py
choices.py
#!/usr/bin/env python3 """Choices""" import argparse # -------------------------------------------------- def get_args(): """get args""" parser = argparse.ArgumentParser( description='Choices', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('color', metavar='color', help='Color', choices=['red', 'yellow', 'blue']) parser.add_argument('size', metavar='size', type=int, choices=range(1, 11), help='The size of the garment') return parser.parse_args() # -------------------------------------------------- def main(): """main""" args = get_args() print('color =', args.color) print('size =', args.size) # -------------------------------------------------- if __name__ == '__main__': main()
a269fa0ce3a214438f06f81e8aab6550b6a35298
6d54a7b26d0eb82152a549a6a9dfde656687752c
/scripts/build/builders/cc13x2x7_26x2x7.py
907d92fe1575b4d1564ee21648db8a67891864cc
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
project-chip/connectedhomeip
81a123d675cf527773f70047d1ed1c43be5ffe6d
ea3970a7f11cd227ac55917edaa835a2a9bc4fc8
refs/heads/master
2023-09-01T11:43:37.546040
2023-09-01T08:01:32
2023-09-01T08:01:32
244,694,174
6,409
1,789
Apache-2.0
2023-09-14T20:56:31
2020-03-03T17:05:10
C++
UTF-8
Python
false
false
3,924
py
cc13x2x7_26x2x7.py
# Copyright (c) 2021 Project CHIP Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from enum import Enum, auto from .gn import GnBuilder class cc13x2x7_26x2x7App(Enum): LOCK = auto() PUMP = auto() PUMP_CONTROLLER = auto() ALL_CLUSTERS = auto() ALL_CLUSTERS_MINIMAL = auto() SHELL = auto() def ExampleName(self): if self == cc13x2x7_26x2x7App.LOCK: return 'lock-app' elif self == cc13x2x7_26x2x7App.PUMP: return 'pump-app' elif self == cc13x2x7_26x2x7App.PUMP_CONTROLLER: return 'pump-controller-app' elif self == cc13x2x7_26x2x7App.ALL_CLUSTERS: return 'all-clusters-app' elif self == cc13x2x7_26x2x7App.ALL_CLUSTERS_MINIMAL: return 'all-clusters-minimal-app' elif self == cc13x2x7_26x2x7App.SHELL: return 'shell' else: raise Exception('Unknown app type: %r' % self) def AppNamePrefix(self): if self == cc13x2x7_26x2x7App.LOCK: return 'chip-LP_CC2652R7-lock-example' elif self == cc13x2x7_26x2x7App.PUMP: return 'chip-LP_CC2652R7-pump-example' elif self == cc13x2x7_26x2x7App.PUMP_CONTROLLER: return 'chip-LP_CC2652R7-pump-controller-example' elif self == cc13x2x7_26x2x7App.ALL_CLUSTERS: return 'chip-LP_CC2652R7-all-clusters-example' elif self == cc13x2x7_26x2x7App.ALL_CLUSTERS_MINIMAL: return 'chip-LP_CC2652R7-all-clusters-minimal-example' elif self == cc13x2x7_26x2x7App.SHELL: return 'chip-LP_CC2652R7-shell-example' else: raise Exception('Unknown app type: %r' % self) def BuildRoot(self, root): return os.path.join(root, 'examples', self.ExampleName(), 'cc13x2x7_26x2x7') class cc13x2x7_26x2x7Builder(GnBuilder): def __init__(self, root, runner, app: cc13x2x7_26x2x7App = cc13x2x7_26x2x7App.LOCK, openthread_ftd: bool = None): super(cc13x2x7_26x2x7Builder, self).__init__( root=app.BuildRoot(root), runner=runner) self.code_root = root self.app = app self.openthread_ftd = openthread_ftd def GnBuildArgs(self): args = [ 'ti_sysconfig_root="%s"' % os.environ['TI_SYSCONFIG_ROOT'], ] if self.openthread_ftd is None: pass elif self.openthread_ftd: args.append('chip_openthread_ftd=true') args.append('chip_progress_logging=false') else: args.append('chip_openthread_ftd=false') return args def build_outputs(self): items = {} if (self.app == cc13x2x7_26x2x7App.LOCK or self.app == cc13x2x7_26x2x7App.PUMP or self.app == cc13x2x7_26x2x7App.PUMP_CONTROLLER): extensions = [".out", ".bin", ".out.map", "-bim.hex"] elif self.app == cc13x2x7_26x2x7App.ALL_CLUSTERS or cc13x2x7_26x2x7App.ALL_CLUSTERS_MINIMAL or self.app == cc13x2x7_26x2x7App.SHELL: extensions = [".out", ".out.map"] else: raise Exception('Unknown app type: %r' % self.app) for extension in extensions: name = '%s%s' % (self.app.AppNamePrefix(), extension) items[name] = os.path.join(self.output_dir, name) return items
14a093bcbc0a86699ee8134a7fb9338a0ca7c13b
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
/alipay/aop/api/response/AlipaySecurityDataAmlassetBatchqueryResponse.py
b1cc32e1d2c020f731965c5d61e4429579cdf38e
[ "Apache-2.0" ]
permissive
alipay/alipay-sdk-python-all
8bd20882852ffeb70a6e929038bf88ff1d1eff1c
1fad300587c9e7e099747305ba9077d4cd7afde9
refs/heads/master
2023-08-27T21:35:01.778771
2023-08-23T07:12:26
2023-08-23T07:12:26
133,338,689
247
70
Apache-2.0
2023-04-25T04:54:02
2018-05-14T09:40:54
Python
UTF-8
Python
false
false
1,122
py
AlipaySecurityDataAmlassetBatchqueryResponse.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.AmlAssetRecord import AmlAssetRecord class AlipaySecurityDataAmlassetBatchqueryResponse(AlipayResponse): def __init__(self): super(AlipaySecurityDataAmlassetBatchqueryResponse, self).__init__() self._asset_records = None @property def asset_records(self): return self._asset_records @asset_records.setter def asset_records(self, value): if isinstance(value, list): self._asset_records = list() for i in value: if isinstance(i, AmlAssetRecord): self._asset_records.append(i) else: self._asset_records.append(AmlAssetRecord.from_alipay_dict(i)) def parse_response_content(self, response_content): response = super(AlipaySecurityDataAmlassetBatchqueryResponse, self).parse_response_content(response_content) if 'asset_records' in response: self.asset_records = response['asset_records']
02bdb9be534bbd7a42b22f13444b4d63b69d2321
a1657a0c5c8f3f8b51b98074293e2f2e9b16e6f4
/libs/pipeline_model/pipeline_model/__init__.py
b778c1973cdf12a3eba6aca8c72beff35b6cc60d
[ "Apache-2.0" ]
permissive
PipelineAI/pipeline
e8067636f5844dea0653aef84bd894ca2e700fc6
0f26e3eaad727c1d10950f592fe1949ece8153aa
refs/heads/master
2023-01-07T15:27:33.741088
2022-10-25T23:01:51
2022-10-25T23:01:51
38,730,494
2,596
512
Apache-2.0
2020-01-30T23:00:08
2015-07-08T03:49:23
Jsonnet
UTF-8
Python
false
false
2,782
py
__init__.py
from grpc.beta import implementations #import tensorflow as tf # These are generated from the TF serving source # or copied from various places such as the following: # https://github.com/Vetal1977/tf_serving_example # https://github.com/tobegit3hub/tensorflow_template_application from tensorflow_serving.apis import predict_pb2, prediction_service_pb2 from tensorflow.core.framework import tensor_pb2, tensor_shape_pb2, types_pb2 __version__ = "1.0.8" # TODO: Add convenience methods for the following techniques: # https://towardsdatascience.com/tensorflow-serving-client-make-it-slimmer-and-faster-b3e5f71208fb # https://medium.com/@stianlindpetlund/tensorflow-serving-101-pt-2-682eaf7469e7 # https://github.com/davyzhang/dict-to-protobuf # # TODO: Add mock tensorflow serving server described here: # https://medium.com/@stianlindpetlund/tensorflow-serving-101-pt-2-682eaf7469e7 class TensorFlowServingModel(): # TODO: Don't expose any of these... # (They're all internal to the model server runtime.) def __init__(self, host: str, port: int, model_name: str, model_signature_name=None, timeout_seconds=5.0): # 5 second timeout self._host = host self._port = port self._model_name = model_name self._model_signature_name = model_signature_name self._timeout_seconds = timeout_seconds def predict(self, input_string_to_tensor_dict): channel = implementations.insecure_channel(self._host, self._port) stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) # Transform input str::nparray dict into TensorFlow PredictRequest/tensors tf_request = predict_pb2.PredictRequest() tf_request.model_spec.name = self._model_name if self._model_signature_name: tf_request.model_spec.signature_name = self._model_signature_name # We assume only a single version per model is running in this model server. # tf_request.model_spec.version.value = ... for input_str_key, input_tensor in input_string_to_tensor_dict.items(): tf_request.inputs[input_str_key].CopyFrom(input_tensor) # Call TensorFlow Serving Predict response = stub.Predict(tf_request, self._timeout_seconds) # Return tensor dict output_string_to_tensor_dict = {} for output_str_key, _ in response.outputs.items(): output_string_to_tensor_dict[output_str_key] = repsonse.outputs[output_str_key] #tf.make_ndarray(response.outputs[output_str_key]) return output_string_to_tensor_dict
ad67e086458b5eb8dded238362c79ffad3ad489d
71b8b60c5627ace1bbda39f679f93f60b55543ca
/tensorflow_federated/python/aggregators/factory.py
90efa74096de4f3faafd094d3a005d9a70e72b5d
[ "Apache-2.0" ]
permissive
tensorflow/federated
ff94b63e9f4af448795bae77cee5b627dcae9051
ad4bca66f4b483e09d8396e9948630813a343d27
refs/heads/main
2023-08-31T11:46:28.559047
2023-08-31T02:04:38
2023-08-31T02:09:59
161,556,784
2,297
631
Apache-2.0
2023-09-13T22:54:14
2018-12-12T23:15:35
Python
UTF-8
Python
false
false
2,926
py
factory.py
# Copyright 2020, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """Abstract base factory classes for creation of `AggregationProcess`.""" import abc from typing import Union from tensorflow_federated.python.core.impl.types import computation_types from tensorflow_federated.python.core.templates import aggregation_process ValueType = Union[computation_types.TensorType, computation_types.StructType] class UnweightedAggregationFactory(abc.ABC): """Factory for creating `tff.templates.AggregationProcess` without weights.""" @abc.abstractmethod def create( self, value_type: ValueType ) -> aggregation_process.AggregationProcess: """Creates a `tff.aggregators.AggregationProcess` without weights. The provided `value_type` is a non-federated `tff.Type`, that is, not a `tff.FederatedType`. The returned `tff.aggregators.AggregationProcess` will be created for aggregation of values matching `value_type` placed at `tff.CLIENTS`. That is, its `next` method will expect type `<S@SERVER, {value_type}@CLIENTS>`, where `S` is the unplaced return type of its `initialize` method. Args: value_type: A non-federated `tff.Type`. Returns: A `tff.templates.AggregationProcess`. """ raise NotImplementedError class WeightedAggregationFactory(abc.ABC): """Factory for creating `tff.templates.AggregationProcess` with weights.""" @abc.abstractmethod def create( self, value_type: ValueType, weight_type: ValueType ) -> aggregation_process.AggregationProcess: """Creates a `tff.aggregators.AggregationProcess` with weights. The provided `value_type` and `weight_type` are non-federated `tff.Type`s. That is, neither is a `tff.FederatedType`. The returned `tff.aggregators.AggregationProcess` will be created for aggregation of pairs of values matching `value_type` and `weight_type` placed at `tff.CLIENTS`. That is, its `next` method will expect type `<S@SERVER, {value_type}@CLIENTS, {weight_type}@CLIENTS>`, where `S` is the unplaced return type of its `initialize` method. Args: value_type: A non-federated `tff.Type`. weight_type: A non-federated `tff.Type`. Returns: A `tff.templates.AggregationProcess`. """ raise NotImplementedError AggregationFactory = Union[ UnweightedAggregationFactory, WeightedAggregationFactory ]
b97fbd071c7665d734df8307f9d93675609743a1
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
/alipay/aop/api/response/AlipayCommerceOperationUserBenefitBatchqueryResponse.py
c6d9160389048734bdf54178bdec8928793550c6
[ "Apache-2.0" ]
permissive
alipay/alipay-sdk-python-all
8bd20882852ffeb70a6e929038bf88ff1d1eff1c
1fad300587c9e7e099747305ba9077d4cd7afde9
refs/heads/master
2023-08-27T21:35:01.778771
2023-08-23T07:12:26
2023-08-23T07:12:26
133,338,689
247
70
Apache-2.0
2023-04-25T04:54:02
2018-05-14T09:40:54
Python
UTF-8
Python
false
false
1,928
py
AlipayCommerceOperationUserBenefitBatchqueryResponse.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.UserBenefitInfo import UserBenefitInfo class AlipayCommerceOperationUserBenefitBatchqueryResponse(AlipayResponse): def __init__(self): super(AlipayCommerceOperationUserBenefitBatchqueryResponse, self).__init__() self._page_num = None self._page_size = None self._total_size = None self._user_benefit_info_list = None @property def page_num(self): return self._page_num @page_num.setter def page_num(self, value): self._page_num = value @property def page_size(self): return self._page_size @page_size.setter def page_size(self, value): self._page_size = value @property def total_size(self): return self._total_size @total_size.setter def total_size(self, value): self._total_size = value @property def user_benefit_info_list(self): return self._user_benefit_info_list @user_benefit_info_list.setter def user_benefit_info_list(self, value): if isinstance(value, UserBenefitInfo): self._user_benefit_info_list = value else: self._user_benefit_info_list = UserBenefitInfo.from_alipay_dict(value) def parse_response_content(self, response_content): response = super(AlipayCommerceOperationUserBenefitBatchqueryResponse, self).parse_response_content(response_content) if 'page_num' in response: self.page_num = response['page_num'] if 'page_size' in response: self.page_size = response['page_size'] if 'total_size' in response: self.total_size = response['total_size'] if 'user_benefit_info_list' in response: self.user_benefit_info_list = response['user_benefit_info_list']
6134b515bbfabb175acb281e8f902768da659674
8245320cd0ccd28d9e8670a80e848ef4a61c8f69
/modelzoo/vision/pytorch/unet/utils.py
a10c26e826b125e4acc2c9213db1697845ef2c4c
[ "Apache-2.0" ]
permissive
Cerebras/modelzoo
b7d3e097dc77b9958db47ddc7029aeef8cd11e19
97bdaf4460ace1681ad437b07ba33f0e179f5ca4
refs/heads/main
2023-08-02T09:44:00.573057
2023-07-28T01:15:20
2023-07-28T01:15:20
479,424,977
644
78
Apache-2.0
2023-07-28T01:15:21
2022-04-08T14:35:05
Python
UTF-8
Python
false
false
5,943
py
utils.py
# Copyright 2022 Cerebras Systems. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from modelzoo.common.pytorch import cb_model as cm from modelzoo.vision.pytorch.utils.run_utils import ( get_default_inis, update_runconfig_debug_args_path, ) def set_defaults(params): """ Update any missing parameters in the params dictionary with default values Args: params: The dictionary containing the params """ default_inis_dict = get_default_inis() update_runconfig_debug_args_path(params, default_inis_dict) # For performance if params["runconfig"]["log_steps"] > 1: params["runconfig"]["skip_train_recv_activations"] = True if params["runconfig"]["checkpoint_steps"] == 0: logging.warning( f"Setting `runconfig.checkpoint_steps` to max_steps. " f"Setting to 0 only saves initial checkpoint" ) params["runconfig"]["checkpoint_steps"] = params["runconfig"][ "max_steps" ] # Data params: params["train_input"]["normalize_data_method"] = params["train_input"].get( "normalize_data_method", None ) # Model params: if "input_channels" not in params["model"].keys(): params["model"]["input_channels"] = params["train_input"].get( "image_shape" )[-1] input_mode = params["runconfig"]["mode"] shape_key = ( "image_shape" if params["train_input"].get("image_shape") else "input_shape" ) if input_mode == "eval_all": input_mode = "eval" params["model"]["image_shape"] = params[f"{input_mode}_input"].get( shape_key ) params["model"]["batch_size"] = params[f"{input_mode}_input"]["batch_size"] convert_to_onehot = params["model"]["loss"] == "multilabel_bce" params['train_input']['convert_to_onehot'] = convert_to_onehot params['train_input']["use_worker_cache"] = params['train_input'].get( "use_worker_cache", False ) params['eval_input']['convert_to_onehot'] = convert_to_onehot params['eval_input']["use_worker_cache"] = params['eval_input'].get( "use_worker_cache", False ) params["model"]["num_classes"] = params["train_input"]["num_classes"] params["model"]["skip_connect"] = params["model"].get("skip_connect", True) params["model"]["downscale_method"] = params["model"].get( "downscale_method", "max_pool" ) params["model"]["downscale_first_conv"] = params["model"].get( "downscale_first_conv", False, ) params["model"]["residual_blocks"] = params["model"].get( "residual_blocks", False ) params["model"]["use_conv3d"] = params["model"].get("use_conv3d", False) params["model"]["downscale_encoder_blocks"] = params["model"].get( "downscale_encoder_blocks", False if (params["model"]["downscale_method"] == "max_pool") else True, ) params["model"]["downscale_bottleneck"] = params["model"].get( "downscale_bottleneck", False ) if (params["model"]["downscale_method"] == "max_pool") and ( params["model"]["downscale_encoder_blocks"] ): logging.warning( "Setting downscale_encoder_blocks has no effect when using max_pool" ) if (params["model"]["downscale_method"] == "max_pool") and ( params["model"]["downscale_bottleneck"] ): logging.warning( "Setting downscale_bottleneck has no effect when using max_pool" ) # ignore_background_class only used by dice + cross entropy loss params["model"]["ignore_background_class"] = params["model"].get( "ignore_background_class", True ) # Param defaults for metrics params["model"]["eval_ignore_classes"] = params["model"].get( "eval_ignore_classes", [] ) params["model"]["compute_eval_metrics"] = params["model"].get( "compute_eval_metrics", True ) params["model"]["eval_metrics"] = params["model"].get( "eval_metrics", ["mIOU", "DSC", "Acc"] ) params["model"]["use_bfloat16"] = params["model"].get("use_bfloat16", False) if params["model"]["use_bfloat16"]: params["optimizer"]["loss_scaling_factor"] = 1.0 params["model"]["shuffle_seed"] = params["train_input"].get("shuffle_seed") downscale_method = params["model"]["downscale_method"] convs_per_block = params["model"]["convs_per_block"] skip_connect = params["model"]["skip_connect"] if ( skip_connect and downscale_method == "strided_conv" and len(convs_per_block) == 1 ): raise ValueError( f"skip_connect cannot be True when " f"downscale_method = {downscale_method} " f"and len(convs_per_block) = {len(convs_per_block)}. " f"Either set `skip_connect` = `False` (or) " f"change `downscale_method` = `max_pool`." ) # Pass settings into data loader. for model_key in ("mixed_precision", "loss", "use_bfloat16"): for input_key in ("train_input", "eval_input"): params[input_key][model_key] = params["model"].get(model_key) def set_custom_stack_params(params): # TODO: Add custom stack params for UNet if any. # Fcn used in `model.py` __init__ if cm.use_cs(): from modelzoo.common.pytorch import cbtorch state = cbtorch.state() runconfig_params = params["runconfig"]
29fd2ba63b0a25a268396b61669a62117d7d75e8
a716f48abe52957cca6013246ef6fce800af2dd1
/pythonbuild/docker.py
905340c800012c91f2ac8d7b216c8645476da33f
[ "OpenSSL", "X11-distribute-modifications-variant", "MIT", "LicenseRef-scancode-public-domain", "Zlib", "MIT-open-group", "Python-2.0", "bzip2-1.0.6", "Sleepycat", "LGPL-2.0-or-later", "LGPL-2.1-or-later", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain-disclaimer", "BSD-3-Clause", "GPL-3.0-or-later", "GPL-3.0-only", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference", "GPL-1.0-or-later", "LicenseRef-scancode-xfree86-1.0", "TCL", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-secret-labs-2011", "HPND", "dtoa", "LicenseRef-scancode-w3c-03-bsd-license", "Python-2.0.1", "BSD-2-Clause", "LicenseRef-scancode-newlib-historical", "BSD-1-Clause", "X11", "LicenseRef-scancode-x11-doc", "NTP", "LicenseRef-scancode-x11-dec1", "HPND-sell-variant", "LicenseRef-scancode-tekhvc", "LicenseRef-scancode-patent-disclaimer" ]
permissive
indygreg/python-build-standalone
3793ead5df9f2a98c172a2a29082df58726573f3
93ee2633c5a182f364672d73c4e0437bc6475d47
refs/heads/main
2023-08-30T22:44:59.639556
2023-08-25T03:45:31
2023-08-26T05:10:26
162,334,160
1,056
97
BSD-3-Clause
2023-07-26T01:57:50
2018-12-18T19:10:32
Python
UTF-8
Python
false
false
4,695
py
docker.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. import contextlib import io import operator import os import pathlib import tarfile import docker import jinja2 from .logging import log, log_raw from .utils import write_if_different def write_dockerfiles(source_dir: pathlib.Path, dest_dir: pathlib.Path): env = jinja2.Environment(loader=jinja2.FileSystemLoader(str(source_dir))) for f in os.listdir(source_dir): if not f.endswith(".Dockerfile"): continue tmpl = env.get_template(f) data = tmpl.render() write_if_different(dest_dir / f, data.encode("utf-8")) def build_docker_image(client, image_data: bytes, image_dir: pathlib.Path, name): image_path = image_dir / ("image-%s" % name) return ensure_docker_image(client, io.BytesIO(image_data), image_path=image_path) def ensure_docker_image(client, fh, image_path=None): res = client.api.build(fileobj=fh, decode=True) image = None for s in res: if "stream" in s: for l in s["stream"].strip().splitlines(): log(l) if "aux" in s and "ID" in s["aux"]: image = s["aux"]["ID"] if not image: raise Exception("unable to determine built Docker image") if image_path: tar_path = pathlib.Path(str(image_path) + ".tar") with tar_path.open("wb") as fh: for chunk in client.images.get(image).save(): fh.write(chunk) with image_path.open("w") as fh: fh.write(image + "\n") return image def get_image(client, source_dir: pathlib.Path, image_dir: pathlib.Path, name): if client is None: return None image_path = image_dir / ("image-%s" % name) tar_path = image_path.with_suffix(".tar") with image_path.open("r") as fh: image_id = fh.read().strip() try: client.images.get(image_id) return image_id except docker.errors.ImageNotFound: if tar_path.exists(): with tar_path.open("rb") as fh: data = fh.read() client.images.load(data) return image_id else: return build_docker_image(client, source_dir, image_dir, name) def copy_file_to_container(path, container, container_path, archive_path=None): """Copy a path on the local filesystem to a running container.""" buf = io.BytesIO() tf = tarfile.open("irrelevant", "w", buf) dest_path = archive_path or path.name tf.add(str(path), dest_path) tf.close() log("copying %s to container:%s/%s" % (path, container_path, dest_path)) container.put_archive(container_path, buf.getvalue()) @contextlib.contextmanager def run_container(client, image): container = client.containers.run( image, command=["/bin/sleep", "86400"], detach=True ) try: yield container finally: container.stop(timeout=0) container.remove() def container_exec(container, command, user="build", environment=None): # docker-py's exec_run() won't return the exit code. So we reinvent the # wheel. create_res = container.client.api.exec_create( container.id, command, user=user, environment=environment ) exec_output = container.client.api.exec_start(create_res["Id"], stream=True) for chunk in exec_output: for l in chunk.strip().splitlines(): log(l) log_raw(chunk) inspect_res = container.client.api.exec_inspect(create_res["Id"]) if inspect_res["ExitCode"] != 0: if "PYBUILD_BREAK_ON_FAILURE" in os.environ: print("to enter container: docker exec -it %s /bin/bash" % container.id) import pdb pdb.set_trace() raise Exception("exit code %d from %s" % (inspect_res["ExitCode"], command)) # 2019-01-01T00:00:00 DEFAULT_MTIME = 1546329600 def container_get_archive(container, path): """Get a deterministic tar archive from a container.""" data, stat = container.get_archive(path) old_data = io.BytesIO() for chunk in data: old_data.write(chunk) old_data.seek(0) new_data = io.BytesIO() with tarfile.open(fileobj=old_data) as itf, tarfile.open( fileobj=new_data, mode="w" ) as otf: for member in sorted(itf.getmembers(), key=operator.attrgetter("name")): file_data = itf.extractfile(member) if not member.linkname else None member.mtime = DEFAULT_MTIME otf.addfile(member, file_data) return new_data.getvalue()
779e27d57c3a76b6977aea4c07d52131d8af9d31
41e424bc0476fe67c22e5f4e9255932a5de277b3
/caffe/data/make_cub2011.py
cb48dce43dea6c937c02704c22ad3a9bcc4a3e09
[]
no_license
abhimanyudubey/confusion
a1228823ee33d5d5e439a6c069e87a6163e43f01
bbc47c305fcca4c462d7852ad306b09d904e12e0
refs/heads/master
2021-01-19T14:52:29.193396
2018-09-11T00:42:39
2018-09-11T00:42:39
100,933,177
219
46
null
null
null
null
UTF-8
Python
false
false
1,282
py
make_cub2011.py
#!/usr/bin/env python import argparse import glob import random import os if __name__ == '__main__': parser = argparse.ArgumentParser('Make CUB dataset text files') parser.add_argument('-i', '--input', help='Path to dataset parent directory', required=True, type=str, default=None) parser.add_argument('-o', '--output', help='Output prefix', required=True, type=str, default=None) args = parser.parse_args() c_train, c_test = 0, 0 file1 = open(os.path.join(args.input, 'images.txt'),'r') file2 = open(os.path.join(args.input, 'train_test_split.txt'), 'r') ofile1 = open(os.path.join(args.output, '_train.txt'), 'w') ofile2 = open(os.path.join(args.output, '_test.txt'), 'w') for i, (line1, line2) in enumerate(zip(file1, file2)): lvars1 = line1.strip().split() lvars2 = line2.strip().split() is_test = bool(int(lvars2[-1])) elem_class = int(lvars1[1].split('.')[0]) elem_fname = os.path.join(args.input, 'images', lvars1[1]) outline = '%s %d\n' % (elem_fname, elem_class) if not is_test: ofile2.write(outline) c_test+=1 else: ofile1.write(outline) c_train+=1 print '%s training files, %s test files' % (c_train, c_test)
9abae4ac901e2e4fa659abcf15d8d1e767873051
993f18c21402d7a4ff21ddb7ff2ec6c80e466f20
/onnx/backend/test/case/node/constant.py
b376079ad5617a92dfe0ee95a4446da794154dbd
[ "Apache-2.0" ]
permissive
onnx/onnx
10d3916803c7babff89ec0fa9045127bcccad376
8a475b34cb3875df311a46f57571646498f5bda7
refs/heads/main
2023-08-18T18:50:03.388353
2023-08-16T22:18:46
2023-08-16T22:18:46
102,692,863
16,164
4,150
Apache-2.0
2023-09-14T17:10:38
2017-09-07T04:53:45
Python
UTF-8
Python
false
false
766
py
constant.py
# Copyright (c) ONNX Project Contributors # # SPDX-License-Identifier: Apache-2.0 import numpy as np import onnx from onnx.backend.test.case.base import Base from onnx.backend.test.case.node import expect class Constant(Base): @staticmethod def export() -> None: values = np.random.randn(5, 5).astype(np.float32) node = onnx.helper.make_node( "Constant", inputs=[], outputs=["values"], value=onnx.helper.make_tensor( name="const_tensor", data_type=onnx.TensorProto.FLOAT, dims=values.shape, vals=values.flatten().astype(float), ), ) expect(node, inputs=[], outputs=[values], name="test_constant")
94320399ea8e108ea53744eb8b122a8effd150e2
b8441dc1987be9e64fa3081d456b2a3060ec44d1
/mars/oscar/backends/router.py
96d3e5cedd6ad3356ca744a4410f7d3bf2e40224
[ "BSD-3-Clause", "MIT", "ISC", "Apache-2.0", "CC0-1.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mars-project/mars
f99fefbce999d58a9249bc72046787a9731c9c73
c36c53fa22e10ef9477d9c454401a2f281375f31
refs/heads/master
2023-07-23T00:23:55.133015
2023-07-03T11:44:54
2023-07-03T11:44:54
160,543,708
2,704
362
Apache-2.0
2023-09-11T07:57:35
2018-12-05T16:04:03
Python
UTF-8
Python
false
false
4,428
py
router.py
# Copyright 1999-2021 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading from typing import Dict, List, Tuple, Type, Any, Optional from .communication import get_client_type, Client class Router: """ Router provides mapping from external address to internal address. """ __slots__ = "_curr_external_addresses", "_local_mapping", "_mapping", "_cache_local" _instance: "Router" = None @staticmethod def set_instance(router: Optional["Router"]): # Default router is set when an actor pool started Router._instance = router @staticmethod def get_instance() -> "Router": return Router._instance @staticmethod def get_instance_or_empty() -> "Router": return Router._instance or Router(list(), None) def __init__( self, external_addresses: List[str], local_address: Optional[str], mapping: Dict[str, str] = None, ): self._curr_external_addresses = external_addresses self._local_mapping = dict() for addr in self._curr_external_addresses: self._local_mapping[addr] = local_address if mapping is None: mapping = dict() self._mapping = mapping self._cache_local = threading.local() @property def _cache(self) -> Dict[Tuple[str, Any], Client]: try: return self._cache_local.cache except AttributeError: cache = self._cache_local.cache = dict() return cache def set_mapping(self, mapping: Dict[str, str]): self._mapping = mapping self._cache_local = threading.local() def add_router(self, router: "Router"): self._curr_external_addresses.extend(router._curr_external_addresses) self._local_mapping.update(router._local_mapping) self._mapping.update(router._mapping) self._cache_local = threading.local() def remove_router(self, router: "Router"): for external_address in router._curr_external_addresses: try: self._curr_external_addresses.remove(external_address) except ValueError: pass for addr in router._local_mapping: self._local_mapping.pop(addr, None) for addr in router._mapping: self._mapping.pop(addr, None) self._cache_local = threading.local() @property def external_address(self): if self._curr_external_addresses: return self._curr_external_addresses[0] def get_internal_address(self, external_address: str) -> str: if external_address in self._curr_external_addresses: # local address, use dummy address return self._local_mapping.get(external_address) # try to lookup inner address from address mapping return self._mapping.get(external_address) async def get_client( self, external_address: str, from_who: Any = None, cached: bool = True, **kw ) -> Client: if cached and (external_address, from_who) in self._cache: cached_client = self._cache[external_address, from_who] if cached_client.closed: # closed before, ignore it del self._cache[external_address, from_who] else: return cached_client address = self.get_internal_address(external_address) if address is None: # no inner address, just use external address address = external_address client_type: Type[Client] = get_client_type(address) local_address = ( self._curr_external_addresses[0] if self._curr_external_addresses else None ) client = await client_type.connect(address, local_address=local_address, **kw) if cached: self._cache[external_address, from_who] = client return client
8e021f9b2fbb6b68f461bc438144cf6dff84f4db
787022de03a2dd6998c1518673830395b389e3df
/migration/migrator/migrations/system/20180817164339_enable_docker.py
c77c8b1718b46650d35c0d89b36c4ef6a187114f
[ "BSD-3-Clause", "MIT" ]
permissive
Submitty/Submitty
e6b8731656291a025aa77f928eb067bc9a307540
b223d9e952bcdb8664721a55593bc75e0e3c8c4f
refs/heads/main
2023-08-31T23:56:11.291752
2023-08-31T19:12:18
2023-08-31T19:12:18
16,236,118
592
727
BSD-3-Clause
2023-09-13T05:36:08
2014-01-25T17:43:57
PHP
UTF-8
Python
false
false
2,246
py
20180817164339_enable_docker.py
import os import json import shutil from pathlib import Path from subprocess import call # The changes in this pull request change the interface/arguments to # the autograding scripts, thus it requires that all gradeables be # rebuilt/recompiled def up(config): # ============================================================ # rebuild all gradeables from pathlib import Path Path(config.submitty['submitty_install_dir'], 'REBUILD_ALL_FLAG.txt').touch() # ============================================================ # create the basic docker image for python & c++ tmp_docker_dir = Path("/tmp/docker") shutil.rmtree(str(tmp_docker_dir), ignore_errors=True) os.makedirs(str(tmp_docker_dir)) dockerfile = Path(config.submitty['submitty_repository'],".setup","Dockerfile") shutil.copy(str(dockerfile),str(Path(tmp_docker_dir,"Dockerfile"))) shutil.copytree(str(Path(config.submitty['submitty_install_dir'],"drmemory")),str(Path(tmp_docker_dir,"drmemory"))) shutil.copytree(str(Path(config.submitty['submitty_install_dir'],"SubmittyAnalysisTools")),str(Path(tmp_docker_dir,"SubmittyAnalysisTools"))) submitty_users_filename = str(Path(config.submitty['submitty_install_dir'], 'config', 'submitty_users.json')) with open (submitty_users_filename,"r") as open_file: my_json = json.load(open_file) daemon_uid = my_json["daemon_uid"] daemon_user = my_json["daemon_user"] daemon_gid = my_json["daemon_gid"] os.chown(str(tmp_docker_dir),daemon_uid,daemon_gid) for root, dirs, files in os.walk(str(tmp_docker_dir)): for d in dirs: os.chown(os.path.join(root, d),daemon_uid,daemon_gid) for f in files: os.chown(os.path.join(root, f),daemon_uid,daemon_gid) print ("GOING TO BUILD DOCKER IMAGE") os.chdir(str(tmp_docker_dir)) call(["su","-c","docker build -t ubuntu:custom -f Dockerfile .",daemon_user]) print ("ALL DONE WITH DOCKER SETUP") def down(config): # ============================================================ # rebuild all gradeables from pathlib import Path Path(config.submitty['submitty_install_dir'], 'REBUILD_ALL_FLAG.txt').touch() pass
4d498cc71441731f0323c7f5758352e49df90e61
e3bb1df7fa4c51900dec7e9ddf5295e1a80938bd
/hummingbot/client/platform.py
80dd039c38b0af0ce92c572b2f8cdc380e6a07ec
[ "Apache-2.0" ]
permissive
CoinAlpha/hummingbot
0d1e2bd94de1280748647108c7d7800a09546eb8
c3f101759ab7e7a2165cd23a3a3e94c90c642a9b
refs/heads/development
2023-09-01T11:24:43.322137
2023-08-31T03:08:06
2023-08-31T03:08:06
439,330,952
135
98
Apache-2.0
2023-08-30T13:55:08
2021-12-17T12:50:42
Python
UTF-8
Python
false
false
516
py
platform.py
import os import platform from pathlib import Path def get_system(): return platform.system() def get_installation_type(): if os.environ.get("INSTALLATION_TYPE", "").lower() == "docker": return "docker" package_dir = Path(__file__).resolve().parent.parent.parent bin_dir = [f for f in os.scandir(str(package_dir)) if f.name == "bin" and f.is_dir()] if not bin_dir: return "binary" return "source" client_system = get_system() installation_type = get_installation_type()
d56df35bfc7a4cdf4c5a3df4a7c06017c5a9c307
5ae0b5c15dda392ea9786394deb6e106b5a156c0
/tests/test_assignment.py
ea194f70daa72a0650b3cd14febf6deae97f9b78
[ "MIT" ]
permissive
dgk/django-business-logic
f68108dd0f3d82c514c09c764455bf6e48cdd916
2372ca9076b06a21bdf4bb6266b8f1e0ace0ed91
refs/heads/develop
2023-09-01T05:24:37.672687
2019-12-20T17:49:46
2019-12-20T17:49:46
47,394,841
201
42
MIT
2023-09-12T15:29:57
2015-12-04T09:37:53
CSS
UTF-8
Python
false
false
1,797
py
test_assignment.py
# -*- coding: utf-8 -*- # from .common import * class AssignmentTest(TestCase): def test_assignment(self): context = Context() root = Node.add_root() var_def = VariableDefinition(name='K1') root.add_child(content_object=var_def) root = Node.objects.get(id=root.id) assignment_node = root.add_child(content_object=Assignment()) var = Variable(definition=var_def) var_node = assignment_node.add_child(content_object=var) tree_1plus2mul3(parent=assignment_node) root = Node.objects.get(id=root.id) result = root.interpret(context) var_value = context.get_variable(var_def) self.assertEqual(7, var_value) def test_var_assignment(self): context = Context() root = Node.add_root() var_def1 = VariableDefinition(name='K1') root.add_child(content_object=var_def1) root = Node.objects.get(id=root.id) var_def2 = VariableDefinition(name='K2') root.add_child(content_object=var_def2) root = Node.objects.get(id=root.id) assignment_node = root.add_child(content_object=Assignment()) var1 = Variable(definition=var_def1) var_node = assignment_node.add_child(content_object=var1) tree_1plus2mul3(parent=assignment_node) root = Node.objects.get(id=root.id) assignment_node = root.add_child(content_object=Assignment()) var2 = Variable(definition=var_def2) var_node = assignment_node.add_child(content_object=var2) var_node = assignment_node.add_child(content_object=var1) root = Node.objects.get(id=root.id) result = root.interpret(context) var_value = context.get_variable(var_def2) self.assertEqual(7, var_value)
1620397a0d4deafa12eb9ccda7d5740ecd9ba928
704976ea552111c6a5af9cd7cb62b9d9abaf3996
/pypy/module/_cffi_backend/__init__.py
76e7369d16638ce8b40f59b0e901ba2f5d374564
[ "BSD-3-Clause" ]
permissive
mesalock-linux/mesapy
4f02c5819ce7f2f6e249d34840f1aa097577645d
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
refs/heads/mesapy2.7
2023-08-16T21:33:02.239581
2019-08-13T10:29:43
2019-08-13T18:06:45
136,080,721
396
33
NOASSERTION
2020-04-01T03:05:18
2018-06-04T20:45:17
Python
UTF-8
Python
false
false
3,161
py
__init__.py
import sys from pypy.interpreter.mixedmodule import MixedModule from rpython.rlib import rdynload, clibffi from rpython.rtyper.lltypesystem import rffi VERSION = "1.11.5" FFI_DEFAULT_ABI = clibffi.FFI_DEFAULT_ABI try: FFI_STDCALL = clibffi.FFI_STDCALL has_stdcall = True except AttributeError: has_stdcall = False class Module(MixedModule): appleveldefs = { } interpleveldefs = { '__version__': 'space.wrap("%s")' % VERSION, 'load_library': 'libraryobj.load_library', 'new_primitive_type': 'newtype.new_primitive_type', 'new_pointer_type': 'newtype.new_pointer_type', 'new_array_type': 'newtype.new_array_type', 'new_struct_type': 'newtype.new_struct_type', 'new_union_type': 'newtype.new_union_type', 'complete_struct_or_union': 'newtype.complete_struct_or_union', 'new_void_type': 'newtype.new_void_type', 'new_enum_type': 'newtype.new_enum_type', 'new_function_type': 'newtype.new_function_type', 'newp': 'func.newp', 'cast': 'func.cast', 'callback': 'func.callback', 'alignof': 'func.alignof', 'sizeof': 'func.sizeof', 'typeof': 'func.typeof', 'typeoffsetof': 'func.typeoffsetof', 'rawaddressof': 'func.rawaddressof', 'getcname': 'func.getcname', 'newp_handle': 'handle.newp_handle', 'from_handle': 'handle.from_handle', '_get_types': 'func._get_types', '_get_common_types': 'func._get_common_types', 'from_buffer': 'func.from_buffer', 'gcp': 'func.gcp', 'string': 'func.string', 'unpack': 'func.unpack', 'buffer': 'cbuffer.MiniBuffer', 'memmove': 'func.memmove', 'get_errno': 'cerrno.get_errno', 'set_errno': 'cerrno.set_errno', 'FFI_DEFAULT_ABI': 'space.wrap(%d)' % FFI_DEFAULT_ABI, 'FFI_CDECL': 'space.wrap(%d)' % FFI_DEFAULT_ABI, # win32 name # CFFI 1.0 'FFI': 'ffi_obj.W_FFIObject', } if sys.platform == 'win32': interpleveldefs['getwinerror'] = 'cerrno.getwinerror' if has_stdcall: interpleveldefs['FFI_STDCALL'] = 'space.wrap(%d)' % FFI_STDCALL def __init__(self, space, *args): MixedModule.__init__(self, space, *args) # if not space.config.objspace.disable_entrypoints: # import 'embedding', which has the side-effect of registering # the 'pypy_init_embedded_cffi_module' entry point from pypy.module._cffi_backend import embedding embedding.glob.space = space def get_dict_rtld_constants(): found = {} for name in ["RTLD_LAZY", "RTLD_NOW", "RTLD_GLOBAL", "RTLD_LOCAL", "RTLD_NODELETE", "RTLD_NOLOAD", "RTLD_DEEPBIND"]: if getattr(rdynload.cConfig, name) is not None: found[name] = getattr(rdynload.cConfig, name) for name in ["RTLD_LAZY", "RTLD_NOW", "RTLD_GLOBAL", "RTLD_LOCAL"]: found.setdefault(name, 0) return found for _name, _value in get_dict_rtld_constants().items(): Module.interpleveldefs[_name] = 'space.wrap(%d)' % _value
97a9ea684e48b4ecd14b80bc30f8340c4acf9146
e7efae2b83216d9621bd93390959d652de779c3d
/ddev/src/ddev/cli/release/agent/integrations.py
9c8281baebe4c7f8f815f027b4501c2af2ef0dc0
[ "MIT", "BSD-3-Clause", "BSD-3-Clause-Modification", "Unlicense", "Apache-2.0", "LGPL-3.0-only", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "CC0-1.0" ]
permissive
DataDog/integrations-core
ee1886cc7655972b2791e6ab8a1c62ab35afdb47
406072e4294edff5b46b513f0cdf7c2c00fac9d2
refs/heads/master
2023-08-31T04:08:06.243593
2023-08-30T18:22:10
2023-08-30T18:22:10
47,203,045
852
1,548
BSD-3-Clause
2023-09-14T16:39:54
2015-12-01T16:41:45
Python
UTF-8
Python
false
false
2,522
py
integrations.py
# (C) Datadog, Inc. 2023-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from __future__ import annotations from io import StringIO from typing import TYPE_CHECKING import click if TYPE_CHECKING: from ddev.cli.application import Application @click.command(short_help="Generate a markdown file of integrations in an Agent release") @click.option('--since', help="Initial Agent version", default='6.3.0') @click.option('--to', help="Final Agent version") @click.option('--write', '-w', is_flag=True, help="Write to file, if omitted contents will be printed to stdout") @click.option('--force', '-f', is_flag=True, default=False, help="Replace an existing file") @click.pass_obj def integrations(app: Application, since: str, to: str, write: bool, force: bool): """ Generates a markdown file containing the list of integrations shipped in a given Agent release. Agent version numbers are derived by inspecting tags on `integrations-core`, so running this tool might provide unexpected results if the repo is not up to date with the Agent release process. If neither `--since` nor `--to` are passed (the most common use case), the tool will generate the list for every Agent since version 6.3.0 (before that point we don't have enough information to build the log). """ from ddev.cli.release.agent.common import get_agent_tags, parse_agent_req_file agent_tags = get_agent_tags(app.repo, since, to) # get the list of integrations shipped with the agent from the requirements file req_file_name = app.repo.agent_release_requirements.name integrations_contents = StringIO() for tag in agent_tags: integrations_contents.write(f'## Datadog Agent version {tag}\n\n') # Requirements for current tag file_contents = app.repo.git.show_file(req_file_name, tag) for name, ver in parse_agent_req_file(file_contents).items(): integrations_contents.write(f'* {name}: {ver}\n') integrations_contents.write('\n') # save the changelog on disk if --write was passed if write: dest = app.repo.agent_integrations_file # don't overwrite an existing file if dest.exists() and not force: msg = "Output file {} already exists, run the command again with --force to overwrite" app.abort(msg.format(dest)) dest.write_text(integrations_contents.getvalue()) else: app.display(integrations_contents.getvalue())
2863b00b4aa384b43feaf07bf7fd631abf68329b
db12b990924703cd74748d8585cd9c11fafa6746
/h2o-py/tests/testdir_algos/modelselection/pyunit_PUBDEV_8785_8758_maxrSweep_fix_replacement_large.py
1f9d40969d6755c6c6d453d42b6eb90bbe8b7a63
[ "Apache-2.0" ]
permissive
h2oai/h2o-3
919019a8f297eec676011a9cfd2cc2d97891ce14
d817ab90c8c47f6787604a0b9639b66234158228
refs/heads/master
2023-08-17T18:50:17.732191
2023-08-17T16:44:42
2023-08-17T16:44:42
17,371,412
6,872
2,345
Apache-2.0
2023-09-14T18:05:40
2014-03-03T16:08:07
Jupyter Notebook
UTF-8
Python
false
false
3,329
py
pyunit_PUBDEV_8785_8758_maxrSweep_fix_replacement_large.py
import sys sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.model_selection import H2OModelSelectionEstimator def test_maxrsweep_replacement(): correct_pred_subsets = [["C78",'Intercept'], ["C78","C97",'Intercept'], ["C78","C97","C75",'Intercept'], ["C78","C97","C75","C76",'Intercept'], ["C78","C97","C75","C76","C88",'Intercept'], ["C78","C97","C75","C76","C88","C89",'Intercept'], ["C78","C97","C75","C76","C88","C89","C101",'Intercept'], ["C78","C97","C75","C76","C88","C89","C7","C86",'Intercept'], ["C78","C97","C75","C76","C88","C89","C7","C86","C101",'Intercept'], ["C78","C97","C75","C76","C88","C89","C7","C86","C101","C4",'Intercept']] train = h2o.import_file(pyunit_utils.locate("bigdata/laptop/model_selection/maxrglm200Cols50KRows.csv")) response="response" predictors = train.names predictors.remove(response) npred = 10 maxrsweep_model = H2OModelSelectionEstimator(mode="maxrsweep", max_predictor_number=npred, intercept=True, standardize=True) maxrsweep_model.train(x=predictors, y=response, training_frame=train) maxrsweep_best_predictors = maxrsweep_model.coef() maxrsweep_model_MM = H2OModelSelectionEstimator(mode="maxrsweep", max_predictor_number=npred, intercept=True, standardize=True, multinode_mode=True) maxrsweep_model_MM.train(x=predictors, y=response, training_frame=train) maxrsweep_best_predictors_MM = maxrsweep_model_MM.coef() maxr_model = H2OModelSelectionEstimator(mode="maxr", max_predictor_number=npred, intercept=True) maxr_model.train(x=predictors, y=response, training_frame=train) maxr_best_predictors = maxr_model.coef() for index in range(npred): correct_pred_subsets[index].sort() maxr_one_coef = list(maxr_best_predictors[index].keys()) maxr_one_coef.sort() maxrsweep_one_coef = list(maxrsweep_best_predictors[index].keys()) maxrsweep_one_coef.sort() maxrsweep_one_coef_MM = list(maxrsweep_best_predictors_MM[index].keys()) maxrsweep_one_coef_MM.sort() assert correct_pred_subsets[index]==maxr_one_coef, "Expected predictor subset: {0}, actual predictor subset from" \ " maxr: {1}. They are different".format(correct_pred_subsets[index], maxr_one_coef) assert correct_pred_subsets[index]==maxrsweep_one_coef, "Expected predictor subset: {0}, actual predictor subset from" \ " maxrsweep: {1}. They are different".format(correct_pred_subsets[index], maxrsweep_one_coef) assert correct_pred_subsets[index]==maxrsweep_one_coef_MM, "Expected predictor subset: {0}, actual predictor subset from" \ " maxrsweep with multinode_mode: {1}. They are " \ "different".format(correct_pred_subsets[index], maxrsweep_one_coef_MM) if __name__ == "__main__": pyunit_utils.standalone_test(test_maxrsweep_replacement) else: test_maxrsweep_replacement()
1a8a0888575abd56891ae662bfa9ac4d3180019b
5917ffcb780cfcfe4e2b87b11fca1f68f387b239
/plenum/test/pool_transactions/test_txn_pool_manager.py
827ac57f19bc0924cf7229b7201168c223b3a38a
[ "Apache-2.0" ]
permissive
hyperledger/indy-plenum
6ff9f705af80dfa28d4cb92743683f78bb937aa3
698b9500ad3a7a15993af72a1c35a406c5673262
refs/heads/main
2023-08-29T01:32:26.384729
2023-06-20T16:42:11
2023-06-20T16:42:11
51,585,028
171
420
Apache-2.0
2023-06-20T16:42:14
2016-02-12T12:03:16
Python
UTF-8
Python
false
false
2,938
py
test_txn_pool_manager.py
import pytest from plenum.common.config_helper import PNodeConfigHelper from plenum.test.test_node import TestNode from stp_core.loop.eventually import eventually from plenum.test.helper import sdk_send_random_and_check, assertExp from plenum.common.txn_util import get_type, get_payload_data from plenum.common.constants import TARGET_NYM, NODE, \ CLIENT_STACK_SUFFIX, DATA, ALIAS, SERVICES, VALIDATOR, TXN_PAYLOAD from plenum.test.pool_transactions.helper import demote_node nodeCount = 7 nodes_wth_bls = 0 def test_twice_demoted_node_dont_write_txns(txnPoolNodeSet, looper, sdk_wallet_stewards, sdk_pool_handle): request_count = 5 demoted_node = txnPoolNodeSet[2] alive_pool = list(txnPoolNodeSet) alive_pool.remove(demoted_node) demote_node(looper, sdk_wallet_stewards[2], sdk_pool_handle, demoted_node) demote_node(looper, sdk_wallet_stewards[2], sdk_pool_handle, demoted_node) demoted_nym = None for _, txn in txnPoolNodeSet[0].poolManager.ledger.getAllTxn(): txn_data = get_payload_data(txn) if txn_data[DATA][ALIAS] == demoted_node.name: demoted_nym = txn_data[TARGET_NYM] break assert demoted_nym # Every node demote `demoted_node` assert all(node.write_manager.get_node_data(demoted_nym)[SERVICES] == [] for node in alive_pool) sdk_send_random_and_check(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_stewards[0], request_count) looper.run( eventually( lambda: assertExp(txnPoolNodeSet[0].domainLedger.size - request_count == \ demoted_node.domainLedger.size))) def test_get_nym_by_name(txnPoolNodeSet, pool_node_txns): check_get_nym_by_name(txnPoolNodeSet, pool_node_txns) def test_get_nym_by_name_not_in_registry(txnPoolNodeSet, pool_node_txns): nodes_to_remove = [txnPoolNodeSet[4].name, txnPoolNodeSet[5].name] for node in txnPoolNodeSet: for node_to_remove in nodes_to_remove: del node.nodeReg[node_to_remove] del node.cliNodeReg[node_to_remove + CLIENT_STACK_SUFFIX] check_get_nym_by_name(txnPoolNodeSet, pool_node_txns) def test_get_nym_by_name_demoted(txnPoolNodeSet, pool_node_txns, looper, sdk_wallet_stewards, sdk_pool_handle): demote_node(looper, sdk_wallet_stewards[0], sdk_pool_handle, txnPoolNodeSet[0]) check_get_nym_by_name(txnPoolNodeSet, pool_node_txns) def check_get_nym_by_name(txnPoolNodeSet, pool_node_txns): for i in range(nodeCount): node = txnPoolNodeSet[i] pool_manager = node.poolManager node_name = node.name node_nym = pool_manager.get_nym_by_name(node_name) expected_data = get_payload_data(pool_node_txns[i])[TARGET_NYM] assert node_nym assert node_nym == expected_data
ad0601f29ad4e2f74f69d48b22c9a0d61e682dfe
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/contrib/python/plotly/py2/plotly/validators/layout/geo/lataxis/__init__.py
228d2eabea733a1c143f219d7a9e5e256851cc00
[ "Apache-2.0", "MIT" ]
permissive
catboost/catboost
854c1a1f439a96f1ae6b48e16644be20aa04dba2
f5042e35b945aded77b23470ead62d7eacefde92
refs/heads/master
2023-09-01T12:14:14.174108
2023-09-01T10:01:01
2023-09-01T10:22:12
97,556,265
8,012
1,425
Apache-2.0
2023-09-11T03:32:32
2017-07-18T05:29:04
Python
UTF-8
Python
false
false
3,037
py
__init__.py
import _plotly_utils.basevalidators class Tick0Validator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="tick0", parent_name="layout.geo.lataxis", **kwargs): super(Tick0Validator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class ShowgridValidator(_plotly_utils.basevalidators.BooleanValidator): def __init__( self, plotly_name="showgrid", parent_name="layout.geo.lataxis", **kwargs ): super(ShowgridValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class RangeValidator(_plotly_utils.basevalidators.InfoArrayValidator): def __init__(self, plotly_name="range", parent_name="layout.geo.lataxis", **kwargs): super(RangeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), items=kwargs.pop( "items", [ {"valType": "number", "editType": "plot"}, {"valType": "number", "editType": "plot"}, ], ), role=kwargs.pop("role", "info"), **kwargs ) import _plotly_utils.basevalidators class GridwidthValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="gridwidth", parent_name="layout.geo.lataxis", **kwargs ): super(GridwidthValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), min=kwargs.pop("min", 0), role=kwargs.pop("role", "style"), **kwargs ) import _plotly_utils.basevalidators class GridcolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="gridcolor", parent_name="layout.geo.lataxis", **kwargs ): super(GridcolorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "style"), **kwargs ) import _plotly_utils.basevalidators class DtickValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="dtick", parent_name="layout.geo.lataxis", **kwargs): super(DtickValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "info"), **kwargs )
2d0311751bd459523c32eafdf5de430c52e227df
9734c93c86c982b1ce046340bac9e53645b261b8
/tests/multi_process/base_process.py
009e8487f7597749e0d1d35e002a2eae958ec034
[ "Apache-2.0" ]
permissive
log2timeline/plaso
cd72dd407d6c5627506c14f58cb8f6a6926aa808
d6022f8cfebfddf2d08ab2d300a41b61f3349933
refs/heads/main
2023-09-02T08:43:48.241198
2023-08-19T07:28:12
2023-08-19T07:28:12
23,812,315
1,506
421
Apache-2.0
2023-09-04T08:24:53
2014-09-08T23:29:28
Python
UTF-8
Python
false
false
1,681
py
base_process.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the multi-processing base process.""" import unittest from plaso.engine import configurations from plaso.multi_process import base_process from tests import test_lib as shared_test_lib class TestProcess(base_process.MultiProcessBaseProcess): """Implementation of the multi-processing base process for testing.""" def _GetStatus(self): """Returns status information. Returns: dict[str, object]: status attributes, indexed by name. """ # TODO: implement. return {} def _Main(self): """The process main loop. This method is called when the process is ready to start. A sub class should override this method to do the necessary actions in the main loop. """ # TODO: implement. return def SignalAbort(self): """Signals the process to abort.""" # TODO: implement. return class MultiProcessBaseProcessTest(shared_test_lib.BaseTestCase): """Tests the multi-processing base process.""" # pylint: disable=protected-access def testInitialization(self): """Tests the initialization.""" configuration = configurations.ProcessingConfiguration() test_process = TestProcess(configuration, name='TestBase') self.assertIsNotNone(test_process) # TODO: add test for name property. # TODO: add test for _OnCriticalError. # TODO: add test for _SigSegvHandler. # TODO: add test for _SigTermHandler. # TODO: add test for _StartProcessStatusRPCServer. # TODO: add test for _StopProcessStatusRPCServer. # TODO: add test for _WaitForStatusNotRunning. # TODO: add test for run. if __name__ == '__main__': unittest.main()
f83e42972698c7ec73e796e0cf97999b56c0fcbb
445b3666585565b9a4a3ed82df0d80bfe859d988
/scripts/extract_embeddings.py
fec8fcbd426bca168534ec5176d663696f1be314
[ "Apache-2.0", "MIT" ]
permissive
dbiir/UER-py
11d669ee6eb94d648039d60e8f7fba91ebc42f77
3ce0127ba8630f978304ea98833eb39ef55fc506
refs/heads/master
2023-09-02T14:50:44.011889
2023-08-25T04:39:53
2023-08-25T04:39:53
180,572,200
2,865
535
Apache-2.0
2023-08-24T08:30:53
2019-04-10T12:00:20
Python
UTF-8
Python
false
false
2,185
py
extract_embeddings.py
""" This script provides an example to wrap UER-py for embedding extraction. """ import sys import os import argparse import torch uer_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.append(uer_dir) from uer.utils.vocab import Vocab if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--load_model_path", default=None, type=str, help="Path of the input model.") parser.add_argument("--vocab_path", default=None, type=str, help="Path of the vocabulary file.") parser.add_argument("--spm_model_path", default=None, type=str, help="Path of the sentence piece model.") parser.add_argument("--word_embedding_path", default=None, type=str, help="Path of the output word embedding.") args = parser.parse_args() if args.spm_model_path: try: import sentencepiece as spm except ImportError: raise ImportError("You need to install SentencePiece to use XLNetTokenizer: https://github.com/google/sentencepiece" "pip install sentencepiece") sp_model = spm.SentencePieceProcessor() sp_model.Load(args.spm_model_path) vocab = Vocab() vocab.i2w = {i: sp_model.IdToPiece(i) for i in range(sp_model.GetPieceSize())} else: vocab = Vocab() vocab.load(args.vocab_path) pretrained_model = torch.load(args.load_model_path) embedding = pretrained_model["embedding.word.embedding.weight"] with open(args.word_embedding_path, mode="w", encoding="utf-8") as f: head = str(list(embedding.size())[0]) + " " + str(list(embedding.size())[1]) + "\n" f.write(head) for i in range(len(vocab.i2w)): word = vocab.i2w[i] word_embedding = embedding[vocab.get(word), :] word_embedding = word_embedding.cpu().numpy().tolist() line = str(word) for j in range(len(word_embedding)): line = line + " " + str(word_embedding[j]) line += "\n" f.write(line)
f8363364438007e5eec67d30e7cae1ea571c1245
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/DQM/SiStripCommissioningDbClients/python/OfflineDbClient_cff.py
6e4f4a2e7bbe3fa9debc0cfcc0679b24945a96b2
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
Python
false
false
5,860
py
OfflineDbClient_cff.py
import FWCore.ParameterSet.Config as cms db_client = cms.EDAnalyzer("SiStripCommissioningOfflineDbClient", # general parameters FilePath = cms.untracked.string('/tmp'), RunNumber = cms.untracked.uint32(0), UseClientFile = cms.untracked.bool(False), UploadHwConfig = cms.untracked.bool(False), UploadAnalyses = cms.untracked.bool(False), DisableDevices = cms.untracked.bool(False), SaveClientFile = cms.untracked.bool(True), SummaryXmlFile = cms.untracked.FileInPath('DQM/SiStripCommissioningClients/data/summary.xml'), # individual parameters ApvTimingParameters = cms.PSet( SkipFecUpdate = cms.bool(False), # skip upload of APV PLL settings SkipFedUpdate = cms.bool(False), # skip upload of FED frame finding threshold TargetDelay = cms.int32(-1) # -1: latest tick (old default), otherwise target delay for all ticks' rising edge ), CalibrationParameters = cms.PSet( targetRiseTime = cms.double(50), targetDecayTime = cms.double(125), tuneSimultaneously = cms.bool(False) ), DaqScopeModeParameters = cms.PSet( HighThreshold = cms.double(5), LowThreshold = cms.double(2), DisableBadStrips = cms.bool(False), DeadStripMax = cms.double(10), NoisyStripMin = cms.double(10), KeepsStripsDisabled = cms.bool(False), SkipPedestalUpdate = cms.bool(False), SkipTickUpdate = cms.bool(False) ), FastFedCablingParameters = cms.PSet(), FedCablingParameters = cms.PSet(), FedTimingParameters = cms.PSet(), FineDelayParameters = cms.PSet( cosmic = cms.bool(True) ), LatencyParamameters = cms.PSet( OptimizePerPartition = cms.bool(False) ), NoiseParameters = cms.PSet(), OptoScanParameters = cms.PSet( TargetGain = cms.double(0.863), # target gain (0.863 ~ 690ADC for tickmark) SkipGainUpdate = cms.bool(False) # wether to keep the gain the same as already on the db ), PedestalsParameters = cms.PSet( DeadStripMax = cms.double(10), # number times the noise spread below mean noise NoisyStripMin = cms.double(10), # number times the noise spread above mean noise HighThreshold = cms.double(5), # analysis-wide high threshold for the fed zero suppression LowThreshold = cms.double(2), # analysis-wide low threshold for the fed zero suppression DisableBadStrips = cms.bool(False), # for experts! disables bad strips on the fed level AddBadStrips = cms.bool(False), #for experts! keep and add disabled bad strips. KeepStripsDisabled = cms.bool(False) # for experts! keep strips disabled as in the db's current state ), PedsOnlyParameters = cms.PSet(), ### Bad channel analysis PedsFullNoiseParameters = cms.PSet( #### selections used to define a bad strip MaxDriftResidualCut = cms.double(20), ### the strip baseline can drift during run .. if more then N ADC count, mark the strip as bad MinStripNoiseCut = cms.double(2), ### if a strip has a noise value less the N ADC, mark as low noisy i.e. bad MaxStripNoiseCut = cms.double(30), ### if a strip has a noise value larger than N ADC, mark strip has high noisy i.e. bad MaxStripNoiseSignificanceCut = cms.double(10), ## if a strip has a noise significance larger than N, mark it as bad AdProbabCut = cms.double(0.002699796063), ### this is 3 sigma quantile selection on the AndersonDarling p-value KsProbabCut = cms.double(0.002699796063), ### this is 3 sigma quantile selection on the Kolmogorov Smirnov p-value GenerateRandomHisto = cms.bool(False), ### random sampling of the gaussian fit or not while computing p-values JbProbabCut = cms.double(0.000000573303), ### this is 3 sigma quantile selection on the jacque-Bera p-value Chi2ProbabCut = cms.double(0.000000573303), ### this is 3 sigma quantile selection on the chi2 p-value (from a Gaussian fit) KurtosisCut = cms.double(2), ### max value of kurtosis to identify strips with long tails IntegralNsigma = cms.int32(5), ### this is expressed in terms of number of gaussian quantiles .. 5 means take the integral 5-sigma from the peak IntegralTailCut = cms.double(0.0005), ### selection on the N-sigma integral AshmanDistance = cms.double(2), ### to flag double peaked strips AmplitudeRatio = cms.double(0.85), ### to flag double peaked strips #### Zero suppression information HighThreshold = cms.double(5), ### analysis-wide high threshold for the fed zero suppression LowThreshold = cms.double(2), ### analysis-wide low threshold for the fed zero suppression #### Flags on bad strips DisableBadStrips = cms.bool(True), ### When the upload is performed, strips are masked in case they are flagged by the analysis KeepStripsDisabled = cms.bool(False), ### True: if a strip is already flagged bad in the db, it will be kept bad; False: if a strip was bad, now the analysis will tell us if it's bad or not UploadOnlyStripBadChannelBit = cms.bool(False), ### True: means that pedestal and noise values are not changed in the FED version --> use old values SkipEmptyStrips = cms.bool(True), ### In the analysis, if true strips with no data are not marked as bad but as dead --> could be mis-configured at the time of the run, not masked UploadPedsFullNoiseDBTable = cms.bool(False) ### Tell whether the PedsFullNoise DB table needs to be uploaded --> for the time being this can be done ONLY on the oracle test account. ), SamplingParameters = cms.PSet(), VpspScanParameters = cms.PSet(), )
01949bb4cd0084b2e5f3d9d554fe986ab45b0629
0e80605f998d065816a79f5b153f66e4769a1105
/tests/common.py
a9094347ddb43255ac079c20e76851d5722433ee
[ "MIT" ]
permissive
sergionr2/RacingRobot
1874da5fc78d5885647e7490a38d6f703f0f7f2f
6885ddb37407dff15845d29f641bc7c39279b216
refs/heads/master
2023-07-19T20:49:01.541721
2020-05-24T12:33:33
2020-05-24T12:33:33
95,389,808
237
99
MIT
2023-07-06T21:15:47
2017-06-25T22:44:19
Python
UTF-8
Python
false
false
350
py
common.py
from __future__ import print_function, division, absolute_import NUM_EPOCHS = 2 DATASET = 'datasets/test_dataset/' TEST_IMAGE_PATH = DATASET + '170.jpg' SEED = 0 BATCHSIZE = 4 def assertEq(left, right): assert left == right, "{} != {}".format(left, right) def assertNeq(left, right): assert left != right, "{} == {}".format(left, right)
16e50fcc3c35b7fdec1323b4e16e5d45f8c79909
c45f99d4fb86a54a81da796d6345d6572e7bc9c4
/bitmapist/__init__.py
8f943595c9c6b1de2f013cf93a04833bc844f1fc
[ "BSD-3-Clause" ]
permissive
Doist/bitmapist
df323f28b68667b1cedeb70b173c0f792db54605
0acd5580dcbe6d8841726c087a96f975cced2249
refs/heads/main
2023-07-05T16:26:58.696494
2023-05-05T00:19:26
2023-05-05T00:19:26
6,390,826
567
60
null
2023-05-05T00:16:49
2012-10-25T16:50:33
Python
UTF-8
Python
false
false
22,543
py
__init__.py
# -*- coding: utf-8 -*- """ bitmapist ~~~~~~~~~ Implements a powerful analytics library on top of Redis's support for bitmaps and bitmap operations. This library makes it possible to implement real-time, highly scalable analytics that can answer following questions: * Has user 123 been online today? This week? This month? This year? * Has user 123 performed action "X"? * How many users have been active have this month? This hour? * How many unique users have performed action "X" this week? * How many % of users that were active last week are still active? * How many % of users that were active last month are still active this month? This library is very easy to use and enables you to create your own reports easily. Using Redis bitmaps you can store events for millions of users in a very little amount of memory (megabytes). You should be careful about using huge ids (e.g. 2^32 or bigger) as this could require larger amounts of memory. If you want to read more about bitmaps please read following: * http://blog.getspool.com/2011/11/29/fast-easy-realtime-metrics-using-redis-bitmaps/ * http://redis.io/commands/setbit * http://en.wikipedia.org/wiki/Bit_array * http://www.slideshare.net/crashlytics/crashlytics-on-redis-analytics Requires Redis 2.6+ and newest version of redis-py. Examples ======== Setting things up:: from datetime import datetime, timedelta from bitmapist import mark_event, MonthEvents now = datetime.utcnow() last_month = datetime.utcnow() - timedelta(days=30) Mark user 123 as active:: mark_event('active', 123) Answer if user 123 has been active this month:: assert 123 in MonthEvents('active', now.year, now.month) How many users have been active this week?:: print len(WeekEvents('active', now.year, now.isocalendar()[1])) Perform bit operations. Which users that have been active last month are still active this month?:: active_2_months = BitOpAnd( MonthEvents('active', last_month.year, last_month.month), MonthEvents('active', now.year, now.month) ) Nest bit operations!:: active_2_months = BitOpAnd( BitOpAnd( MonthEvents('active', last_month.year, last_month.month), MonthEvents('active', now.year, now.month) ), MonthEvents('active', now.year, now.month) ) As something new tracking hourly is disabled (to save memory!) To enable it as default do:: import bitmapist bitmapist.TRACK_HOURLY = True Additionally you can supply an extra argument to mark_event to bypass the default value:: mark_event('active', 123, track_hourly=False) :copyright: 2012 by Doist Ltd. :developer: Amir Salihefendic ( http://amix.dk ) :license: BSD """ from builtins import range, bytes import threading import redis from typing import Union, Optional from redis.client import Redis, Pipeline import calendar from collections import defaultdict from datetime import datetime, date, timedelta local_thread = threading.local() # --- Systems related SYSTEMS = {"default": redis.StrictRedis(host="localhost", port=6379)} # Should hourly be tracked as default? # Note that this can have huge implications in amounts # of memory that Redis uses (especially with huge integers) TRACK_HOURLY = False # Should unique events be tracked as default? TRACK_UNIQUE = False def setup_redis(name: str, host: str, port: int, **kw) -> None: """ Setup a redis system. :param :name The name of the system :param :host The host of the redis installation :param :port The port of the redis installation :param :**kw Any additional keyword arguments will be passed to `redis.StrictRedis`. Example:: setup_redis('stats_redis', 'localhost', 6380) mark_event('active', 1, system='stats_redis') """ redis_client = kw.pop("redis_client", redis.StrictRedis) SYSTEMS[name] = redis_client(host=host, port=port, **kw) def get_redis(system: str = "default") -> Union[Redis, Pipeline]: """ Get a redis-py client instance with entry `system`. :param :system The name of the system, redis.StrictRedis or redis.Pipeline instance, extra systems can be setup via `setup_redis` """ if isinstance(system, redis.StrictRedis): return system else: return SYSTEMS[system] # --- Events marking and deleting def mark_event( event_name: str, uuid: int, system: str = "default", now: Optional[datetime] = None, track_hourly: Optional[bool] = None, track_unique: Optional[bool] = None, use_pipeline: bool = True, ) -> None: """ Marks an event for hours, days, weeks and months. :param :event_name The name of the event, could be "active" or "new_signups" :param :uuid An unique id, typically user id. The id should not be huge, read Redis documentation why (bitmaps) :param :system The Redis system to use (string, Redis instance, or Pipeline instance). :param :now Which date should be used as a reference point, default is `datetime.utcnow()` :param :track_hourly Should hourly stats be tracked, defaults to bitmapist.TRACK_HOURLY :param :track_unique Should unique stats be tracked, defaults to bitmapist.TRACK_UNIQUE :param :use_pipeline Boolean flag indicating if the command should use pipelines or not. You may want to avoid using pipeline within the command if you provide the pipeline object in `system` argument and want to manage the pipe execution yourself. Examples:: # Mark id 1 as active mark_event('active', 1) # Mark task completed for id 252 mark_event('tasks:completed', 252) """ _mark( event_name, uuid, system, now, track_hourly, track_unique, use_pipeline, value=1 ) def unmark_event( event_name: str, uuid: int, system: str = "default", now: Optional[datetime] = None, track_hourly: Optional[bool] = None, track_unique: Optional[bool] = None, use_pipeline: bool = True, ) -> None: _mark( event_name, uuid, system, now, track_hourly, track_unique, use_pipeline, value=0 ) def _mark( event_name, uuid, system="default", now=None, track_hourly=None, track_unique=None, use_pipeline=True, value=1, ): if track_hourly is None: track_hourly = TRACK_HOURLY if track_unique is None: track_unique = TRACK_UNIQUE if not now: now = datetime.utcnow() obj_classes = [MonthEvents, WeekEvents, DayEvents] if track_hourly: obj_classes.append(HourEvents) if track_unique: obj_classes.append(UniqueEvents) client = get_redis(system) if use_pipeline: client = client.pipeline() for obj_class in obj_classes: client.setbit(obj_class.from_date(event_name, now).redis_key, uuid, value) if use_pipeline: client.execute() def mark_unique(event_name: str, uuid: int, system: str = "default") -> None: """ Mark unique event Unique event (aka "user flag") is an event which doesn't depend on date. Can be used for storing user properties, A/B testing, extra filtering, etc. :param :event_name The name of the event, could be "active" or "new_signups" :param :uuid An unique id, typically user id. The id should not be huge, read Redis documentation why (bitmaps) :param :system The Redis system to use (string, Redis instance, or Pipeline Examples:: # Mark id 42 as premium mark_unique('premium', 42) """ _mark_unique(event_name, uuid, system, value=1) def unmark_unique(event_name: str, uuid: int, system: str = "default") -> None: """ Unmark unique event Unique event (aka "user flag") is an event which doesn't depend on date. Can be used for storing user properties, A/B testing, extra filtering, etc. :param :event_name The name of the event, could be "active" or "new_signups" :param :uuid An unique id, typically user id. The id should not be huge, read Redis documentation why (bitmaps) :param :system The Redis system to use (string, Redis instance, or Pipeline Examples:: # Mark id 42 as not premium anymore unmark_unique('premium', 42) """ _mark_unique(event_name, uuid, system, value=0) def _mark_unique(event_name, uuid, system="default", value=1): get_redis(system).setbit(UniqueEvents(event_name).redis_key, uuid, value) def get_event_names( system: str = "default", prefix: str = "", batch: int = 10000 ) -> list[str]: """ Return the list of all event names, with no particular order. Optional `prefix` value is used to filter only subset of keys """ cli = get_redis(system) expr = "trackist_%s*" % prefix ret = set() for result in cli.scan_iter(match=expr, count=batch): result = result.decode() chunks = result.split("_") event_name = "_".join(chunks[1:-1]) if not event_name.startswith("bitop_"): ret.add(event_name) return list(ret) def delete_all_events(system: str = "default") -> None: """ Delete all events from the database. """ cli = get_redis(system) keys = cli.keys("trackist_*") if keys: cli.delete(*keys) def delete_temporary_bitop_keys(system: str = "default") -> None: """ Delete all temporary keys that are used when using bit operations. """ cli = get_redis(system) keys = cli.keys("trackist_bitop_*") if keys: cli.delete(*keys) def delete_runtime_bitop_keys() -> None: """ Delete all BitOp keys that were created. """ bitop_keys = _bitop_keys() for system in bitop_keys: if len(bitop_keys[system]) > 0: cli = get_redis(system) cli.delete(*bitop_keys[system]) bitop_keys.clear() # --- Events class MixinIter: """ Extends with an obj.get_uuids() returning the iterator of uuids in a key (unpacks the key) """ def get_uuids(self): cli = get_redis(self.system) val = cli.get(self.redis_key) if val is None: return val = bytes(val) for char_num, char in enumerate(val): # shortcut if char == 0: continue # find set bits, generate smth like [1, 0, ...] bits = [(char >> i) & 1 for i in range(7, -1, -1)] # list of positions with ones set_bits = list(pos for pos, val in enumerate(bits) if val) # yield everything we need for bit in set_bits: yield char_num * 8 + bit def __iter__(self): for item in self.get_uuids(): yield item class MixinBitOperations: def __invert__(self): return BitOpNot(self) def __or__(self, other): return BitOpOr(self, other) def __and__(self, other): return BitOpAnd(self, other) def __xor__(self, other): return BitOpXor(self, other) class MixinEventsMisc: """ Extends with an obj.has_events_marked() that returns `True` if there are any events marked, otherwise `False` is returned. Extends also with a obj.delete() (useful for deleting temporary calculations). """ def has_events_marked(self): cli = get_redis(self.system) return bool(cli.exists(self.redis_key)) def delete(self): cli = get_redis(self.system) cli.delete(self.redis_key) def __eq__(self, other): other_key = getattr(other, "redis_key", None) if other_key is None: return NotImplemented return self.redis_key == other_key class MixinCounts: """ Extends with an obj.get_count() that uses BITCOUNT to count all the events. Supports also __len__ """ def get_count(self): cli = get_redis(self.system) count = cli.bitcount(self.redis_key) return count def __len__(self) -> int: return self.get_count() class MixinContains: """ Makes it possible to see if an uuid has been marked. Example:: user_active_today = 123 in DayEvents('active', 2012, 10, 23) """ def __contains__(self, uuid): cli = get_redis(self.system) if cli.getbit(self.redis_key, uuid): return True else: return False class UniqueEvents( MixinIter, MixinCounts, MixinContains, MixinEventsMisc, MixinBitOperations ): @classmethod def from_date(cls, event_name, dt=None, system="default"): return cls(event_name, system=system) def __init__(self, event_name, system="default"): self.event_name = event_name self.system = system self.redis_key = _prefix_key(event_name, "u") def next(self): return self def prev(self): return self class GenericPeriodEvents( MixinIter, MixinCounts, MixinContains, MixinEventsMisc, MixinBitOperations ): def next(self): """next object in a datetime line""" return self.delta(value=1) def prev(self): """prev object in a datetime line""" return self.delta(value=-1) class YearEvents(GenericPeriodEvents): """ Events for a year. Example:: YearEvents('active', 2012) """ @classmethod def from_date(cls, event_name, dt=None, system="default"): dt = dt or datetime.utcnow() return cls(event_name, dt.year, system=system) def __init__(self, event_name, year=None, system="default"): now = datetime.utcnow() self.event_name = event_name self.year = not_none(year, now.year) self.system = system months = [] for m in range(1, 13): months.append(MonthEvents(event_name, self.year, m, system)) or_op = BitOpOr(system, *months) self.redis_key = or_op.redis_key def delta(self, value): return self.__class__(self.event_name, self.year + value, self.system) def period_start(self): return datetime(self.year, 1, 1) def period_end(self): return datetime(self.year, 12, 31, 23, 59, 59, 999999) class MonthEvents(GenericPeriodEvents): """ Events for a month. Example:: MonthEvents('active', 2012, 10) """ @classmethod def from_date(cls, event_name, dt=None, system="default"): dt = dt or datetime.utcnow() return cls(event_name, dt.year, dt.month, system=system) def __init__(self, event_name, year=None, month=None, system="default"): now = datetime.utcnow() self.event_name = event_name self.year = not_none(year, now.year) self.month = not_none(month, now.month) self.system = system self.redis_key = _prefix_key(event_name, "%s-%s" % (self.year, self.month)) def delta(self, value): year, month = add_month(self.year, self.month, value) return self.__class__(self.event_name, year, month, self.system) def period_start(self): return datetime(self.year, self.month, 1) def period_end(self): _, day = calendar.monthrange(self.year, self.month) return datetime(self.year, self.month, day, 23, 59, 59, 999999) class WeekEvents(GenericPeriodEvents): """ Events for a week. Example:: WeekEvents('active', 2012, 48) """ @classmethod def from_date(cls, event_name, dt=None, system="default"): dt = dt or datetime.utcnow() dt_year, dt_week, _ = dt.isocalendar() return cls(event_name, dt_year, dt_week, system=system) def __init__(self, event_name, year=None, week=None, system="default"): now = datetime.utcnow() now_year, now_week, _ = now.isocalendar() self.event_name = event_name self.year = not_none(year, now_year) self.week = not_none(week, now_week) self.system = system self.redis_key = _prefix_key(event_name, "W%s-%s" % (self.year, self.week)) def delta(self, value): dt = iso_to_gregorian(self.year, self.week + value, 1) year, week, _ = dt.isocalendar() return self.__class__(self.event_name, year, week, self.system) def period_start(self): s = iso_to_gregorian(self.year, self.week, 1) # mon return datetime(s.year, s.month, s.day) def period_end(self): e = iso_to_gregorian(self.year, self.week, 7) # mon return datetime(e.year, e.month, e.day, 23, 59, 59, 999999) class DayEvents(GenericPeriodEvents): """ Events for a day. Example:: DayEvents('active', 2012, 10, 23) """ @classmethod def from_date(cls, event_name, dt=None, system="default"): dt = dt or datetime.utcnow() return cls(event_name, dt.year, dt.month, dt.day, system=system) def __init__(self, event_name, year=None, month=None, day=None, system="default"): now = datetime.utcnow() self.event_name = event_name self.year = not_none(year, now.year) self.month = not_none(month, now.month) self.day = not_none(day, now.day) self.system = system self.redis_key = _prefix_key( event_name, "%s-%s-%s" % (self.year, self.month, self.day) ) def delta(self, value): dt = date(self.year, self.month, self.day) + timedelta(days=value) return self.__class__(self.event_name, dt.year, dt.month, dt.day, self.system) def period_start(self): return datetime(self.year, self.month, self.day) def period_end(self): return datetime(self.year, self.month, self.day, 23, 59, 59, 999999) class HourEvents(GenericPeriodEvents): """ Events for a hour. Example:: HourEvents('active', 2012, 10, 23, 13) """ @classmethod def from_date(cls, event_name, dt=None, system="default"): dt = dt or datetime.utcnow() return cls(event_name, dt.year, dt.month, dt.day, dt.hour, system=system) def __init__( self, event_name, year=None, month=None, day=None, hour=None, system="default" ): now = datetime.utcnow() self.event_name = event_name self.year = not_none(year, now.year) self.month = not_none(month, now.month) self.day = not_none(day, now.day) self.hour = not_none(hour, now.hour) self.system = system self.redis_key = _prefix_key( event_name, "%s-%s-%s-%s" % (self.year, self.month, self.day, self.hour) ) def delta(self, value): dt = datetime(self.year, self.month, self.day, self.hour) + timedelta( hours=value ) return self.__class__( self.event_name, dt.year, dt.month, dt.day, dt.hour, self.system ) def period_start(self): return datetime(self.year, self.month, self.day, self.hour) def period_end(self): return datetime(self.year, self.month, self.day, self.hour, 59, 59, 999999) # --- Bit operations class BitOperation( MixinIter, MixinContains, MixinCounts, MixinEventsMisc, MixinBitOperations ): """ Base class for bit operations (AND, OR, XOR). Please note that each bit operation creates a new key prefixed with `trackist_bitop_`. These temporary keys can be deleted with `delete_temporary_bitop_keys` or `delete_runtime_bitop_keys`. You can even nest bit operations. Example:: active_2_months = BitOpAnd( MonthEvents('active', last_month.year, last_month.month), MonthEvents('active', now.year, now.month) ) active_2_months = BitOpAnd( BitOpAnd( MonthEvents('active', last_month.year, last_month.month), MonthEvents('active', now.year, now.month) ), MonthEvents('active', now.year, now.month) ) """ def __init__(self, op_name, system_or_event, *events): # Smartly resolve system_or_event, makes it possible to build a cleaner API if hasattr(system_or_event, "redis_key"): events = list(events) events.insert(0, system_or_event) system = self.system = "default" else: system = self.system = system_or_event event_redis_keys = [ev.redis_key for ev in events] self.redis_key = "trackist_bitop_%s_%s" % (op_name, "-".join(event_redis_keys)) _bitop_keys()[system].add(self.redis_key) cli = get_redis(system) cli.bitop(op_name, self.redis_key, *event_redis_keys) class BitOpAnd(BitOperation): def __init__(self, system_or_event, *events): BitOperation.__init__(self, "AND", system_or_event, *events) class BitOpOr(BitOperation): def __init__(self, system_or_event, *events): BitOperation.__init__(self, "OR", system_or_event, *events) class BitOpXor(BitOperation): def __init__(self, system_or_event, *events): BitOperation.__init__(self, "XOR", system_or_event, *events) class BitOpNot(BitOperation): def __init__(self, system_or_event, *events): BitOperation.__init__(self, "NOT", system_or_event, *events) # --- Private def _prefix_key(event_name: str, date: str): return "trackist_%s_%s" % (event_name, date) # --- Helper functions def add_month(year: int, month: int, delta: int) -> tuple[int, int]: """ Helper function which adds `delta` months to current `(year, month)` tuple and returns a new valid tuple `(year, month)` """ year, month = divmod(year * 12 + month + delta, 12) if month == 0: month = 12 year = year - 1 return year, month def not_none(*keys): """ Helper function returning first value which is not None """ for key in keys: if key is not None: return key def iso_year_start(iso_year): "The gregorian calendar date of the first day of the given ISO year" fourth_jan = date(iso_year, 1, 4) delta = timedelta(fourth_jan.isoweekday() - 1) return fourth_jan - delta def iso_to_gregorian(iso_year, iso_week, iso_day): "Gregorian calendar date for the given ISO year, week and day" year_start = iso_year_start(iso_year) return year_start + timedelta(days=iso_day - 1, weeks=iso_week - 1) def _bitop_keys(): """Hold created BitOp keys (per thread)""" v = getattr(local_thread, "bitop_keys", None) if v is None: v = defaultdict(set) setattr(local_thread, "bitop_keys", v) return v
99bb6227cba88b8e76554a960dbb633733e51062
a1fc902d48c476c342014f6399fc03a180d9ac04
/keras_csp/data_generators.py
37018b5d5a07c5460b58b70733c208eeb2f40d11
[]
no_license
liuwei16/CSP
574441fe34ee4741e2db118ff7fb20ab448839d0
9d5a0bcc7d44bfb27dbeef85ef92320cce5bae68
refs/heads/master
2022-12-04T02:19:02.147004
2021-10-07T05:04:39
2021-10-07T05:04:39
179,669,192
829
218
null
2022-11-22T01:39:09
2019-04-05T11:26:44
Jupyter Notebook
UTF-8
Python
false
false
11,664
py
data_generators.py
from __future__ import absolute_import from __future__ import division # import numpy as np # import cv2 import random from . import data_augment from .bbox_transform import * def calc_gt_center(C, img_data,r=2, down=4,scale='h',offset=True): def gaussian(kernel): sigma = ((kernel-1) * 0.5 - 1) * 0.3 + 0.8 s = 2*(sigma**2) dx = np.exp(-np.square(np.arange(kernel) - int(kernel / 2)) / s) return np.reshape(dx,(-1,1)) gts = np.copy(img_data['bboxes']) igs = np.copy(img_data['ignoreareas']) scale_map = np.zeros((int(C.size_train[0]/down), int(C.size_train[1]/down), 2)) if scale=='hw': scale_map = np.zeros((int(C.size_train[0] / down), int(C.size_train[1] / down), 3)) if offset: offset_map = np.zeros((int(C.size_train[0] / down), int(C.size_train[1] / down), 3)) seman_map = np.zeros((int(C.size_train[0]/down), int(C.size_train[1]/down), 3)) seman_map[:,:,1] = 1 if len(igs) > 0: igs = igs/down for ind in range(len(igs)): x1,y1,x2,y2 = int(igs[ind,0]), int(igs[ind,1]), int(np.ceil(igs[ind,2])), int(np.ceil(igs[ind,3])) seman_map[y1:y2, x1:x2,1] = 0 if len(gts)>0: gts = gts/down for ind in range(len(gts)): # x1, y1, x2, y2 = int(round(gts[ind, 0])), int(round(gts[ind, 1])), int(round(gts[ind, 2])), int(round(gts[ind, 3])) x1, y1, x2, y2 = int(np.ceil(gts[ind, 0])), int(np.ceil(gts[ind, 1])), int(gts[ind, 2]), int(gts[ind, 3]) c_x, c_y = int((gts[ind, 0] + gts[ind, 2]) / 2), int((gts[ind, 1] + gts[ind, 3]) / 2) dx = gaussian(x2-x1) dy = gaussian(y2-y1) gau_map = np.multiply(dy, np.transpose(dx)) seman_map[y1:y2, x1:x2,0] = np.maximum(seman_map[y1:y2, x1:x2,0], gau_map) seman_map[y1:y2, x1:x2,1] = 1 seman_map[c_y, c_x, 2] = 1 if scale == 'h': scale_map[c_y-r:c_y+r+1, c_x-r:c_x+r+1, 0] = np.log(gts[ind, 3] - gts[ind, 1]) scale_map[c_y-r:c_y+r+1, c_x-r:c_x+r+1, 1] = 1 elif scale=='w': scale_map[c_y-r:c_y+r+1, c_x-r:c_x+r+1, 0] = np.log(gts[ind, 2] - gts[ind, 0]) scale_map[c_y-r:c_y+r+1, c_x-r:c_x+r+1, 1] = 1 elif scale=='hw': scale_map[c_y-r:c_y+r+1, c_x-r:c_x+r+1, 0] = np.log(gts[ind, 3] - gts[ind, 1]) scale_map[c_y-r:c_y+r+1, c_x-r:c_x+r+1, 1] = np.log(gts[ind, 2] - gts[ind, 0]) scale_map[c_y-r:c_y+r+1, c_x-r:c_x+r+1, 2] = 1 if offset: offset_map[c_y, c_x, 0] = (gts[ind, 1] + gts[ind, 3]) / 2 - c_y - 0.5 offset_map[c_y, c_x, 1] = (gts[ind, 0] + gts[ind, 2]) / 2 - c_x - 0.5 offset_map[c_y, c_x, 2] = 1 if offset: return seman_map,scale_map,offset_map else: return seman_map, scale_map def calc_gt_top(C, img_data,r=2): def gaussian(kernel): sigma = ((kernel-1) * 0.5 - 1) * 0.3 + 0.8 s = 2*(sigma**2) dx = np.exp(-np.square(np.arange(kernel) - int(kernel / 2)) / s) return np.reshape(dx,(-1,1)) gts = np.copy(img_data['bboxes']) igs = np.copy(img_data['ignoreareas']) scale_map = np.zeros((int(C.size_train[0]/4), int(C.size_train[1]/4), 2)) seman_map = np.zeros((int(C.size_train[0]/4), int(C.size_train[1]/4), 3)) seman_map[:,:,1] = 1 if len(igs) > 0: igs = igs/4 for ind in range(len(igs)): x1,y1,x2,y2 = int(igs[ind,0]), int(igs[ind,1]), int(np.ceil(igs[ind,2])), int(np.ceil(igs[ind,3])) seman_map[y1:y2, x1:x2,1] = 0 if len(gts)>0: gts = gts/4 for ind in range(len(gts)): x1, y1, x2, y2 = int(round(gts[ind, 0])), int(round(gts[ind, 1])), int(round(gts[ind, 2])), int(round(gts[ind, 3])) w = x2-x1 c_x = int((gts[ind, 0] + gts[ind, 2]) / 2) dx = gaussian(w) dy = gaussian(w) gau_map = np.multiply(dy, np.transpose(dx)) ty = np.maximum(0,int(round(y1-w/2))) ot = ty-int(round(y1-w/2)) seman_map[ty:ty+w-ot, x1:x2,0] = np.maximum(seman_map[ty:ty+w-ot, x1:x2,0], gau_map[ot:,:]) seman_map[ty:ty+w-ot, x1:x2,1] = 1 seman_map[y1, c_x, 2] = 1 scale_map[y1-r:y1+r+1, c_x-r:c_x+r+1, 0] = np.log(gts[ind,3]-gts[ind,1]) scale_map[y1-r:y1+r+1, c_x-r:c_x+r+1, 1] = 1 return seman_map,scale_map def calc_gt_bottom(C, img_data, r=2): def gaussian(kernel): sigma = ((kernel-1) * 0.5 - 1) * 0.3 + 0.8 s = 2*(sigma**2) dx = np.exp(-np.square(np.arange(kernel) - int(kernel / 2)) / s) return np.reshape(dx,(-1,1)) gts = np.copy(img_data['bboxes']) igs = np.copy(img_data['ignoreareas']) scale_map = np.zeros((int(C.size_train[0]/4), int(C.size_train[1]/4), 2)) seman_map = np.zeros((int(C.size_train[0]/4), int(C.size_train[1]/4), 3)) seman_map[:,:,1] = 1 if len(igs) > 0: igs = igs/4 for ind in range(len(igs)): x1,y1,x2,y2 = int(igs[ind,0]), int(igs[ind,1]), int(np.ceil(igs[ind,2])), int(np.ceil(igs[ind,3])) seman_map[y1:y2, x1:x2,1] = 0 if len(gts)>0: gts = gts/4 for ind in range(len(gts)): x1, y1, x2, y2 = int(np.ceil(gts[ind, 0])), int(np.ceil(gts[ind, 1])), int(gts[ind, 2]), int(gts[ind, 3]) y2 = np.minimum(int(C.random_crop[0] / 4) - 1, y2) w = x2 - x1 c_x = int((gts[ind, 0] + gts[ind, 2]) / 2) dx = gaussian(w) dy = gaussian(w) gau_map = np.multiply(dy, np.transpose(dx)) by = np.minimum(int(C.random_crop[0]/4)-1, int(round(y2+w/2))) ob = int(round(y2+w/2))-by seman_map[by-w+ob:by, x1:x2, 0] = np.maximum(seman_map[by-w+ob:by, x1:x2, 0], gau_map[:w-ob, :]) seman_map[by-w+ob:by, x1:x2, 1] = 1 seman_map[y2, c_x, 2] = 1 scale_map[y2-r:y2+r+1, c_x-r:c_x+r+1, 0] = np.log(gts[ind,3]-gts[ind,1]) scale_map[y2-r:y2+r+1, c_x-r:c_x+r+1, 1] = 1 return seman_map,scale_map def get_data(ped_data, C, batchsize = 8): current_ped = 0 while True: x_img_batch, y_seman_batch, y_height_batch, y_offset_batch = [], [], [], [] if current_ped>len(ped_data)-batchsize: random.shuffle(ped_data) current_ped = 0 for img_data in ped_data[current_ped:current_ped + batchsize]: try: img_data, x_img = data_augment.augment(img_data, C) if C.offset: y_seman, y_height, y_offset = calc_gt_center(C, img_data, down=C.down, scale=C.scale, offset=True) else: if C.point == 'top': y_seman, y_height = calc_gt_top(C, img_data) elif C.point == 'bottom': y_seman, y_height = calc_gt_bottom(C, img_data) else: y_seman, y_height = calc_gt_center(C, img_data,down=C.down, scale=C.scale, offset=False) x_img = x_img.astype(np.float32) x_img[:, :, 0] -= C.img_channel_mean[0] x_img[:, :, 1] -= C.img_channel_mean[1] x_img[:, :, 2] -= C.img_channel_mean[2] x_img_batch.append(np.expand_dims(x_img, axis=0)) y_seman_batch.append(np.expand_dims(y_seman, axis=0)) y_height_batch.append(np.expand_dims(y_height, axis=0)) if C.offset: y_offset_batch.append(np.expand_dims(y_offset, axis=0)) except Exception as e: print ('get_batch_gt:',e) x_img_batch = np.concatenate(x_img_batch,axis=0) y_seman_batch = np.concatenate(y_seman_batch, axis=0) y_height_batch = np.concatenate(y_height_batch, axis=0) if C.offset: y_offset_batch = np.concatenate(y_offset_batch, axis=0) current_ped += batchsize if C.offset: yield np.copy(x_img_batch), [np.copy(y_seman_batch), np.copy(y_height_batch), np.copy(y_offset_batch)] else: yield np.copy(x_img_batch), [np.copy(y_seman_batch), np.copy(y_height_batch)] def get_data_hybrid(ped_data, emp_data, C, batchsize = 8,hyratio=0.5): current_ped = 0 current_emp = 0 batchsize_ped = int(batchsize * hyratio) batchsize_emp = batchsize - batchsize_ped while True: x_img_batch, y_seman_batch, y_height_batch, y_offset_batch = [], [], [], [] if current_ped>len(ped_data)-batchsize_ped: random.shuffle(ped_data) current_ped = 0 if current_emp>len(emp_data)-batchsize_emp: random.shuffle(emp_data) current_emp = 0 for img_data in ped_data[current_ped:current_ped + batchsize_ped]: try: img_data, x_img = data_augment.augment(img_data, C) if C.offset: y_seman, y_height, y_offset = calc_gt_center(C, img_data, down=C.down, scale=C.scale, offset=C.offset) else: if C.point == 'top': y_seman, y_height = calc_gt_top(C, img_data) elif C.point == 'bottom': y_seman, y_height = calc_gt_bottom(C, img_data) else: y_seman, y_height = calc_gt_center(C, img_data,down=C.down, scale=C.scale, offset=False) x_img = x_img.astype(np.float32) x_img[:, :, 0] -= C.img_channel_mean[0] x_img[:, :, 1] -= C.img_channel_mean[1] x_img[:, :, 2] -= C.img_channel_mean[2] x_img_batch.append(np.expand_dims(x_img, axis=0)) y_seman_batch.append(np.expand_dims(y_seman, axis=0)) y_height_batch.append(np.expand_dims(y_height, axis=0)) if C.offset: y_offset_batch.append(np.expand_dims(y_offset, axis=0)) except Exception as e: print ('get_batch_gt:',e) for img_data in emp_data[current_emp:current_emp + batchsize_emp]: try: img_data, x_img = data_augment.augment(img_data, C) if C.offset: y_seman, y_height, y_offset = calc_gt_center(C, img_data, down=C.down, scale=C.scale, offset=C.offset) else: if C.point == 'top': y_seman, y_height = calc_gt_top(C, img_data) elif C.point == 'bottom': y_seman, y_height = calc_gt_bottom(C, img_data) else: y_seman, y_height = calc_gt_center(C, img_data,down=C.down, scale=C.scale, offset=False) x_img = x_img.astype(np.float32) x_img[:, :, 0] -= C.img_channel_mean[0] x_img[:, :, 1] -= C.img_channel_mean[1] x_img[:, :, 2] -= C.img_channel_mean[2] x_img_batch.append(np.expand_dims(x_img, axis=0)) y_seman_batch.append(np.expand_dims(y_seman, axis=0)) y_height_batch.append(np.expand_dims(y_height, axis=0)) if C.offset: y_offset_batch.append(np.expand_dims(y_offset, axis=0)) except Exception as e: print ('get_batch_gt_emp:',e) x_img_batch = np.concatenate(x_img_batch,axis=0) y_seman_batch = np.concatenate(y_seman_batch, axis=0) y_height_batch = np.concatenate(y_height_batch, axis=0) if C.offset: y_offset_batch = np.concatenate(y_offset_batch, axis=0) current_ped += batchsize_ped current_emp += batchsize_emp if C.offset: yield np.copy(x_img_batch), [np.copy(y_seman_batch), np.copy(y_height_batch), np.copy(y_offset_batch)] else: yield np.copy(x_img_batch), [np.copy(y_seman_batch), np.copy(y_height_batch)] def get_data_wider(ped_data, C, batchsize = 8): current_ped = 0 while True: x_img_batch, y_seman_batch, y_height_batch, y_offset_batch = [], [], [], [] if current_ped>len(ped_data)-batchsize: random.shuffle(ped_data) current_ped = 0 for img_data in ped_data[current_ped:current_ped + batchsize]: try: img_data, x_img = data_augment.augment_wider(img_data, C) if C.offset: y_seman, y_height, y_offset = calc_gt_center(C, img_data, down=C.down, scale=C.scale, offset=True) else: y_seman, y_height = calc_gt_center(C, img_data,down=C.down, scale=C.scale, offset=False) x_img = x_img.astype(np.float32) x_img[:, :, 0] -= C.img_channel_mean[0] x_img[:, :, 1] -= C.img_channel_mean[1] x_img[:, :, 2] -= C.img_channel_mean[2] x_img_batch.append(np.expand_dims(x_img, axis=0)) y_seman_batch.append(np.expand_dims(y_seman, axis=0)) y_height_batch.append(np.expand_dims(y_height, axis=0)) if C.offset: y_offset_batch.append(np.expand_dims(y_offset, axis=0)) except Exception as e: print ('get_batch_gt:',e) x_img_batch = np.concatenate(x_img_batch,axis=0) y_seman_batch = np.concatenate(y_seman_batch, axis=0) y_height_batch = np.concatenate(y_height_batch, axis=0) if C.offset: y_offset_batch = np.concatenate(y_offset_batch, axis=0) current_ped += batchsize if C.offset: yield np.copy(x_img_batch), [np.copy(y_seman_batch), np.copy(y_height_batch), np.copy(y_offset_batch)] else: yield np.copy(x_img_batch), [np.copy(y_seman_batch), np.copy(y_height_batch)]
aaa0ef917667b7c133f0d2c3c6f87031f74e7751
3dc647cd07a7361ed401e40d2b7cce8c826c8f6c
/Lib/sqlite3/dbapi2.py
56fc0461e6c92249a9bbe6e9a775ac8b4a28bd59
[ "Python-2.0", "CC-BY-4.0", "MIT" ]
permissive
RustPython/RustPython
5ddce4a9848b9de8c041ffd2634f83c0105d3f39
b864e5da1f18897fc884180b7093df5aa170024f
refs/heads/main
2023-09-04T12:38:29.458699
2023-09-03T12:33:42
2023-09-03T12:33:42
135,201,145
15,815
1,302
MIT
2023-09-14T08:11:45
2018-05-28T19:27:01
Rust
UTF-8
Python
false
false
3,631
py
dbapi2.py
# pysqlite2/dbapi2.py: the DB-API 2.0 interface # # Copyright (C) 2004-2005 Gerhard Häring <gh@ghaering.de> # # This file is part of pysqlite. # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. import datetime import time import collections.abc from _sqlite3 import * from _sqlite3 import _deprecated_version _deprecated_names = frozenset({"version", "version_info"}) paramstyle = "qmark" apilevel = "2.0" Date = datetime.date Time = datetime.time Timestamp = datetime.datetime def DateFromTicks(ticks): return Date(*time.localtime(ticks)[:3]) def TimeFromTicks(ticks): return Time(*time.localtime(ticks)[3:6]) def TimestampFromTicks(ticks): return Timestamp(*time.localtime(ticks)[:6]) _deprecated_version_info = tuple(map(int, _deprecated_version.split("."))) sqlite_version_info = tuple([int(x) for x in sqlite_version.split(".")]) Binary = memoryview collections.abc.Sequence.register(Row) def register_adapters_and_converters(): from warnings import warn msg = ("The default {what} is deprecated as of Python 3.12; " "see the sqlite3 documentation for suggested replacement recipes") def adapt_date(val): warn(msg.format(what="date adapter"), DeprecationWarning, stacklevel=2) return val.isoformat() def adapt_datetime(val): warn(msg.format(what="datetime adapter"), DeprecationWarning, stacklevel=2) return val.isoformat(" ") def convert_date(val): warn(msg.format(what="date converter"), DeprecationWarning, stacklevel=2) return datetime.date(*map(int, val.split(b"-"))) def convert_timestamp(val): warn(msg.format(what="timestamp converter"), DeprecationWarning, stacklevel=2) datepart, timepart = val.split(b" ") year, month, day = map(int, datepart.split(b"-")) timepart_full = timepart.split(b".") hours, minutes, seconds = map(int, timepart_full[0].split(b":")) if len(timepart_full) == 2: microseconds = int('{:0<6.6}'.format(timepart_full[1].decode())) else: microseconds = 0 val = datetime.datetime(year, month, day, hours, minutes, seconds, microseconds) return val register_adapter(datetime.date, adapt_date) register_adapter(datetime.datetime, adapt_datetime) register_converter("date", convert_date) register_converter("timestamp", convert_timestamp) register_adapters_and_converters() # Clean up namespace del(register_adapters_and_converters) def __getattr__(name): if name in _deprecated_names: from warnings import warn warn(f"{name} is deprecated and will be removed in Python 3.14", DeprecationWarning, stacklevel=2) return globals()[f"_deprecated_{name}"] raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
21376acda89fba0869fb222c80e365bf52d62f6d
e7e536df0263ae2a7ac44ef30f19110f891213a9
/src/pretalx/common/language.py
9505490a25879f0fbe6121f651798150d84e522c
[ "Apache-2.0" ]
permissive
pretalx/pretalx
b3b3808266f4810dfc8445dc1ed33ba398e7a9c2
269dce90a6fb1ce0064008c40ce5dd4dad61e2e3
refs/heads/main
2023-09-05T11:09:23.538325
2023-09-04T19:57:47
2023-09-04T19:57:47
83,081,285
563
195
Apache-2.0
2023-09-13T19:12:28
2017-02-24T20:46:51
Python
UTF-8
Python
false
false
727
py
language.py
from django.conf import global_settings, settings from django.utils.translation import get_language LANGUAGE_CODES_MAPPING = { language.lower(): language for language in settings.LANGUAGES_INFORMATION } LANGUAGE_NAMES = dict(global_settings.LANGUAGES) LANGUAGE_NAMES.update( (language["code"], language["natural_name"]) for language in settings.LANGUAGES_INFORMATION.values() ) def get_language_information(lang: str): lang_key = LANGUAGE_CODES_MAPPING[lang.lower()] information = settings.LANGUAGES_INFORMATION[lang_key] information["code"] = lang return information def get_current_language_information(): language_code = get_language() return get_language_information(language_code)
54def90cc3ce33a1e2bf5d4b8d5dd5ba0b7a6dfa
ab4011a43c040f57919a5c4aabf413515f04262e
/aio_pika/patterns/__init__.py
1d83cdd4d37c7773f5183094f53bd1cb588aef5c
[ "Apache-2.0" ]
permissive
mosquito/aio-pika
e75a4994d947c1f72c3f587b484ca2c11d392eed
8cad8ee92b91e406c0bcb0c12450e84d79350433
refs/heads/master
2023-08-24T16:44:21.979691
2023-08-14T14:08:07
2023-08-14T14:08:07
69,458,400
1,078
230
Apache-2.0
2023-09-12T06:51:24
2016-09-28T11:54:18
Python
UTF-8
Python
false
false
233
py
__init__.py
from .master import JsonMaster, Master, NackMessage, RejectMessage, Worker from .rpc import RPC, JsonRPC __all__ = ( "Master", "NackMessage", "RejectMessage", "RPC", "Worker", "JsonMaster", "JsonRPC", )
98d40ab8370f54e95e070b6da37d475680819178
88d555a009f9075e59177fac70036892f397b439
/basenji/archive/seqnn_util.py
ea1dd94e3f35456cafcce7986857d858d908cf80
[ "Apache-2.0" ]
permissive
calico/basenji
f9f406971d355dda81821dcf274696a7d27e332d
615b9eec8a591783b16d959029ddad08edae853d
refs/heads/master
2023-09-04T11:14:15.620786
2023-07-27T00:05:13
2023-07-27T00:05:13
96,346,574
326
143
Apache-2.0
2023-08-16T00:36:32
2017-07-05T17:54:18
Python
UTF-8
Python
false
false
41,308
py
seqnn_util.py
""" General utility code for test-time interraction with a SeqNN model. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import pdb import sys import numpy as np import tensorflow as tf from basenji.dna_io import hot1_augment from basenji import accuracy class SeqNNModel(object): def build_grads(self, layers=[0], center=False): ''' Build gradient ops for predictions summed across the sequence for each target with respect to some set of layers. In layers: Optional layer subset list ''' self.grad_layers = layers self.grad_ops = [] ci = self.preds_length // 2 for ti in range(self.hp.num_targets): if center: grad_ti_op = tf.gradients(self.preds_train[:,ci:ci+2,ti], [self.layer_reprs[li] for li in self.grad_layers]) else: grad_ti_op = tf.gradients(self.preds_train[:,:,ti], [self.layer_reprs[li] for li in self.grad_layers]) self.grad_ops.append(grad_ti_op) def build_grads_genes(self, gene_seqs, layers=[0]): ''' Build gradient ops for TSS position-specific predictions for each target with respect to some set of layers. In gene_seqs: GeneSeq list, from which to extract TSS positions layers: Layer subset list. ''' # save layer indexes self.grad_layers = layers # initialize ops self.grad_pos_ops = [] # determine TSS positions tss_pos = set() for gene_seq in gene_seqs: for tss in gene_seq.tss_list: tss_pos.add(tss.seq_bin(width=self.hp.target_pool, pred_buffer=self.hp.batch_buffer)) # for each position for pi in range(self.preds_length): self.grad_pos_ops.append([]) # if it's a TSS position if pi in tss_pos: # build position-specific, target-specific gradient ops for ti in range(self.hp.num_targets): grad_piti_op = tf.gradients(self.preds_eval[:,pi,ti], [self.layer_reprs[li] for li in self.grad_layers]) self.grad_pos_ops[-1].append(grad_piti_op) def gradients(self, sess, batcher, rc=False, shifts=[0], mc_n=0, return_all=False): """ Compute predictions on a test set. In sess: TensorFlow session batcher: Batcher class with sequence(s) rc: Average predictions from the forward and reverse complement sequences. shifts: mc_n: return_all: Return all ensemble predictions. Out layer_grads: [S (sequences) x T (targets) x P (seq position) x U (Units layer i) array] * (L layers) layer_reprs: [S (sequences) x P (seq position) x U (Units layer i) array] * (L layers) preds: """ ####################################################################### # determine ensemble iteration parameters ensemble_fwdrc = [] ensemble_shifts = [] for shift in shifts: ensemble_fwdrc.append(True) ensemble_shifts.append(shift) if rc: ensemble_fwdrc.append(False) ensemble_shifts.append(shift) if mc_n > 0: # setup feed dict fd = self.set_mode('test_mc') else: # setup feed dict fd = self.set_mode('test') # co-opt the variable to represent # iterations per fwdrc/shift. mc_n = 1 # total ensemble predictions all_n = mc_n * len(ensemble_fwdrc) ####################################################################### # initialize data structures # initialize gradients # (I need a list for layers because the sizes are different within) # (Targets up front, because I need to run their ops one by one) layer_reprs = [] layer_grads = [] layer_reprs_all = [] layer_grads_all = [] for lii in range(len(self.grad_layers)): li = self.grad_layers[lii] layer_seq_len = self.layer_reprs[li].shape[1].value layer_units = self.layer_reprs[li].shape[2].value lr = np.zeros((batcher.num_seqs, layer_seq_len, layer_units), dtype='float32') layer_reprs.append(lr) lg = np.zeros((self.hp.num_targets, batcher.num_seqs, layer_seq_len, layer_units), dtype='float32') layer_grads.append(lg) if return_all: lra = np.zeros((batcher.num_seqs, layer_seq_len, layer_units, all_n), dtype='float32') layer_reprs_all.append(lra) lgr = np.zeros((self.hp.num_targets, batcher.num_seqs, layer_seq_len, layer_units, all_n), dtype='float32') layer_grads_all.append(lgr) # initialize predictions preds = np.zeros((batcher.num_seqs, self.preds_length, self.hp.num_targets), dtype='float32') if return_all: preds_all = np.zeros((batcher.num_seqs, self.preds_length, self.hp.num_targets, all_n), dtype='float32') ####################################################################### # compute # sequence index si = 0 # get first batch Xb, _, _, Nb = batcher.next() while Xb is not None: # ensemble predict preds_batch, layer_reprs_batch, layer_grads_batch = self._gradients_ensemble( sess, fd, Xb, ensemble_fwdrc, ensemble_shifts, mc_n, return_all=return_all) # unpack if return_all: preds_batch, preds_batch_all = preds_batch layer_reprs_batch, layer_reprs_batch_all = layer_reprs_batch layer_grads_batch, layer_grads_batch_all = layer_grads_batch # accumulate predictions preds[si:si+Nb,:,:] = preds_batch[:Nb,:,:] if return_all: preds_all[si:si+Nb,:,:,:] = preds_batch_all[:Nb,:,:,:] # accumulate representations for lii in range(len(self.grad_layers)): layer_reprs[lii][si:si+Nb] = layer_reprs_batch[lii][:Nb] if return_all: layer_reprs_all[lii][si:si+Nb] = layer_reprs_batch_all[lii][:Nb] # accumulate gradients for lii in range(len(self.grad_layers)): for ti in range(self.hp.num_targets): layer_grads[lii][ti,si:si+Nb,:,:] = layer_grads_batch[lii][ti,:Nb,:,:] if return_all: layer_grads_all[lii][ti,si:si+Nb,:,:,:] = layer_grads_batch_all[lii][ti,:Nb,:,:,:] # update sequence index si += Nb # next batch Xb, _, _, Nb = batcher.next() # reset training batcher batcher.reset() ####################################################################### # modify and return # move sequences to front for lii in range(len(self.grad_layers)): layer_grads[lii] = np.transpose(layer_grads[lii], [1,0,2,3]) if return_all: layer_grads_all[lii] = np.transpose(layer_grads_all[lii], [1,0,2,3,4]) if return_all: return layer_grads, layer_reprs, preds, layer_grads_all, layer_reprs_all, preds_all else: return layer_grads, layer_reprs, preds def _gradients_ensemble(self, sess, fd, Xb, ensemble_fwdrc, ensemble_shifts, mc_n, return_var=False, return_all=False): """ Compute gradients over an ensemble of input augmentations. In sess: TensorFlow session fd: feed dict Xb: input data ensemble_fwdrc: ensemble_shifts: mc_n: return_var: return_all: Return all ensemble predictions. Out preds: layer_reprs: layer_grads """ # initialize batch predictions preds = np.zeros((Xb.shape[0], self.preds_length, self.hp.num_targets), dtype='float32') # initialize layer representations and gradients layer_reprs = [] layer_grads = [] for lii in range(len(self.grad_layers)): li = self.grad_layers[lii] layer_seq_len = self.layer_reprs[li].shape[1].value layer_units = self.layer_reprs[li].shape[2].value lr = np.zeros((Xb.shape[0], layer_seq_len, layer_units), dtype='float16') layer_reprs.append(lr) lg = np.zeros((self.hp.num_targets, Xb.shape[0], layer_seq_len, layer_units), dtype='float32') layer_grads.append(lg) # initialize variance if return_var: preds_var = np.zeros(preds.shape, dtype='float32') layer_reprs_var = [] layer_grads_var = [] for lii in range(len(self.grad_layers)): layer_reprs_var.append(np.zeros(layer_reprs.shape, dtype='float32')) layer_grads_var.append(np.zeros(layer_grads.shape, dtype='float32')) else: preds_var = None layer_grads_var = [None]*len(self.grad_layers) # initialize all-saving arrays if return_all: all_n = mc_n * len(ensemble_fwdrc) preds_all = np.zeros((Xb.shape[0], self.preds_length, self.hp.num_targets, all_n), dtype='float32') layer_reprs_all = [] layer_grads_all = [] for lii in range(len(self.grad_layers)): ls = tuple(list(layer_reprs[lii].shape) + [all_n]) layer_reprs_all.append(np.zeros(ls, dtype='float32')) ls = tuple(list(layer_grads[lii].shape) + [all_n]) layer_grads_all.append(np.zeros(ls, dtype='float32')) else: preds_all = None layer_grads_all = [None]*len(self.grad_layers) running_i = 0 for ei in range(len(ensemble_fwdrc)): # construct sequence Xb_ensemble = hot1_augment(Xb, ensemble_fwdrc[ei], ensemble_shifts[ei]) # update feed dict fd[self.inputs_ph] = Xb_ensemble # for each monte carlo (or non-mc single) iteration for mi in range(mc_n): # print('ei=%d, mi=%d, fwdrc=%d, shifts=%d' % \ # (ei, mi, ensemble_fwdrc[ei], ensemble_shifts[ei]), # flush=True) ################################################## # prediction # predict preds_ei, layer_reprs_ei = sess.run([self.preds_train, self.layer_reprs], feed_dict=fd) # reverse if ensemble_fwdrc[ei] is False: preds_ei = preds_ei[:,::-1,:] # save previous mean preds1 = preds # update mean preds = self.running_mean(preds1, preds_ei, running_i+1) # update variance sum if return_var: preds_var = self.running_varsum(preds_var, preds_ei, preds1, preds) # save iteration if return_all: preds_all[:,:,:,running_i] = preds_ei[:,:,:] ################################################## # representations for lii in range(len(self.grad_layers)): li = self.grad_layers[lii] # reverse if ensemble_fwdrc[ei] is False: layer_reprs_ei[li] = layer_reprs_ei[li][:,::-1,:] # save previous mean layer_reprs_lii1 = layer_reprs[lii] # update mean layer_reprs[lii] = self.running_mean(layer_reprs_lii1, layer_reprs_ei[li], running_i+1) # update variance sum if return_var: layer_reprs_var[lii] = self.running_varsum(layer_reprs_var[lii], layer_reprs_ei[li], layer_reprs_lii1, layer_reprs[lii]) # save iteration if return_all: layer_reprs_all[lii][:,:,:,running_i] = layer_reprs_ei[li] ################################################## # gradients # compute gradients for each target individually for ti in range(self.hp.num_targets): # compute gradients layer_grads_ti_ei = sess.run(self.grad_ops[ti], feed_dict=fd) for lii in range(len(self.grad_layers)): # reverse if ensemble_fwdrc[ei] is False: layer_grads_ti_ei[lii] = layer_grads_ti_ei[lii][:,::-1,:] # save predious mean layer_grads_lii_ti1 = layer_grads[lii][ti] # update mean layer_grads[lii][ti] = self.running_mean(layer_grads_lii_ti1, layer_grads_ti_ei[lii], running_i+1) # update variance sum if return_var: layer_grads_var[lii][ti] = self.running_varsum(layer_grads_var[lii][ti], layer_grads_ti_ei[lii], layer_grads_lii_ti1, layer_grads[lii][ti]) # save iteration if return_all: layer_grads_all[lii][ti,:,:,:,running_i] = layer_grads_ti_ei[lii] # update running index running_i += 1 if return_var: return (preds, preds_var), (layer_reprs, layer_reprs_var), (layer_grads, layer_grads_var) elif return_all: return (preds, preds_all), (layer_reprs, layer_reprs_all), (layer_grads, layer_grads_all) else: return preds, layer_reprs, layer_grads def gradients_genes(self, sess, batcher, gene_seqs): ''' Compute predictions on a test set. In sess: TensorFlow session batcher: Batcher class with sequence(s) gene_seqs: List of GeneSeq instances specifying gene positions in sequences. Out layer_grads: [G (TSSs) x T (targets) x P (seq position) x U (Units layer i) array] * (L layers) layer_reprs: [S (sequences) x P (seq position) x U (Units layer i) array] * (L layers) Notes -Reverse complements aren't implemented yet. They're trickier here, because I'd need to build more gradient ops to match the flipped positions. ''' # count TSSs tss_num = 0 for gene_seq in gene_seqs: tss_num += len(gene_seq.tss_list) # initialize gradients and representations # (I need a list for layers because the sizes are different within) # (TSSxTargets up front, because I need to run their ops one by one) layer_grads = [] layer_reprs = [] for lii in range(len(self.grad_layers)): li = self.grad_layers[lii] layer_seq_len = self.layer_reprs[li].shape[1].value layer_units = self.layer_reprs[li].shape[2].value # gradients lg = np.zeros((tss_num, self.hp.num_targets, layer_seq_len, layer_units), dtype='float32') layer_grads.append(lg) # representations lr = np.zeros((batcher.num_seqs, layer_seq_len, layer_units), dtype='float32') layer_reprs.append(lr) # setup feed dict for dropout fd = self.set_mode('test') # TSS index tss_i = 0 # sequence index si = 0 # get first batch Xb, _, _, Nb = batcher.next() while Xb is not None: # update feed dict fd[self.inputs_ph] = Xb # predict reprs_batch, _ = sess.run([self.layer_reprs, self.preds_train], feed_dict=fd) # save representations for lii in range(len(self.grad_layers)): li = self.grad_layers[lii] layer_reprs[lii][si:si+Nb] = reprs_batch[li][:Nb] # compute gradients for each TSS position individually for bi in range(Nb): for tss in gene_seqs[si+bi].tss_list: # get TSS prediction bin position pi = tss.seq_bin(width=self.hp.target_pool, pred_buffer=self.hp.batch_buffer) for ti in range(self.hp.num_targets): # compute gradients over all positions grads_batch = sess.run(self.grad_pos_ops[pi][ti], feed_dict=fd) # accumulate gradients for lii in range(len(self.grad_layers)): layer_grads[lii][tss_i,ti,:,:] = grads_batch[lii][bi] # update TSS index tss_i += 1 # update sequence index si += Nb # next batch Xb, _, _, Nb = batcher.next() # reset training batcher batcher.reset() return layer_grads, layer_reprs def hidden(self, sess, batcher, layers=None, test_batches=None): """ Compute hidden representations for a test set. In sess: TensorFlow session batcher: Batcher class with sequences. layers: Layer indexes to return representations. test_batches: Number of test batches to use. Out preds: S (sequences) x L (unbuffered length) x T (targets) array """ if layers is None: layers = list(range(self.hp.cnn_layers)) # initialize layer representation data structure layer_reprs = [] for li in range(1 + np.max(layers)): layer_reprs.append([]) preds = [] # setup feed dict fd = self.set_mode('test') # get first batch Xb, _, _, Nb = batcher.next() batch_num = 0 while Xb is not None and (test_batches is None or batch_num < test_batches): # update feed dict fd[self.inputs_ph] = Xb # compute predictions layer_reprs_batch, preds_batch = sess.run( [self.layer_reprs, self.preds_train], feed_dict=fd) # accumulate representationsmakes the number of members for self smaller and also for li in layers: # squeeze (conv_2d-expanded) second dimension if layer_reprs_batch[li].shape[1] == 1: layer_reprs_batch[li] = layer_reprs_batch[li].squeeze(axis=1) # append layer_reprs[li].append(layer_reprs_batch[li][:Nb].astype('float16')) # accumualte predictions preds.append(preds_batch[:Nb]) # next batch Xb, _, _, Nb = batcher.next() batch_num += 1 # reset batcher batcher.reset() # accumulate representations for li in layers: layer_reprs[li] = np.vstack(layer_reprs[li]) preds = np.vstack(preds) return layer_reprs, preds def _predict_ensemble(self, sess, fd, Xb, ensemble_fwdrc, ensemble_shifts, mc_n, ds_indexes=None, target_indexes=None, return_var=False, return_all=False, embed_penultimate=False): # determine predictions length preds_length = self.preds_length if ds_indexes is not None: preds_length = len(ds_indexes) # determine num targets if embed_penultimate: num_targets = self.hp.cnn_params[-1].filters else: num_targets = self.hp.sum_targets if target_indexes is not None: num_targets = len(target_indexes) # initialize batch predictions preds_batch = np.zeros( (Xb.shape[0], preds_length, num_targets), dtype='float32') if return_var: preds_batch_var = np.zeros(preds_batch.shape, dtype='float32') else: preds_batch_var = None if return_all: all_n = mc_n * len(ensemble_fwdrc) preds_all = np.zeros( (Xb.shape[0], preds_length, num_targets, all_n), dtype='float32') else: preds_all = None running_i = 0 for ei in range(len(ensemble_fwdrc)): # construct sequence Xb_ensemble = hot1_augment(Xb, ensemble_fwdrc[ei], ensemble_shifts[ei]) # update feed dict fd[self.inputs_ph] = Xb_ensemble # for each monte carlo (or non-mc single) iteration for mi in range(mc_n): # print('ei=%d, mi=%d, fwdrc=%d, shifts=%d' % (ei, mi, ensemble_fwdrc[ei], ensemble_shifts[ei]), flush=True) # predict preds_ei = sess.run(self.preds_eval, feed_dict=fd) # reverse if ensemble_fwdrc[ei] is False: preds_ei = preds_ei[:, ::-1, :] # down-sample if ds_indexes is not None: preds_ei = preds_ei[:, ds_indexes, :] if target_indexes is not None: preds_ei = preds_ei[:, :, target_indexes] # save previous mean preds_batch1 = preds_batch # update mean preds_batch = self.running_mean(preds_batch1, preds_ei, running_i + 1) # update variance sum if return_var: preds_batch_var = self.running_varsum(preds_batch_var, preds_ei, preds_batch1, preds_batch) # save iteration if return_all: preds_all[:, :, :, running_i] = preds_ei[:, :, :] # update running index running_i += 1 return preds_batch, preds_batch_var, preds_all def predict_h5_manual(self, sess, batcher, rc=False, shifts=[0], mc_n=0, target_indexes=None, return_var=False, return_all=False, down_sample=1, embed_penultimate=False, test_batches=None, dtype='float32'): """ Compute predictions on a test set. In sess: TensorFlow session batcher: Batcher class with sequences. rc: Average predictions from the forward and reverse complement sequences. shifts: Average predictions from sequence shifts left/right. mc_n: Monte Carlo iterations per rc/shift. target_indexes: Optional target subset list return_var: Return variance estimates down_sample: Int specifying to consider uniformly spaced sampled positions embed_penultimate: Predict the embed_penultimate layer. test_batches Number of test batches to use. dtype: Float resolution to return. Out preds: S (sequences) x L (unbuffered length) x T (targets) array """ # uniformly sample indexes ds_indexes = None preds_length = self.preds_length if down_sample != 1: ds_indexes = np.arange(0, self.preds_length, down_sample) preds_length = len(ds_indexes) # initialize prediction arrays if embed_penultimate: num_targets = self.hp.cnn_params[-1].filters else: num_targets = self.hp.sum_targets if target_indexes is not None: num_targets = len(target_indexes) # determine ensemble iteration parameters ensemble_fwdrc = [] ensemble_shifts = [] for shift in shifts: ensemble_fwdrc.append(True) ensemble_shifts.append(shift) if rc: ensemble_fwdrc.append(False) ensemble_shifts.append(shift) if mc_n > 0: # setup feed dict fd = self.set_mode('test_mc') else: # setup feed dict fd = self.set_mode('test') # co-opt the variable to represent # iterations per fwdrc/shift. mc_n = 1 # total ensemble predictions all_n = mc_n * len(ensemble_fwdrc) # initialize prediction data structures if test_batches is None: num_seqs = batcher.remaining() else: num_seqs = min(batcher.remaining(), self.hp.batch_size*test_batches) preds = np.zeros( (num_seqs, preds_length, num_targets), dtype=dtype) if return_var: if all_n == 1: print( 'Cannot return prediction variance. Add rc, shifts, or mc.', file=sys.stderr) exit(1) preds_var = np.zeros( (num_seqs, preds_length, num_targets), dtype=dtype) if return_all: preds_all = np.zeros( (num_seqs, preds_length, num_targets, all_n), dtype=dtype) # indexes si = 0 batch_num = 0 # while we want more batches while test_batches is None or batch_num < test_batches: # get batch Xb, _, _, Nb = batcher.next() # verify fidelity if Xb is None: break else: # make ensemble predictions preds_batch, preds_batch_var, preds_batch_all = self._predict_ensemble( sess, fd, Xb, ensemble_fwdrc, ensemble_shifts, mc_n, ds_indexes, target_indexes, return_var, return_all, embed_penultimate) # accumulate predictions preds[si:si + Nb, :, :] = preds_batch[:Nb, :, :] if return_var: preds_var[si:si + Nb, :, :] = preds_batch_var[:Nb, :, :] / (all_n - 1) if return_all: preds_all[si:si + Nb, :, :, :] = preds_batch_all[:Nb, :, :, :] # update sequence index si += Nb # next batch batch_num += 1 if return_var: if return_all: return preds, preds_var, preds_all else: return preds, preds_var else: return preds def predict_h5(self, sess, batcher, test_batches=None, return_var=False, return_all=False): """ Compute preidctions on an HDF5 test set. Args: sess: TensorFlow session batcher: Batcher class with sequences. test_batches: Number of test batches to use. return_var: Return variance estimates return_all: Retyrn all predictions. Returns: preds: S (sequences) x L (unbuffered length) x T (targets) array """ fd = self.set_mode('test') # initialize prediction data structures preds = [] if return_var: preds_var = [] if return_all: preds_all = [] # count batches batch_num = 0 # while we want more batches while test_batches is None or batch_num < test_batches: # get batch Xb, _, _, Nb = batcher.next() # verify fidelity if Xb is None: break else: # update feed dict fd[self.inputs_ph] = Xb # make predictions if return_var or return_all: preds_batch, preds_ensemble_batch = sess.run([self.preds_eval, self.preds_ensemble], feed_dict=fd) # move ensemble to back preds_ensemble_batch = np.moveaxis(preds_ensemble_batch, 0, -1) else: preds_batch = sess.run(self.preds_eval, feed_dict=fd) # accumulate predictions and targets preds.append(preds_batch[:Nb]) if return_var: preds_var_batch = np.var(preds_ensemble_batch, axis=-1) preds_var.append(preds_var_batch[:Nb]) if return_all: preds_all.append(preds_ensemble_batch[:Nb]) # next batch batch_num += 1 # construct arrays preds = np.concatenate(preds, axis=0) if return_var: preds_var = np.concatenate(preds_var, axis=0) if return_all: preds_all = np.concatenate(preds_all, axis=0) if return_var: if return_all: return preds, preds_var, preds_all else: return preds, preds_var else: return preds def predict_tfr(self, sess, test_batches=None, sample=1., return_var=False, return_all=False): """ Compute preidctions on a TFRecord test set. Args: sess: TensorFlow session test_batches: Number of test batches to use. sample: Down sample positions uniformly. return_var: Return variance estimates return_all: Retyrn all predictions. Returns: preds: S (sequences) x L (unbuffered length) x T (targets) array """ fd = self.set_mode('test') # down sample if sample != 1: assert(0 < sample < 1) sample_pos_len = int(sample*self.preds_length) sample_pos = np.linspace(0, self.preds_length-1, sample_pos_len, dtype='int') # initialize prediction data structures preds = [] preds_var = [] preds_all = [] # sequence index data_available = True batch_num = 0 while data_available and (test_batches is None or batch_num < test_batches): try: # make predictions if return_var or return_all: preds_batch, preds_ensemble_batch = sess.run([self.preds_eval, self.preds_ensemble], feed_dict=fd) # move ensemble to back preds_ensemble_batch = np.moveaxis(preds_ensemble_batch, 0, -1) else: preds_batch = sess.run(self.preds_eval, feed_dict=fd) # down sample if sample != 1: preds_batch = preds_batch[:,sample_pos,:] if return_var or return_all: preds_ensemble_batch = preds_ensemble_batch[:,sample_pos,:,:] # accumulate predictions and targets preds.append(preds_batch.astype('float16')) if return_var: preds_var_batch = np.var(preds_ensemble_batch, axis=-1) preds_var.append(preds_var_batch.astype('float16')) if return_all: preds_all.append(preds_ensemble_batch.astype('float16')) batch_num += 1 except tf.errors.OutOfRangeError: data_available = False if preds: # concatenate into arrays preds = np.concatenate(preds, axis=0) if return_var and preds_var: preds_var = np.concatenate(preds_var, axis=0) if return_all and preds_all: preds_all = np.concatenate(preds_all, axis=0) else: # return empty array objects preds = np.array(preds) preds_var = np.array(preds_var) preds_all = np.array(preds_all) if return_var: if return_all: return preds, preds_var, preds_all else: return preds, preds_var else: return preds def predict_genes(self, sess, batcher, gene_seqs, rc=False, shifts=[0], mc_n=0, target_indexes=None, tss_radius=0, embed_penultimate=False, test_batches_per=256, dtype='float32'): """ Compute predictions on a test set. In sess: TensorFlow session batcher: Batcher class with transcript-covering sequences gene_seqs List of GeneSeq instances specifying gene positions in sequences. index, position) tuples marking TSSs. rc: Average predictions from the forward and reverse complement sequences. shifts: Average predictions from sequence shifts left/right. mc_n: Monte Carlo iterations per rc/shift. target_indexes: Optional target subset list tss_radius: Radius of bins to quantify TSS. embed_penultimate: Predict the embed_penultimate layer. dtype: Float resolution to return. Out transcript_preds: G (gene transcripts) X T (targets) array """ # count TSSs tss_num = 0 for gene_seq in gene_seqs: tss_num += len(gene_seq.tss_list) # count targets if embed_penultimate: num_targets = self.hp.cnn_params[-1].filters else: num_targets = self.hp.sum_targets if target_indexes is not None: num_targets = len(target_indexes) # initialize TSS preds tss_preds = np.zeros((tss_num, num_targets), dtype=dtype) # initialize indexes tss_i = 0 si = 0 while not batcher.empty(): # predict gene sequences gseq_preds = self.predict_h5_manual(sess, batcher, rc=rc, shifts=shifts, mc_n=mc_n, target_indexes=target_indexes, embed_penultimate=embed_penultimate, test_batches=test_batches_per) # slice TSSs for bsi in range(gseq_preds.shape[0]): for tss in gene_seqs[si].tss_list: bi = tss.seq_bin(width=self.hp.target_pool, pred_buffer=self.hp.batch_buffer) tss_preds[tss_i,:] = gseq_preds[bsi,bi-tss_radius:bi+1+tss_radius,:].sum(axis=0) tss_i += 1 si += 1 batcher.reset() return tss_preds def test_tfr(self, sess, dataset, handle_ph=None, test_batches=None, sample=1.0): """ Compute model accuracy on a test set, where data is loaded from a queue. Args: sess: TensorFlow session dataset: Dataset handle_ph: Dataset handle placeholder test_batches: Number of test batches to use. sample: Sample sequence positions to save predictions/targets. Returns: acc: Accuracy object """ fd = self.set_mode('test') if handle_ph is not None: fd[handle_ph] = dataset.handle # initialize prediction and target arrays if test_batches is None: num_seqs = dataset.num_seqs else: num_seqs = min(dataset.num_seqs, test_batches*self.hp.batch_size) # need to wait for variable num_targets sample_length = int(np.round(sample*self.preds_length)) preds = None targets = None targets_na = np.zeros((num_seqs, sample_length), dtype='bool') batch_losses = [] batch_target_losses = [] batch_sizes = [] # sequence index data_available = True batch_num = 0 si = 0 while data_available and (test_batches is None or batch_num < test_batches): try: # make predictions # run_ops = [self.targets_eval, self.preds_eval_loss, # self.loss_eval, self.loss_eval_targets] run_ops = [self.targets_train, self.preds_train_loss, self.loss_train, self.loss_train_targets] run_returns = sess.run(run_ops, feed_dict=fd) targets_batch, preds_batch, loss_batch, target_losses_batch = run_returns batch_size, _, num_targets = preds_batch.shape # w/ target knowledge, create arrays if preds is None: preds = np.zeros((num_seqs, sample_length, num_targets), dtype='float16') targets = np.zeros((num_seqs, sample_length, num_targets), dtype='float16') # accumulate predictions and targets if sample_length < self.preds_length: sampled_indexes = np.random.choice(np.arange(self.preds_length), size=sample_length, replace=False) sampled_indexes.sort() preds[si:si+batch_size] = preds_batch[:,sampled_indexes,:] targets[si:si+batch_size] = targets_batch[:,sampled_indexes,:] else: preds[si:si+batch_size] = preds_batch targets[si:si+batch_size] = targets_batch # targets_na is already zero # accumulate loss batch_losses.append(loss_batch) batch_target_losses.append(target_losses_batch) batch_sizes.append(preds_batch.shape[0]) batch_num += 1 si += batch_size except tf.errors.OutOfRangeError: data_available = False # mean across batches batch_losses = np.array(batch_losses, dtype='float64') batch_losses = np.average(batch_losses, weights=batch_sizes) batch_target_losses = np.array(batch_target_losses, dtype='float64') batch_target_losses = np.average(batch_target_losses, axis=0, weights=batch_sizes) # instantiate accuracy object acc = accuracy.Accuracy(targets, preds, targets_na, batch_losses, batch_target_losses) return acc def test_h5(self, sess, batcher, test_batches=None): """ Compute model accuracy on a test set. Args: sess: TensorFlow session batcher: Batcher object to provide data test_batches: Number of test batches Returns: acc: Accuracy object """ # setup feed dict fd = self.set_mode('test') # initialize prediction and target arrays preds = [] targets = [] targets_na = [] batch_losses = [] batch_target_losses = [] batch_sizes = [] # get first batch batch_num = 0 Xb, Yb, NAb, Nb = batcher.next() while Xb is not None and (test_batches is None or batch_num < test_batches): # update feed dict fd[self.inputs_ph] = Xb fd[self.targets_ph] = Yb # make predictions run_ops = [self.targets_eval, self.preds_eval_loss, self.loss_eval, self.loss_eval_targets] run_returns = sess.run(run_ops, feed_dict=fd) targets_batch, preds_batch, loss_batch, target_losses_batch = run_returns # accumulate predictions and targets preds.append(preds_batch[:Nb,:,:].astype('float16')) targets.append(targets_batch[:Nb,:,:].astype('float16')) targets_na.append(np.zeros([Nb, self.preds_length], dtype='bool')) # accumulate loss batch_losses.append(loss_batch) batch_target_losses.append(target_losses_batch) batch_sizes.append(Nb) # next batch batch_num += 1 Xb, Yb, NAb, Nb = batcher.next() # reset batcher batcher.reset() # construct arrays targets = np.concatenate(targets, axis=0) preds = np.concatenate(preds, axis=0) targets_na = np.concatenate(targets_na, axis=0) # mean across batches batch_losses = np.array(batch_losses, dtype='float64') batch_losses = np.average(batch_losses, weights=batch_sizes) batch_target_losses = np.array(batch_target_losses, dtype='float64') batch_target_losses = np.average(batch_target_losses, axis=0, weights=batch_sizes) # instantiate accuracy object acc = accuracy.Accuracy(targets, preds, targets_na, batch_losses, batch_target_losses) return acc def test_h5_manual(self, sess, batcher, rc=False, shifts=[0], mc_n=0, test_batches=None): """ Compute model accuracy on a test set. Args: sess: TensorFlow session batcher: Batcher object to provide data rc: Average predictions from the forward and reverse complement sequences. shifts: Average predictions from sequence shifts left/right. mc_n: Monte Carlo iterations per rc/shift. test_batches: Number of test batches Returns: acc: Accuracy object """ # determine ensemble iteration parameters ensemble_fwdrc = [] ensemble_shifts = [] for shift in shifts: ensemble_fwdrc.append(True) ensemble_shifts.append(shift) if rc: ensemble_fwdrc.append(False) ensemble_shifts.append(shift) if mc_n > 0: # setup feed dict fd = self.set_mode('test_mc') else: # setup feed dict fd = self.set_mode('test') # co-opt the variable to represent # iterations per fwdrc/shift. mc_n = 1 # initialize prediction and target arrays preds = [] targets = [] targets_na = [] batch_losses = [] batch_target_losses = [] batch_size = [] # get first batch Xb, Yb, NAb, Nb = batcher.next() batch_num = 0 while Xb is not None and (test_batches is None or batch_num < test_batches): # make ensemble predictions preds_batch, preds_batch_var, preds_all = self._predict_ensemble( sess, fd, Xb, ensemble_fwdrc, ensemble_shifts, mc_n) # add target info fd[self.targets_ph] = Yb fd[self.targets_na_ph] = NAb targets_na.append(np.zeros([Nb, self.preds_length], dtype='bool')) # recompute loss w/ ensembled prediction fd[self.preds_adhoc] = preds_batch targets_batch, loss_batch, target_losses_batch = sess.run( [self.targets_train, self.loss_adhoc, self.target_losses_adhoc], feed_dict=fd) # accumulate predictions and targets if preds_batch.ndim == 3: preds.append(preds_batch[:Nb, :, :].astype('float16')) targets.append(targets_batch[:Nb, :, :].astype('float16')) else: for qi in range(preds_batch.shape[3]): # TEMP, ideally this will be in the HDF5 and set previously self.quantile_means = np.geomspace(0.1, 256, 16) # softmax preds_batch_norm = np.expand_dims( np.sum(np.exp(preds_batch[:Nb, :, :, :]), axis=3), axis=3) pred_probs_batch = np.exp( preds_batch[:Nb, :, :, :]) / preds_batch_norm # expectation over quantile medians preds.append(np.dot(pred_probs_batch, self.quantile_means)) # compare to quantile median targets.append(self.quantile_means[targets_batch[:Nb, :, :] - 1]) # accumulate loss batch_losses.append(loss_batch) batch_target_losses.append(target_losses_batch) batch_sizes.append(Nb) # next batch Xb, Yb, NAb, Nb = batcher.next() batch_num += 1 targets = np.concatenate(targets, axis=0) preds = np.concatenate(preds, axis=0) targets_na = np.concatenate(targets_na, axis=0) # reset batcher batcher.reset() # mean across batches batch_losses = np.array(batch_losses, dtype='float64') batch_losses = np.average(batch_losses, weights=batch_sizes) batch_target_losses = np.array(batch_target_losses, dtype='float64') batch_target_losses = np.average(batch_target_losses, axis=0, weights=batch_sizes) # instantiate accuracy object acc = accuracy.Accuracy(targets, preds, targets_na, batch_losses, batch_target_losses) return acc def running_mean(self, u_k1, x_k, k): return u_k1 + (x_k - u_k1) / k def running_varsum(self, v_k1, x_k, m_k1, m_k): """ Computing the running variance numerator. Ref: https://www.johndcook.com/blog/standard_deviation/ """ return v_k1 + (x_k - m_k1) * (x_k - m_k)
98f880d851d7eb19bfbf5e3c542eb971ce71eaa6
4bcc9806152542ab43fc2cf47c499424f200896c
/tensorflow/python/distribute/cluster_resolver/sagemaker_cluster_resolver_test.py
19d067aceb76f0c848a843e9dc94c1ded9081a22
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
tensorflow/tensorflow
906276dbafcc70a941026aa5dc50425ef71ee282
a7f3934a67900720af3d3b15389551483bee50b8
refs/heads/master
2023-08-25T04:24:41.611870
2023-08-25T04:06:24
2023-08-25T04:14:08
45,717,250
208,740
109,943
Apache-2.0
2023-09-14T20:55:50
2015-11-07T01:19:20
C++
UTF-8
Python
false
false
4,373
py
sagemaker_cluster_resolver_test.py
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for SageMakerClusterResolver.""" import os from tensorflow.python.distribute.cluster_resolver.sagemaker_cluster_resolver import SageMakerClusterResolver from tensorflow.python.framework import test_util from tensorflow.python.platform import test from tensorflow.python.training import server_lib mock = test.mock @test_util.run_all_in_graph_and_eager_modes class SageMakerClusterResolverTest(test.TestCase): def _verifyClusterSpecEquality(self, cluster_spec, expected_proto): self.assertProtoEquals(expected_proto, cluster_spec.as_cluster_def()) self.assertProtoEquals( expected_proto, server_lib.ClusterSpec(cluster_spec).as_cluster_def()) self.assertProtoEquals( expected_proto, server_lib.ClusterSpec(cluster_spec.as_cluster_def()).as_cluster_def()) self.assertProtoEquals( expected_proto, server_lib.ClusterSpec(cluster_spec.as_dict()).as_cluster_def()) def testNormalClusterSpecRead(self): os.environ['SM_HOSTS'] = '["algo-1","algo-2"]' os.environ['SM_CURRENT_HOST'] = 'algo-2' cluster_resolver = SageMakerClusterResolver() expected_proto = """ job { name: 'worker' tasks { key: 0 value: 'algo-1:2223' } tasks { key: 1 value: 'algo-2:2223' } } """ actual_cluster_spec = cluster_resolver.cluster_spec() self._verifyClusterSpecEquality(actual_cluster_spec, expected_proto) def testAutomaticMasterRead(self): os.environ['SM_HOSTS'] = '["algo-1","algo-2"]' os.environ['SM_CURRENT_HOST'] = 'algo-1' cluster_resolver = SageMakerClusterResolver() self.assertEqual('algo-1:2223', cluster_resolver.master()) def testSpecifiedTaskTypeAndIndexMasterRead(self): os.environ['SM_HOSTS'] = '["algo-1","algo-2"]' os.environ['SM_CURRENT_HOST'] = 'algo-2' cluster_resolver = SageMakerClusterResolver() self.assertEqual('algo-2:2223', cluster_resolver.master('worker', 1)) def testRpcLayerRead(self): os.environ['SM_HOSTS'] = '["algo-1","algo-2"]' os.environ['SM_CURRENT_HOST'] = 'algo-1' cluster_resolver = SageMakerClusterResolver(rpc_layer='grpc') self.assertEqual('grpc://algo-1:2223', cluster_resolver.master()) def testParameterOverrides(self): os.environ['SM_HOSTS'] = '["algo-1","algo-2"]' os.environ['SM_CURRENT_HOST'] = 'algo-1' cluster_resolver = SageMakerClusterResolver(task_type='worker', task_id=0) self.assertEqual('algo-1:2223', cluster_resolver.master()) self.assertEqual('worker', cluster_resolver.task_type) self.assertEqual(0, cluster_resolver.task_id) cluster_resolver.task_type = 'worker' cluster_resolver.task_id = 1 cluster_resolver.rpc_layer = 'test' self.assertEqual('test://algo-2:2223', cluster_resolver.master()) self.assertEqual('worker', cluster_resolver.task_type) self.assertEqual(1, cluster_resolver.task_id) self.assertEqual('test', cluster_resolver.rpc_layer) def testTaskIndexOverride(self): os.environ['SM_HOSTS'] = '["algo-1","algo-2"]' os.environ['SM_CURRENT_HOST'] = 'algo-2' cluster_resolver = SageMakerClusterResolver(task_id=1) self.assertEqual(1, cluster_resolver.task_id) def testZeroItemsInClusterSpecMasterRead(self): os.environ['SM_HOSTS'] = '' os.environ['SM_CURRENT_HOST'] = '' cluster_resolver = SageMakerClusterResolver() self.assertEqual('', cluster_resolver.master()) def testOneItemInClusterSpecMasterRead(self): os.environ['SM_HOSTS'] = '["algo-1"]' os.environ['SM_CURRENT_HOST'] = '' cluster_resolver = SageMakerClusterResolver() self.assertEqual('', cluster_resolver.master()) if __name__ == '__main__': test.main()
d12671233992db9a7312d35e4ae4cbeee2173435
d110546d747d7e3865ce5742d5fca09f404623c0
/pkg/tests/integration/test_salt_output.py
e05cf457ded0ffbcc4f221a9e5f952ab6b5e1c98
[ "Apache-2.0", "MIT", "BSD-2-Clause" ]
permissive
saltstack/salt
354fc86a7be1f69514b3dd3b2edb9e6f66844c1d
1ef90cbdc7203f97775edb7666db86a41eb9fc15
refs/heads/master
2023-07-19T20:56:20.210556
2023-06-29T23:12:28
2023-07-19T11:47:47
1,390,248
11,026
6,296
Apache-2.0
2023-09-14T20:45:37
2011-02-20T20:16:56
Python
UTF-8
Python
false
false
444
py
test_salt_output.py
import pytest pytestmark = [ pytest.mark.skip_on_windows, ] @pytest.mark.parametrize("output_fmt", ["yaml", "json"]) def test_salt_output(salt_cli, salt_minion, output_fmt): """ Test --output """ ret = salt_cli.run( f"--output={output_fmt}", "test.fib", "7", minion_tgt=salt_minion.id ) if output_fmt == "json": assert 13 in ret.data else: ret.stdout.matcher.fnmatch_lines(["*- 13*"])
9a31a8b0acb4e43841b8ed946380e1caa557715f
97efdfac795c44f9a2a62e48ba71bf1783c523bf
/message_ix/tests/test_feature_storage.py
8d44f804ed0b3e77d91e71a091ef813d36424092
[ "CC-BY-4.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
iiasa/message_ix
1e96ee254b6f67117faf4fb78ef8fd75d9ee0a6c
bf4469111a2d10c5dbc2c921e6a7e502e96aea34
refs/heads/main
2023-08-17T20:36:23.055462
2023-08-14T08:46:24
2023-08-14T08:46:24
113,015,968
103
162
Apache-2.0
2023-09-08T11:56:21
2017-12-04T08:29:06
Jupyter Notebook
UTF-8
Python
false
false
12,826
py
test_feature_storage.py
"""Test storage representation. This is a unit test for representing storage in the MESSAGEix model, and testing the functionality of storage equations. The workflow is as follows: - Build a stylized MESSAGEix model. - Add seasonality and modify parameters for timesteps accordingly. - Add storage implementation (dam: storage device, pump: charger, turbine: discharger). - Test storage functionality and equations. """ import logging from itertools import product import pandas as pd import pandas.testing as pdt import pytest from ixmp.testing import assert_logs from message_ix import Scenario from message_ix.models import MESSAGE from message_ix.testing import make_dantzig from message_ix.util import expand_dims # A function for generating a simple MESSAGEix model with two technologies def model_setup(scen, years): scen.add_set("node", "node") scen.add_set("commodity", "electr") scen.add_set("level", "level") scen.add_set("year", years) scen.add_set("type_year", years) scen.add_set("technology", ["wind_ppl", "gas_ppl"]) scen.add_set("mode", "M1") output_specs = ["node", "electr", "level", "year", "year"] # Two technologies, one cheaper than the other var_cost = {"wind_ppl": 0, "gas_ppl": 2} for year, (tec, cost) in product(years, var_cost.items()): scen.add_par("demand", ["node", "electr", "level", year, "year"], 1, "GWa") tec_specs = ["node", tec, year, year, "M1"] scen.add_par("output", tec_specs + output_specs, 1, "GWa") scen.add_par("var_cost", tec_specs + ["year"], cost, "USD/GWa") # A function for adding sub-annual time steps to a MESSAGEix model def add_seasonality(scen, time_duration): scen.add_set("time", sorted(list(set(time_duration.keys())))) scen.add_set("lvl_temporal", "season") for h, duration in time_duration.items(): scen.add_set("map_temporal_hierarchy", ["season", h, "year"]) scen.add_par("duration_time", [h], duration, "-") # A function for modifying model parameters after adding sub-annual time steps def year_to_time(scen, parname, time_share): old = scen.par(parname) scen.remove_par(parname, old) time_idx = [x for x in scen.idx_names(parname) if "time" in x] for h, share in time_share.items(): new = old.copy() for index in time_idx: new[index] = h new["value"] = share * old["value"] scen.add_par(parname, new) # A function for adding storage technologies and parameterization def add_storage_data(scen, time_order): # Adding level of storage scen.add_set("level", "storage") # Adding storage technologies (reservoir, charger, and discharger) scen.add_set("technology", ["dam", "pump", "turbine"]) # Adding a storage commodity scen.add_set("commodity", ["water", "cooling", "dummay"]) # Specifying storage reservoir technology scen.add_set("storage_tec", "dam") # Specifying storage level scen.add_set("level_storage", "storage") # Adding mapping for storage and charger/discharger technologies for tec in ["pump", "turbine"]: scen.add_set( "map_tec_storage", ["node", tec, "M1", "dam", "M1", "storage", "water", "season"], ) # Adding time sequence for h in time_order.keys(): scen.add_par("time_order", ["season", h], time_order[h], "-") # Adding input, output, and capacity factor for storage technologies output_spec = { "dam": ["node", "dummay", "level"], "pump": ["node", "water", "storage"], "turbine": ["node", "electr", "level"], } input_spec = { "dam": ["node", "cooling", "level"], "pump": ["node", "electr", "level"], "turbine": ["node", "water", "storage"], } var_cost = {"dam": 0, "pump": 0.2, "turbine": 0.3} stor_tecs = ["dam", "pump", "turbine"] for year, h, tec in product(set(scen.set("year")), time_order.keys(), stor_tecs): tec_sp = ["node", tec, year, year, "M1"] scen.add_par("output", tec_sp + output_spec[tec] + [h, h], 1, "GWa") scen.add_par("input", tec_sp + input_spec[tec] + [h, h], 1, "GWa") scen.add_par("var_cost", tec_sp + [h], var_cost[tec], "USD/GWa") # Adding storage self-discharge (as %) and initial content for year, h in product(set(scen.set("year")), time_order.keys()): storage_spec = ["node", "dam", "M1", "storage", "water", year, h] scen.add_par("storage_self_discharge", storage_spec, 0.05, "%") # Adding initial content of storage (optional) storage_spec = ["node", "dam", "M1", "storage", "water", year, "a"] scen.add_par("storage_initial", storage_spec, 0.5, "%") # Main function for building a model with storage and testing the functionality def storage_setup(test_mp, time_duration, comment): # First, building a simple model and adding seasonality scen = Scenario(test_mp, "no_storage", "standard", version="new") model_setup(scen, [2020]) add_seasonality(scen, time_duration) # Fixed share for parameters that don't change across timesteps fixed_share = {"a": 1, "b": 1, "c": 1, "d": 1} year_to_time(scen, "output", fixed_share) year_to_time(scen, "var_cost", fixed_share) # Variable share for parameters that are changing in each timestep # share of demand in each season from annual demand demand_share = {"a": 0.15, "b": 0.2, "c": 0.4, "d": 0.25} year_to_time(scen, "demand", demand_share) scen.commit("initialized a model with timesteps") scen.solve(case="no_storage" + comment, quiet=True) # Second, adding upper bound on activity of the cheap technology (wind_ppl) scen.remove_solution() scen.check_out() for h in time_duration.keys(): scen.add_par( "bound_activity_up", ["node", "wind_ppl", 2020, "M1", h], 0.25, "GWa" ) scen.commit("activity bounded") scen.solve(case="no_storage_bounded" + comment, quiet=True) cost_no_stor = scen.var("OBJ")["lvl"] act_no_stor = scen.var("ACT", {"technology": "gas_ppl"})["lvl"].sum() # Third, adding storage technologies but with no input to storage device scen.remove_solution() scen.check_out() # Chronological order of timesteps in the year time_order = {"a": 1, "b": 2, "c": 3, "d": 4} add_storage_data(scen, time_order) scen.commit("storage data added") scen.solve(case="with_storage_no_input" + comment, quiet=True) act = scen.var("ACT") # Forth, adding storage technologies and providing input to storage device scen.remove_solution() scen.check_out() # Adding a new technology "cooler" to provide input of "cooling" to dam scen.add_set("technology", "cooler") df = scen.par("output", {"technology": "turbine"}) df["technology"] = "cooler" df["commodity"] = "cooling" scen.add_par("output", df) # Changing input of dam from 1 to 1.2 to test commodity balance df = scen.par("input", {"technology": "dam"}) df["value"] = 1.2 scen.add_par("input", df) scen.commit("storage needs no separate input") scen.solve( case="with_storage_and_input" + comment, quiet=True, var_list=["STORAGE", "STORAGE_CHARGE"], ) cost_with_stor = scen.var("OBJ")["lvl"] act_with_stor = scen.var("ACT", {"technology": "gas_ppl"})["lvl"].sum() # Fifth. Tests for the functionality of storage # 1. Check that "dam" is not active if no "input" commodity is defined assert "dam" not in act[act["lvl"] > 0]["technology"].tolist() # 2. Testing functionality of storage # Check the contribution of storage to the system cost assert cost_with_stor < cost_no_stor # Activity of expensive technology should be lower with storage assert act_with_stor < act_no_stor # 3. Activity of discharger <= activity of charger act_pump = scen.var("ACT", {"technology": "pump"})["lvl"] act_turb = scen.var("ACT", {"technology": "turbine"})["lvl"] assert act_turb.sum() <= act_pump.sum() # 4. Activity of input provider to storage = act of storage * storage input act_cooler = scen.var("ACT", {"technology": "cooler"})["lvl"] inp = scen.par("input", {"technology": "dam"})["value"] act_stor = scen.var("ACT", {"technology": "dam"})["lvl"] pdt.assert_series_equal(inp * act_stor, act_cooler, check_names=False) # 5. Max activity of charger <= max activity of storage max_pump = max(act_pump) act_storage = scen.var("ACT", {"technology": "dam"})["lvl"] max_stor = max(act_storage) assert max_pump <= max_stor # 6. Max activity of discharger <= max storage act - self discharge losses max_turb = max(act_turb) loss = scen.par("storage_self_discharge")["value"][0] assert max_turb <= max_stor * (1 - loss) # Sixth, testing equations of storage (when added to ixmp variables) if scen.has_var("STORAGE") and not scen.var("STORAGE").empty: # 1. Equality: storage content at the end is equal to the beginning # (i.e., the difference is what is pumped in the first time slice) storage_first = scen.var("STORAGE", {"time": "a"})["lvl"].item() storage_last = scen.var("STORAGE", {"time": "d"})["lvl"].item() pump_first = scen.var("ACT", {"technology": "pump", "time": "a"}).at[0, "lvl"] assert storage_last == storage_first - pump_first # 2. Storage content should never exceed storage activity assert max(scen.var("STORAGE")["lvl"]) <= max_stor # 3. Commodity balance: charge - discharge - losses = 0 change = scen.var("STORAGE_CHARGE").set_index(["year", "time"])["lvl"] loss = scen.par("storage_self_discharge").set_index(["year", "time"])["value"] assert (change[change > 0] * (1 - loss)).sum() >= -(change[change < 0]).sum() # 4. Energy balance: storage change + losses = storage content storage = scen.var("STORAGE").set_index(["year", "time"])["lvl"] assert storage[(2020, "b")] * (1 - loss[(2020, "b")]) == -change[(2020, "c")] # Storage test for different duration times def test_storage(test_mp): """ Testing storage setup with equal and unequal duration of seasons" """ time_duration = {"a": 0.25, "b": 0.25, "c": 0.25, "d": 0.25} storage_setup(test_mp, time_duration, "_equal_time") time_duration = {"a": 0.3, "b": 0.25, "c": 0.25, "d": 0.2} storage_setup(test_mp, time_duration, "_unequal_time") def test_structure(caplog, test_mp): """:meth:`MESSAGE.initialize` and :meth:`MESSAGE.enforce` handle old structure.""" scen = make_dantzig(test_mp) # Item name to use for the tests, a parameter, and its dimensions name = "storage_initial" dims = ["node", "technology", "level", "commodity", "year", "time"] # NB here we cannot use make_df, since that refers to the current dimensionality of # storage_initial per MESSAGE_ITEMS data = pd.Series( ["topeka", "canning_plant", "supply", "cases", 1963, "year", 1.0, "kg"], index=dims + ["value", "unit"], ) def prepare(s, with_data=False): """Re-initialize to the former definition, i.e. omitting mode.""" with scen.transact(): scen.remove_par(name) scen.init_par(name, idx_sets=dims) if with_data: scen.add_par(name, data.to_frame().transpose()) # Test by calling the MESSAGE model class methods directory. This is not the typical # user behaviour; we just want to avoid a more complex way of doing so. # Calling initialize() with no data automatically expands the dimensions prepare(scen) assert "mode" not in scen.idx_sets(name) with scen.transact(): MESSAGE.initialize(scen) assert "mode" in scen.idx_sets(name) # …and enforce() completes without raising an exception MESSAGE.enforce(scen) # Now with data in storage_initial, a warning is raised prepare(scen, with_data=True) # Two context managers for the with: block c1 = pytest.warns(UserWarning, match="'storage_initial' has data with dimensions") c2 = assert_logs(caplog, "Existing index sets of 'stora", at_level=logging.WARNING) with c1, c2: with scen.transact(): MESSAGE.initialize(scen) # …the dimensions are *not* expanded automatically assert "mode" not in scen.idx_sets(name) # …and the scenario would not solve with pytest.raises(ValueError, match="'storage_initial' has data with dimensions"): MESSAGE.enforce(scen) # expand_dims() results in the correct dimensionality and complete data expand_dims(scen, name, mode="production") assert "mode" in scen.idx_sets(name) # …and enforce() completes without raising an exception MESSAGE.enforce(scen)
85990588fd22d4c8dba0b4a5bde8a1aebc157b6b
01b61d78d99c3a6caeda65cf770e87a794b5689d
/Chapter08/Code/parameters.py
cd65f685be1442b924b9362079f1892fb39e00f7
[ "MIT" ]
permissive
PacktPublishing/TensorFlow-Machine-Learning-Projects
b62b6e945f9272b92c164eb1610684ba8a5b2bc1
157d13317780d845fd2c781a036c8281c780ab30
refs/heads/master
2023-03-02T20:25:02.245771
2023-01-30T09:58:37
2023-01-30T09:58:37
139,389,726
104
65
MIT
2023-03-01T20:33:32
2018-07-02T04:14:29
Jupyter Notebook
UTF-8
Python
false
false
289
py
parameters.py
import os #DATA_DIR = '/Users/ankit.jain/Documents/Teaching&Learning/Packt/Book/BNN/Data' DATA_DIR = os.path.join(os.getcwd(),"..","Data") NUM_CLASSES = 43 IMG_SIZE = 32 #Training Parameters BATCH_SIZE =128 EPOCHS =1000 LEARNING_RATE = 0.001 # Inference Parameters NUM_MONTE_CARLO = 50
1c305445fa2d5226ff6794429191adb5218d6c4c
b8d80a23cb27af08a1c4d34b478c76228ae5fbb4
/insights/tests/combiners/test_ceph_version.py
881d25469dc0cd47a4714fd59ced8ff284d09582
[ "Apache-2.0" ]
permissive
RedHatInsights/insights-core
bb243e2bf8a52446fefb95ebe05478d6e35efe2e
b0ea07fc3f4dd8801b505fe70e9b36e628152c4a
refs/heads/master
2023-09-04T21:15:40.456257
2023-09-04T10:46:56
2023-09-04T10:46:56
92,518,221
144
290
Apache-2.0
2023-09-14T02:40:13
2017-05-26T14:23:11
Python
UTF-8
Python
false
false
4,682
py
test_ceph_version.py
from insights.parsers.ceph_version import CephVersion as CephV from insights.parsers.ceph_insights import CephInsights from insights.parsers.ceph_cmd_json_parsing import CephReport from insights.combiners import ceph_version from insights.combiners.ceph_version import CephVersion from insights.tests import context_wrap import doctest CEPH_INSIGHTS = """ { "version": { "release": 12, "major": 2, "full": "ceph version 12.2.8-52.el7cp (3af3ca15b68572a357593c261f95038d02f46201) luminous (stable)", "minor": 8 } } """.strip() CEPH_VERSION = "ceph version 12.2.8-52.el7cp (3af3ca15b68572a357593c261f95038d02f46201) luminous (stable)".strip() CEPH_REPORT = """ report 1188805303 { "cluster_fingerprint": "0d5f8f7a-0241-4a2e-8401-9dcf37a1039b", "version": "12.2.8-52.el7cp", "commit": "3af3ca15b68572a357593c261f95038d02f46201", "timestamp": "2019-06-05 23:33:08.514032", "tag": "", "health": { "checks": { "POOL_APP_NOT_ENABLED": { "severity": "HEALTH_WARN", "summary": { "message": "application not enabled on 1 pool(s)" }, "detail": [ { "message": "application not enabled on pool 'pool-a'" }, { "message": "use 'ceph osd pool application enable <pool-name> <app-name>', where <app-name> is 'cephfs', 'rbd', 'rgw', or freeform for custom applications." } ] }, "MON_DOWN": { "severity": "HEALTH_WARN", "summary": { "message": "1/3 mons down, quorum ceph2,ceph_1" }, "detail": [ { "message": "mon.ceph3 (rank 0) addr 10.72.37.76:6789/0 is down (out of quorum)" } ] } }, "status": "HEALTH_WARN", "summary": [ { "severity": "HEALTH_WARN", "summary": "'ceph health' JSON format has changed in luminous. If you see this your monitoring system is scraping the wrong fields. Disable this with 'mon health preluminous compat warning = false'" } ], "overall_status": "HEALTH_WARN", "detail": [ "'ceph health' JSON format has changed in luminous. If you see this your monitoring system is scraping the wrong fields. Disable this with 'mon health preluminous compat warning = false'" ] }, "monmap_first_committed": 1, "monmap_last_committed": 1, "quorum": [ 1, 2 ], "osdmap_first_committed": 1, "osdmap_last_committed": 92 } """.strip() def test_ceph_version(): cv = CephV(context_wrap(CEPH_VERSION)) ret = CephVersion(cv, None, None) assert ret.version == "3.2" assert ret.major == "3" assert ret.minor == "2" assert not ret.is_els assert ret.downstream_release == "0" assert ret.upstream_version["release"] == 12 assert ret.upstream_version["major"] == 2 assert ret.upstream_version["minor"] == 8 def test_ceph_version_2(): cv = CephV(context_wrap(CEPH_VERSION)) ci = CephInsights(context_wrap(CEPH_INSIGHTS)) ret = CephVersion(cv, ci, None) assert ret.version == "3.2" assert ret.major == "3" assert ret.minor == "2" assert not ret.is_els assert ret.downstream_release == "0" assert ret.upstream_version["release"] == 12 assert ret.upstream_version["major"] == 2 assert ret.upstream_version["minor"] == 8 def test_ceph_insights(): ci = CephInsights(context_wrap(CEPH_INSIGHTS)) ret = CephVersion(None, ci, None) assert ret.version == "3.2" assert ret.major == "3" assert ret.minor == "2" assert not ret.is_els assert ret.downstream_release == "0" assert ret.upstream_version["release"] == 12 assert ret.upstream_version["major"] == 2 assert ret.upstream_version["minor"] == 8 def test_ceph_report(): cr = CephReport(context_wrap(CEPH_REPORT)) ret = CephVersion(None, None, cr) assert ret.version == "3.2" assert ret.major == "3" assert ret.minor == "2" assert not ret.is_els assert ret.downstream_release == "0" assert ret.upstream_version["release"] == 12 assert ret.upstream_version["major"] == 2 assert ret.upstream_version["minor"] == 8 def test_ceph_version_doc_examples(): env = { 'cv': CephVersion(CephV(context_wrap(CEPH_VERSION)), None, None) } failed, total = doctest.testmod(ceph_version, globs=env) assert failed == 0
12447efd747278c8703ec3615bd23c860b6c29f5
cf8182ecc88888719cfaff79751834500800151a
/applications/tapkee/samples/dm.py
036028dfd44d1158abf77b19d6c977c858d3af08
[ "BSD-3-Clause", "DOC", "GPL-3.0-only" ]
permissive
shogun-toolbox/shogun
17beb82a04fbf1179d300c4fcd16ee68850ad994
9b8d856971af5a295dd6ad70623ae45647a6334c
refs/heads/develop
2023-03-11T04:46:36.167073
2020-12-08T16:56:38
2020-12-08T16:56:38
1,555,094
2,938
1,246
BSD-3-Clause
2022-08-12T11:12:34
2011-04-01T10:44:32
C++
UTF-8
Python
false
false
952
py
dm.py
import shogun as sg import data import numpy as np # load data feature_matrix = data.swissroll() # create features instance features = sg.RealFeatures(feature_matrix) # create Diffusion Maps converter instance converter = sg.DiffusionMaps() # set target dimensionality converter.set_target_dim(2) # set number of time-steps converter.set_t(2) # set width of gaussian kernel converter.set_width(10.0) # create euclidean distance instance distance = sg.EuclideanDistance() # enable converter instance to use created distance instance converter.set_distance(distance) # compute embedding with Diffusion Maps method embedding = converter.embed(features) # compute custom distance matrix distance_matrix = np.exp(-np.dot(feature_matrix.T,feature_matrix)) # create Custom Kernel instance custom_distance = sg.CustomDistance(distance_matrix) # construct embedding based on created distance distance_embedding = converter.embed_distance(custom_distance)
4e64ac8421f1fe7e4d68c331ea3c46c2a3567a46
9c8de4dbc6c7e4411fa3b8088fe630e6db67146f
/gym_collision_avoidance/envs/policies/RVOPolicy.py
15eed12b20acd0f1e3258d132a804a0290392528
[ "MIT" ]
permissive
mit-acl/gym-collision-avoidance
8379c1f022b7e01f30d98dcb701fbda429bd7ba8
903564097509e3fbdbbb850a3a89729a28377b81
refs/heads/release
2023-05-29T06:56:19.482580
2023-04-28T18:18:22
2023-04-28T18:18:22
241,484,799
212
68
MIT
2022-06-07T18:50:32
2020-02-18T22:52:24
OpenEdge ABL
UTF-8
Python
false
false
5,487
py
RVOPolicy.py
import numpy as np from gym_collision_avoidance.envs.policies.InternalPolicy import InternalPolicy from gym_collision_avoidance.envs import Config from gym_collision_avoidance.envs.util import * import rvo2 import matplotlib.pyplot as plt class RVOPolicy(InternalPolicy): def __init__(self): InternalPolicy.__init__(self, str="RVO") self.dt = Config.DT neighbor_dist = Config.SENSING_HORIZON max_neighbors = Config.MAX_NUM_AGENTS_IN_ENVIRONMENT self.has_fixed_speed = False self.heading_noise = False self.max_delta_heading = np.pi/6 # TODO share this parameter with environment time_horizon = Config.RVO_TIME_HORIZON # NOTE: bjorn used 1.0 in training for corl19 # Initialize RVO simulator self.sim = rvo2.PyRVOSimulator(timeStep=self.dt, neighborDist=neighbor_dist, maxNeighbors=max_neighbors, timeHorizon=time_horizon, timeHorizonObst=time_horizon, radius=0.0, maxSpeed=0.0) self.is_init = False self.use_non_coop_policy = True def init(self): state_dim = 2 self.pos_agents = np.empty((self.n_agents, state_dim)) self.vel_agents = np.empty((self.n_agents, state_dim)) self.goal_agents = np.empty((self.n_agents, state_dim)) self.pref_vel_agents = np.empty((self.n_agents, state_dim)) self.pref_speed_agents = np.empty((self.n_agents)) self.rvo_agents = [None]*self.n_agents # Init simulation for a in range(self.n_agents): self.rvo_agents[a] = self.sim.addAgent((0,0)) self.is_init = True def find_next_action(self, obs, agents, agent_index): # Initialize vectors on first call to infer number of agents if not self.is_init: self.n_agents = len(agents) self.init() # Share all agent positions and preferred velocities from environment with RVO simulator for a in range(self.n_agents): # Copy current agent positions, goal and preferred speeds into np arrays self.pos_agents[a,:] = agents[a].pos_global_frame[:] self.vel_agents[a,:] = agents[a].vel_global_frame[:] self.goal_agents[a,:] = agents[a].goal_global_frame[:] self.pref_speed_agents[a] = agents[a].pref_speed # Calculate preferred velocity # Assumes non RVO agents are acting like RVO agents self.pref_vel_agents[a,:] = self.goal_agents[a,:] - self.pos_agents[a,:] self.pref_vel_agents[a,:] = self.pref_speed_agents[a] / np.linalg.norm(self.pref_vel_agents[a,:]) * self.pref_vel_agents[a,:] # Set agent positions and velocities in RVO simulator self.sim.setAgentMaxSpeed(self.rvo_agents[a], agents[a].pref_speed) self.sim.setAgentRadius(self.rvo_agents[a], (1+5e-2)*agents[a].radius) self.sim.setAgentPosition(self.rvo_agents[a], tuple(self.pos_agents[a,:])) self.sim.setAgentVelocity(self.rvo_agents[a], tuple(self.vel_agents[a,:])) self.sim.setAgentPrefVelocity(self.rvo_agents[a], tuple(self.pref_vel_agents[a,:])) # Set ego agent's collaborativity if Config.RVO_COLLAB_COEFF < 0: # agent is anti-collaborative ==> every X seconds, it chooses btwn non-coop and adversarial, # where the PMF of which policy to run is defined by abs(collab_coeff)\in(0,1]. # if a certain freq, randomly select btwn use non coop policy vs. rvo if round(agents[agent_index].t % Config.RVO_ANTI_COLLAB_T, 3) < Config.DT or \ round(Config.RVO_ANTI_COLLAB_T - agents[agent_index].t % Config.RVO_ANTI_COLLAB_T, 3) < Config.DT: self.use_non_coop_policy = np.random.choice([True, False], p=[1-abs(Config.RVO_COLLAB_COEFF), abs(Config.RVO_COLLAB_COEFF)]) if self.use_non_coop_policy: self.sim.setAgentCollabCoeff(self.rvo_agents[agent_index], 0.0) else: self.sim.setAgentCollabCoeff(self.rvo_agents[agent_index], Config.RVO_COLLAB_COEFF) else: self.sim.setAgentCollabCoeff(self.rvo_agents[agent_index], Config.RVO_COLLAB_COEFF) # Execute one step in the RVO simulator self.sim.doStep() # Calculate desired change of heading self.new_rvo_pos = self.sim.getAgentPosition(self.rvo_agents[agent_index])[:] deltaPos = self.new_rvo_pos - self.pos_agents[agent_index,:] p1 = deltaPos p2 = np.array([1,0]) # Angle zero is parallel to x-axis ang1 = np.arctan2(*p1[::-1]) ang2 = np.arctan2(*p2[::-1]) new_heading_global_frame = (ang1 - ang2) % (2 * np.pi) delta_heading = wrap(new_heading_global_frame - agents[agent_index].heading_global_frame) # Calculate desired speed pref_speed = 1/self.dt * np.linalg.norm(deltaPos) # Limit the turning rate: stop and turn in place if exceeds if abs(delta_heading) > self.max_delta_heading: delta_heading = np.sign(delta_heading)*self.max_delta_heading pref_speed = 0. # Ignore speed if self.has_fixed_speed: pref_speed = self.max_speed # Add noise if self.heading_noise: delta_heading = delta_heading + np.random.normal(0,0.5) action = np.array([pref_speed, delta_heading]) return action
65606d46e47241851fb31df0a348fa23cdbc7d33
b3cde44e48d293d94b612a34506e03feb2ab7fcc
/scripts/fsqio/python3-port-utils/pants/update_decode_encode.py
3e7db1779d48a691782f3dc0e47fd31ab75fcdf6
[ "Apache-2.0" ]
permissive
foursquare/fsqio
0cfd51e71d572f9f5682c03fdaba7c79ffff6785
f5a5699c18babaa6810de84bcc6dd1522bcfe259
refs/heads/master
2022-08-10T10:29:28.004139
2022-06-28T22:42:39
2022-06-28T22:42:39
48,192,426
267
66
Apache-2.0
2022-06-28T22:42:40
2015-12-17T18:53:44
Scala
UTF-8
Python
false
false
1,478
py
update_decode_encode.py
#!/usr/bin/env python3 import argparse import re from pathlib import Path from typing import Sequence, Set ENCODING_REGEX = r"""('utf-8'|"utf-8"|'UTF-8'|"UTF-8")""" DECODE_REGEX = rf".decode\({ENCODING_REGEX}\)" ENCODE_REGEX = rf".encode\({ENCODING_REGEX}\)" def main() -> None: folders = create_parser().parse_args().folders for fp in get_relevant_files(folders): simplify(file_path=fp, regex=DECODE_REGEX, replacement=".decode()") simplify(file_path=fp, regex=ENCODE_REGEX, replacement=r".encode()") def create_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description='Remove `from builtins import x`, and possibly the BUILD entry for `future`.') parser.add_argument('folders', nargs='*') return parser def get_relevant_files(folders: Sequence[str]) -> Set[Path]: return { fp for folder in folders for fp in Path(folder).rglob("*.py") if any( re.search(ENCODE_REGEX, line) or re.search(DECODE_REGEX, line) for line in fp.read_text().splitlines() ) } def simplify(*, file_path: Path, regex: str, replacement: str) -> None: lines = file_path.read_text().splitlines() indexes = [i for i, line in enumerate(lines) if re.search(regex, line)] for index in indexes: new_line = re.sub(regex, replacement, lines[index]) lines[index] = new_line file_path.write_text("\n".join(lines) + "\n") if __name__ == '__main__': try: main() except KeyboardInterrupt: pass
186e0317e9ce8aa37fcbf6deb9198e248ac6b1e4
c3351062731885d604a39856b2f933144cac70bc
/tools/Sikuli/ClickUITab.sikuli/ClickUITab.py
5c198c738e6e3f045a385af2db8a28937b4c9100
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-3-Clause" ]
permissive
Pr-Mex/vanessa-automation
4efb7924242b70d86f1ef34b48de638602a6d8f3
e9fcb486384a3c96db8ee7218294550c78bf096c
refs/heads/develop
2023-09-04T00:48:40.953195
2023-08-30T19:28:16
2023-08-30T19:28:16
133,170,708
395
356
BSD-3-Clause
2023-09-11T17:17:02
2018-05-12T17:55:53
1C Enterprise
UTF-8
Python
false
false
89
py
ClickUITab.py
if not exists("Pa60TacUI.png"): exit(1) click("Pa60TacUI.png") sleep(1) exit(0)
afb29497d4771ca314b652401e47ab4d8f7031e8
f305f84ea6f721c2391300f0a60e21d2ce14f2a5
/19_数学/组合/直角三角形的个数.py
be87d10a23ecb20deb4ee7fcf2f72b2288d7c8b3
[]
no_license
981377660LMT/algorithm-study
f2ada3e6959338ae1bc21934a84f7314a8ecff82
7e79e26bb8f641868561b186e34c1127ed63c9e0
refs/heads/master
2023-09-01T18:26:16.525579
2023-09-01T12:21:58
2023-09-01T12:21:58
385,861,235
225
24
null
null
null
null
UTF-8
Python
false
false
881
py
直角三角形的个数.py
from typing import List, Tuple def cal(points: List[Tuple[int, int]]) -> int: """求点集组成的不同直角三角形个数""" n = len(points) res = 0 for i in range(n): # 枚举直角顶点 x0, y0 = points[i] for j in range(n): if j == i: continue x1, y1 = points[j] for k in range(j + 1, n): if k == i or k == j: continue x2, y2 = points[k] ij = (x1 - x0, y1 - y0) ik = (x2 - x0, y2 - y0) if ij[0] * ik[0] + ij[1] * ik[1] == 0: # 垂直 res += 1 return res n = int(input()) nums = list(map(int, input().split())) points = [] for i in range(0, 2 * n, 2): points.append((nums[i], nums[i + 1])) print(cal(list(set(points))))
a15e375de35e894f4b91e08e46e06029a0763180
8287ced5b14dd2a0060545b1fb53aa8a8deb878b
/precise/pocketsphinx/scripts/listen.py
b2381a234f0bcb2989c035a3b983f3700ba81f00
[ "Apache-2.0" ]
permissive
MycroftAI/mycroft-precise
30fa89e632189e27d9fa2dabcef82a7867d4f6ae
e1a635e9675047eb86f64ca489a1b941321c489a
refs/heads/dev
2023-07-19T06:19:58.303669
2020-08-05T02:09:50
2020-08-05T02:09:50
101,455,393
777
233
Apache-2.0
2023-06-22T16:14:39
2017-08-26T01:56:48
Python
UTF-8
Python
false
false
1,990
py
listen.py
#!/usr/bin/env python3 # Copyright 2019 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """ Run Pocketsphinx on microphone audio input :key_phrase str Key phrase composed of words from dictionary :dict_file str Filename of dictionary with word pronunciations :hmm_folder str Folder containing hidden markov model :-th --threshold str 1e-90 Threshold for activations :-c --chunk-size int 2048 Samples between inferences """ from precise_runner import PreciseRunner from precise_runner.runner import ListenerEngine from prettyparse import Usage from threading import Event from precise.pocketsphinx.listener import PocketsphinxListener from precise.scripts.base_script import BaseScript from precise.util import activate_notify class PocketsphinxListenScript(BaseScript): usage = Usage(__doc__) def run(self): def on_activation(): activate_notify() def on_prediction(conf): print('!' if conf > 0.5 else '.', end='', flush=True) args = self.args runner = PreciseRunner( ListenerEngine( PocketsphinxListener( args.key_phrase, args.dict_file, args.hmm_folder, args.threshold, args.chunk_size ) ), 3, on_activation=on_activation, on_prediction=on_prediction ) runner.start() Event().wait() # Wait forever main = PocketsphinxListenScript.run_main if __name__ == '__main__': main()
a76eb14c20cd8ba3819410020da7d5505b411d6a
b60f84142c6a704621a49522ed1364439a38be19
/litedram/phy/rpc/basephy.py
e3247699bc4866e6e7a1cc0b9a413dceb5127f13
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
enjoy-digital/litedram
cf0ad16a6a7b22b5b5257af313ed59f3f2bba477
ed81c8cc861ae14e44b2df83adce3ff39ca7f7ac
refs/heads/master
2023-09-04T06:27:33.897454
2023-08-29T14:48:10
2023-08-29T14:48:10
31,147,284
321
111
NOASSERTION
2023-07-07T06:53:26
2015-02-22T00:43:35
Python
UTF-8
Python
false
false
27,428
py
basephy.py
# # This file is part of LiteDRAM. # # Copyright (c) 2020-2021 Antmicro <www.antmicro.com> # SPDX-License-Identifier: BSD-2-Clause from math import ceil from operator import and_ from migen import * from litex.gen.genlib.misc import WaitTimer from litex.soc.interconnect.csr import AutoCSR, CSR, CSRStatus, CSRStorage from litedram.common import * from litedram.phy.utils import chunks, bitpattern from litedram.phy.dfi import Interface as DFIInterface from litedram.phy.rpc.commands import DFIAdapter class ShiftRegister(Module): def __init__(self, n, i=None): if i is None: i = Signal() assert len(i) == 1 self.i = i self.sr = sr = Signal(n) last = Signal.like(sr) self.comb += sr.eq(Cat(i, last)) self.sync += last.eq(sr) def __getitem__(self, key): return self.sr[key] class RPCPads: _layout = [ ("clk_p", 1), ("clk_n", 1), ("cs_n", 1), ("dqs_p", 1), # may be 2 (hardware option; 2-bit DQS strobes DB by bytes: [0:7], [8:15]) ("dqs_n", 1), # may be 2 ("stb", 1), ("db", 16), ] def __init__(self, pads): self.map(pads) for pad, width in self._layout: assert len(getattr(self, pad)) >= width, \ "Pad {} has width {} < {}".format(pad, len(getattr(self, pad)), width) # reimplement if a specific mapping is needed def map(self, pads): for pad, _ in self._layout: setattr(self, pad, getattr(pads, pad)) class BasePHY(Module, AutoCSR): def __init__(self, pads, sys_clk_freq, write_ser_latency, read_des_latency, phytype): # TODO: pads groups for multiple chips # pads = PHYPadsCombiner(pads) if not isinstance(pads, RPCPads): pads = RPCPads(pads) self.pads = pads self.memtype = memtype = "RPC" self.nranks = nranks = 1 self.databits = databits = 16 self.addressbits = addressbits = 12 self.bankbits = bankbits = 2 self.nphases = nphases = 4 self.tck = tck = 1 / (nphases*sys_clk_freq) # CSRs ------------------------------------------------------------------------------------- bitslip_cycles = 1 self._rst = CSRStorage() self._dly_sel = CSRStorage(databits//8) self._rdly_dq_bitslip_rst = CSR() self._rdly_dq_bitslip = CSR() self._reset_done = CSRStatus() self._init_done = CSRStatus() self._reset_fsm = CSR() self._burst_stop = CSRStorage(reset=1) # PHY settings ----------------------------------------------------------------------------- def get_cl(tck): # FIXME: for testing it's easier to use CL=8; read/write will be on phase 3; max sys_clk_freq=100e6 return 8 # tck is for DDR frequency f_to_cl = OrderedDict() f_to_cl[533e6] = 3 f_to_cl[800e6] = 8 f_to_cl[1200e6] = 8 f_to_cl[1333e6] = 10 f_to_cl[1600e6] = 11 f_to_cl[1866e6] = 13 for f, cl in f_to_cl.items(): if tck >= 2/f: return cl raise ValueError(tck) # RPC always has AL=1 and both read and write latencies are equal: RL=WL=AL+CL al = 1 cwl = cl = get_cl(tck) + al cl_sys_latency = get_sys_latency(nphases, cl) cwl_sys_latency = get_sys_latency(nphases, cwl) rdphase = get_sys_phase(nphases, cl_sys_latency, cl) wrphase = get_sys_phase(nphases, cwl_sys_latency, cwl) # Read latency db_cmd_dly = 2 # (need 1 cycle to insert STB preamble + 1 more to always meet tCSS) cmd_ser_dly = write_ser_latency read_mux_dly = 1 bitslip_dly = bitslip_cycles # Time until first data is available on DB read_db_dly = db_cmd_dly + cmd_ser_dly + cl_sys_latency # Time until data is deserialized (data present on 1ck signal) read_db_des_dly = read_db_dly + read_des_latency # Time until data is set on DFI (+1 because all data is present only on 2nd cycle) read_dfi_dly = read_mux_dly + bitslip_dly + 1 # Final latency read_latency = read_db_des_dly + read_dfi_dly # Write latency for the controller. We must send 1 cycles of data mask before the # data, and we serialize data over 2 sysclk cycles due to minimal BL=16, so we # are writing in the 2 cycles following the cycle when we obtain data on DFI. # Other PHYs can send everything in 1 sysclk. Because of this spcific delay, we # have to increate tWR in the RPC SDRModule definition to meet tWR requirements. # +1 cycle needed to insert CS before command write_latency = cwl_sys_latency + 1 self.settings = PhySettings( phytype = phytype, memtype = memtype, databits = databits, dfi_databits = 4*databits, nranks = nranks, nphases = nphases, rdphase = rdphase, wrphase = wrphase, cl = cl, cwl = cwl, read_latency = read_latency, write_latency = write_latency, bitslips = bitslip_cycles*2*2*nphases, ) # DFI Interface ---------------------------------------------------------------------------- # minimal BL=16, which gives 16*16=256 bits; with 4 phases we need 16/4=4 data widths dfi_params = dict(addressbits=addressbits, bankbits=bankbits, nranks=nranks, databits=4*databits, nphases=nphases) # Register DFI history (from newest to oldest), as we need to operate on 3 subsequent cycles # hist[0] = dfi[N], hist[1] = dfi[N-1], ... self.dfi = dfi = DFIInterface(**dfi_params) dfi_hist = [dfi, DFIInterface(**dfi_params), DFIInterface(**dfi_params)] self.sync += dfi_hist[0].connect(dfi_hist[1], omit={"rddata", "rddata_valid"}) self.sync += dfi_hist[1].connect(dfi_hist[2], omit={"rddata", "rddata_valid"}) # Serialization ---------------------------------------------------------------------------- # We have the following signals that have to be serialized: # - CLK (O) - full-rate clock # - CS (O) - chip select # - STB (O) - serial commands, serial preamble # - DB (IO) - transmits data in/out, data mask, parallel commands # - DQS (IO) - strobe for commands/data/mask on DB pins # DQS is edge-aligned to CLK, while DB and STB are center-aligned to CLK (phase = -90). # Sending a parallel command (on DB pins): # CLK: ____----____----____----____----____----____ # STB: ----------________________------------------ # DQS: ....................----____----____........ # DB: ..........................PPPPnnnn.......... # The signals prepared by BasePHY will all be phase-aligned. The concrete PHY should shift # them so that DB/STB/CS are delayed by 90 degrees in relation to CLK/DQS. # Signal values (de)serialized during 1 sysclk. # These signals must be populated in specific PHY implementations. self.clk_1ck_out = clk_1ck_out = Signal(2*nphases) self.stb_1ck_out = stb_1ck_out = Signal(2*nphases) self.cs_n_1ck_out = cs_n_1ck_out = Signal(2*nphases) self.dqs_1ck_out = dqs_1ck_out = Signal(2*nphases) self.dqs_1ck_in = dqs_1ck_in = Signal(2*nphases) self.dqs_oe = dqs_oe = Signal() self.db_1ck_out = db_1ck_out = [Signal(2*nphases) for _ in range(databits)] self.db_1ck_in = db_1ck_in = [Signal(2*nphases) for _ in range(databits)] self.db_oe = db_oe = Signal() # Clocks ----------------------------------------------------------------------------------- self.comb += clk_1ck_out.eq(bitpattern("-_-_-_-_")) # DB muxing -------------------------------------------------------------------------------- # Commands allowed by FSM cmd_valid = Signal() # Muxed cmd/data/mask db_1ck_data = [Signal(2*nphases) for _ in range(databits)] db_1ck_mask = [Signal(2*nphases) for _ in range(databits)] db_1ck_cmd = [Signal(2*nphases) for _ in range(databits)] dq_data_en = Signal() dq_mask_en = Signal() dq_cmd_en = Signal() dq_read_stb = Signal() # Output enable when writing cmd/data/mask # Mask is being send during negative half of sysclk self.comb += db_oe.eq(cmd_valid & (dq_data_en | dq_mask_en | dq_cmd_en)) # Mux between cmd/data/mask for i in range(databits): self.comb += \ If(dq_data_en, db_1ck_out[i].eq(db_1ck_data[i]) ).Elif(dq_mask_en, db_1ck_out[i].eq(db_1ck_mask[i]) ).Else( db_1ck_out[i].eq(db_1ck_cmd[i]) ) # Parallel commands ------------------------------------------------------------------------ # We need to insert 2 full-clk cycles of STB=0 before any command, to mark the beginning of # Request Packet. For that reason we use the previous values of DFI commands. To always be # able to meet tCSS, we have to add a delay of 1 more sysclk. # list from oldest to newest: dfi[N-1][p0], dfi[N-1][p1], ..., dfi[N][p0], dfi[N][p1], ... dfi_adapters = [] for phase in dfi_hist[2].phases + dfi_hist[1].phases + dfi_hist[0].phases: adapter = DFIAdapter(phase) self.submodules += adapter dfi_adapters.append(adapter) self.comb += [ # We always send one WORD, which consists of 32 bytes. adapter.bc.eq(0), # Always use fast refresh (equivalent to auto refresh) instead of low-power refresh # (equivalent to self refresh). adapter.ref_op.eq(adapter.REF_OP["FST"]), ] # Serialize commands to DB pins for i in range(databits): # A list of differential DB values using previous DFI coomand: # db_p[p][i], db_n[p][i], db_p[p+1][i], db_n[p+1][i], ... bits = [db for a in dfi_adapters[:nphases] for db in [a.db_p[i], a.db_n[i]]] self.comb += db_1ck_cmd[i].eq(Cat(*bits)) # Commands go on the 2nd cycle, so use previous DFI self.comb += dq_cmd_en.eq(reduce(or_, [a.cmd_valid for a in dfi_adapters[:nphases]])) # Power Up Reset --------------------------------------------------------------------------- # During Power Up, after stabilizing clocks, Power Up Reset must be done. It consists of a # a Parallel Reset followed by two Serial Resets (2x8=16 full-rate cycles = 4 sys cycles). # We use an FSM to make sure that we pass only the commands from the controller that are # supported in the current state. t_reset = 5e-6 t_zqcinit = 1e-6 serial_reset_len = 4 stb_reset_seq = Signal() serial_reset_count = Signal(max=serial_reset_len + 1) # prolong the cmd_valid for the cmd latency (length of history) self.submodules.cmd_valid_sr = ShiftRegister(len(dfi_adapters) // nphases) self.comb += cmd_valid.eq(reduce(or_, self.cmd_valid_sr)) self.submodules.reset_timer = WaitTimer(ceil(t_reset * sys_clk_freq)) self.submodules.zqcinit_timer = WaitTimer(ceil(t_zqcinit * sys_clk_freq)) self.submodules.reset_fsm = fsm = FSM() fsm.act("IDLE", NextValue(serial_reset_count, 0), NextValue(self._reset_done.status, 0), self.cmd_valid_sr.i.eq(dfi_adapters[2*nphases+0].is_cmd("RESET")), If(self.cmd_valid_sr.i, NextState("RESET_RECEIVED") ), ) fsm.act("RESET_RECEIVED", NextState("SERIAL_RESET") ) fsm.act("SERIAL_RESET", self.reset_timer.wait.eq(1), If(serial_reset_count != serial_reset_len, stb_reset_seq.eq(1), NextValue(serial_reset_count, serial_reset_count + 1), ), If(self.reset_timer.done, NextValue(self._reset_done.status, 1), NextState("RESET_DONE") ) ) fsm.act("RESET_DONE", self.cmd_valid_sr.i.eq(dfi_adapters[2*nphases+0].is_cmd(["PRE", "MRS", "ZQC_INIT"])), If(dfi_adapters[2*nphases+0].is_cmd("ZQC_INIT"), NextState("ZQC_INIT") ) ) fsm.act("ZQC_INIT", self.zqcinit_timer.wait.eq(1), If(self.zqcinit_timer.done, NextState("READY") ) ) fsm.act("READY", self._init_done.status.eq(1), self.cmd_valid_sr.i.eq(1), If(dfi_adapters[2*nphases+0].is_cmd("UTR") & (dfi_adapters[2*nphases+0].utr_en == 1), NextState("UTR_MODE") ), If(self._reset_fsm.re, NextState("IDLE") ) ) fsm.act("UTR_MODE", self._init_done.status.eq(1), self.cmd_valid_sr.i.eq(reduce(or_, [dfi_adapters[p].is_cmd(["UTR", "RD"]) for p in [2*nphases, 2*nphases+self.settings.rdphase]])), If(dfi_adapters[2*nphases+0].is_cmd("UTR") & (dfi_adapters[2*nphases+0].utr_en == 0), NextState("READY") ) ) # STB -------------------------------------------------------------------------------------- # Currently not sending any serial commands, but the STB pin must be held low for 2 full # rate cycles before writing a parallel command to activate the DRAM. stb_bits = [] assert self.settings.rdphase == 3 read_sent = [Signal(), Signal()] self.comb += read_sent[0].eq(dfi_adapters[3].cmd_valid & (dfi_adapters[3].is_cmd("RD") | dfi_adapters[3].is_cmd("WR"))) self.sync += read_sent[1].eq(read_sent[0]) for p in range(nphases): # Use cmd from current and prev cycle, depending on which phase the command appears on preamble = (dfi_adapters[p+2].cmd_valid | dfi_adapters[p+1].cmd_valid) & cmd_valid # force 000100xxxxxxxxxx after preamble to generate Burst Stop assert self.settings.rdphase == 3 burst_stop = { 0: [0, 0], 1: [0, 1], 2: [0, 0], 3: [1, 1], }[(p+1)%4] read = read_sent[0] if p == 3 else read_sent[1] burst_stop_zero = [cmd_valid & read & (bs == 0) & self._burst_stop.storage for bs in burst_stop] # We only want to use STB to start parallel commands, serial reset or to send NOPs. NOP # is indicated by the first two bits being high (0b11, and other as "don't care"), so # we can simply hold STB high all the time and reset is zeros for 8 cycles (1 sysclk). # stb_bits += 2 * [~(preamble | stb_reset_seq)] stb_bits += [ ~(preamble | stb_reset_seq | burst_stop_zero[0]), ~(preamble | stb_reset_seq | burst_stop_zero[1]), ] self.comb += stb_1ck_out.eq(Cat(*stb_bits)) # Chip Select ------------------------------------------------------------------------------ # RPC has quite high required time of CS# low before sending a command (tCSS), this means # that we would need 1 more cmd_latency to support it for all standard frequencies. To meet # tCSH we hold CS# low 1 cycle after each command (and for writes until the burst ends). tCSS = 10e-9 tCSH = 5e-9 # CS# is held for 2 sysclks before any command, and 1 sysclk after any command assert 2 * 1/sys_clk_freq >= tCSS, "tCSS not met for commands on phase 0" assert 1 * 1/sys_clk_freq >= tCSH, "tCSH not met for commands on phase 3" cs = Signal() cs_burst_hold = Signal() self.submodules.cs_hold = ShiftRegister(2) # FIXME: currently we hold CS low constantly to avoid problems with signal integrity on our board # lock CS when DFI sends cs_n=0 only on phase 0 (avoids start condition problems) cs_lock = Signal() cs_lock_cond = reduce(and_, [dfi_hist[0].phases[p].cs_n for p in range(1, nphases)]) cs_lock_cond = cs_lock_cond & ~dfi_hist[0].p0.cs_n self.sync += If(cs_lock_cond, cs_lock.eq(1)).Elif(self._reset_fsm.re, cs_lock.eq(0)) _any_cmd_valid = reduce(or_, (a.cmd_valid for a in dfi_adapters)) self.comb += [ # self.cs_hold.i.eq(cmd_valid & (_any_cmd_valid | cs_burst_hold)), # cs.eq(reduce(or_, self.cs_hold.sr)), # cs_n_1ck_out.eq(Replicate(~cs, len(cs_n_1ck_out))), cs_n_1ck_out.eq(Replicate(~cs_lock, len(cs_n_1ck_out))), ] # Data IN ---------------------------------------------------------------------------------- # Synchronize the deserializer because we deserialize over 2 cycles. dq_in_cnt = Signal() self.sync += If(dq_read_stb, dq_in_cnt.eq(~dq_in_cnt)).Else(dq_in_cnt.eq(0)) # Deserialize read data # sys_clk: ------------____________------------____________ # sysx4_clk: ---___---___---___---___---___---___---___---___ # DB num: <0><1><2><3><4><5><6><7><8><9><a><b><c><d><e><f> for i in range(databits): # BL=16 -> 2ck n_1ck = 2*nphases rbits_2ck = Signal(2*n_1ck) rbits_1ck = Signal(n_1ck) self.comb += rbits_1ck.eq(db_1ck_in[i]) self.sync += Case(dq_in_cnt, { 0: rbits_2ck[:n_1ck].eq(rbits_1ck), 1: rbits_2ck[n_1ck:].eq(rbits_1ck), }) bs = BitSlip(len(rbits_2ck), cycles=bitslip_cycles, rst = self.get_rst(i//8, self._rdly_dq_bitslip_rst.re), slp = self.get_inc(i//8, self._rdly_dq_bitslip.re), ) self.submodules += bs self.comb += bs.i.eq(rbits_2ck) for p in range(nphases): self.comb += [ dfi.phases[p].rddata[i+0*databits].eq(bs.o[p*nphases+0]), dfi.phases[p].rddata[i+1*databits].eq(bs.o[p*nphases+1]), dfi.phases[p].rddata[i+2*databits].eq(bs.o[p*nphases+2]), dfi.phases[p].rddata[i+3*databits].eq(bs.o[p*nphases+3]), ] # Data OUT --------------------------------------------------------------------------------- # TODO: add 1 to tWR bacause we need 2 cycles to send data from 1 cycle # Before sending the actual data we have to send 2 32-bit data masks (4 DDR cycles). In the # mask each 0 bit means "write byte" and 1 means "mask byte". The 1st 32-bits mask the first # data WORD (32 bytes), and the 2nd 32-bits mask the last data WORD. Because we always send # 1 WORD of data (BC=0), we don't care about the 2nd mask (can send 1). # # Write data # DFI valid: xxxxxxxxxxxxxxxxxx # sys_clk: ------____________------------____________------------____________ # sysx4_clk: ---___---___---___---___---___---___---___---___---___---___---___ # DB num: <M><M><M><M><0><1><2><3><4><5><6><7><8><9><a><b><c><d><e><f> # Synchronize to 2 cycles, reset counting when dq_data_en turns high. db_cnt = Signal() self.sync += If(dq_data_en, db_cnt.eq(~db_cnt)).Else(db_cnt.eq(0)) for i in range(databits): # Write data --------------------------------------------------------------------------- wbits = [] for p in range(nphases): _dfi = dfi_hist[1] if p < nphases//2 else dfi_hist[2] wbits += [ _dfi.phases[p].wrdata[i+0*databits], _dfi.phases[p].wrdata[i+1*databits], _dfi.phases[p].wrdata[i+2*databits], _dfi.phases[p].wrdata[i+3*databits], ] # Mux datas from 2 cycles to always serialize single cycle. wbits_2ck = [Cat(*wbits[:2*nphases]), Cat(*wbits[2*nphases:])] wbits_1ck = Signal(2*nphases) self.comb += wbits_1ck.eq(Array(wbits_2ck)[db_cnt]) self.comb += db_1ck_data[i].eq(Cat(*wbits_1ck)) # Data mask ---------------------------------------------------------------------------- mask = [ Constant(0), # phase 0 Constant(0), # phase 0 Constant(0), # phase 1 Constant(0), # phase 1 dfi_hist[0].phases[i//8 + 0].wrdata_mask[i%8], # WL-2 dfi_hist[0].phases[i//8 + 2].wrdata_mask[i%8], # WL-2 Constant(1), # WL-1 Constant(1), # WL-1 ] self.comb += db_1ck_mask[i].eq(Cat(*mask)) # DQS -------------------------------------------------------------------------------------- # Strobe pattern can go over 2 sysclk (do not count while transmitting mask) dqs_cnt = Signal() self.sync += If(dqs_oe & (~dq_mask_en), dqs_cnt.eq(~dqs_cnt)).Else(dqs_cnt.eq(0)) pattern_2ck = [Signal(2*nphases), Signal(2*nphases)] self.comb += dqs_1ck_out.eq(Array(pattern_2ck)[dqs_cnt]) # To avoid having to serialize dqs_oe, we serialize predefined pattern on dqs_out # All the patterns will be shifted back 90 degrees! data_pattern = [bitpattern("-_-_-_-_"), bitpattern("-_-_-_-_")] mask_pattern = [bitpattern("__-_-_-_"), bitpattern("-_-_-_-_")] phase_patterns = { 0: [bitpattern("______-_"), bitpattern("-_______")], 1: [bitpattern("________"), bitpattern("-_-_____")], 2: [bitpattern("________"), bitpattern("__-_-___")], 3: [bitpattern("________"), bitpattern("____-_-_")], } pattern_cases = \ If(dq_mask_en, pattern_2ck[0].eq(mask_pattern[0]), pattern_2ck[1].eq(mask_pattern[1]), ).Elif(dq_data_en, pattern_2ck[0].eq(data_pattern[0]), pattern_2ck[1].eq(data_pattern[1]), ).Else( pattern_2ck[0].eq(0), pattern_2ck[1].eq(0), ) any_phase_valid = 0 for p in range(nphases): phase_valid = dfi_adapters[p].cmd_valid | dfi_adapters[nphases+p].cmd_valid pattern_cases = \ If(phase_valid, pattern_2ck[0].eq(phase_patterns[p][0]), pattern_2ck[1].eq(phase_patterns[p][1]), ).Else(pattern_cases) any_phase_valid = any_phase_valid | phase_valid self.comb += pattern_cases self.comb += dqs_oe.eq(cmd_valid & (any_phase_valid | dq_mask_en | dq_data_en)) # Read Control Path ------------------------------------------------------------------------ # Creates a shift register of read commands coming from the DFI interface. This shift # register is used to indicate to the DFI interface that the read data is valid. self.submodules.rddata_en = rddata_en = ShiftRegister(self.settings.read_latency) self.comb += rddata_en.i.eq(dfi.phases[self.settings.rdphase].rddata_en) # -1 because of syncronious assignment self.sync += [phase.rddata_valid.eq(rddata_en[-1]) for phase in dfi.phases] # Strobe high when data from DRAM is available, before we can send it to DFI. self.sync += dq_read_stb.eq(rddata_en[read_db_des_dly-1] | rddata_en[read_db_des_dly-1 + 1]) # Write Control Path ----------------------------------------------------------------------- # Creates a shift register of write commands coming from the DFI interface. This shift # register is used to control DQ/DQS tristates. self.submodules.wrdata_en = wrdata_en = ShiftRegister(self.settings.write_latency + 2 + 1) self.comb += wrdata_en.i.eq(dfi.phases[self.settings.wrphase].wrdata_en & cmd_valid) # DQS Preamble and data mask are transmitted 1 cycle before data, then 2 cycles of data self.comb += dq_mask_en.eq(wrdata_en[write_latency]) self.comb += dq_data_en.eq(wrdata_en[write_latency + 1] | wrdata_en[write_latency + 2]) # Hold CS# low until end of write burst (use a latch as there can only be 1 write at a time) cs_wr_hold = Signal() self.sync += If(wrdata_en[0], cs_wr_hold.eq(1)).Elif(wrdata_en[-1], cs_wr_hold.eq(0)) cs_rd_hold = Signal() self.sync += If(rddata_en[0], cs_rd_hold.eq(1)).Elif(rddata_en[-1], cs_rd_hold.eq(0)) self.comb += cs_burst_hold.eq(cs_wr_hold | cs_rd_hold) # Additional variables for LiteScope ------------------------------------------------------- variables = ["dq_data_en", "dq_mask_en", "dq_cmd_en", "dq_read_stb", "dfi_adapters", "dq_in_cnt", "db_cnt", "dqs_cnt", "rddata_en", "wrdata_en"] for v in variables: setattr(self, v, locals()[v]) def get_rst(self, byte, rst): return (self._dly_sel.storage[byte] & rst) | self._rst.storage def get_inc(self, byte, inc): return self._dly_sel.storage[byte] & inc def do_finalize(self): self.do_clock_serialization(self.clk_1ck_out, self.pads.clk_p, self.pads.clk_n) self.do_stb_serialization(self.stb_1ck_out, self.pads.stb) self.do_dqs_serialization(self.dqs_1ck_out, self.dqs_1ck_in, self.dqs_oe, self.pads.dqs_p, self.pads.dqs_n) self.do_db_serialization(self.db_1ck_out, self.db_1ck_in, self.db_oe, self.pads.db) self.do_cs_serialization(self.cs_n_1ck_out, self.pads.cs_n) # I/O implementation --------------------------------------------------------------------------- def do_clock_serialization(self, clk_1ck_out, clk_p, clk_n): raise NotImplementedError("Serialize the full-rate clock with 90 deg phase delay") def do_stb_serialization(self, stb_1ck_out, stb): raise NotImplementedError("Serialize the STB line") def do_dqs_serialization(self, dqs_1ck_out, dqs_1ck_in, dqs_oe, dqs_p, dqs_n): raise NotImplementedError("Tristate and (de)serialize DQS with 90 deg phase delay") def do_db_serialization(self, db_1ck_out, db_1ck_in, db_oe, db): raise NotImplementedError("Tristate and (de)serialize DB") def do_cs_serialization(self, cs_n_1ck_out, cs_n): raise NotImplementedError("Serialize the chip select line (CS#)")
3b6d593b2cdfe8492c5c1ad82ba6931830d5628e
fa1ad2e2ac7e376fc7cb3b3a6e1bb88eed3e80be
/govern/data-meta/OpenMetadata/ingestion/src/metadata/orm_profiler/sink/file.py
05c456e407d7dbb625d42675c718568b1728ed7b
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
alldatacenter/alldata
7bc7713c9f1d56ad6b8e59ea03206d1073b7e047
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
refs/heads/master
2023-08-05T07:32:25.442740
2023-08-03T13:17:24
2023-08-03T13:17:24
213,321,771
774
250
Apache-2.0
2023-09-06T17:35:32
2019-10-07T07:36:18
null
UTF-8
Python
false
false
2,405
py
file.py
# Copyright 2021 Collate # 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. """ Profiler File Sink """ from pathlib import Path from metadata.config.common import ConfigModel from metadata.ingestion.api.common import Entity from metadata.ingestion.api.sink import Sink, SinkStatus from metadata.orm_profiler.api.models import ProfilerResponse from metadata.utils.logger import profiler_logger logger = profiler_logger() class FileSinkConfig(ConfigModel): filename: str class FileSink(Sink[Entity]): """ Helper sink to save profiler results in a file for analysis """ config: FileSinkConfig report: SinkStatus def __init__( self, config: FileSinkConfig, ): super().__init__() self.config = config self.report = SinkStatus() fpath = Path(self.config.filename) # Build the path if it does not exist if not fpath.parent.is_dir(): Path(self.config.filename).mkdir(parents=True, exist_ok=True) self.file = fpath.open("w", encoding="utf-8") self.wrote_something = False @classmethod def create(cls, config_dict: dict, _): config = FileSinkConfig.parse_obj(config_dict) return cls(config) def write_record(self, record: ProfilerResponse) -> None: if self.wrote_something: self.file.write("\n") self.file.write(f"Profile for: {record.table.fullyQualifiedName.__root__}\n") self.file.write(f"{record.profile.json()}\n") if record.record_tests: self.file.write("\nTest results:\n") self.file.write(f"{record.record_tests.json()}\n") self.wrote_something = True self.report.records_written(record.table.fullyQualifiedName.__root__) def get_status(self): return self.report def close(self): self.file.write("\n]") self.file.close()
7728727cefb5f7cdb300a670b3ef6e8b9b1a7f26
2e6b87dccfaf95eded0c26215f42b584cc0ce393
/tina/pars/simple.py
acdae04ea07dab65382771411e4029120e81dbdd
[ "MIT" ]
permissive
taichi-dev/taichi_three
2d3c4022436777bbd6005a38f8cc27cd1f442430
62596cf36fba1c5a528796c51942ce44ed76292a
refs/heads/master
2023-06-20T19:59:09.218689
2021-07-10T09:32:09
2021-07-10T09:32:09
272,924,688
204
30
MIT
2021-07-10T09:32:10
2020-06-17T08:52:31
Python
UTF-8
Python
false
false
1,485
py
simple.py
from ..common import * @ti.data_oriented class SimpleParticles: def __init__(self, maxpars=65536, radius=0.02): self.verts = ti.Vector.field(3, float, maxpars) self.sizes = ti.field(float, maxpars) self.colors = ti.Vector.field(3, float, maxpars) self.npars = ti.field(int, ()) @ti.materialize_callback def init_pars(): self.sizes.fill(radius) self.colors.fill(1) self.maxpars = maxpars @ti.func def pre_compute(self): pass @ti.func def get_npars(self): return min(self.npars[None], self.maxpars) @ti.func def get_particle_position(self, n): return self.verts[n] @ti.func def get_particle_radius(self, n): return self.sizes[n] @ti.func def get_particle_color(self, n): return self.colors[n] @ti.kernel def set_particles(self, verts: ti.ext_arr()): self.npars[None] = min(verts.shape[0], self.verts.shape[0]) for i in range(self.npars[None]): for k in ti.static(range(3)): self.verts[i][k] = verts[i, k] @ti.kernel def set_particle_radii(self, sizes: ti.ext_arr()): for i in range(self.npars[None]): self.sizes[i] = sizes[i] @ti.kernel def set_particle_colors(self, colors: ti.ext_arr()): for i in range(self.npars[None]): for k in ti.static(range(3)): self.colors[i][k] = colors[i, k]
e1af4812989c89f38f31e5563b1d0bbcb6c54f1f
2853845c003d03db22f67c3303fa1ec333180ae7
/fedlearner/model/crypto/gmpy_math.py
a5d698eb17e06f8b92af923e61d414fd91387737
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
permissive
bytedance/fedlearner
fc1dd2ba2ec88092e83a32732eccea52451ce552
436e4959952c970917ee8f47b920f0a76cd4dd05
refs/heads/master
2023-08-14T23:01:02.875453
2023-05-23T03:44:03
2023-05-23T03:44:03
235,348,659
893
243
Apache-2.0
2023-06-08T07:37:18
2020-01-21T13:26:35
Python
UTF-8
Python
false
false
1,466
py
gmpy_math.py
# # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # pylint: disable-all import os import random import gmpy2 POWMOD_GMP_SIZE = pow(2, 64) def powmod(a, b, c): """ return int: (a ** b) % c """ if a == 1: return 1 if max(a, b, c) < POWMOD_GMP_SIZE: return pow(a, b, c) else: return int(gmpy2.powmod(a, b, c)) def invert(a, b): """return int: x, where a * x == 1 mod b """ x = int(gmpy2.invert(a, b)) if x == 0: raise ZeroDivisionError('invert(a, b) no inverse exists') return x def getprimeover(n): """return a random n-bit prime number """ r = gmpy2.mpz(random.SystemRandom().getrandbits(n)) r = gmpy2.bit_set(r, n - 1) return int(gmpy2.next_prime(r)) def isqrt(n): """ return the integer square root of N """ return int(gmpy2.isqrt(n))
d5fe30ed26f4347188ce3c3c905ede60974aa235
d1c2d00078520cd556f60b7213c27856f8b3460d
/sdks/python/apache_beam/utils/windowed_value_test.py
1e4892aa9bd32893c3f88e416549df5ae7d18347
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-protobuf", "Apache-2.0", "Python-2.0" ]
permissive
apache/beam
ed11b9e043465c720659eac20ac71b5b171bfa88
6d5048e05087ea54abc889ce402ae2a0abb9252b
refs/heads/master
2023-09-04T07:41:07.002653
2023-09-01T23:01:05
2023-09-01T23:01:05
50,904,245
7,061
4,522
Apache-2.0
2023-09-14T21:43:38
2016-02-02T08:00:06
Java
UTF-8
Python
false
false
6,410
py
windowed_value_test.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # """Unit tests for the windowed_value.""" # pytype: skip-file import copy import itertools import pickle import unittest from parameterized import parameterized from parameterized import parameterized_class from apache_beam.utils import windowed_value from apache_beam.utils.timestamp import Timestamp class WindowedValueTest(unittest.TestCase): def test_timestamps(self): wv = windowed_value.WindowedValue(None, 3, ()) self.assertEqual(wv.timestamp, Timestamp.of(3)) self.assertTrue(wv.timestamp is wv.timestamp) self.assertEqual( windowed_value.WindowedValue(None, -2.5, ()).timestamp, Timestamp.of(-2.5)) def test_with_value(self): pane_info = windowed_value.PaneInfo( True, True, windowed_value.PaneInfoTiming.ON_TIME, 0, 0) wv = windowed_value.WindowedValue(1, 3, (), pane_info) self.assertEqual( wv.with_value(10), windowed_value.WindowedValue(10, 3, (), pane_info)) def test_equality(self): self.assertEqual( windowed_value.WindowedValue(1, 3, ()), windowed_value.WindowedValue(1, 3, ())) self.assertNotEqual( windowed_value.WindowedValue(1, 3, ()), windowed_value.WindowedValue(100, 3, ())) self.assertNotEqual( windowed_value.WindowedValue(1, 3, ()), windowed_value.WindowedValue(1, 300, ())) self.assertNotEqual( windowed_value.WindowedValue(1, 3, ()), windowed_value.WindowedValue(1, 300, ((), ))) self.assertNotEqual(windowed_value.WindowedValue(1, 3, ()), object()) def test_hash(self): wv = windowed_value.WindowedValue(1, 3, ()) wv_copy = copy.copy(wv) self.assertFalse(wv is wv_copy) self.assertEqual({wv: 100}.get(wv_copy), 100) def test_pickle(self): pane_info = windowed_value.PaneInfo( True, True, windowed_value.PaneInfoTiming.ON_TIME, 0, 0) wv = windowed_value.WindowedValue(1, 3, (), pane_info) self.assertTrue(pickle.loads(pickle.dumps(wv)) == wv) WINDOWED_BATCH_INSTANCES = [ windowed_value.HomogeneousWindowedBatch.of( None, 3, (), windowed_value.PANE_INFO_UNKNOWN), windowed_value.HomogeneousWindowedBatch.of( None, 3, (), windowed_value.PaneInfo( True, False, windowed_value.PaneInfoTiming.ON_TIME, 0, 0)), ] class WindowedBatchTest(unittest.TestCase): def test_homogeneous_windowed_batch_with_values(self): pane_info = windowed_value.PaneInfo( True, True, windowed_value.PaneInfoTiming.ON_TIME, 0, 0) wb = windowed_value.HomogeneousWindowedBatch.of(['foo', 'bar'], 6, (), pane_info) self.assertEqual( wb.with_values(['baz', 'foo']), windowed_value.HomogeneousWindowedBatch.of(['baz', 'foo'], 6, (), pane_info)) def test_homogeneous_windowed_batch_as_windowed_values(self): pane_info = windowed_value.PaneInfo( True, True, windowed_value.PaneInfoTiming.ON_TIME, 0, 0) wb = windowed_value.HomogeneousWindowedBatch.of(['foo', 'bar'], 3, (), pane_info) self.assertEqual( list(wb.as_windowed_values(iter)), [ windowed_value.WindowedValue('foo', 3, (), pane_info), windowed_value.WindowedValue('bar', 3, (), pane_info) ]) @parameterized.expand(itertools.combinations(WINDOWED_BATCH_INSTANCES, 2)) def test_inequality(self, left_wb, right_wb): self.assertNotEqual(left_wb, right_wb) def test_equals_different_type(self): wb = windowed_value.HomogeneousWindowedBatch.of( None, 3, (), windowed_value.PANE_INFO_UNKNOWN) self.assertNotEqual(wb, object()) def test_homogeneous_from_windowed_values(self): pane_info = windowed_value.PaneInfo( True, True, windowed_value.PaneInfoTiming.ON_TIME, 0, 0) windowed_values = [ windowed_value.WindowedValue('foofoo', 3, (), pane_info), windowed_value.WindowedValue('foobar', 6, (), pane_info), windowed_value.WindowedValue('foobaz', 9, (), pane_info), windowed_value.WindowedValue('barfoo', 3, (), pane_info), windowed_value.WindowedValue('barbar', 6, (), pane_info), windowed_value.WindowedValue('barbaz', 9, (), pane_info), windowed_value.WindowedValue('bazfoo', 3, (), pane_info), windowed_value.WindowedValue('bazbar', 6, (), pane_info), windowed_value.WindowedValue('bazbaz', 9, (), pane_info), ] self.assertEqual( list( windowed_value.WindowedBatch.from_windowed_values( windowed_values, produce_fn=list)), [ windowed_value.HomogeneousWindowedBatch.of( ['foofoo', 'barfoo', 'bazfoo'], 3, (), pane_info), windowed_value.HomogeneousWindowedBatch.of( ['foobar', 'barbar', 'bazbar'], 6, (), pane_info), windowed_value.HomogeneousWindowedBatch.of( ['foobaz', 'barbaz', 'bazbaz'], 9, (), pane_info) ]) @parameterized_class(('wb', ), [(wb, ) for wb in WINDOWED_BATCH_INSTANCES]) class WindowedBatchUtilitiesTest(unittest.TestCase): def test_hash(self): wb_copy = copy.copy(self.wb) self.assertFalse(self.wb is wb_copy) self.assertEqual({self.wb: 100}.get(wb_copy), 100) def test_pickle(self): self.assertTrue(pickle.loads(pickle.dumps(self.wb)) == self.wb) if __name__ == '__main__': unittest.main()
5cfc61169126ab13e2c276fd44b8e30e032d866c
90b974771cff3addd43ded8c62c3667c64045976
/tensorflow_data_validation/statistics/generators/cross_feature_stats_generator.py
bf1c1b183575af9f68bb31af772b6d8de16e55e6
[ "Apache-2.0" ]
permissive
tensorflow/data-validation
84066c9c8db76d6b49bab0cec95113508d86dbdb
606cd26b69f648e1f151c024d38baa6ab1d7d0c8
refs/heads/master
2023-09-01T11:54:32.797061
2023-08-21T19:21:20
2023-08-21T19:21:48
139,463,182
736
180
Apache-2.0
2023-08-14T06:28:47
2018-07-02T15:47:02
Python
UTF-8
Python
false
false
9,872
py
cross_feature_stats_generator.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module that computes cross feature statistics. We compute the following statistics for numeric feature crosses (only univalent feature values are considered): - Standard covariance. E[(X-E[X])*(Y-E[Y])] - Pearson product-moment correlation coefficient. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import math import random from typing import Dict, Iterable, List, Optional, Text import numpy as np import pandas as pd from pandas import DataFrame, Series # pylint: disable=g-multiple-import import pyarrow as pa from tensorflow_data_validation import types from tensorflow_data_validation.statistics.generators import stats_generator from tensorflow_data_validation.utils import stats_util from tfx_bsl.arrow import array_util from tensorflow_metadata.proto.v0 import path_pb2 from tensorflow_metadata.proto.v0 import statistics_pb2 class _PartialCrossFeatureStats(object): """Holds partial cross feature statistics for a feature cross.""" __slots__ = ['sum_x', 'sum_y', 'sum_square_x', 'sum_square_y', 'sum_xy', 'count'] def __init__(self): self.sum_x = 0 self.sum_y = 0 self.sum_square_x = 0 self.sum_square_y = 0 self.sum_xy = 0 self.count = 0 def __iadd__(self, other: '_PartialCrossFeatureStats' ) -> '_PartialCrossFeatureStats': """Merges two partial cross feature statistics.""" self.sum_x += other.sum_x self.sum_y += other.sum_y self.sum_square_x += other.sum_square_x self.sum_square_y += other.sum_square_y self.sum_xy += other.sum_xy self.count += other.count return self def update(self, feature_x: Series, feature_y: Series) -> None: """Updates partial cross feature statistics.""" self.sum_x += feature_x.sum() self.sum_y += feature_y.sum() # pytype: disable=unsupported-operands # typed-pandas self.sum_square_x += (feature_x ** 2).sum() self.sum_square_y += (feature_y ** 2).sum() self.sum_xy += (feature_x * feature_y).sum() # pytype: enable=unsupported-operands # typed-pandas self.count += len(feature_x) CrossFeatureStatsGeneratorAccumulator = Dict[types.FeatureCross, _PartialCrossFeatureStats] class CrossFeatureStatsGenerator(stats_generator.CombinerStatsGenerator): """A combiner statistics generator that computes cross feature statistics. """ def __init__( self, # pylint: disable=useless-super-delegation name: Text = 'CrossFeatureStatsGenerator', feature_crosses: Optional[List[types.FeatureCross]] = None, sample_rate: float = 0.1) -> None: """Initializes cross feature statistics generator. Args: name: An optional unique name associated with the statistics generator. feature_crosses: List of numeric feature crosses for which to compute statistics. If None, we compute statistics for all numeric crosses. sample_rate: Sample rate. """ super(CrossFeatureStatsGenerator, self).__init__(name, None) self._feature_crosses = feature_crosses self._features_needed = None if self._feature_crosses: self._features_needed = set() for (feat_x, feat_y) in self._feature_crosses: self._features_needed.add(feat_x) self._features_needed.add(feat_y) self._sample_rate = sample_rate # Create an accumulator, which maps feature name to the partial stats # associated with the feature. def create_accumulator(self) -> CrossFeatureStatsGeneratorAccumulator: return {} def _get_univalent_values_with_parent_indices( self, examples: pa.RecordBatch) -> Dict[types.FeatureName, DataFrame]: """Extracts univalent values for each feature along with parent indices.""" result = {} for feature_name, feat_arr in zip(examples.schema.names, examples.columns): if (self._features_needed is not None and feature_name not in self._features_needed): continue feature_type = stats_util.get_feature_type_from_arrow_type( feature_name, feat_arr.type) # Only consider crosses of numeric features. # TODO(zhuo): Support numeric features nested under structs. if feature_type in (None, statistics_pb2.FeatureNameStatistics.STRING, statistics_pb2.FeatureNameStatistics.STRUCT): continue value_lengths = np.asarray(array_util.ListLengthsFromListArray(feat_arr)) univalent_parent_indices = set((value_lengths == 1).nonzero()[0]) # If there are no univalent values, continue to the next feature. if not univalent_parent_indices: continue flattened, value_parent_indices = array_util.flatten_nested( feat_arr, True) non_missing_values = np.asarray(flattened) if feature_type == statistics_pb2.FeatureNameStatistics.FLOAT: # Remove any NaN values if present. non_nan_mask = ~np.isnan(non_missing_values) non_missing_values = non_missing_values[non_nan_mask] value_parent_indices = value_parent_indices[non_nan_mask] df = pd.DataFrame({feature_name: non_missing_values, 'parent_index': value_parent_indices}) # Only keep the univalent feature values. df = df[df['parent_index'].isin(univalent_parent_indices)] result[feature_name] = df return result # Incorporates the input (an arrow RecordBatch) into the accumulator. def add_input( self, accumulator: CrossFeatureStatsGeneratorAccumulator, examples: pa.RecordBatch ) -> Dict[types.FeatureCross, _PartialCrossFeatureStats]: if random.random() > self._sample_rate: return accumulator # Cache the values and parent indices for each feature. We cache this to # avoid doing the same computation for a feature multiple times in # each cross. features_for_cross = self._get_univalent_values_with_parent_indices( examples) # Generate crosses of numeric univalent features and update the partial # cross stats. if self._feature_crosses is not None: feature_crosses = self._feature_crosses else: feature_crosses = itertools.combinations( sorted(list(features_for_cross.keys())), 2) for feat_name_x, feat_name_y in feature_crosses: feat_cross = (feat_name_x, feat_name_y) if feat_cross not in accumulator: accumulator[feat_cross] = _PartialCrossFeatureStats() df_x, df_y = (features_for_cross[feat_name_x], features_for_cross[feat_name_y]) # Join based on parent index so that we have the value pairs # corresponding to each example. merged_df = pd.merge(df_x, df_y, on='parent_index') # Update the partial cross stats. accumulator[feat_cross].update(merged_df[feat_name_x], merged_df[feat_name_y]) return accumulator # Merge together a list of cross feature statistics. def merge_accumulators( self, accumulators: Iterable[CrossFeatureStatsGeneratorAccumulator] ) -> CrossFeatureStatsGeneratorAccumulator: it = iter(accumulators) result = next(it) for accumulator in it: for feat_cross, cross_feat_stats in accumulator.items(): if feat_cross not in result: result[feat_cross] = cross_feat_stats else: result[feat_cross] += cross_feat_stats return result # Return final stats as a DatasetFeatureStatistics proto. def extract_output(self, accumulator: CrossFeatureStatsGeneratorAccumulator ) -> statistics_pb2.DatasetFeatureStatistics: # Create a new DatasetFeatureStatistics proto. result = statistics_pb2.DatasetFeatureStatistics() for feat_cross, cross_feat_stats in accumulator.items(): # Construct the CrossFeatureStatistics proto from the partial # cross feature stats. cross_feat_stats_proto = result.cross_features.add() path_x = path_pb2.Path() path_x.step.append(feat_cross[0]) path_y = path_pb2.Path() path_y.step.append(feat_cross[1]) cross_feat_stats_proto.path_x.CopyFrom(path_x) cross_feat_stats_proto.path_y.CopyFrom(path_y) cross_feat_stats_proto.count = cross_feat_stats.count if cross_feat_stats.count > 0: num_cross_stats_proto = statistics_pb2.NumericCrossStatistics() covariance = (cross_feat_stats.sum_xy / cross_feat_stats.count) -\ (cross_feat_stats.sum_x / cross_feat_stats.count) *\ (cross_feat_stats.sum_y / cross_feat_stats.count) num_cross_stats_proto.covariance = covariance std_dev_x = math.sqrt(max( 0, (cross_feat_stats.sum_square_x / cross_feat_stats.count) - math.pow(cross_feat_stats.sum_x / cross_feat_stats.count, 2))) std_dev_y = math.sqrt(max( 0, (cross_feat_stats.sum_square_y / cross_feat_stats.count) - math.pow(cross_feat_stats.sum_y / cross_feat_stats.count, 2))) if std_dev_x != 0 and std_dev_y != 0: correlation = covariance / (std_dev_x * std_dev_y) num_cross_stats_proto.correlation = correlation cross_feat_stats_proto.num_cross_stats.CopyFrom(num_cross_stats_proto) return result
19c000bc5c17a9ab4f39ad1e725a5a2240cc5a45
5b7c2feb27a71837edf526315d413706a6bf82ff
/mmf/datasets/databases/scene_graph_database.py
bc778a2fb4b3e9a37afca4bb80a18eac986b2fb9
[ "BSD-3-Clause" ]
permissive
facebookresearch/mmf
df675223566dc8fb2359aa3e1a2d49db5e3c2b9a
63f76fbcfe2d056b88734fc41a983251d20e6c61
refs/heads/main
2023-08-23T23:40:46.827046
2023-07-11T06:18:50
2023-07-11T06:18:50
138,831,170
2,432
592
NOASSERTION
2023-08-11T20:26:11
2018-06-27T04:52:40
Python
UTF-8
Python
false
false
487
py
scene_graph_database.py
# Copyright (c) Facebook, Inc. and its affiliates. from mmf.datasets.databases.annotation_database import AnnotationDatabase class SceneGraphDatabase(AnnotationDatabase): def __init__(self, config, scene_graph_path, *args, **kwargs): super().__init__(config, scene_graph_path, *args, **kwargs) self.data_dict = {} for item in self.data: self.data_dict[item["image_id"]] = item def __getitem__(self, idx): return self.data_dict[idx]
e8c7b249e221809effac8447acc6cc5298dc6ac7
e210c28eeed9d38eb78c14b3a6388eca1e0e85d8
/nvflare/fuel/utils/fsm.py
b09e62867abcb17a8ebe0039c32b49b694555f45
[ "Apache-2.0" ]
permissive
NVIDIA/NVFlare
5a2d2e4c85a3fd0948e25f1ba510449727529a15
1433290c203bd23f34c29e11795ce592bc067888
refs/heads/main
2023-08-03T09:21:32.779763
2023-07-05T21:17:16
2023-07-05T21:17:16
388,876,833
442
140
Apache-2.0
2023-09-14T19:12:35
2021-07-23T17:26:12
Python
UTF-8
Python
false
false
3,137
py
fsm.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from nvflare.security.logging import secure_format_exception class State(object): def __init__(self, name: str): assert isinstance(name, str), "name must be str but got {}".format(type(name)) name = name.strip() assert len(name) > 0, "name must not be empty" self.name = name self.fsm = None def execute(self, **kwargs): pass def leave(self): pass def enter(self): pass class FSM(object): STATE_NAME_EXIT = "__exit__" def __init__(self, name: str): self.name = name self.props = {} self.states = {} # state name => State self.current_state = None self.error = None def set_prop(self, name, value): self.props[name] = value def get_prop(self, name, default=None): return self.props.get(name, default=default) def add_state(self, state: State): assert isinstance(state, State), "state must be State but got {}".format(type(state)) s = self.states.get(state.name, None) assert s is None, 'duplicate state "{}"'.format(state.name) state.fsm = self self.states[state.name] = state def set_current_state(self, name: str): s = self.states.get(name) assert s, 'unknown state "{}"'.format(name) self.current_state = s def get_current_state(self): return self.current_state def execute(self, **kwargs) -> State: try: self.current_state = self._try_execute(**kwargs) except Exception as e: self.error = f"exception occurred in state execution: {secure_format_exception(e)}" self.current_state = None return self.current_state def _try_execute(self, **kwargs) -> State: assert self.current_state, "FSM has no current state" next_state_name = self.current_state.execute(**kwargs) if next_state_name: if next_state_name == FSM.STATE_NAME_EXIT: # go to the end return None # enter next state next_state = self.states.get(next_state_name, None) assert next_state, 'FSM has no such state "{}"'.format(next_state_name) # leave current state self.current_state.leave() # enter the next state next_state.enter() # change to the new state return next_state else: # stay in current state! return self.current_state
1dfe6c4990af2eb9f4c5ef3e407c9d8bfd472e83
32ebd1bf59f0e9be34363e3c9e34b10d2cf3eb9e
/2021/Misc/blackStab Cloud/Handout/server/server.py
a50cf49b19536eeeec8e21f41cee804be8f9bfe9
[]
no_license
teambi0s/InCTFi
d7fb450ec7b8b08e36dcee656d6111d9bd14127c
b249e5b41dba80bcbfc6ccd986c8fd64d8afa87c
refs/heads/master
2022-07-22T09:54:58.393301
2021-08-19T18:14:40
2021-08-19T18:14:40
152,749,662
139
64
null
2022-07-05T22:14:31
2018-10-12T12:48:23
CSS
UTF-8
Python
false
false
8,701
py
server.py
import socket from time import sleep from blackStab.utils import * from binascii import hexlify, unhexlify from _thread import start_new_thread from blackStab.cloud import console as cshell from blackStab.cloud import accounts as manager def main(host, port): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) except socket.error as msg: logger.error("Could not create socket. Error: " + str(msg)) exit() logger.info("Socket Created") try: s.bind((host, port)) logger.info("Socket Bound to port " + str(port)) except socket.error as msg: logger.error("Bind Failed. Error: {}".format(msg)) exit() s.listen(10) while True: conn, addr = s.accept() logger.info("Connection received from " + addr[0] + ":" + str(addr[1])) start_new_thread(onConnect, (conn,addr)) s.close() def onConnect(conn, addr): console = cshell() account = manager() actions = ["'createVM'", "'ruleAddTCP'", "'ruleAddUDP'", "'scaleMemory'", "'scaleCPU'", "'deleteVM'", "'deleteAccount'", "'statusofmyVM'", "'viewSubscription'", "'listallmyVMs'", "'expandRegion'", "'getmyKey'" ] if(authenticate(conn)): logger.info("{} authenticated".format(addr[0])) put(conn, str(0), makefield=False) else: logger.info("Wrong auth attempt from {}") put(conn, str(-1), makefield=False) conn.close() exit(-1) action_code = get(conn, onlypara=True) if(action_code == 1): logger.info("{} requested register function".format(addr[0])) register(conn, account, addr) elif(action_code == 2): email, password = login(conn, account, addr) logger.info("{} logged in to {}".format(addr[0],email)) else: conn.close() logger.info("{} Bye Bye requested".format(addr[0])) exit() while True: action = get(conn, onlypara=True) if(action == -337): logger.info("{} Bye Bye requested".format(addr[0])) conn.close() exit() elif(action == 0): action = get(conn) if(action not in actions): put(conn, str(-337), makefield=False) conn.close() exit() else: pass if(cmp(action, 'createVM')): logger.info("{} requested {} function".format(addr[0], action)) vmname = get(conn) vmtag = get(conn) imageid = get(conn, onlypara=True) sshkey = get(conn) sshkeyname = get(conn) balance = account.showCredits(email=email) resp = console.createVM(funds=balance, account=hexlify(email.encode() + password.encode()), name=vmname.encode(), tag=vmtag.encode(), imageid=imageid, key=sshkey.encode(), keyname=sshkeyname.encode()) put(conn, str(resp), makefield=False) if(resp == 0): account.useCredits(email=email, credits=150) logger.info("Created VM {} for {}".format(vmtag, email)) elif(cmp(action, 'ruleAddTCP')): logger.info("{} requested {} function".format(addr[0], action)) name = get(conn) port = get(conn, onlypara=True) operation = get(conn, onlypara=True) response = console.modifyFirewall(account=hexlify(email.encode() + password.encode()), name=name.encode(), proto='tcp', port=port, operation=operation) put(conn, str(response), makefield=False) elif(cmp(action, 'ruleAddUDP')): logger.info("{} requested {} function".format(addr[0], action)) name = get(conn) port = get(conn, onlypara=True) operation = get(conn, onlypara=True) response = console.modifyFirewall(account=hexlify(email.encode() + password.encode()), name=name.encode(), proto='udp', port=port, operation=operation) put(conn, str(response), makefield=False) elif(cmp(action, 'scaleMemory')): logger.info("{} requested {} function".format(addr[0], action)) name = get(conn) operation = get(conn, onlypara=True) count = get(conn, onlypara=4) _credits = account.showCredits(email=email) response = console.modifyShape(account=hexlify(email.encode() + password.encode()), balance=_credits, name=name.encode(), resource='ram', count=count, operation=operation) put(conn, str(response), makefield=False) if(response == 0 and operation == 1): account.useCredits(email=email, credits=count*30) elif(cmp(action, 'scaleCPU')): logger.info("{} requested {} function".format(addr[0], action)) name = get(conn) operation = get(conn, onlypara=True) count = get(conn, onlypara=True) _credits = account.showCredits(email=email) response = console.modifyShape(account=hexlify(email.encode() + password.encode()), balance=_credits, name=name.encode(), resource='cpu', count=count, operation=operation) put(conn, str(response), makefield=False) if(response == 0 and operation == 1): account.useCredits(email=email, credits=count*70) elif(cmp(action, 'deleteVM')): logger.info("{} requested {} function".format(addr[0], action)) name = get(conn) response = console.deleteVM(account=hexlify(email.encode() + password.encode()), name=name.encode()) put(conn, str(response), makefield=False) elif(cmp(action, 'deleteAccount')): logger.info("{} requested {} function".format(addr[0], action)) password = get(conn) response = account.removeAccount(email=email, password=password) console.removeAccount(account=hexlify(email.encode()+password.encode()), challenge=True) put(conn, str(response), makefield=False) if(response == 0): logger.info("Deleted account of {} : Request from {}".format(email, addr[0])) conn.close() exit() else: pass elif(cmp(action, 'statusofmyVM')): logger.info("{} requested {} function".format(addr[0], action)) name = get(conn) status = console.statusofVM(account=hexlify(email.encode() + password.encode()), name=name.encode()) put(conn, str(status)) elif(cmp(action, 'viewSubscription')): logger.info("{} requested {} function".format(addr[0], action)) credits_left = account.showCredits(email=email) put(conn, str(credits_left), makefield=False) elif(cmp(action, 'listallmyVMs')): logger.info("{} requested {} function".format(addr[0], action)) all_my_vms = console.listmyVMs(account=hexlify(email.encode() + password.encode())) if(all_my_vms == 0): put(conn, str(0), makefield=False) else: count = len(all_my_vms) put(conn, str(all_my_vms)) elif(cmp(action, 'getmyKey')): logger.info("{} requested {} function".format(addr[0], action)) name = get(conn) keyname = get(conn) key = console.getmykey(account=hexlify(email.encode()+password.encode()), name=name.encode(), keyname=keyname.encode()) put(conn, key) elif(cmp(action, 'expandRegion')): logger.info("{} requested {} function".format(addr[0], action)) allstatus = console.expandregion() if(isprivileged(conn, email)): put(conn, allstatus) else: message = "Authentication Failed :(" put(conn, message) else: logger.warn("Unexpected function call from {} : {}".format(addr[0], action)) conn.send(unhexlify(b'4655434b')) if __name__ == "__main__": main("", 9999)
2f9b4b02564583eabf7dd3fc22efb54721c84925
a1363262959d20fc9b4e1dc12a6a2e97297dd32a
/tftrt/examples-cpp/mnist_demo/mnist_train.py
18d460951df201c86530cd854fb30fe85d1a66e3
[ "Apache-2.0" ]
permissive
tensorflow/tensorrt
cfc1baddc5555cdcfc8be3748df38dc3606374d0
b828e794dea9bd284497e5747152f4efae43b947
refs/heads/master
2023-08-24T15:07:13.756635
2023-02-07T15:57:39
2023-02-07T15:57:54
157,606,202
753
264
Apache-2.0
2022-12-13T12:27:53
2018-11-14T20:22:24
Jupyter Notebook
UTF-8
Python
false
false
2,353
py
mnist_train.py
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import tensorflow as tf from tensorflow.python.compiler.tensorrt import trt_convert as trt from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import tag_constants from tensorflow.python.framework import convert_to_constants import numpy as np mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), #tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.summary() model.input_shape model.fit(x_train, y_train, epochs=5) model.evaluate(x_test, y_test, verbose=2) model.save('mnist_model') print("Model trained and saved under mnist_model") # Load the model, save the variables and save it def get_func_from_saved_model(saved_model_dir): saved_model_loaded = tf.saved_model.load( saved_model_dir, tags=[tag_constants.SERVING]) graph_func = saved_model_loaded.signatures[ signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] return graph_func, saved_model_loaded func, loaded_model = get_func_from_saved_model('mnist_model') # Create frozen func frozen_func = convert_to_constants.convert_variables_to_constants_v2(func) module = tf.Module() module.myfunc = frozen_func tf.saved_model.save(module,'mnist_model_frozen', signatures=frozen_func) print("Model frozen and saved under mnist_model_frozen")
84aae6e1b3538f16eeda8037a5fc32ecb7e11a6a
f8c5b73c9706470c4dd60d523096e18bc448a960
/certbot-dns-nsone/certbot_dns_nsone/_internal/__init__.py
40a095edfd6727c1bdf707073fa7c936068cbf59
[ "Apache-2.0", "MIT" ]
permissive
certbot/certbot
14ab43d76fcf0242d875d551f0d98334c43e7957
b1978ff18837e40d16eedf2090330af53d8ceaa5
refs/heads/master
2023-09-04T00:37:03.739195
2023-08-26T23:19:38
2023-08-26T23:19:38
26,516,210
18,581
3,265
NOASSERTION
2023-09-12T15:18:59
2014-11-12T02:52:20
Python
UTF-8
Python
false
false
72
py
__init__.py
"""Internal implementation of `~certbot_dns_nsone.dns_nsone` plugin."""
56bb47ea9fdf6333e94eade74fe17e0c02f8e22e
091a6200be74bf6577c86f623665bcc24e16b02b
/I2C_Multiple_Same_Address/circuitpython/multi_bme280_4x/code.py
e078c93f6fa445c7f51bdde5cb5c129c342a3887
[ "MIT" ]
permissive
adafruit/Adafruit_Learning_System_Guides
b5f7bce40a16da64e7a79d4b39de032f2cca41d4
5eaa7a15a437c533b89f359a25983e24bb6b5438
refs/heads/main
2023-09-05T18:31:41.621956
2023-09-05T15:36:09
2023-09-05T15:36:09
105,065,494
937
937
MIT
2023-09-12T18:48:53
2017-09-27T20:22:44
C
UTF-8
Python
false
false
1,435
py
code.py
# SPDX-FileCopyrightText: 2022 Carter Nelson for Adafruit Industries # # SPDX-License-Identifier: MIT import time import board import adafruit_tca9548a from adafruit_bme280 import basic as adafruit_bme280 # Create I2C bus as normal i2c = board.I2C() # uses board.SCL and board.SDA # i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller # Create the TCA9548A object and give it the I2C bus tca = adafruit_tca9548a.TCA9548A(i2c) #-------------------------------------------------------------------- # NOTE!!! This is the "special" part of the code # # Create each BME280 using the TCA9548A channel instead of the I2C object bme1 = adafruit_bme280.Adafruit_BME280_I2C(tca[0]) # TCA Channel 0 bme2 = adafruit_bme280.Adafruit_BME280_I2C(tca[1]) # TCA Channel 1 bme3 = adafruit_bme280.Adafruit_BME280_I2C(tca[2]) # TCA Channel 2 bme4 = adafruit_bme280.Adafruit_BME280_I2C(tca[3]) # TCA Channel 3 #-------------------------------------------------------------------- print("Four BME280 Example") while True: # Access each sensor via its instance pressure1 = bme1.pressure pressure2 = bme2.pressure pressure3 = bme3.pressure pressure4 = bme4.pressure print("-"*20) print("BME280 #1 Pressure =", pressure1) print("BME280 #2 Pressure =", pressure2) print("BME280 #3 Pressure =", pressure3) print("BME280 #4 Pressure =", pressure4) time.sleep(1)
72f554db5c9495a811da44b5fc393a84b8d0c2d3
abe6c00f9790df7e6ef20dc02d0b1b225b5020cb
/tests/packaging/test_docker_packager.py
205882bc07c5203c9c08e7a4058b3ddf20adbb81
[ "Apache-2.0" ]
permissive
PrefectHQ/prefect
000e6c5f7df80f76a181f0a30f8661c96417c8bd
2c50d2b64c811c364cbc5faa2b5c80a742572090
refs/heads/main
2023-09-05T20:25:42.965208
2023-09-05T18:58:06
2023-09-05T18:58:06
139,199,684
12,917
1,539
Apache-2.0
2023-09-14T20:25:45
2018-06-29T21:59:26
Python
UTF-8
Python
false
false
8,012
py
test_docker_packager.py
import re import textwrap import warnings from io import BytesIO from pathlib import Path, PurePosixPath from tarfile import TarFile, TarInfo import pytest from prefect.packaging.docker import DockerPackageManifest, DockerPackager from prefect.software.conda import CondaEnvironment from prefect.software.python import PythonEnvironment from prefect.utilities.callables import parameter_schema from prefect.utilities.dockerutils import ( get_prefect_image_name, silence_docker_warnings, ) from . import howdy pytestmark = pytest.mark.skip( reason="These tests are incredibly brittle and causing noise." ) with silence_docker_warnings(): from docker import DockerClient from docker.models.containers import Container IMAGE_ID_PATTERN = re.compile("^sha256:[a-fA-F0-9]{64}$") @pytest.fixture(autouse=True) def silence_user_warnings_about_editable_packages(): # For the duration of these tests, ignore our UserWarning coming from # prefect.software.pip.current_environment_requirements about editable packages; # when working locally, the prefect package is almost always editable with warnings.catch_warnings(): warnings.filterwarnings( "ignore", message="The following requirements will not be installable.*", category=UserWarning, module="prefect.software.pip", ) yield @pytest.fixture def contexts() -> Path: return Path(__file__).parent.parent / "docker" / "contexts" def test_base_image_defaults_to_prefect_base(): packager = DockerPackager() assert packager.base_image == get_prefect_image_name() def test_base_image_defaults_to_conda_flavor_of_prefect_base(): packager = DockerPackager(python_environment=CondaEnvironment()) assert packager.base_image == get_prefect_image_name(flavor="conda") def test_dockerfile_exclusive_with_building(): with pytest.raises(ValueError, match="Either `base_image` or `dockerfile`"): DockerPackager(base_image="yep", dockerfile="nope") def test_python_environment_autodetected_when_building(): packager = DockerPackager(base_image="yep", python_environment=None) assert packager.base_image == "yep" assert packager.python_environment assert packager.python_environment.pip_requirements def test_python_environment_not_autodetected_with_dockerfile(): packager = DockerPackager(dockerfile="Docky") # Test the string representations of the path object because # on Windows, we'll get a WindowsPath object, which isn't # comparable to a PurePosixPath. assert str(packager.dockerfile) == str(PurePosixPath("Docky")) assert not packager.python_environment @pytest.mark.service("docker") async def test_packaging_a_flow_to_local_docker_daemon(prefect_base_image: str): packager = DockerPackager( base_image=prefect_base_image, python_environment=PythonEnvironment( python_version="3.9", pip_requirements=["requests==2.28.0"], ), ) manifest = await packager.package(howdy) assert isinstance(manifest, DockerPackageManifest) assert IMAGE_ID_PATTERN.match(manifest.image) assert manifest.image_flow_location == "/flow.py" assert manifest.flow_name == "howdy" @pytest.mark.service("docker") async def test_packaging_a_flow_to_registry(prefect_base_image: str, registry: str): packager = DockerPackager( base_image=prefect_base_image, python_environment=PythonEnvironment( python_version="3.9", pip_requirements=["requests==2.28.0"], ), registry_url=registry, ) manifest = await packager.package(howdy) assert isinstance(manifest, DockerPackageManifest) assert manifest.image.startswith("localhost:5555/howdy:") assert manifest.image_flow_location == "/flow.py" assert manifest.flow_name == "howdy" @pytest.mark.service("docker") async def test_packaging_a_flow_to_registry_without_scheme( prefect_base_image: str, registry: str ): packager = DockerPackager( base_image=prefect_base_image, python_environment=PythonEnvironment( python_version="3.9", pip_requirements=["requests==2.28.0"], ), registry_url="localhost:5555", ) manifest = await packager.package(howdy) assert isinstance(manifest, DockerPackageManifest) assert manifest.image.startswith("localhost:5555/howdy:") assert manifest.image_flow_location == "/flow.py" assert manifest.flow_name == "howdy" @pytest.fixture def howdy_context(prefect_base_image: str, tmp_path: Path) -> Path: (tmp_path / "Dockerfile").write_text( textwrap.dedent( f""" FROM {prefect_base_image} COPY howdy.py /howdy.py """ ) ) (tmp_path / "howdy.py").write_text( textwrap.dedent( """ from prefect import flow @flow def howdy(name: str) -> str: return f"howdy, {name}!" """ ) ) return tmp_path @pytest.mark.service("docker") async def test_unpackaging_outside_container(howdy_context: Path): # This test is contrived to pretend we're in a Docker container right now and giving # a known test file path as the image_flow_location packager = DockerPackager( dockerfile=howdy_context / "Dockerfile", image_flow_location=str(howdy_context / "howdy.py"), ) manifest = await packager.package(howdy) unpackaged_howdy = await manifest.unpackage() assert unpackaged_howdy("dude") == "howdy, dude!" @pytest.mark.service("docker") async def test_packager_sets_manifest_flow_parameter_schema(howdy_context: Path): packager = DockerPackager( dockerfile=howdy_context / "Dockerfile", image_flow_location=str(howdy_context / "howdy.py"), ) manifest = await packager.package(howdy) assert manifest.flow_parameter_schema == parameter_schema(howdy.fn) @pytest.mark.service("docker") @pytest.mark.flaky(max_runs=3) async def test_unpackaging_inside_container( prefect_base_image: str, docker: DockerClient ): packager = DockerPackager( base_image=prefect_base_image, python_environment=PythonEnvironment( python_version="3.9", pip_requirements=["requests==2.28.0"], ), ) manifest = await packager.package(howdy) assert_unpackaged_flow_works(docker, manifest) @pytest.mark.service("docker") @pytest.mark.flaky(max_runs=3) async def test_custom_dockerfile_unpackaging(howdy_context: Path, docker: DockerClient): packager = DockerPackager( dockerfile=howdy_context / "Dockerfile", image_flow_location="/howdy.py", ) manifest = await packager.package(howdy) assert_unpackaged_flow_works(docker, manifest) @pytest.mark.service("docker") def assert_unpackaged_flow_works(docker: DockerClient, manifest: DockerPackageManifest): test_script = textwrap.dedent( f""" import asyncio from prefect.packaging.docker import DockerPackageManifest manifest = DockerPackageManifest.parse_raw({manifest.json()!r}) flow = asyncio.get_event_loop().run_until_complete(manifest.unpackage()) assert flow('there') == 'howdy, there!' """ ) container: Container = docker.containers.create( manifest.image, command="python /tmp/test.py", ) try: buffer = BytesIO() with TarFile(mode="w", fileobj=buffer) as script_tarball: script_bytes = test_script.encode() info = TarInfo("test.py") info.size = len(script_bytes) script_tarball.addfile(info, BytesIO(script_bytes)) container.put_archive("/tmp", buffer.getvalue()) container.start() response = container.wait() output = container.logs().decode() assert response["StatusCode"] == 0, output finally: container.remove(force=True)
c076231ea11077436d341263e7bc098568a52f5c
278ccf2860d1bd737f5d70136e8a1c309dbea8a8
/kubernetes_py/models/v1/NodeSelectorTerm.py
bc9aceb7c49509aaf85f8f43e6406090d07413df
[ "Apache-2.0" ]
permissive
mnubo/kubernetes-py
3b0f9c0655bcaccb6c3aa172b1d85ce67872d53c
5a3a365375a49ec85ed7a25fe7fce4e74f17be86
refs/heads/master
2021-07-16T20:21:05.161888
2020-04-19T15:21:12
2020-04-19T15:21:12
49,596,156
139
58
Apache-2.0
2021-06-02T01:35:17
2016-01-13T19:22:10
Python
UTF-8
Python
false
false
1,755
py
NodeSelectorTerm.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is subject to the terms and conditions defined in # file 'LICENSE.md', which is part of this source code package. # from kubernetes_py.models.v1.NodeSelectorRequirement import NodeSelectorRequirement from kubernetes_py.utils import is_valid_list class NodeSelectorTerm(object): """ https://kubernetes.io/docs/api-reference/v1.6/#nodeselectorterm-v1-core """ def __init__(self, model=None): super(NodeSelectorTerm, self).__init__() self._match_expressions = [] if model is not None: self._build_with_model(model) def _build_with_model(self, model=None): if "matchExpressions" in model: exps = [] for e in model["matchExpressions"]: exp = NodeSelectorRequirement(e) exps.append(exp) self.match_expressions = exps # ------------------------------------------------------------------------------------- matchExpressions @property def match_expressions(self): return self._match_expressions @match_expressions.setter def match_expressions(self, e=None): if not is_valid_list(e, NodeSelectorRequirement): raise SyntaxError("NodeSelectorTerm: match_expressions: [ {} ] is invalid.".format(e)) self._match_expressions = e # ------------------------------------------------------------------------------------- serialize def serialize(self): data = {} if self.match_expressions: reqs = [] for r in self.match_expressions: req = r.serialize() reqs.append(req) data["matchExpressions"] = reqs return data
9d5d6b9b503c270c63b91a573fae7a2e2602a73e
ca9b7710fbbf465ffc14896f4b32e39f0c0d813c
/pdf-password-breaker/passwordBreaker.py
448ce8c1de8eb9e175404126029f065ed6a9c8f6
[ "MIT" ]
permissive
kudeh/automate-the-boring-stuff-projects
80e782281eeb3bb9d0a3ef2074fa0802b2c04482
6889aa930cb198e52557d4cfe0dd4bbb0da92ef4
refs/heads/master
2022-12-11T09:46:23.765200
2021-07-31T15:00:04
2021-07-31T15:00:04
174,255,855
346
100
MIT
2022-12-08T05:09:11
2019-03-07T02:22:13
Python
UTF-8
Python
false
false
1,070
py
passwordBreaker.py
#! python3 # passwordBreaker.py # Author: Kene Udeh # Source: Automate the Boring stuff with python Ch. 13 Project import os import PyPDF2 def breakPassword(filename): """Breaks a single word password of a PDF Args: filename (str): Filename for encrypted pdf Returns: None """ encryptedFile = open(filename, 'rb') pdfReader = PyPDF2.PdfFileReader(encryptedFile) with open('dictionary.txt') as words: wordList = words.read().split('\n') for word in wordList: wordLower = word.lower() wordCap = word.capitalize() if pdfReader.decrypt(word): return word elif pdfReader.decrypt(wordCap): return wordCap elif pdfReader.decrypt(wordLower): return wordLower return if __name__ == "__main__": pdfWriter = PyPDF2.PdfFileWriter() pdfWriter.encrypt('ASPIRE') encryptedPdf = open('pdf_encrypted.pdf', 'wb') pdfWriter.write(encryptedPdf) encryptedPdf.close() print(breakPassword('pdf_encrypted.pdf'))
a60a0afc2e707e282e3109068ffb9a3b20ee555a
ae9c05da72fccc064d62d551bcf14be24e14baa7
/scripts/zfs_root_gen_bash.py
f3384b2093befa55578cdcd88fc3867653617e45
[]
no_license
openzfs/openzfs-docs
f0c0f6cdbd6aedb3eff321aeb50b6371ec98273a
469f2e4a020138b6497428c48eea584569efcbcb
refs/heads/master
2023-08-10T03:33:54.949182
2023-07-30T17:37:47
2023-07-31T10:40:35
265,646,150
111
208
null
2023-09-13T15:54:14
2020-05-20T17:59:18
Python
UTF-8
Python
false
false
268
py
zfs_root_gen_bash.py
#!/usr/bin/env python3 # # Copyright 2023 Maurice Zhou <yuchen@apvc.uk> # # Released without warranty under the terms of the # Apache License 2.0. import pylit pylit.defaults.code_block_markers['shell'] = '::' pylit.defaults.text_extensions = [".rst"] pylit.main()
86041f64313552f769ca4db1d3aed315b1a420a4
acf80e5a2a68bb5ed929ad158fa98a606009e73b
/sagemaker/28_train_llms_with_qlora/scripts/run_clm.py
771708950549f21e87f348c70c25b83af125e4b7
[ "Apache-2.0" ]
permissive
huggingface/notebooks
cf2faab14557b1503ee2a4d38592a8446ec8a0ee
9a35d43f91529652ce353dfedd73f19c6dd22558
refs/heads/main
2023-08-19T03:37:39.536743
2023-08-18T21:25:09
2023-08-18T21:25:09
272,452,525
2,626
1,227
Apache-2.0
2023-09-12T20:17:28
2020-06-15T13:55:11
Jupyter Notebook
UTF-8
Python
false
false
5,524
py
run_clm.py
import os import argparse from transformers import ( AutoModelForCausalLM, AutoTokenizer, set_seed, default_data_collator, BitsAndBytesConfig, Trainer, TrainingArguments, ) from datasets import load_from_disk import torch from peft import PeftConfig, PeftModel def parse_arge(): """Parse the arguments.""" parser = argparse.ArgumentParser() # add model id and dataset path argument parser.add_argument( "--model_id", type=str, default="google/flan-t5-xl", help="Model id to use for training.", ) parser.add_argument("--dataset_path", type=str, default="lm_dataset", help="Path to dataset.") # add training hyperparameters for epochs, batch size, learning rate, and seed parser.add_argument("--epochs", type=int, default=3, help="Number of epochs to train for.") parser.add_argument( "--per_device_train_batch_size", type=int, default=1, help="Batch size to use for training.", ) parser.add_argument("--lr", type=float, default=5e-5, help="Learning rate to use for training.") parser.add_argument("--seed", type=int, default=42, help="Seed to use for training.") parser.add_argument( "--gradient_checkpointing", type=bool, default=True, help="Path to deepspeed config file.", ) parser.add_argument( "--bf16", type=bool, default=True if torch.cuda.get_device_capability()[0] == 8 else False, help="Whether to use bf16.", ) parser.add_argument( "--merge_weights", type=bool, default=True, help="Whether to merge LoRA weights with base model.", ) args = parser.parse_known_args() return args def create_peft_config(model, gradient_checkpointing=True): from peft import ( get_peft_model, LoraConfig, TaskType, prepare_model_for_kbit_training, ) peft_config = LoraConfig( r=64, lora_alpha=16, target_modules=[ "query_key_value", "dense", "dense_h_to_4h", "dense_4h_to_h", ], lora_dropout=0.1, bias="none", task_type=TaskType.CAUSAL_LM, ) # prepare int-4 model for training model = prepare_model_for_kbit_training(model) if gradient_checkpointing: model.gradient_checkpointing_enable() model = get_peft_model(model, peft_config) model.print_trainable_parameters() return model def training_function(args): # set seed set_seed(args.seed) dataset = load_from_disk(args.dataset_path) # load model from the hub with a bnb config bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, ) model = AutoModelForCausalLM.from_pretrained( args.model_id, use_cache=False if args.gradient_checkpointing else True, # this is needed for gradient checkpointing trust_remote_code=True, # ATTENTION: This allows remote code execution device_map="auto", quantization_config=bnb_config, ) # create peft config model = create_peft_config(model, args.gradient_checkpointing) # Define training args output_dir = "/tmp" training_args = TrainingArguments( output_dir=output_dir, overwrite_output_dir=True, per_device_train_batch_size=args.per_device_train_batch_size, bf16=args.bf16, # Use BF16 if available learning_rate=args.lr, num_train_epochs=args.epochs, gradient_checkpointing=args.gradient_checkpointing, # logging strategies logging_dir=f"{output_dir}/logs", logging_strategy="steps", logging_steps=10, save_strategy="no", ) # Create Trainer instance trainer = Trainer( model=model, args=training_args, train_dataset=dataset, data_collator=default_data_collator, ) # pre-process the model by upcasting the layer norms in float 32 for for name, module in trainer.model.named_modules(): if "norm" in name: module = module.to(torch.float32) # Start training trainer.train() if args.merge_weights: # merge adapter weights with base model and save # save int 4 model trainer.model.save_pretrained(output_dir, safe_serialization=False) # clear memory del model del trainer torch.cuda.empty_cache() from peft import AutoPeftModelForCausalLM # load PEFT model in fp16 offload_folder = "/tmp/offload" model = AutoPeftModelForCausalLM.from_pretrained( output_dir, torch_dtype=torch.float16, low_cpu_mem_usage=True, trust_remote_code=True, # ATTENTION: This allows remote code execution ) # Merge LoRA and base model and save merged_model = model.merge_and_unload() merged_model.save_pretrained("/opt/ml/model/",safe_serialization=True) else: trainer.model.save_pretrained("/opt/ml/model/", safe_serialization=True) # save tokenizer for easy inference tokenizer = AutoTokenizer.from_pretrained(args.model_id, trust_remote_code=True) tokenizer.save_pretrained("/opt/ml/model/") def main(): args, _ = parse_arge() training_function(args) if __name__ == "__main__": main()
fa51aff4c3f598bbabc363e4771d1e07997ce436
0faf534ebb6db6f32279e5bee25b968bd425ce3a
/examples/thread_multithread_top_nexys4/test_thread_multithread_top.py
2eb1b7fd1bd2f262f794fdd5fb3bac2c3c6c3e8a
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
PyHDI/veriloggen
e8647cb2d40737d84e31d6b89c5799bab9cbd583
f2b1b9567150af097eed1b5e79ba2b412854ef43
refs/heads/develop
2023-08-09T10:02:35.626403
2023-08-09T00:50:14
2023-08-09T00:50:14
37,813,184
282
60
Apache-2.0
2023-07-20T03:03:29
2015-06-21T15:05:30
Python
UTF-8
Python
false
false
303,573
py
test_thread_multithread_top.py
from __future__ import absolute_import from __future__ import print_function import veriloggen import thread_multithread_top expected_verilog = """ module test; reg CLK; reg RST; reg btnC; reg btnU; reg btnL; reg btnR; reg btnD; reg [16-1:0] sw; wire [16-1:0] led; blinkled uut ( .CLK(CLK), .RST(RST), .btnC(btnC), .btnU(btnU), .btnL(btnL), .btnR(btnR), .btnD(btnD), .sw(sw), .led(led) ); initial begin $dumpfile("thread_multithread_top.vcd"); $dumpvars(0, uut); end initial begin CLK = 0; forever begin #5 CLK = !CLK; end end initial begin RST = 0; #100; RST = 1; #100; RST = 0; #100000; $finish; end reg [32-1:0] test; localparam test_init = 0; reg signed [32-1:0] _test_i_322; localparam test_1 = 1; localparam test_2 = 2; localparam test_3 = 3; localparam test_4 = 4; localparam test_5 = 5; localparam test_6 = 6; localparam test_7 = 7; localparam test_8 = 8; localparam test_9 = 9; localparam test_10 = 10; localparam test_11 = 11; localparam test_12 = 12; always @(posedge CLK) begin if(RST) begin test <= test_init; _test_i_322 <= 0; end else begin case(test) test_init: begin test <= test_1; end test_1: begin sw <= 0; test <= test_2; end test_2: begin btnC <= 0; test <= test_3; end test_3: begin btnC <= 1; test <= test_4; end test_4: begin _test_i_322 <= 0; test <= test_5; end test_5: begin if(_test_i_322 < 4) begin test <= test_6; end else begin test <= test_12; end end test_6: begin sw <= _test_i_322; test <= test_7; end test_7: begin btnC <= 0; test <= test_8; end test_8: begin btnC <= 1; test <= test_9; end test_9: begin if(!led[15]) begin test <= test_10; end else begin test <= test_11; end end test_10: begin test <= test_9; end test_11: begin _test_i_322 <= _test_i_322 + 1; test <= test_5; end endcase end end endmodule module blinkled ( input CLK, input RST, input btnC, input btnU, input btnL, input btnR, input btnD, input [16-1:0] sw, output [16-1:0] led ); reg [15-1:0] count; reg done; assign led = { done, count }; reg _mymutex_lock_reg; reg [32-1:0] _mymutex_lock_id; reg [64-1:0] _th_myfunc_start; reg [32-1:0] th_blink; localparam th_blink_init = 0; reg signed [32-1:0] _th_blink_polarity_0; reg signed [32-1:0] _th_blink_tid_1; reg [32-1:0] th_myfunc_0; localparam th_myfunc_0_init = 0; reg [32-1:0] th_myfunc_1; localparam th_myfunc_1_init = 0; reg [32-1:0] th_myfunc_2; localparam th_myfunc_2_init = 0; reg [32-1:0] th_myfunc_3; localparam th_myfunc_3_init = 0; reg [32-1:0] th_myfunc_4; localparam th_myfunc_4_init = 0; reg [32-1:0] th_myfunc_5; localparam th_myfunc_5_init = 0; reg [32-1:0] th_myfunc_6; localparam th_myfunc_6_init = 0; reg [32-1:0] th_myfunc_7; localparam th_myfunc_7_init = 0; reg [32-1:0] th_myfunc_8; localparam th_myfunc_8_init = 0; reg [32-1:0] th_myfunc_9; localparam th_myfunc_9_init = 0; reg [32-1:0] th_myfunc_10; localparam th_myfunc_10_init = 0; reg [32-1:0] th_myfunc_11; localparam th_myfunc_11_init = 0; reg [32-1:0] th_myfunc_12; localparam th_myfunc_12_init = 0; reg [32-1:0] th_myfunc_13; localparam th_myfunc_13_init = 0; reg [32-1:0] th_myfunc_14; localparam th_myfunc_14_init = 0; reg [32-1:0] th_myfunc_15; localparam th_myfunc_15_init = 0; reg [32-1:0] th_myfunc_16; localparam th_myfunc_16_init = 0; reg [32-1:0] th_myfunc_17; localparam th_myfunc_17_init = 0; reg [32-1:0] th_myfunc_18; localparam th_myfunc_18_init = 0; reg [32-1:0] th_myfunc_19; localparam th_myfunc_19_init = 0; reg [32-1:0] th_myfunc_20; localparam th_myfunc_20_init = 0; reg [32-1:0] th_myfunc_21; localparam th_myfunc_21_init = 0; reg [32-1:0] th_myfunc_22; localparam th_myfunc_22_init = 0; reg [32-1:0] th_myfunc_23; localparam th_myfunc_23_init = 0; reg [32-1:0] th_myfunc_24; localparam th_myfunc_24_init = 0; reg [32-1:0] th_myfunc_25; localparam th_myfunc_25_init = 0; reg [32-1:0] th_myfunc_26; localparam th_myfunc_26_init = 0; reg [32-1:0] th_myfunc_27; localparam th_myfunc_27_init = 0; reg [32-1:0] th_myfunc_28; localparam th_myfunc_28_init = 0; reg [32-1:0] th_myfunc_29; localparam th_myfunc_29_init = 0; reg [32-1:0] th_myfunc_30; localparam th_myfunc_30_init = 0; reg [32-1:0] th_myfunc_31; localparam th_myfunc_31_init = 0; reg [32-1:0] th_myfunc_32; localparam th_myfunc_32_init = 0; reg [32-1:0] th_myfunc_33; localparam th_myfunc_33_init = 0; reg [32-1:0] th_myfunc_34; localparam th_myfunc_34_init = 0; reg [32-1:0] th_myfunc_35; localparam th_myfunc_35_init = 0; reg [32-1:0] th_myfunc_36; localparam th_myfunc_36_init = 0; reg [32-1:0] th_myfunc_37; localparam th_myfunc_37_init = 0; reg [32-1:0] th_myfunc_38; localparam th_myfunc_38_init = 0; reg [32-1:0] th_myfunc_39; localparam th_myfunc_39_init = 0; reg [32-1:0] th_myfunc_40; localparam th_myfunc_40_init = 0; reg [32-1:0] th_myfunc_41; localparam th_myfunc_41_init = 0; reg [32-1:0] th_myfunc_42; localparam th_myfunc_42_init = 0; reg [32-1:0] th_myfunc_43; localparam th_myfunc_43_init = 0; reg [32-1:0] th_myfunc_44; localparam th_myfunc_44_init = 0; reg [32-1:0] th_myfunc_45; localparam th_myfunc_45_init = 0; reg [32-1:0] th_myfunc_46; localparam th_myfunc_46_init = 0; reg [32-1:0] th_myfunc_47; localparam th_myfunc_47_init = 0; reg [32-1:0] th_myfunc_48; localparam th_myfunc_48_init = 0; reg [32-1:0] th_myfunc_49; localparam th_myfunc_49_init = 0; reg [32-1:0] th_myfunc_50; localparam th_myfunc_50_init = 0; reg [32-1:0] th_myfunc_51; localparam th_myfunc_51_init = 0; reg [32-1:0] th_myfunc_52; localparam th_myfunc_52_init = 0; reg [32-1:0] th_myfunc_53; localparam th_myfunc_53_init = 0; reg [32-1:0] th_myfunc_54; localparam th_myfunc_54_init = 0; reg [32-1:0] th_myfunc_55; localparam th_myfunc_55_init = 0; reg [32-1:0] th_myfunc_56; localparam th_myfunc_56_init = 0; reg [32-1:0] th_myfunc_57; localparam th_myfunc_57_init = 0; reg [32-1:0] th_myfunc_58; localparam th_myfunc_58_init = 0; reg [32-1:0] th_myfunc_59; localparam th_myfunc_59_init = 0; reg [32-1:0] th_myfunc_60; localparam th_myfunc_60_init = 0; reg [32-1:0] th_myfunc_61; localparam th_myfunc_61_init = 0; reg [32-1:0] th_myfunc_62; localparam th_myfunc_62_init = 0; reg [32-1:0] th_myfunc_63; localparam th_myfunc_63_init = 0; reg _th_myfunc_0_called; reg signed [32-1:0] _th_myfunc_0_tid_2; reg signed [32-1:0] _th_myfunc_0_tid_3; reg signed [32-1:0] _th_myfunc_0_time_4; reg signed [32-1:0] _th_myfunc_0_i_5; reg signed [32-1:0] _th_myfunc_0___6; reg _th_myfunc_1_called; reg signed [32-1:0] _th_myfunc_1_tid_7; reg signed [32-1:0] _th_myfunc_1_tid_8; reg signed [32-1:0] _th_myfunc_1_time_9; reg signed [32-1:0] _th_myfunc_1_i_10; reg signed [32-1:0] _th_myfunc_1___11; reg _th_myfunc_2_called; reg signed [32-1:0] _th_myfunc_2_tid_12; reg signed [32-1:0] _th_myfunc_2_tid_13; reg signed [32-1:0] _th_myfunc_2_time_14; reg signed [32-1:0] _th_myfunc_2_i_15; reg signed [32-1:0] _th_myfunc_2___16; reg _th_myfunc_3_called; reg signed [32-1:0] _th_myfunc_3_tid_17; reg signed [32-1:0] _th_myfunc_3_tid_18; reg signed [32-1:0] _th_myfunc_3_time_19; reg signed [32-1:0] _th_myfunc_3_i_20; reg signed [32-1:0] _th_myfunc_3___21; reg _th_myfunc_4_called; reg signed [32-1:0] _th_myfunc_4_tid_22; reg signed [32-1:0] _th_myfunc_4_tid_23; reg signed [32-1:0] _th_myfunc_4_time_24; reg signed [32-1:0] _th_myfunc_4_i_25; reg signed [32-1:0] _th_myfunc_4___26; reg _th_myfunc_5_called; reg signed [32-1:0] _th_myfunc_5_tid_27; reg signed [32-1:0] _th_myfunc_5_tid_28; reg signed [32-1:0] _th_myfunc_5_time_29; reg signed [32-1:0] _th_myfunc_5_i_30; reg signed [32-1:0] _th_myfunc_5___31; reg _th_myfunc_6_called; reg signed [32-1:0] _th_myfunc_6_tid_32; reg signed [32-1:0] _th_myfunc_6_tid_33; reg signed [32-1:0] _th_myfunc_6_time_34; reg signed [32-1:0] _th_myfunc_6_i_35; reg signed [32-1:0] _th_myfunc_6___36; reg _th_myfunc_7_called; reg signed [32-1:0] _th_myfunc_7_tid_37; reg signed [32-1:0] _th_myfunc_7_tid_38; reg signed [32-1:0] _th_myfunc_7_time_39; reg signed [32-1:0] _th_myfunc_7_i_40; reg signed [32-1:0] _th_myfunc_7___41; reg _th_myfunc_8_called; reg signed [32-1:0] _th_myfunc_8_tid_42; reg signed [32-1:0] _th_myfunc_8_tid_43; reg signed [32-1:0] _th_myfunc_8_time_44; reg signed [32-1:0] _th_myfunc_8_i_45; reg signed [32-1:0] _th_myfunc_8___46; reg _th_myfunc_9_called; reg signed [32-1:0] _th_myfunc_9_tid_47; reg signed [32-1:0] _th_myfunc_9_tid_48; reg signed [32-1:0] _th_myfunc_9_time_49; reg signed [32-1:0] _th_myfunc_9_i_50; reg signed [32-1:0] _th_myfunc_9___51; reg _th_myfunc_10_called; reg signed [32-1:0] _th_myfunc_10_tid_52; reg signed [32-1:0] _th_myfunc_10_tid_53; reg signed [32-1:0] _th_myfunc_10_time_54; reg signed [32-1:0] _th_myfunc_10_i_55; reg signed [32-1:0] _th_myfunc_10___56; reg _th_myfunc_11_called; reg signed [32-1:0] _th_myfunc_11_tid_57; reg signed [32-1:0] _th_myfunc_11_tid_58; reg signed [32-1:0] _th_myfunc_11_time_59; reg signed [32-1:0] _th_myfunc_11_i_60; reg signed [32-1:0] _th_myfunc_11___61; reg _th_myfunc_12_called; reg signed [32-1:0] _th_myfunc_12_tid_62; reg signed [32-1:0] _th_myfunc_12_tid_63; reg signed [32-1:0] _th_myfunc_12_time_64; reg signed [32-1:0] _th_myfunc_12_i_65; reg signed [32-1:0] _th_myfunc_12___66; reg _th_myfunc_13_called; reg signed [32-1:0] _th_myfunc_13_tid_67; reg signed [32-1:0] _th_myfunc_13_tid_68; reg signed [32-1:0] _th_myfunc_13_time_69; reg signed [32-1:0] _th_myfunc_13_i_70; reg signed [32-1:0] _th_myfunc_13___71; reg _th_myfunc_14_called; reg signed [32-1:0] _th_myfunc_14_tid_72; reg signed [32-1:0] _th_myfunc_14_tid_73; reg signed [32-1:0] _th_myfunc_14_time_74; reg signed [32-1:0] _th_myfunc_14_i_75; reg signed [32-1:0] _th_myfunc_14___76; reg _th_myfunc_15_called; reg signed [32-1:0] _th_myfunc_15_tid_77; reg signed [32-1:0] _th_myfunc_15_tid_78; reg signed [32-1:0] _th_myfunc_15_time_79; reg signed [32-1:0] _th_myfunc_15_i_80; reg signed [32-1:0] _th_myfunc_15___81; reg _th_myfunc_16_called; reg signed [32-1:0] _th_myfunc_16_tid_82; reg signed [32-1:0] _th_myfunc_16_tid_83; reg signed [32-1:0] _th_myfunc_16_time_84; reg signed [32-1:0] _th_myfunc_16_i_85; reg signed [32-1:0] _th_myfunc_16___86; reg _th_myfunc_17_called; reg signed [32-1:0] _th_myfunc_17_tid_87; reg signed [32-1:0] _th_myfunc_17_tid_88; reg signed [32-1:0] _th_myfunc_17_time_89; reg signed [32-1:0] _th_myfunc_17_i_90; reg signed [32-1:0] _th_myfunc_17___91; reg _th_myfunc_18_called; reg signed [32-1:0] _th_myfunc_18_tid_92; reg signed [32-1:0] _th_myfunc_18_tid_93; reg signed [32-1:0] _th_myfunc_18_time_94; reg signed [32-1:0] _th_myfunc_18_i_95; reg signed [32-1:0] _th_myfunc_18___96; reg _th_myfunc_19_called; reg signed [32-1:0] _th_myfunc_19_tid_97; reg signed [32-1:0] _th_myfunc_19_tid_98; reg signed [32-1:0] _th_myfunc_19_time_99; reg signed [32-1:0] _th_myfunc_19_i_100; reg signed [32-1:0] _th_myfunc_19___101; reg _th_myfunc_20_called; reg signed [32-1:0] _th_myfunc_20_tid_102; reg signed [32-1:0] _th_myfunc_20_tid_103; reg signed [32-1:0] _th_myfunc_20_time_104; reg signed [32-1:0] _th_myfunc_20_i_105; reg signed [32-1:0] _th_myfunc_20___106; reg _th_myfunc_21_called; reg signed [32-1:0] _th_myfunc_21_tid_107; reg signed [32-1:0] _th_myfunc_21_tid_108; reg signed [32-1:0] _th_myfunc_21_time_109; reg signed [32-1:0] _th_myfunc_21_i_110; reg signed [32-1:0] _th_myfunc_21___111; reg _th_myfunc_22_called; reg signed [32-1:0] _th_myfunc_22_tid_112; reg signed [32-1:0] _th_myfunc_22_tid_113; reg signed [32-1:0] _th_myfunc_22_time_114; reg signed [32-1:0] _th_myfunc_22_i_115; reg signed [32-1:0] _th_myfunc_22___116; reg _th_myfunc_23_called; reg signed [32-1:0] _th_myfunc_23_tid_117; reg signed [32-1:0] _th_myfunc_23_tid_118; reg signed [32-1:0] _th_myfunc_23_time_119; reg signed [32-1:0] _th_myfunc_23_i_120; reg signed [32-1:0] _th_myfunc_23___121; reg _th_myfunc_24_called; reg signed [32-1:0] _th_myfunc_24_tid_122; reg signed [32-1:0] _th_myfunc_24_tid_123; reg signed [32-1:0] _th_myfunc_24_time_124; reg signed [32-1:0] _th_myfunc_24_i_125; reg signed [32-1:0] _th_myfunc_24___126; reg _th_myfunc_25_called; reg signed [32-1:0] _th_myfunc_25_tid_127; reg signed [32-1:0] _th_myfunc_25_tid_128; reg signed [32-1:0] _th_myfunc_25_time_129; reg signed [32-1:0] _th_myfunc_25_i_130; reg signed [32-1:0] _th_myfunc_25___131; reg _th_myfunc_26_called; reg signed [32-1:0] _th_myfunc_26_tid_132; reg signed [32-1:0] _th_myfunc_26_tid_133; reg signed [32-1:0] _th_myfunc_26_time_134; reg signed [32-1:0] _th_myfunc_26_i_135; reg signed [32-1:0] _th_myfunc_26___136; reg _th_myfunc_27_called; reg signed [32-1:0] _th_myfunc_27_tid_137; reg signed [32-1:0] _th_myfunc_27_tid_138; reg signed [32-1:0] _th_myfunc_27_time_139; reg signed [32-1:0] _th_myfunc_27_i_140; reg signed [32-1:0] _th_myfunc_27___141; reg _th_myfunc_28_called; reg signed [32-1:0] _th_myfunc_28_tid_142; reg signed [32-1:0] _th_myfunc_28_tid_143; reg signed [32-1:0] _th_myfunc_28_time_144; reg signed [32-1:0] _th_myfunc_28_i_145; reg signed [32-1:0] _th_myfunc_28___146; reg _th_myfunc_29_called; reg signed [32-1:0] _th_myfunc_29_tid_147; reg signed [32-1:0] _th_myfunc_29_tid_148; reg signed [32-1:0] _th_myfunc_29_time_149; reg signed [32-1:0] _th_myfunc_29_i_150; reg signed [32-1:0] _th_myfunc_29___151; reg _th_myfunc_30_called; reg signed [32-1:0] _th_myfunc_30_tid_152; reg signed [32-1:0] _th_myfunc_30_tid_153; reg signed [32-1:0] _th_myfunc_30_time_154; reg signed [32-1:0] _th_myfunc_30_i_155; reg signed [32-1:0] _th_myfunc_30___156; reg _th_myfunc_31_called; reg signed [32-1:0] _th_myfunc_31_tid_157; reg signed [32-1:0] _th_myfunc_31_tid_158; reg signed [32-1:0] _th_myfunc_31_time_159; reg signed [32-1:0] _th_myfunc_31_i_160; reg signed [32-1:0] _th_myfunc_31___161; reg _th_myfunc_32_called; reg signed [32-1:0] _th_myfunc_32_tid_162; reg signed [32-1:0] _th_myfunc_32_tid_163; reg signed [32-1:0] _th_myfunc_32_time_164; reg signed [32-1:0] _th_myfunc_32_i_165; reg signed [32-1:0] _th_myfunc_32___166; reg _th_myfunc_33_called; reg signed [32-1:0] _th_myfunc_33_tid_167; reg signed [32-1:0] _th_myfunc_33_tid_168; reg signed [32-1:0] _th_myfunc_33_time_169; reg signed [32-1:0] _th_myfunc_33_i_170; reg signed [32-1:0] _th_myfunc_33___171; reg _th_myfunc_34_called; reg signed [32-1:0] _th_myfunc_34_tid_172; reg signed [32-1:0] _th_myfunc_34_tid_173; reg signed [32-1:0] _th_myfunc_34_time_174; reg signed [32-1:0] _th_myfunc_34_i_175; reg signed [32-1:0] _th_myfunc_34___176; reg _th_myfunc_35_called; reg signed [32-1:0] _th_myfunc_35_tid_177; reg signed [32-1:0] _th_myfunc_35_tid_178; reg signed [32-1:0] _th_myfunc_35_time_179; reg signed [32-1:0] _th_myfunc_35_i_180; reg signed [32-1:0] _th_myfunc_35___181; reg _th_myfunc_36_called; reg signed [32-1:0] _th_myfunc_36_tid_182; reg signed [32-1:0] _th_myfunc_36_tid_183; reg signed [32-1:0] _th_myfunc_36_time_184; reg signed [32-1:0] _th_myfunc_36_i_185; reg signed [32-1:0] _th_myfunc_36___186; reg _th_myfunc_37_called; reg signed [32-1:0] _th_myfunc_37_tid_187; reg signed [32-1:0] _th_myfunc_37_tid_188; reg signed [32-1:0] _th_myfunc_37_time_189; reg signed [32-1:0] _th_myfunc_37_i_190; reg signed [32-1:0] _th_myfunc_37___191; reg _th_myfunc_38_called; reg signed [32-1:0] _th_myfunc_38_tid_192; reg signed [32-1:0] _th_myfunc_38_tid_193; reg signed [32-1:0] _th_myfunc_38_time_194; reg signed [32-1:0] _th_myfunc_38_i_195; reg signed [32-1:0] _th_myfunc_38___196; reg _th_myfunc_39_called; reg signed [32-1:0] _th_myfunc_39_tid_197; reg signed [32-1:0] _th_myfunc_39_tid_198; reg signed [32-1:0] _th_myfunc_39_time_199; reg signed [32-1:0] _th_myfunc_39_i_200; reg signed [32-1:0] _th_myfunc_39___201; reg _th_myfunc_40_called; reg signed [32-1:0] _th_myfunc_40_tid_202; reg signed [32-1:0] _th_myfunc_40_tid_203; reg signed [32-1:0] _th_myfunc_40_time_204; reg signed [32-1:0] _th_myfunc_40_i_205; reg signed [32-1:0] _th_myfunc_40___206; reg _th_myfunc_41_called; reg signed [32-1:0] _th_myfunc_41_tid_207; reg signed [32-1:0] _th_myfunc_41_tid_208; reg signed [32-1:0] _th_myfunc_41_time_209; reg signed [32-1:0] _th_myfunc_41_i_210; reg signed [32-1:0] _th_myfunc_41___211; reg _th_myfunc_42_called; reg signed [32-1:0] _th_myfunc_42_tid_212; reg signed [32-1:0] _th_myfunc_42_tid_213; reg signed [32-1:0] _th_myfunc_42_time_214; reg signed [32-1:0] _th_myfunc_42_i_215; reg signed [32-1:0] _th_myfunc_42___216; reg _th_myfunc_43_called; reg signed [32-1:0] _th_myfunc_43_tid_217; reg signed [32-1:0] _th_myfunc_43_tid_218; reg signed [32-1:0] _th_myfunc_43_time_219; reg signed [32-1:0] _th_myfunc_43_i_220; reg signed [32-1:0] _th_myfunc_43___221; reg _th_myfunc_44_called; reg signed [32-1:0] _th_myfunc_44_tid_222; reg signed [32-1:0] _th_myfunc_44_tid_223; reg signed [32-1:0] _th_myfunc_44_time_224; reg signed [32-1:0] _th_myfunc_44_i_225; reg signed [32-1:0] _th_myfunc_44___226; reg _th_myfunc_45_called; reg signed [32-1:0] _th_myfunc_45_tid_227; reg signed [32-1:0] _th_myfunc_45_tid_228; reg signed [32-1:0] _th_myfunc_45_time_229; reg signed [32-1:0] _th_myfunc_45_i_230; reg signed [32-1:0] _th_myfunc_45___231; reg _th_myfunc_46_called; reg signed [32-1:0] _th_myfunc_46_tid_232; reg signed [32-1:0] _th_myfunc_46_tid_233; reg signed [32-1:0] _th_myfunc_46_time_234; reg signed [32-1:0] _th_myfunc_46_i_235; reg signed [32-1:0] _th_myfunc_46___236; reg _th_myfunc_47_called; reg signed [32-1:0] _th_myfunc_47_tid_237; reg signed [32-1:0] _th_myfunc_47_tid_238; reg signed [32-1:0] _th_myfunc_47_time_239; reg signed [32-1:0] _th_myfunc_47_i_240; reg signed [32-1:0] _th_myfunc_47___241; reg _th_myfunc_48_called; reg signed [32-1:0] _th_myfunc_48_tid_242; reg signed [32-1:0] _th_myfunc_48_tid_243; reg signed [32-1:0] _th_myfunc_48_time_244; reg signed [32-1:0] _th_myfunc_48_i_245; reg signed [32-1:0] _th_myfunc_48___246; reg _th_myfunc_49_called; reg signed [32-1:0] _th_myfunc_49_tid_247; reg signed [32-1:0] _th_myfunc_49_tid_248; reg signed [32-1:0] _th_myfunc_49_time_249; reg signed [32-1:0] _th_myfunc_49_i_250; reg signed [32-1:0] _th_myfunc_49___251; reg _th_myfunc_50_called; reg signed [32-1:0] _th_myfunc_50_tid_252; reg signed [32-1:0] _th_myfunc_50_tid_253; reg signed [32-1:0] _th_myfunc_50_time_254; reg signed [32-1:0] _th_myfunc_50_i_255; reg signed [32-1:0] _th_myfunc_50___256; reg _th_myfunc_51_called; reg signed [32-1:0] _th_myfunc_51_tid_257; reg signed [32-1:0] _th_myfunc_51_tid_258; reg signed [32-1:0] _th_myfunc_51_time_259; reg signed [32-1:0] _th_myfunc_51_i_260; reg signed [32-1:0] _th_myfunc_51___261; reg _th_myfunc_52_called; reg signed [32-1:0] _th_myfunc_52_tid_262; reg signed [32-1:0] _th_myfunc_52_tid_263; reg signed [32-1:0] _th_myfunc_52_time_264; reg signed [32-1:0] _th_myfunc_52_i_265; reg signed [32-1:0] _th_myfunc_52___266; reg _th_myfunc_53_called; reg signed [32-1:0] _th_myfunc_53_tid_267; reg signed [32-1:0] _th_myfunc_53_tid_268; reg signed [32-1:0] _th_myfunc_53_time_269; reg signed [32-1:0] _th_myfunc_53_i_270; reg signed [32-1:0] _th_myfunc_53___271; reg _th_myfunc_54_called; reg signed [32-1:0] _th_myfunc_54_tid_272; reg signed [32-1:0] _th_myfunc_54_tid_273; reg signed [32-1:0] _th_myfunc_54_time_274; reg signed [32-1:0] _th_myfunc_54_i_275; reg signed [32-1:0] _th_myfunc_54___276; reg _th_myfunc_55_called; reg signed [32-1:0] _th_myfunc_55_tid_277; reg signed [32-1:0] _th_myfunc_55_tid_278; reg signed [32-1:0] _th_myfunc_55_time_279; reg signed [32-1:0] _th_myfunc_55_i_280; reg signed [32-1:0] _th_myfunc_55___281; reg _th_myfunc_56_called; reg signed [32-1:0] _th_myfunc_56_tid_282; reg signed [32-1:0] _th_myfunc_56_tid_283; reg signed [32-1:0] _th_myfunc_56_time_284; reg signed [32-1:0] _th_myfunc_56_i_285; reg signed [32-1:0] _th_myfunc_56___286; reg _th_myfunc_57_called; reg signed [32-1:0] _th_myfunc_57_tid_287; reg signed [32-1:0] _th_myfunc_57_tid_288; reg signed [32-1:0] _th_myfunc_57_time_289; reg signed [32-1:0] _th_myfunc_57_i_290; reg signed [32-1:0] _th_myfunc_57___291; reg _th_myfunc_58_called; reg signed [32-1:0] _th_myfunc_58_tid_292; reg signed [32-1:0] _th_myfunc_58_tid_293; reg signed [32-1:0] _th_myfunc_58_time_294; reg signed [32-1:0] _th_myfunc_58_i_295; reg signed [32-1:0] _th_myfunc_58___296; reg _th_myfunc_59_called; reg signed [32-1:0] _th_myfunc_59_tid_297; reg signed [32-1:0] _th_myfunc_59_tid_298; reg signed [32-1:0] _th_myfunc_59_time_299; reg signed [32-1:0] _th_myfunc_59_i_300; reg signed [32-1:0] _th_myfunc_59___301; reg _th_myfunc_60_called; reg signed [32-1:0] _th_myfunc_60_tid_302; reg signed [32-1:0] _th_myfunc_60_tid_303; reg signed [32-1:0] _th_myfunc_60_time_304; reg signed [32-1:0] _th_myfunc_60_i_305; reg signed [32-1:0] _th_myfunc_60___306; reg _th_myfunc_61_called; reg signed [32-1:0] _th_myfunc_61_tid_307; reg signed [32-1:0] _th_myfunc_61_tid_308; reg signed [32-1:0] _th_myfunc_61_time_309; reg signed [32-1:0] _th_myfunc_61_i_310; reg signed [32-1:0] _th_myfunc_61___311; reg _th_myfunc_62_called; reg signed [32-1:0] _th_myfunc_62_tid_312; reg signed [32-1:0] _th_myfunc_62_tid_313; reg signed [32-1:0] _th_myfunc_62_time_314; reg signed [32-1:0] _th_myfunc_62_i_315; reg signed [32-1:0] _th_myfunc_62___316; reg _th_myfunc_63_called; reg signed [32-1:0] _th_myfunc_63_tid_317; reg signed [32-1:0] _th_myfunc_63_tid_318; reg signed [32-1:0] _th_myfunc_63_time_319; reg signed [32-1:0] _th_myfunc_63_i_320; reg signed [32-1:0] _th_myfunc_63___321; always @(posedge CLK) begin if(RST) begin _mymutex_lock_reg <= 0; _mymutex_lock_id <= 0; end else begin if((th_myfunc_0 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 0; end if((th_myfunc_0 == 14) && (_mymutex_lock_id == 0)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_1 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 1; end if((th_myfunc_1 == 14) && (_mymutex_lock_id == 1)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_2 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 2; end if((th_myfunc_2 == 14) && (_mymutex_lock_id == 2)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_3 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 3; end if((th_myfunc_3 == 14) && (_mymutex_lock_id == 3)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_4 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 4; end if((th_myfunc_4 == 14) && (_mymutex_lock_id == 4)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_5 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 5; end if((th_myfunc_5 == 14) && (_mymutex_lock_id == 5)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_6 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 6; end if((th_myfunc_6 == 14) && (_mymutex_lock_id == 6)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_7 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 7; end if((th_myfunc_7 == 14) && (_mymutex_lock_id == 7)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_8 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 8; end if((th_myfunc_8 == 14) && (_mymutex_lock_id == 8)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_9 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 9; end if((th_myfunc_9 == 14) && (_mymutex_lock_id == 9)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_10 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 10; end if((th_myfunc_10 == 14) && (_mymutex_lock_id == 10)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_11 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 11; end if((th_myfunc_11 == 14) && (_mymutex_lock_id == 11)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_12 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 12; end if((th_myfunc_12 == 14) && (_mymutex_lock_id == 12)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_13 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 13; end if((th_myfunc_13 == 14) && (_mymutex_lock_id == 13)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_14 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 14; end if((th_myfunc_14 == 14) && (_mymutex_lock_id == 14)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_15 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 15; end if((th_myfunc_15 == 14) && (_mymutex_lock_id == 15)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_16 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 16; end if((th_myfunc_16 == 14) && (_mymutex_lock_id == 16)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_17 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 17; end if((th_myfunc_17 == 14) && (_mymutex_lock_id == 17)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_18 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 18; end if((th_myfunc_18 == 14) && (_mymutex_lock_id == 18)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_19 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 19; end if((th_myfunc_19 == 14) && (_mymutex_lock_id == 19)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_20 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 20; end if((th_myfunc_20 == 14) && (_mymutex_lock_id == 20)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_21 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 21; end if((th_myfunc_21 == 14) && (_mymutex_lock_id == 21)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_22 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 22; end if((th_myfunc_22 == 14) && (_mymutex_lock_id == 22)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_23 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 23; end if((th_myfunc_23 == 14) && (_mymutex_lock_id == 23)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_24 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 24; end if((th_myfunc_24 == 14) && (_mymutex_lock_id == 24)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_25 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 25; end if((th_myfunc_25 == 14) && (_mymutex_lock_id == 25)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_26 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 26; end if((th_myfunc_26 == 14) && (_mymutex_lock_id == 26)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_27 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 27; end if((th_myfunc_27 == 14) && (_mymutex_lock_id == 27)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_28 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 28; end if((th_myfunc_28 == 14) && (_mymutex_lock_id == 28)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_29 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 29; end if((th_myfunc_29 == 14) && (_mymutex_lock_id == 29)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_30 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 30; end if((th_myfunc_30 == 14) && (_mymutex_lock_id == 30)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_31 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 31; end if((th_myfunc_31 == 14) && (_mymutex_lock_id == 31)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_32 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 32; end if((th_myfunc_32 == 14) && (_mymutex_lock_id == 32)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_33 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 33; end if((th_myfunc_33 == 14) && (_mymutex_lock_id == 33)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_34 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 34; end if((th_myfunc_34 == 14) && (_mymutex_lock_id == 34)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_35 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 35; end if((th_myfunc_35 == 14) && (_mymutex_lock_id == 35)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_36 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 36; end if((th_myfunc_36 == 14) && (_mymutex_lock_id == 36)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_37 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 37; end if((th_myfunc_37 == 14) && (_mymutex_lock_id == 37)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_38 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 38; end if((th_myfunc_38 == 14) && (_mymutex_lock_id == 38)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_39 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 39; end if((th_myfunc_39 == 14) && (_mymutex_lock_id == 39)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_40 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 40; end if((th_myfunc_40 == 14) && (_mymutex_lock_id == 40)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_41 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 41; end if((th_myfunc_41 == 14) && (_mymutex_lock_id == 41)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_42 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 42; end if((th_myfunc_42 == 14) && (_mymutex_lock_id == 42)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_43 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 43; end if((th_myfunc_43 == 14) && (_mymutex_lock_id == 43)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_44 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 44; end if((th_myfunc_44 == 14) && (_mymutex_lock_id == 44)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_45 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 45; end if((th_myfunc_45 == 14) && (_mymutex_lock_id == 45)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_46 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 46; end if((th_myfunc_46 == 14) && (_mymutex_lock_id == 46)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_47 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 47; end if((th_myfunc_47 == 14) && (_mymutex_lock_id == 47)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_48 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 48; end if((th_myfunc_48 == 14) && (_mymutex_lock_id == 48)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_49 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 49; end if((th_myfunc_49 == 14) && (_mymutex_lock_id == 49)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_50 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 50; end if((th_myfunc_50 == 14) && (_mymutex_lock_id == 50)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_51 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 51; end if((th_myfunc_51 == 14) && (_mymutex_lock_id == 51)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_52 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 52; end if((th_myfunc_52 == 14) && (_mymutex_lock_id == 52)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_53 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 53; end if((th_myfunc_53 == 14) && (_mymutex_lock_id == 53)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_54 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 54; end if((th_myfunc_54 == 14) && (_mymutex_lock_id == 54)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_55 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 55; end if((th_myfunc_55 == 14) && (_mymutex_lock_id == 55)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_56 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 56; end if((th_myfunc_56 == 14) && (_mymutex_lock_id == 56)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_57 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 57; end if((th_myfunc_57 == 14) && (_mymutex_lock_id == 57)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_58 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 58; end if((th_myfunc_58 == 14) && (_mymutex_lock_id == 58)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_59 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 59; end if((th_myfunc_59 == 14) && (_mymutex_lock_id == 59)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_60 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 60; end if((th_myfunc_60 == 14) && (_mymutex_lock_id == 60)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_61 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 61; end if((th_myfunc_61 == 14) && (_mymutex_lock_id == 61)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_62 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 62; end if((th_myfunc_62 == 14) && (_mymutex_lock_id == 62)) begin _mymutex_lock_reg <= 0; end if((th_myfunc_63 == 2) && !_mymutex_lock_reg) begin _mymutex_lock_reg <= 1; _mymutex_lock_id <= 63; end if((th_myfunc_63 == 14) && (_mymutex_lock_id == 63)) begin _mymutex_lock_reg <= 0; end end end localparam th_blink_1 = 1; localparam th_blink_2 = 2; localparam th_blink_3 = 3; localparam th_blink_4 = 4; localparam th_blink_5 = 5; localparam th_blink_6 = 6; localparam th_blink_7 = 7; localparam th_blink_8 = 8; localparam th_blink_9 = 9; localparam th_blink_10 = 10; localparam th_blink_11 = 11; localparam th_blink_12 = 12; localparam th_blink_13 = 13; localparam th_blink_14 = 14; localparam th_blink_15 = 15; localparam th_blink_16 = 16; localparam th_blink_17 = 17; localparam th_blink_18 = 18; localparam th_blink_19 = 19; localparam th_blink_20 = 20; localparam th_blink_21 = 21; localparam th_blink_22 = 22; always @(posedge CLK) begin if(RST) begin th_blink <= th_blink_init; done <= 0; _th_blink_polarity_0 <= 0; _th_blink_tid_1 <= 0; _th_myfunc_start[_th_blink_tid_1] <= (0 >> _th_blink_tid_1) & 1'd1; end else begin case(th_blink) th_blink_init: begin th_blink <= th_blink_1; end th_blink_1: begin th_blink <= th_blink_2; end th_blink_2: begin if(1) begin th_blink <= th_blink_3; end else begin th_blink <= th_blink_22; end end th_blink_3: begin done <= 0; th_blink <= th_blink_4; end th_blink_4: begin _th_blink_polarity_0 <= 1; th_blink <= th_blink_5; end th_blink_5: begin if(btnC != _th_blink_polarity_0) begin th_blink <= th_blink_6; end else begin th_blink <= th_blink_7; end end th_blink_6: begin th_blink <= th_blink_5; end th_blink_7: begin _th_blink_tid_1 <= 0; th_blink <= th_blink_8; end th_blink_8: begin if(_th_blink_tid_1 < 64) begin th_blink <= th_blink_9; end else begin th_blink <= th_blink_13; end end th_blink_9: begin _th_myfunc_start[_th_blink_tid_1] <= 1; th_blink <= th_blink_10; end th_blink_10: begin th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; th_blink <= th_blink_11; end th_blink_11: begin _th_myfunc_start[_th_blink_tid_1] <= 0; th_blink <= th_blink_12; end th_blink_12: begin _th_blink_tid_1 <= _th_blink_tid_1 + 1; th_blink <= th_blink_8; end th_blink_13: begin _th_blink_tid_1 <= 0; th_blink <= th_blink_14; end th_blink_14: begin if(_th_blink_tid_1 < 64) begin th_blink <= th_blink_15; end else begin th_blink <= th_blink_17; end end th_blink_15: begin if((_th_blink_tid_1 == 0)? th_myfunc_0 == 16 : (_th_blink_tid_1 == 1)? th_myfunc_1 == 16 : (_th_blink_tid_1 == 2)? th_myfunc_2 == 16 : (_th_blink_tid_1 == 3)? th_myfunc_3 == 16 : (_th_blink_tid_1 == 4)? th_myfunc_4 == 16 : (_th_blink_tid_1 == 5)? th_myfunc_5 == 16 : (_th_blink_tid_1 == 6)? th_myfunc_6 == 16 : (_th_blink_tid_1 == 7)? th_myfunc_7 == 16 : (_th_blink_tid_1 == 8)? th_myfunc_8 == 16 : (_th_blink_tid_1 == 9)? th_myfunc_9 == 16 : (_th_blink_tid_1 == 10)? th_myfunc_10 == 16 : (_th_blink_tid_1 == 11)? th_myfunc_11 == 16 : (_th_blink_tid_1 == 12)? th_myfunc_12 == 16 : (_th_blink_tid_1 == 13)? th_myfunc_13 == 16 : (_th_blink_tid_1 == 14)? th_myfunc_14 == 16 : (_th_blink_tid_1 == 15)? th_myfunc_15 == 16 : (_th_blink_tid_1 == 16)? th_myfunc_16 == 16 : (_th_blink_tid_1 == 17)? th_myfunc_17 == 16 : (_th_blink_tid_1 == 18)? th_myfunc_18 == 16 : (_th_blink_tid_1 == 19)? th_myfunc_19 == 16 : (_th_blink_tid_1 == 20)? th_myfunc_20 == 16 : (_th_blink_tid_1 == 21)? th_myfunc_21 == 16 : (_th_blink_tid_1 == 22)? th_myfunc_22 == 16 : (_th_blink_tid_1 == 23)? th_myfunc_23 == 16 : (_th_blink_tid_1 == 24)? th_myfunc_24 == 16 : (_th_blink_tid_1 == 25)? th_myfunc_25 == 16 : (_th_blink_tid_1 == 26)? th_myfunc_26 == 16 : (_th_blink_tid_1 == 27)? th_myfunc_27 == 16 : (_th_blink_tid_1 == 28)? th_myfunc_28 == 16 : (_th_blink_tid_1 == 29)? th_myfunc_29 == 16 : (_th_blink_tid_1 == 30)? th_myfunc_30 == 16 : (_th_blink_tid_1 == 31)? th_myfunc_31 == 16 : (_th_blink_tid_1 == 32)? th_myfunc_32 == 16 : (_th_blink_tid_1 == 33)? th_myfunc_33 == 16 : (_th_blink_tid_1 == 34)? th_myfunc_34 == 16 : (_th_blink_tid_1 == 35)? th_myfunc_35 == 16 : (_th_blink_tid_1 == 36)? th_myfunc_36 == 16 : (_th_blink_tid_1 == 37)? th_myfunc_37 == 16 : (_th_blink_tid_1 == 38)? th_myfunc_38 == 16 : (_th_blink_tid_1 == 39)? th_myfunc_39 == 16 : (_th_blink_tid_1 == 40)? th_myfunc_40 == 16 : (_th_blink_tid_1 == 41)? th_myfunc_41 == 16 : (_th_blink_tid_1 == 42)? th_myfunc_42 == 16 : (_th_blink_tid_1 == 43)? th_myfunc_43 == 16 : (_th_blink_tid_1 == 44)? th_myfunc_44 == 16 : (_th_blink_tid_1 == 45)? th_myfunc_45 == 16 : (_th_blink_tid_1 == 46)? th_myfunc_46 == 16 : (_th_blink_tid_1 == 47)? th_myfunc_47 == 16 : (_th_blink_tid_1 == 48)? th_myfunc_48 == 16 : (_th_blink_tid_1 == 49)? th_myfunc_49 == 16 : (_th_blink_tid_1 == 50)? th_myfunc_50 == 16 : (_th_blink_tid_1 == 51)? th_myfunc_51 == 16 : (_th_blink_tid_1 == 52)? th_myfunc_52 == 16 : (_th_blink_tid_1 == 53)? th_myfunc_53 == 16 : (_th_blink_tid_1 == 54)? th_myfunc_54 == 16 : (_th_blink_tid_1 == 55)? th_myfunc_55 == 16 : (_th_blink_tid_1 == 56)? th_myfunc_56 == 16 : (_th_blink_tid_1 == 57)? th_myfunc_57 == 16 : (_th_blink_tid_1 == 58)? th_myfunc_58 == 16 : (_th_blink_tid_1 == 59)? th_myfunc_59 == 16 : (_th_blink_tid_1 == 60)? th_myfunc_60 == 16 : (_th_blink_tid_1 == 61)? th_myfunc_61 == 16 : (_th_blink_tid_1 == 62)? th_myfunc_62 == 16 : (_th_blink_tid_1 == 63)? th_myfunc_63 == 16 : 0) begin th_blink <= th_blink_16; end end th_blink_16: begin _th_blink_tid_1 <= _th_blink_tid_1 + 1; th_blink <= th_blink_14; end th_blink_17: begin _th_blink_tid_1 <= 0; th_blink <= th_blink_18; end th_blink_18: begin if(_th_blink_tid_1 < 64) begin th_blink <= th_blink_19; end else begin th_blink <= th_blink_20; end end th_blink_19: begin _th_blink_tid_1 <= _th_blink_tid_1 + 1; th_blink <= th_blink_18; end th_blink_20: begin done <= 1; th_blink <= th_blink_21; end th_blink_21: begin th_blink <= th_blink_2; end endcase end end always @(posedge CLK) begin if(RST) begin count <= 0; end else begin if(th_blink == 1) begin count <= 0; end if(th_myfunc_0 == 12) begin count <= count + 1; end if(th_myfunc_1 == 12) begin count <= count + 1; end if(th_myfunc_2 == 12) begin count <= count + 1; end if(th_myfunc_3 == 12) begin count <= count + 1; end if(th_myfunc_4 == 12) begin count <= count + 1; end if(th_myfunc_5 == 12) begin count <= count + 1; end if(th_myfunc_6 == 12) begin count <= count + 1; end if(th_myfunc_7 == 12) begin count <= count + 1; end if(th_myfunc_8 == 12) begin count <= count + 1; end if(th_myfunc_9 == 12) begin count <= count + 1; end if(th_myfunc_10 == 12) begin count <= count + 1; end if(th_myfunc_11 == 12) begin count <= count + 1; end if(th_myfunc_12 == 12) begin count <= count + 1; end if(th_myfunc_13 == 12) begin count <= count + 1; end if(th_myfunc_14 == 12) begin count <= count + 1; end if(th_myfunc_15 == 12) begin count <= count + 1; end if(th_myfunc_16 == 12) begin count <= count + 1; end if(th_myfunc_17 == 12) begin count <= count + 1; end if(th_myfunc_18 == 12) begin count <= count + 1; end if(th_myfunc_19 == 12) begin count <= count + 1; end if(th_myfunc_20 == 12) begin count <= count + 1; end if(th_myfunc_21 == 12) begin count <= count + 1; end if(th_myfunc_22 == 12) begin count <= count + 1; end if(th_myfunc_23 == 12) begin count <= count + 1; end if(th_myfunc_24 == 12) begin count <= count + 1; end if(th_myfunc_25 == 12) begin count <= count + 1; end if(th_myfunc_26 == 12) begin count <= count + 1; end if(th_myfunc_27 == 12) begin count <= count + 1; end if(th_myfunc_28 == 12) begin count <= count + 1; end if(th_myfunc_29 == 12) begin count <= count + 1; end if(th_myfunc_30 == 12) begin count <= count + 1; end if(th_myfunc_31 == 12) begin count <= count + 1; end if(th_myfunc_32 == 12) begin count <= count + 1; end if(th_myfunc_33 == 12) begin count <= count + 1; end if(th_myfunc_34 == 12) begin count <= count + 1; end if(th_myfunc_35 == 12) begin count <= count + 1; end if(th_myfunc_36 == 12) begin count <= count + 1; end if(th_myfunc_37 == 12) begin count <= count + 1; end if(th_myfunc_38 == 12) begin count <= count + 1; end if(th_myfunc_39 == 12) begin count <= count + 1; end if(th_myfunc_40 == 12) begin count <= count + 1; end if(th_myfunc_41 == 12) begin count <= count + 1; end if(th_myfunc_42 == 12) begin count <= count + 1; end if(th_myfunc_43 == 12) begin count <= count + 1; end if(th_myfunc_44 == 12) begin count <= count + 1; end if(th_myfunc_45 == 12) begin count <= count + 1; end if(th_myfunc_46 == 12) begin count <= count + 1; end if(th_myfunc_47 == 12) begin count <= count + 1; end if(th_myfunc_48 == 12) begin count <= count + 1; end if(th_myfunc_49 == 12) begin count <= count + 1; end if(th_myfunc_50 == 12) begin count <= count + 1; end if(th_myfunc_51 == 12) begin count <= count + 1; end if(th_myfunc_52 == 12) begin count <= count + 1; end if(th_myfunc_53 == 12) begin count <= count + 1; end if(th_myfunc_54 == 12) begin count <= count + 1; end if(th_myfunc_55 == 12) begin count <= count + 1; end if(th_myfunc_56 == 12) begin count <= count + 1; end if(th_myfunc_57 == 12) begin count <= count + 1; end if(th_myfunc_58 == 12) begin count <= count + 1; end if(th_myfunc_59 == 12) begin count <= count + 1; end if(th_myfunc_60 == 12) begin count <= count + 1; end if(th_myfunc_61 == 12) begin count <= count + 1; end if(th_myfunc_62 == 12) begin count <= count + 1; end if(th_myfunc_63 == 12) begin count <= count + 1; end end end localparam th_myfunc_0_1 = 1; localparam th_myfunc_0_2 = 2; localparam th_myfunc_0_3 = 3; localparam th_myfunc_0_4 = 4; localparam th_myfunc_0_5 = 5; localparam th_myfunc_0_6 = 6; localparam th_myfunc_0_7 = 7; localparam th_myfunc_0_8 = 8; localparam th_myfunc_0_9 = 9; localparam th_myfunc_0_10 = 10; localparam th_myfunc_0_11 = 11; localparam th_myfunc_0_12 = 12; localparam th_myfunc_0_13 = 13; localparam th_myfunc_0_14 = 14; localparam th_myfunc_0_15 = 15; localparam th_myfunc_0_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_0 <= th_myfunc_0_init; _th_myfunc_0_called <= 0; _th_myfunc_0_tid_2 <= 0; _th_myfunc_0_tid_3 <= 0; _th_myfunc_0_time_4 <= 0; _th_myfunc_0_i_5 <= 0; _th_myfunc_0___6 <= 0; end else begin case(th_myfunc_0) th_myfunc_0_init: begin if(_th_myfunc_start[0] && (th_blink == 10)) begin _th_myfunc_0_called <= 1; end if(_th_myfunc_start[0] && (th_blink == 10)) begin _th_myfunc_0_tid_2 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[0]) begin th_myfunc_0 <= th_myfunc_0_1; end end th_myfunc_0_1: begin _th_myfunc_0_tid_3 <= _th_myfunc_0_tid_2; th_myfunc_0 <= th_myfunc_0_2; end th_myfunc_0_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 0)) begin th_myfunc_0 <= th_myfunc_0_3; end end th_myfunc_0_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 0))) begin th_myfunc_0 <= th_myfunc_0_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 0)) begin th_myfunc_0 <= th_myfunc_0_4; end end th_myfunc_0_4: begin $display("Thread %d Lock", _th_myfunc_0_tid_3); th_myfunc_0 <= th_myfunc_0_5; end th_myfunc_0_5: begin _th_myfunc_0_time_4 <= sw; th_myfunc_0 <= th_myfunc_0_6; end th_myfunc_0_6: begin _th_myfunc_0_i_5 <= 0; th_myfunc_0 <= th_myfunc_0_7; end th_myfunc_0_7: begin if(_th_myfunc_0_i_5 < _th_myfunc_0_time_4) begin th_myfunc_0 <= th_myfunc_0_8; end else begin th_myfunc_0 <= th_myfunc_0_12; end end th_myfunc_0_8: begin _th_myfunc_0___6 <= 0; th_myfunc_0 <= th_myfunc_0_9; end th_myfunc_0_9: begin if(_th_myfunc_0___6 < 1024) begin th_myfunc_0 <= th_myfunc_0_10; end else begin th_myfunc_0 <= th_myfunc_0_11; end end th_myfunc_0_10: begin _th_myfunc_0___6 <= _th_myfunc_0___6 + 1; th_myfunc_0 <= th_myfunc_0_9; end th_myfunc_0_11: begin _th_myfunc_0_i_5 <= _th_myfunc_0_i_5 + 1; th_myfunc_0 <= th_myfunc_0_7; end th_myfunc_0_12: begin th_myfunc_0 <= th_myfunc_0_13; end th_myfunc_0_13: begin $display("Thread %d count = %d", _th_myfunc_0_tid_3, count); th_myfunc_0 <= th_myfunc_0_14; end th_myfunc_0_14: begin th_myfunc_0 <= th_myfunc_0_15; end th_myfunc_0_15: begin $display("Thread %d Unlock", _th_myfunc_0_tid_3); th_myfunc_0 <= th_myfunc_0_16; end th_myfunc_0_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 0)) begin _th_myfunc_0_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 0)) begin th_myfunc_0 <= th_myfunc_0_init; end end endcase end end localparam th_myfunc_1_1 = 1; localparam th_myfunc_1_2 = 2; localparam th_myfunc_1_3 = 3; localparam th_myfunc_1_4 = 4; localparam th_myfunc_1_5 = 5; localparam th_myfunc_1_6 = 6; localparam th_myfunc_1_7 = 7; localparam th_myfunc_1_8 = 8; localparam th_myfunc_1_9 = 9; localparam th_myfunc_1_10 = 10; localparam th_myfunc_1_11 = 11; localparam th_myfunc_1_12 = 12; localparam th_myfunc_1_13 = 13; localparam th_myfunc_1_14 = 14; localparam th_myfunc_1_15 = 15; localparam th_myfunc_1_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_1 <= th_myfunc_1_init; _th_myfunc_1_called <= 0; _th_myfunc_1_tid_7 <= 0; _th_myfunc_1_tid_8 <= 0; _th_myfunc_1_time_9 <= 0; _th_myfunc_1_i_10 <= 0; _th_myfunc_1___11 <= 0; end else begin case(th_myfunc_1) th_myfunc_1_init: begin if(_th_myfunc_start[1] && (th_blink == 10)) begin _th_myfunc_1_called <= 1; end if(_th_myfunc_start[1] && (th_blink == 10)) begin _th_myfunc_1_tid_7 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[1]) begin th_myfunc_1 <= th_myfunc_1_1; end end th_myfunc_1_1: begin _th_myfunc_1_tid_8 <= _th_myfunc_1_tid_7; th_myfunc_1 <= th_myfunc_1_2; end th_myfunc_1_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 1)) begin th_myfunc_1 <= th_myfunc_1_3; end end th_myfunc_1_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 1))) begin th_myfunc_1 <= th_myfunc_1_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 1)) begin th_myfunc_1 <= th_myfunc_1_4; end end th_myfunc_1_4: begin $display("Thread %d Lock", _th_myfunc_1_tid_8); th_myfunc_1 <= th_myfunc_1_5; end th_myfunc_1_5: begin _th_myfunc_1_time_9 <= sw; th_myfunc_1 <= th_myfunc_1_6; end th_myfunc_1_6: begin _th_myfunc_1_i_10 <= 0; th_myfunc_1 <= th_myfunc_1_7; end th_myfunc_1_7: begin if(_th_myfunc_1_i_10 < _th_myfunc_1_time_9) begin th_myfunc_1 <= th_myfunc_1_8; end else begin th_myfunc_1 <= th_myfunc_1_12; end end th_myfunc_1_8: begin _th_myfunc_1___11 <= 0; th_myfunc_1 <= th_myfunc_1_9; end th_myfunc_1_9: begin if(_th_myfunc_1___11 < 1024) begin th_myfunc_1 <= th_myfunc_1_10; end else begin th_myfunc_1 <= th_myfunc_1_11; end end th_myfunc_1_10: begin _th_myfunc_1___11 <= _th_myfunc_1___11 + 1; th_myfunc_1 <= th_myfunc_1_9; end th_myfunc_1_11: begin _th_myfunc_1_i_10 <= _th_myfunc_1_i_10 + 1; th_myfunc_1 <= th_myfunc_1_7; end th_myfunc_1_12: begin th_myfunc_1 <= th_myfunc_1_13; end th_myfunc_1_13: begin $display("Thread %d count = %d", _th_myfunc_1_tid_8, count); th_myfunc_1 <= th_myfunc_1_14; end th_myfunc_1_14: begin th_myfunc_1 <= th_myfunc_1_15; end th_myfunc_1_15: begin $display("Thread %d Unlock", _th_myfunc_1_tid_8); th_myfunc_1 <= th_myfunc_1_16; end th_myfunc_1_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 1)) begin _th_myfunc_1_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 1)) begin th_myfunc_1 <= th_myfunc_1_init; end end endcase end end localparam th_myfunc_2_1 = 1; localparam th_myfunc_2_2 = 2; localparam th_myfunc_2_3 = 3; localparam th_myfunc_2_4 = 4; localparam th_myfunc_2_5 = 5; localparam th_myfunc_2_6 = 6; localparam th_myfunc_2_7 = 7; localparam th_myfunc_2_8 = 8; localparam th_myfunc_2_9 = 9; localparam th_myfunc_2_10 = 10; localparam th_myfunc_2_11 = 11; localparam th_myfunc_2_12 = 12; localparam th_myfunc_2_13 = 13; localparam th_myfunc_2_14 = 14; localparam th_myfunc_2_15 = 15; localparam th_myfunc_2_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_2 <= th_myfunc_2_init; _th_myfunc_2_called <= 0; _th_myfunc_2_tid_12 <= 0; _th_myfunc_2_tid_13 <= 0; _th_myfunc_2_time_14 <= 0; _th_myfunc_2_i_15 <= 0; _th_myfunc_2___16 <= 0; end else begin case(th_myfunc_2) th_myfunc_2_init: begin if(_th_myfunc_start[2] && (th_blink == 10)) begin _th_myfunc_2_called <= 1; end if(_th_myfunc_start[2] && (th_blink == 10)) begin _th_myfunc_2_tid_12 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[2]) begin th_myfunc_2 <= th_myfunc_2_1; end end th_myfunc_2_1: begin _th_myfunc_2_tid_13 <= _th_myfunc_2_tid_12; th_myfunc_2 <= th_myfunc_2_2; end th_myfunc_2_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 2)) begin th_myfunc_2 <= th_myfunc_2_3; end end th_myfunc_2_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 2))) begin th_myfunc_2 <= th_myfunc_2_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 2)) begin th_myfunc_2 <= th_myfunc_2_4; end end th_myfunc_2_4: begin $display("Thread %d Lock", _th_myfunc_2_tid_13); th_myfunc_2 <= th_myfunc_2_5; end th_myfunc_2_5: begin _th_myfunc_2_time_14 <= sw; th_myfunc_2 <= th_myfunc_2_6; end th_myfunc_2_6: begin _th_myfunc_2_i_15 <= 0; th_myfunc_2 <= th_myfunc_2_7; end th_myfunc_2_7: begin if(_th_myfunc_2_i_15 < _th_myfunc_2_time_14) begin th_myfunc_2 <= th_myfunc_2_8; end else begin th_myfunc_2 <= th_myfunc_2_12; end end th_myfunc_2_8: begin _th_myfunc_2___16 <= 0; th_myfunc_2 <= th_myfunc_2_9; end th_myfunc_2_9: begin if(_th_myfunc_2___16 < 1024) begin th_myfunc_2 <= th_myfunc_2_10; end else begin th_myfunc_2 <= th_myfunc_2_11; end end th_myfunc_2_10: begin _th_myfunc_2___16 <= _th_myfunc_2___16 + 1; th_myfunc_2 <= th_myfunc_2_9; end th_myfunc_2_11: begin _th_myfunc_2_i_15 <= _th_myfunc_2_i_15 + 1; th_myfunc_2 <= th_myfunc_2_7; end th_myfunc_2_12: begin th_myfunc_2 <= th_myfunc_2_13; end th_myfunc_2_13: begin $display("Thread %d count = %d", _th_myfunc_2_tid_13, count); th_myfunc_2 <= th_myfunc_2_14; end th_myfunc_2_14: begin th_myfunc_2 <= th_myfunc_2_15; end th_myfunc_2_15: begin $display("Thread %d Unlock", _th_myfunc_2_tid_13); th_myfunc_2 <= th_myfunc_2_16; end th_myfunc_2_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 2)) begin _th_myfunc_2_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 2)) begin th_myfunc_2 <= th_myfunc_2_init; end end endcase end end localparam th_myfunc_3_1 = 1; localparam th_myfunc_3_2 = 2; localparam th_myfunc_3_3 = 3; localparam th_myfunc_3_4 = 4; localparam th_myfunc_3_5 = 5; localparam th_myfunc_3_6 = 6; localparam th_myfunc_3_7 = 7; localparam th_myfunc_3_8 = 8; localparam th_myfunc_3_9 = 9; localparam th_myfunc_3_10 = 10; localparam th_myfunc_3_11 = 11; localparam th_myfunc_3_12 = 12; localparam th_myfunc_3_13 = 13; localparam th_myfunc_3_14 = 14; localparam th_myfunc_3_15 = 15; localparam th_myfunc_3_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_3 <= th_myfunc_3_init; _th_myfunc_3_called <= 0; _th_myfunc_3_tid_17 <= 0; _th_myfunc_3_tid_18 <= 0; _th_myfunc_3_time_19 <= 0; _th_myfunc_3_i_20 <= 0; _th_myfunc_3___21 <= 0; end else begin case(th_myfunc_3) th_myfunc_3_init: begin if(_th_myfunc_start[3] && (th_blink == 10)) begin _th_myfunc_3_called <= 1; end if(_th_myfunc_start[3] && (th_blink == 10)) begin _th_myfunc_3_tid_17 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[3]) begin th_myfunc_3 <= th_myfunc_3_1; end end th_myfunc_3_1: begin _th_myfunc_3_tid_18 <= _th_myfunc_3_tid_17; th_myfunc_3 <= th_myfunc_3_2; end th_myfunc_3_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 3)) begin th_myfunc_3 <= th_myfunc_3_3; end end th_myfunc_3_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 3))) begin th_myfunc_3 <= th_myfunc_3_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 3)) begin th_myfunc_3 <= th_myfunc_3_4; end end th_myfunc_3_4: begin $display("Thread %d Lock", _th_myfunc_3_tid_18); th_myfunc_3 <= th_myfunc_3_5; end th_myfunc_3_5: begin _th_myfunc_3_time_19 <= sw; th_myfunc_3 <= th_myfunc_3_6; end th_myfunc_3_6: begin _th_myfunc_3_i_20 <= 0; th_myfunc_3 <= th_myfunc_3_7; end th_myfunc_3_7: begin if(_th_myfunc_3_i_20 < _th_myfunc_3_time_19) begin th_myfunc_3 <= th_myfunc_3_8; end else begin th_myfunc_3 <= th_myfunc_3_12; end end th_myfunc_3_8: begin _th_myfunc_3___21 <= 0; th_myfunc_3 <= th_myfunc_3_9; end th_myfunc_3_9: begin if(_th_myfunc_3___21 < 1024) begin th_myfunc_3 <= th_myfunc_3_10; end else begin th_myfunc_3 <= th_myfunc_3_11; end end th_myfunc_3_10: begin _th_myfunc_3___21 <= _th_myfunc_3___21 + 1; th_myfunc_3 <= th_myfunc_3_9; end th_myfunc_3_11: begin _th_myfunc_3_i_20 <= _th_myfunc_3_i_20 + 1; th_myfunc_3 <= th_myfunc_3_7; end th_myfunc_3_12: begin th_myfunc_3 <= th_myfunc_3_13; end th_myfunc_3_13: begin $display("Thread %d count = %d", _th_myfunc_3_tid_18, count); th_myfunc_3 <= th_myfunc_3_14; end th_myfunc_3_14: begin th_myfunc_3 <= th_myfunc_3_15; end th_myfunc_3_15: begin $display("Thread %d Unlock", _th_myfunc_3_tid_18); th_myfunc_3 <= th_myfunc_3_16; end th_myfunc_3_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 3)) begin _th_myfunc_3_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 3)) begin th_myfunc_3 <= th_myfunc_3_init; end end endcase end end localparam th_myfunc_4_1 = 1; localparam th_myfunc_4_2 = 2; localparam th_myfunc_4_3 = 3; localparam th_myfunc_4_4 = 4; localparam th_myfunc_4_5 = 5; localparam th_myfunc_4_6 = 6; localparam th_myfunc_4_7 = 7; localparam th_myfunc_4_8 = 8; localparam th_myfunc_4_9 = 9; localparam th_myfunc_4_10 = 10; localparam th_myfunc_4_11 = 11; localparam th_myfunc_4_12 = 12; localparam th_myfunc_4_13 = 13; localparam th_myfunc_4_14 = 14; localparam th_myfunc_4_15 = 15; localparam th_myfunc_4_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_4 <= th_myfunc_4_init; _th_myfunc_4_called <= 0; _th_myfunc_4_tid_22 <= 0; _th_myfunc_4_tid_23 <= 0; _th_myfunc_4_time_24 <= 0; _th_myfunc_4_i_25 <= 0; _th_myfunc_4___26 <= 0; end else begin case(th_myfunc_4) th_myfunc_4_init: begin if(_th_myfunc_start[4] && (th_blink == 10)) begin _th_myfunc_4_called <= 1; end if(_th_myfunc_start[4] && (th_blink == 10)) begin _th_myfunc_4_tid_22 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[4]) begin th_myfunc_4 <= th_myfunc_4_1; end end th_myfunc_4_1: begin _th_myfunc_4_tid_23 <= _th_myfunc_4_tid_22; th_myfunc_4 <= th_myfunc_4_2; end th_myfunc_4_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 4)) begin th_myfunc_4 <= th_myfunc_4_3; end end th_myfunc_4_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 4))) begin th_myfunc_4 <= th_myfunc_4_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 4)) begin th_myfunc_4 <= th_myfunc_4_4; end end th_myfunc_4_4: begin $display("Thread %d Lock", _th_myfunc_4_tid_23); th_myfunc_4 <= th_myfunc_4_5; end th_myfunc_4_5: begin _th_myfunc_4_time_24 <= sw; th_myfunc_4 <= th_myfunc_4_6; end th_myfunc_4_6: begin _th_myfunc_4_i_25 <= 0; th_myfunc_4 <= th_myfunc_4_7; end th_myfunc_4_7: begin if(_th_myfunc_4_i_25 < _th_myfunc_4_time_24) begin th_myfunc_4 <= th_myfunc_4_8; end else begin th_myfunc_4 <= th_myfunc_4_12; end end th_myfunc_4_8: begin _th_myfunc_4___26 <= 0; th_myfunc_4 <= th_myfunc_4_9; end th_myfunc_4_9: begin if(_th_myfunc_4___26 < 1024) begin th_myfunc_4 <= th_myfunc_4_10; end else begin th_myfunc_4 <= th_myfunc_4_11; end end th_myfunc_4_10: begin _th_myfunc_4___26 <= _th_myfunc_4___26 + 1; th_myfunc_4 <= th_myfunc_4_9; end th_myfunc_4_11: begin _th_myfunc_4_i_25 <= _th_myfunc_4_i_25 + 1; th_myfunc_4 <= th_myfunc_4_7; end th_myfunc_4_12: begin th_myfunc_4 <= th_myfunc_4_13; end th_myfunc_4_13: begin $display("Thread %d count = %d", _th_myfunc_4_tid_23, count); th_myfunc_4 <= th_myfunc_4_14; end th_myfunc_4_14: begin th_myfunc_4 <= th_myfunc_4_15; end th_myfunc_4_15: begin $display("Thread %d Unlock", _th_myfunc_4_tid_23); th_myfunc_4 <= th_myfunc_4_16; end th_myfunc_4_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 4)) begin _th_myfunc_4_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 4)) begin th_myfunc_4 <= th_myfunc_4_init; end end endcase end end localparam th_myfunc_5_1 = 1; localparam th_myfunc_5_2 = 2; localparam th_myfunc_5_3 = 3; localparam th_myfunc_5_4 = 4; localparam th_myfunc_5_5 = 5; localparam th_myfunc_5_6 = 6; localparam th_myfunc_5_7 = 7; localparam th_myfunc_5_8 = 8; localparam th_myfunc_5_9 = 9; localparam th_myfunc_5_10 = 10; localparam th_myfunc_5_11 = 11; localparam th_myfunc_5_12 = 12; localparam th_myfunc_5_13 = 13; localparam th_myfunc_5_14 = 14; localparam th_myfunc_5_15 = 15; localparam th_myfunc_5_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_5 <= th_myfunc_5_init; _th_myfunc_5_called <= 0; _th_myfunc_5_tid_27 <= 0; _th_myfunc_5_tid_28 <= 0; _th_myfunc_5_time_29 <= 0; _th_myfunc_5_i_30 <= 0; _th_myfunc_5___31 <= 0; end else begin case(th_myfunc_5) th_myfunc_5_init: begin if(_th_myfunc_start[5] && (th_blink == 10)) begin _th_myfunc_5_called <= 1; end if(_th_myfunc_start[5] && (th_blink == 10)) begin _th_myfunc_5_tid_27 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[5]) begin th_myfunc_5 <= th_myfunc_5_1; end end th_myfunc_5_1: begin _th_myfunc_5_tid_28 <= _th_myfunc_5_tid_27; th_myfunc_5 <= th_myfunc_5_2; end th_myfunc_5_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 5)) begin th_myfunc_5 <= th_myfunc_5_3; end end th_myfunc_5_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 5))) begin th_myfunc_5 <= th_myfunc_5_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 5)) begin th_myfunc_5 <= th_myfunc_5_4; end end th_myfunc_5_4: begin $display("Thread %d Lock", _th_myfunc_5_tid_28); th_myfunc_5 <= th_myfunc_5_5; end th_myfunc_5_5: begin _th_myfunc_5_time_29 <= sw; th_myfunc_5 <= th_myfunc_5_6; end th_myfunc_5_6: begin _th_myfunc_5_i_30 <= 0; th_myfunc_5 <= th_myfunc_5_7; end th_myfunc_5_7: begin if(_th_myfunc_5_i_30 < _th_myfunc_5_time_29) begin th_myfunc_5 <= th_myfunc_5_8; end else begin th_myfunc_5 <= th_myfunc_5_12; end end th_myfunc_5_8: begin _th_myfunc_5___31 <= 0; th_myfunc_5 <= th_myfunc_5_9; end th_myfunc_5_9: begin if(_th_myfunc_5___31 < 1024) begin th_myfunc_5 <= th_myfunc_5_10; end else begin th_myfunc_5 <= th_myfunc_5_11; end end th_myfunc_5_10: begin _th_myfunc_5___31 <= _th_myfunc_5___31 + 1; th_myfunc_5 <= th_myfunc_5_9; end th_myfunc_5_11: begin _th_myfunc_5_i_30 <= _th_myfunc_5_i_30 + 1; th_myfunc_5 <= th_myfunc_5_7; end th_myfunc_5_12: begin th_myfunc_5 <= th_myfunc_5_13; end th_myfunc_5_13: begin $display("Thread %d count = %d", _th_myfunc_5_tid_28, count); th_myfunc_5 <= th_myfunc_5_14; end th_myfunc_5_14: begin th_myfunc_5 <= th_myfunc_5_15; end th_myfunc_5_15: begin $display("Thread %d Unlock", _th_myfunc_5_tid_28); th_myfunc_5 <= th_myfunc_5_16; end th_myfunc_5_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 5)) begin _th_myfunc_5_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 5)) begin th_myfunc_5 <= th_myfunc_5_init; end end endcase end end localparam th_myfunc_6_1 = 1; localparam th_myfunc_6_2 = 2; localparam th_myfunc_6_3 = 3; localparam th_myfunc_6_4 = 4; localparam th_myfunc_6_5 = 5; localparam th_myfunc_6_6 = 6; localparam th_myfunc_6_7 = 7; localparam th_myfunc_6_8 = 8; localparam th_myfunc_6_9 = 9; localparam th_myfunc_6_10 = 10; localparam th_myfunc_6_11 = 11; localparam th_myfunc_6_12 = 12; localparam th_myfunc_6_13 = 13; localparam th_myfunc_6_14 = 14; localparam th_myfunc_6_15 = 15; localparam th_myfunc_6_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_6 <= th_myfunc_6_init; _th_myfunc_6_called <= 0; _th_myfunc_6_tid_32 <= 0; _th_myfunc_6_tid_33 <= 0; _th_myfunc_6_time_34 <= 0; _th_myfunc_6_i_35 <= 0; _th_myfunc_6___36 <= 0; end else begin case(th_myfunc_6) th_myfunc_6_init: begin if(_th_myfunc_start[6] && (th_blink == 10)) begin _th_myfunc_6_called <= 1; end if(_th_myfunc_start[6] && (th_blink == 10)) begin _th_myfunc_6_tid_32 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[6]) begin th_myfunc_6 <= th_myfunc_6_1; end end th_myfunc_6_1: begin _th_myfunc_6_tid_33 <= _th_myfunc_6_tid_32; th_myfunc_6 <= th_myfunc_6_2; end th_myfunc_6_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 6)) begin th_myfunc_6 <= th_myfunc_6_3; end end th_myfunc_6_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 6))) begin th_myfunc_6 <= th_myfunc_6_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 6)) begin th_myfunc_6 <= th_myfunc_6_4; end end th_myfunc_6_4: begin $display("Thread %d Lock", _th_myfunc_6_tid_33); th_myfunc_6 <= th_myfunc_6_5; end th_myfunc_6_5: begin _th_myfunc_6_time_34 <= sw; th_myfunc_6 <= th_myfunc_6_6; end th_myfunc_6_6: begin _th_myfunc_6_i_35 <= 0; th_myfunc_6 <= th_myfunc_6_7; end th_myfunc_6_7: begin if(_th_myfunc_6_i_35 < _th_myfunc_6_time_34) begin th_myfunc_6 <= th_myfunc_6_8; end else begin th_myfunc_6 <= th_myfunc_6_12; end end th_myfunc_6_8: begin _th_myfunc_6___36 <= 0; th_myfunc_6 <= th_myfunc_6_9; end th_myfunc_6_9: begin if(_th_myfunc_6___36 < 1024) begin th_myfunc_6 <= th_myfunc_6_10; end else begin th_myfunc_6 <= th_myfunc_6_11; end end th_myfunc_6_10: begin _th_myfunc_6___36 <= _th_myfunc_6___36 + 1; th_myfunc_6 <= th_myfunc_6_9; end th_myfunc_6_11: begin _th_myfunc_6_i_35 <= _th_myfunc_6_i_35 + 1; th_myfunc_6 <= th_myfunc_6_7; end th_myfunc_6_12: begin th_myfunc_6 <= th_myfunc_6_13; end th_myfunc_6_13: begin $display("Thread %d count = %d", _th_myfunc_6_tid_33, count); th_myfunc_6 <= th_myfunc_6_14; end th_myfunc_6_14: begin th_myfunc_6 <= th_myfunc_6_15; end th_myfunc_6_15: begin $display("Thread %d Unlock", _th_myfunc_6_tid_33); th_myfunc_6 <= th_myfunc_6_16; end th_myfunc_6_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 6)) begin _th_myfunc_6_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 6)) begin th_myfunc_6 <= th_myfunc_6_init; end end endcase end end localparam th_myfunc_7_1 = 1; localparam th_myfunc_7_2 = 2; localparam th_myfunc_7_3 = 3; localparam th_myfunc_7_4 = 4; localparam th_myfunc_7_5 = 5; localparam th_myfunc_7_6 = 6; localparam th_myfunc_7_7 = 7; localparam th_myfunc_7_8 = 8; localparam th_myfunc_7_9 = 9; localparam th_myfunc_7_10 = 10; localparam th_myfunc_7_11 = 11; localparam th_myfunc_7_12 = 12; localparam th_myfunc_7_13 = 13; localparam th_myfunc_7_14 = 14; localparam th_myfunc_7_15 = 15; localparam th_myfunc_7_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_7 <= th_myfunc_7_init; _th_myfunc_7_called <= 0; _th_myfunc_7_tid_37 <= 0; _th_myfunc_7_tid_38 <= 0; _th_myfunc_7_time_39 <= 0; _th_myfunc_7_i_40 <= 0; _th_myfunc_7___41 <= 0; end else begin case(th_myfunc_7) th_myfunc_7_init: begin if(_th_myfunc_start[7] && (th_blink == 10)) begin _th_myfunc_7_called <= 1; end if(_th_myfunc_start[7] && (th_blink == 10)) begin _th_myfunc_7_tid_37 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[7]) begin th_myfunc_7 <= th_myfunc_7_1; end end th_myfunc_7_1: begin _th_myfunc_7_tid_38 <= _th_myfunc_7_tid_37; th_myfunc_7 <= th_myfunc_7_2; end th_myfunc_7_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 7)) begin th_myfunc_7 <= th_myfunc_7_3; end end th_myfunc_7_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 7))) begin th_myfunc_7 <= th_myfunc_7_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 7)) begin th_myfunc_7 <= th_myfunc_7_4; end end th_myfunc_7_4: begin $display("Thread %d Lock", _th_myfunc_7_tid_38); th_myfunc_7 <= th_myfunc_7_5; end th_myfunc_7_5: begin _th_myfunc_7_time_39 <= sw; th_myfunc_7 <= th_myfunc_7_6; end th_myfunc_7_6: begin _th_myfunc_7_i_40 <= 0; th_myfunc_7 <= th_myfunc_7_7; end th_myfunc_7_7: begin if(_th_myfunc_7_i_40 < _th_myfunc_7_time_39) begin th_myfunc_7 <= th_myfunc_7_8; end else begin th_myfunc_7 <= th_myfunc_7_12; end end th_myfunc_7_8: begin _th_myfunc_7___41 <= 0; th_myfunc_7 <= th_myfunc_7_9; end th_myfunc_7_9: begin if(_th_myfunc_7___41 < 1024) begin th_myfunc_7 <= th_myfunc_7_10; end else begin th_myfunc_7 <= th_myfunc_7_11; end end th_myfunc_7_10: begin _th_myfunc_7___41 <= _th_myfunc_7___41 + 1; th_myfunc_7 <= th_myfunc_7_9; end th_myfunc_7_11: begin _th_myfunc_7_i_40 <= _th_myfunc_7_i_40 + 1; th_myfunc_7 <= th_myfunc_7_7; end th_myfunc_7_12: begin th_myfunc_7 <= th_myfunc_7_13; end th_myfunc_7_13: begin $display("Thread %d count = %d", _th_myfunc_7_tid_38, count); th_myfunc_7 <= th_myfunc_7_14; end th_myfunc_7_14: begin th_myfunc_7 <= th_myfunc_7_15; end th_myfunc_7_15: begin $display("Thread %d Unlock", _th_myfunc_7_tid_38); th_myfunc_7 <= th_myfunc_7_16; end th_myfunc_7_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 7)) begin _th_myfunc_7_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 7)) begin th_myfunc_7 <= th_myfunc_7_init; end end endcase end end localparam th_myfunc_8_1 = 1; localparam th_myfunc_8_2 = 2; localparam th_myfunc_8_3 = 3; localparam th_myfunc_8_4 = 4; localparam th_myfunc_8_5 = 5; localparam th_myfunc_8_6 = 6; localparam th_myfunc_8_7 = 7; localparam th_myfunc_8_8 = 8; localparam th_myfunc_8_9 = 9; localparam th_myfunc_8_10 = 10; localparam th_myfunc_8_11 = 11; localparam th_myfunc_8_12 = 12; localparam th_myfunc_8_13 = 13; localparam th_myfunc_8_14 = 14; localparam th_myfunc_8_15 = 15; localparam th_myfunc_8_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_8 <= th_myfunc_8_init; _th_myfunc_8_called <= 0; _th_myfunc_8_tid_42 <= 0; _th_myfunc_8_tid_43 <= 0; _th_myfunc_8_time_44 <= 0; _th_myfunc_8_i_45 <= 0; _th_myfunc_8___46 <= 0; end else begin case(th_myfunc_8) th_myfunc_8_init: begin if(_th_myfunc_start[8] && (th_blink == 10)) begin _th_myfunc_8_called <= 1; end if(_th_myfunc_start[8] && (th_blink == 10)) begin _th_myfunc_8_tid_42 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[8]) begin th_myfunc_8 <= th_myfunc_8_1; end end th_myfunc_8_1: begin _th_myfunc_8_tid_43 <= _th_myfunc_8_tid_42; th_myfunc_8 <= th_myfunc_8_2; end th_myfunc_8_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 8)) begin th_myfunc_8 <= th_myfunc_8_3; end end th_myfunc_8_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 8))) begin th_myfunc_8 <= th_myfunc_8_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 8)) begin th_myfunc_8 <= th_myfunc_8_4; end end th_myfunc_8_4: begin $display("Thread %d Lock", _th_myfunc_8_tid_43); th_myfunc_8 <= th_myfunc_8_5; end th_myfunc_8_5: begin _th_myfunc_8_time_44 <= sw; th_myfunc_8 <= th_myfunc_8_6; end th_myfunc_8_6: begin _th_myfunc_8_i_45 <= 0; th_myfunc_8 <= th_myfunc_8_7; end th_myfunc_8_7: begin if(_th_myfunc_8_i_45 < _th_myfunc_8_time_44) begin th_myfunc_8 <= th_myfunc_8_8; end else begin th_myfunc_8 <= th_myfunc_8_12; end end th_myfunc_8_8: begin _th_myfunc_8___46 <= 0; th_myfunc_8 <= th_myfunc_8_9; end th_myfunc_8_9: begin if(_th_myfunc_8___46 < 1024) begin th_myfunc_8 <= th_myfunc_8_10; end else begin th_myfunc_8 <= th_myfunc_8_11; end end th_myfunc_8_10: begin _th_myfunc_8___46 <= _th_myfunc_8___46 + 1; th_myfunc_8 <= th_myfunc_8_9; end th_myfunc_8_11: begin _th_myfunc_8_i_45 <= _th_myfunc_8_i_45 + 1; th_myfunc_8 <= th_myfunc_8_7; end th_myfunc_8_12: begin th_myfunc_8 <= th_myfunc_8_13; end th_myfunc_8_13: begin $display("Thread %d count = %d", _th_myfunc_8_tid_43, count); th_myfunc_8 <= th_myfunc_8_14; end th_myfunc_8_14: begin th_myfunc_8 <= th_myfunc_8_15; end th_myfunc_8_15: begin $display("Thread %d Unlock", _th_myfunc_8_tid_43); th_myfunc_8 <= th_myfunc_8_16; end th_myfunc_8_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 8)) begin _th_myfunc_8_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 8)) begin th_myfunc_8 <= th_myfunc_8_init; end end endcase end end localparam th_myfunc_9_1 = 1; localparam th_myfunc_9_2 = 2; localparam th_myfunc_9_3 = 3; localparam th_myfunc_9_4 = 4; localparam th_myfunc_9_5 = 5; localparam th_myfunc_9_6 = 6; localparam th_myfunc_9_7 = 7; localparam th_myfunc_9_8 = 8; localparam th_myfunc_9_9 = 9; localparam th_myfunc_9_10 = 10; localparam th_myfunc_9_11 = 11; localparam th_myfunc_9_12 = 12; localparam th_myfunc_9_13 = 13; localparam th_myfunc_9_14 = 14; localparam th_myfunc_9_15 = 15; localparam th_myfunc_9_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_9 <= th_myfunc_9_init; _th_myfunc_9_called <= 0; _th_myfunc_9_tid_47 <= 0; _th_myfunc_9_tid_48 <= 0; _th_myfunc_9_time_49 <= 0; _th_myfunc_9_i_50 <= 0; _th_myfunc_9___51 <= 0; end else begin case(th_myfunc_9) th_myfunc_9_init: begin if(_th_myfunc_start[9] && (th_blink == 10)) begin _th_myfunc_9_called <= 1; end if(_th_myfunc_start[9] && (th_blink == 10)) begin _th_myfunc_9_tid_47 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[9]) begin th_myfunc_9 <= th_myfunc_9_1; end end th_myfunc_9_1: begin _th_myfunc_9_tid_48 <= _th_myfunc_9_tid_47; th_myfunc_9 <= th_myfunc_9_2; end th_myfunc_9_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 9)) begin th_myfunc_9 <= th_myfunc_9_3; end end th_myfunc_9_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 9))) begin th_myfunc_9 <= th_myfunc_9_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 9)) begin th_myfunc_9 <= th_myfunc_9_4; end end th_myfunc_9_4: begin $display("Thread %d Lock", _th_myfunc_9_tid_48); th_myfunc_9 <= th_myfunc_9_5; end th_myfunc_9_5: begin _th_myfunc_9_time_49 <= sw; th_myfunc_9 <= th_myfunc_9_6; end th_myfunc_9_6: begin _th_myfunc_9_i_50 <= 0; th_myfunc_9 <= th_myfunc_9_7; end th_myfunc_9_7: begin if(_th_myfunc_9_i_50 < _th_myfunc_9_time_49) begin th_myfunc_9 <= th_myfunc_9_8; end else begin th_myfunc_9 <= th_myfunc_9_12; end end th_myfunc_9_8: begin _th_myfunc_9___51 <= 0; th_myfunc_9 <= th_myfunc_9_9; end th_myfunc_9_9: begin if(_th_myfunc_9___51 < 1024) begin th_myfunc_9 <= th_myfunc_9_10; end else begin th_myfunc_9 <= th_myfunc_9_11; end end th_myfunc_9_10: begin _th_myfunc_9___51 <= _th_myfunc_9___51 + 1; th_myfunc_9 <= th_myfunc_9_9; end th_myfunc_9_11: begin _th_myfunc_9_i_50 <= _th_myfunc_9_i_50 + 1; th_myfunc_9 <= th_myfunc_9_7; end th_myfunc_9_12: begin th_myfunc_9 <= th_myfunc_9_13; end th_myfunc_9_13: begin $display("Thread %d count = %d", _th_myfunc_9_tid_48, count); th_myfunc_9 <= th_myfunc_9_14; end th_myfunc_9_14: begin th_myfunc_9 <= th_myfunc_9_15; end th_myfunc_9_15: begin $display("Thread %d Unlock", _th_myfunc_9_tid_48); th_myfunc_9 <= th_myfunc_9_16; end th_myfunc_9_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 9)) begin _th_myfunc_9_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 9)) begin th_myfunc_9 <= th_myfunc_9_init; end end endcase end end localparam th_myfunc_10_1 = 1; localparam th_myfunc_10_2 = 2; localparam th_myfunc_10_3 = 3; localparam th_myfunc_10_4 = 4; localparam th_myfunc_10_5 = 5; localparam th_myfunc_10_6 = 6; localparam th_myfunc_10_7 = 7; localparam th_myfunc_10_8 = 8; localparam th_myfunc_10_9 = 9; localparam th_myfunc_10_10 = 10; localparam th_myfunc_10_11 = 11; localparam th_myfunc_10_12 = 12; localparam th_myfunc_10_13 = 13; localparam th_myfunc_10_14 = 14; localparam th_myfunc_10_15 = 15; localparam th_myfunc_10_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_10 <= th_myfunc_10_init; _th_myfunc_10_called <= 0; _th_myfunc_10_tid_52 <= 0; _th_myfunc_10_tid_53 <= 0; _th_myfunc_10_time_54 <= 0; _th_myfunc_10_i_55 <= 0; _th_myfunc_10___56 <= 0; end else begin case(th_myfunc_10) th_myfunc_10_init: begin if(_th_myfunc_start[10] && (th_blink == 10)) begin _th_myfunc_10_called <= 1; end if(_th_myfunc_start[10] && (th_blink == 10)) begin _th_myfunc_10_tid_52 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[10]) begin th_myfunc_10 <= th_myfunc_10_1; end end th_myfunc_10_1: begin _th_myfunc_10_tid_53 <= _th_myfunc_10_tid_52; th_myfunc_10 <= th_myfunc_10_2; end th_myfunc_10_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 10)) begin th_myfunc_10 <= th_myfunc_10_3; end end th_myfunc_10_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 10))) begin th_myfunc_10 <= th_myfunc_10_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 10)) begin th_myfunc_10 <= th_myfunc_10_4; end end th_myfunc_10_4: begin $display("Thread %d Lock", _th_myfunc_10_tid_53); th_myfunc_10 <= th_myfunc_10_5; end th_myfunc_10_5: begin _th_myfunc_10_time_54 <= sw; th_myfunc_10 <= th_myfunc_10_6; end th_myfunc_10_6: begin _th_myfunc_10_i_55 <= 0; th_myfunc_10 <= th_myfunc_10_7; end th_myfunc_10_7: begin if(_th_myfunc_10_i_55 < _th_myfunc_10_time_54) begin th_myfunc_10 <= th_myfunc_10_8; end else begin th_myfunc_10 <= th_myfunc_10_12; end end th_myfunc_10_8: begin _th_myfunc_10___56 <= 0; th_myfunc_10 <= th_myfunc_10_9; end th_myfunc_10_9: begin if(_th_myfunc_10___56 < 1024) begin th_myfunc_10 <= th_myfunc_10_10; end else begin th_myfunc_10 <= th_myfunc_10_11; end end th_myfunc_10_10: begin _th_myfunc_10___56 <= _th_myfunc_10___56 + 1; th_myfunc_10 <= th_myfunc_10_9; end th_myfunc_10_11: begin _th_myfunc_10_i_55 <= _th_myfunc_10_i_55 + 1; th_myfunc_10 <= th_myfunc_10_7; end th_myfunc_10_12: begin th_myfunc_10 <= th_myfunc_10_13; end th_myfunc_10_13: begin $display("Thread %d count = %d", _th_myfunc_10_tid_53, count); th_myfunc_10 <= th_myfunc_10_14; end th_myfunc_10_14: begin th_myfunc_10 <= th_myfunc_10_15; end th_myfunc_10_15: begin $display("Thread %d Unlock", _th_myfunc_10_tid_53); th_myfunc_10 <= th_myfunc_10_16; end th_myfunc_10_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 10)) begin _th_myfunc_10_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 10)) begin th_myfunc_10 <= th_myfunc_10_init; end end endcase end end localparam th_myfunc_11_1 = 1; localparam th_myfunc_11_2 = 2; localparam th_myfunc_11_3 = 3; localparam th_myfunc_11_4 = 4; localparam th_myfunc_11_5 = 5; localparam th_myfunc_11_6 = 6; localparam th_myfunc_11_7 = 7; localparam th_myfunc_11_8 = 8; localparam th_myfunc_11_9 = 9; localparam th_myfunc_11_10 = 10; localparam th_myfunc_11_11 = 11; localparam th_myfunc_11_12 = 12; localparam th_myfunc_11_13 = 13; localparam th_myfunc_11_14 = 14; localparam th_myfunc_11_15 = 15; localparam th_myfunc_11_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_11 <= th_myfunc_11_init; _th_myfunc_11_called <= 0; _th_myfunc_11_tid_57 <= 0; _th_myfunc_11_tid_58 <= 0; _th_myfunc_11_time_59 <= 0; _th_myfunc_11_i_60 <= 0; _th_myfunc_11___61 <= 0; end else begin case(th_myfunc_11) th_myfunc_11_init: begin if(_th_myfunc_start[11] && (th_blink == 10)) begin _th_myfunc_11_called <= 1; end if(_th_myfunc_start[11] && (th_blink == 10)) begin _th_myfunc_11_tid_57 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[11]) begin th_myfunc_11 <= th_myfunc_11_1; end end th_myfunc_11_1: begin _th_myfunc_11_tid_58 <= _th_myfunc_11_tid_57; th_myfunc_11 <= th_myfunc_11_2; end th_myfunc_11_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 11)) begin th_myfunc_11 <= th_myfunc_11_3; end end th_myfunc_11_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 11))) begin th_myfunc_11 <= th_myfunc_11_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 11)) begin th_myfunc_11 <= th_myfunc_11_4; end end th_myfunc_11_4: begin $display("Thread %d Lock", _th_myfunc_11_tid_58); th_myfunc_11 <= th_myfunc_11_5; end th_myfunc_11_5: begin _th_myfunc_11_time_59 <= sw; th_myfunc_11 <= th_myfunc_11_6; end th_myfunc_11_6: begin _th_myfunc_11_i_60 <= 0; th_myfunc_11 <= th_myfunc_11_7; end th_myfunc_11_7: begin if(_th_myfunc_11_i_60 < _th_myfunc_11_time_59) begin th_myfunc_11 <= th_myfunc_11_8; end else begin th_myfunc_11 <= th_myfunc_11_12; end end th_myfunc_11_8: begin _th_myfunc_11___61 <= 0; th_myfunc_11 <= th_myfunc_11_9; end th_myfunc_11_9: begin if(_th_myfunc_11___61 < 1024) begin th_myfunc_11 <= th_myfunc_11_10; end else begin th_myfunc_11 <= th_myfunc_11_11; end end th_myfunc_11_10: begin _th_myfunc_11___61 <= _th_myfunc_11___61 + 1; th_myfunc_11 <= th_myfunc_11_9; end th_myfunc_11_11: begin _th_myfunc_11_i_60 <= _th_myfunc_11_i_60 + 1; th_myfunc_11 <= th_myfunc_11_7; end th_myfunc_11_12: begin th_myfunc_11 <= th_myfunc_11_13; end th_myfunc_11_13: begin $display("Thread %d count = %d", _th_myfunc_11_tid_58, count); th_myfunc_11 <= th_myfunc_11_14; end th_myfunc_11_14: begin th_myfunc_11 <= th_myfunc_11_15; end th_myfunc_11_15: begin $display("Thread %d Unlock", _th_myfunc_11_tid_58); th_myfunc_11 <= th_myfunc_11_16; end th_myfunc_11_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 11)) begin _th_myfunc_11_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 11)) begin th_myfunc_11 <= th_myfunc_11_init; end end endcase end end localparam th_myfunc_12_1 = 1; localparam th_myfunc_12_2 = 2; localparam th_myfunc_12_3 = 3; localparam th_myfunc_12_4 = 4; localparam th_myfunc_12_5 = 5; localparam th_myfunc_12_6 = 6; localparam th_myfunc_12_7 = 7; localparam th_myfunc_12_8 = 8; localparam th_myfunc_12_9 = 9; localparam th_myfunc_12_10 = 10; localparam th_myfunc_12_11 = 11; localparam th_myfunc_12_12 = 12; localparam th_myfunc_12_13 = 13; localparam th_myfunc_12_14 = 14; localparam th_myfunc_12_15 = 15; localparam th_myfunc_12_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_12 <= th_myfunc_12_init; _th_myfunc_12_called <= 0; _th_myfunc_12_tid_62 <= 0; _th_myfunc_12_tid_63 <= 0; _th_myfunc_12_time_64 <= 0; _th_myfunc_12_i_65 <= 0; _th_myfunc_12___66 <= 0; end else begin case(th_myfunc_12) th_myfunc_12_init: begin if(_th_myfunc_start[12] && (th_blink == 10)) begin _th_myfunc_12_called <= 1; end if(_th_myfunc_start[12] && (th_blink == 10)) begin _th_myfunc_12_tid_62 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[12]) begin th_myfunc_12 <= th_myfunc_12_1; end end th_myfunc_12_1: begin _th_myfunc_12_tid_63 <= _th_myfunc_12_tid_62; th_myfunc_12 <= th_myfunc_12_2; end th_myfunc_12_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 12)) begin th_myfunc_12 <= th_myfunc_12_3; end end th_myfunc_12_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 12))) begin th_myfunc_12 <= th_myfunc_12_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 12)) begin th_myfunc_12 <= th_myfunc_12_4; end end th_myfunc_12_4: begin $display("Thread %d Lock", _th_myfunc_12_tid_63); th_myfunc_12 <= th_myfunc_12_5; end th_myfunc_12_5: begin _th_myfunc_12_time_64 <= sw; th_myfunc_12 <= th_myfunc_12_6; end th_myfunc_12_6: begin _th_myfunc_12_i_65 <= 0; th_myfunc_12 <= th_myfunc_12_7; end th_myfunc_12_7: begin if(_th_myfunc_12_i_65 < _th_myfunc_12_time_64) begin th_myfunc_12 <= th_myfunc_12_8; end else begin th_myfunc_12 <= th_myfunc_12_12; end end th_myfunc_12_8: begin _th_myfunc_12___66 <= 0; th_myfunc_12 <= th_myfunc_12_9; end th_myfunc_12_9: begin if(_th_myfunc_12___66 < 1024) begin th_myfunc_12 <= th_myfunc_12_10; end else begin th_myfunc_12 <= th_myfunc_12_11; end end th_myfunc_12_10: begin _th_myfunc_12___66 <= _th_myfunc_12___66 + 1; th_myfunc_12 <= th_myfunc_12_9; end th_myfunc_12_11: begin _th_myfunc_12_i_65 <= _th_myfunc_12_i_65 + 1; th_myfunc_12 <= th_myfunc_12_7; end th_myfunc_12_12: begin th_myfunc_12 <= th_myfunc_12_13; end th_myfunc_12_13: begin $display("Thread %d count = %d", _th_myfunc_12_tid_63, count); th_myfunc_12 <= th_myfunc_12_14; end th_myfunc_12_14: begin th_myfunc_12 <= th_myfunc_12_15; end th_myfunc_12_15: begin $display("Thread %d Unlock", _th_myfunc_12_tid_63); th_myfunc_12 <= th_myfunc_12_16; end th_myfunc_12_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 12)) begin _th_myfunc_12_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 12)) begin th_myfunc_12 <= th_myfunc_12_init; end end endcase end end localparam th_myfunc_13_1 = 1; localparam th_myfunc_13_2 = 2; localparam th_myfunc_13_3 = 3; localparam th_myfunc_13_4 = 4; localparam th_myfunc_13_5 = 5; localparam th_myfunc_13_6 = 6; localparam th_myfunc_13_7 = 7; localparam th_myfunc_13_8 = 8; localparam th_myfunc_13_9 = 9; localparam th_myfunc_13_10 = 10; localparam th_myfunc_13_11 = 11; localparam th_myfunc_13_12 = 12; localparam th_myfunc_13_13 = 13; localparam th_myfunc_13_14 = 14; localparam th_myfunc_13_15 = 15; localparam th_myfunc_13_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_13 <= th_myfunc_13_init; _th_myfunc_13_called <= 0; _th_myfunc_13_tid_67 <= 0; _th_myfunc_13_tid_68 <= 0; _th_myfunc_13_time_69 <= 0; _th_myfunc_13_i_70 <= 0; _th_myfunc_13___71 <= 0; end else begin case(th_myfunc_13) th_myfunc_13_init: begin if(_th_myfunc_start[13] && (th_blink == 10)) begin _th_myfunc_13_called <= 1; end if(_th_myfunc_start[13] && (th_blink == 10)) begin _th_myfunc_13_tid_67 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[13]) begin th_myfunc_13 <= th_myfunc_13_1; end end th_myfunc_13_1: begin _th_myfunc_13_tid_68 <= _th_myfunc_13_tid_67; th_myfunc_13 <= th_myfunc_13_2; end th_myfunc_13_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 13)) begin th_myfunc_13 <= th_myfunc_13_3; end end th_myfunc_13_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 13))) begin th_myfunc_13 <= th_myfunc_13_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 13)) begin th_myfunc_13 <= th_myfunc_13_4; end end th_myfunc_13_4: begin $display("Thread %d Lock", _th_myfunc_13_tid_68); th_myfunc_13 <= th_myfunc_13_5; end th_myfunc_13_5: begin _th_myfunc_13_time_69 <= sw; th_myfunc_13 <= th_myfunc_13_6; end th_myfunc_13_6: begin _th_myfunc_13_i_70 <= 0; th_myfunc_13 <= th_myfunc_13_7; end th_myfunc_13_7: begin if(_th_myfunc_13_i_70 < _th_myfunc_13_time_69) begin th_myfunc_13 <= th_myfunc_13_8; end else begin th_myfunc_13 <= th_myfunc_13_12; end end th_myfunc_13_8: begin _th_myfunc_13___71 <= 0; th_myfunc_13 <= th_myfunc_13_9; end th_myfunc_13_9: begin if(_th_myfunc_13___71 < 1024) begin th_myfunc_13 <= th_myfunc_13_10; end else begin th_myfunc_13 <= th_myfunc_13_11; end end th_myfunc_13_10: begin _th_myfunc_13___71 <= _th_myfunc_13___71 + 1; th_myfunc_13 <= th_myfunc_13_9; end th_myfunc_13_11: begin _th_myfunc_13_i_70 <= _th_myfunc_13_i_70 + 1; th_myfunc_13 <= th_myfunc_13_7; end th_myfunc_13_12: begin th_myfunc_13 <= th_myfunc_13_13; end th_myfunc_13_13: begin $display("Thread %d count = %d", _th_myfunc_13_tid_68, count); th_myfunc_13 <= th_myfunc_13_14; end th_myfunc_13_14: begin th_myfunc_13 <= th_myfunc_13_15; end th_myfunc_13_15: begin $display("Thread %d Unlock", _th_myfunc_13_tid_68); th_myfunc_13 <= th_myfunc_13_16; end th_myfunc_13_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 13)) begin _th_myfunc_13_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 13)) begin th_myfunc_13 <= th_myfunc_13_init; end end endcase end end localparam th_myfunc_14_1 = 1; localparam th_myfunc_14_2 = 2; localparam th_myfunc_14_3 = 3; localparam th_myfunc_14_4 = 4; localparam th_myfunc_14_5 = 5; localparam th_myfunc_14_6 = 6; localparam th_myfunc_14_7 = 7; localparam th_myfunc_14_8 = 8; localparam th_myfunc_14_9 = 9; localparam th_myfunc_14_10 = 10; localparam th_myfunc_14_11 = 11; localparam th_myfunc_14_12 = 12; localparam th_myfunc_14_13 = 13; localparam th_myfunc_14_14 = 14; localparam th_myfunc_14_15 = 15; localparam th_myfunc_14_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_14 <= th_myfunc_14_init; _th_myfunc_14_called <= 0; _th_myfunc_14_tid_72 <= 0; _th_myfunc_14_tid_73 <= 0; _th_myfunc_14_time_74 <= 0; _th_myfunc_14_i_75 <= 0; _th_myfunc_14___76 <= 0; end else begin case(th_myfunc_14) th_myfunc_14_init: begin if(_th_myfunc_start[14] && (th_blink == 10)) begin _th_myfunc_14_called <= 1; end if(_th_myfunc_start[14] && (th_blink == 10)) begin _th_myfunc_14_tid_72 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[14]) begin th_myfunc_14 <= th_myfunc_14_1; end end th_myfunc_14_1: begin _th_myfunc_14_tid_73 <= _th_myfunc_14_tid_72; th_myfunc_14 <= th_myfunc_14_2; end th_myfunc_14_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 14)) begin th_myfunc_14 <= th_myfunc_14_3; end end th_myfunc_14_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 14))) begin th_myfunc_14 <= th_myfunc_14_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 14)) begin th_myfunc_14 <= th_myfunc_14_4; end end th_myfunc_14_4: begin $display("Thread %d Lock", _th_myfunc_14_tid_73); th_myfunc_14 <= th_myfunc_14_5; end th_myfunc_14_5: begin _th_myfunc_14_time_74 <= sw; th_myfunc_14 <= th_myfunc_14_6; end th_myfunc_14_6: begin _th_myfunc_14_i_75 <= 0; th_myfunc_14 <= th_myfunc_14_7; end th_myfunc_14_7: begin if(_th_myfunc_14_i_75 < _th_myfunc_14_time_74) begin th_myfunc_14 <= th_myfunc_14_8; end else begin th_myfunc_14 <= th_myfunc_14_12; end end th_myfunc_14_8: begin _th_myfunc_14___76 <= 0; th_myfunc_14 <= th_myfunc_14_9; end th_myfunc_14_9: begin if(_th_myfunc_14___76 < 1024) begin th_myfunc_14 <= th_myfunc_14_10; end else begin th_myfunc_14 <= th_myfunc_14_11; end end th_myfunc_14_10: begin _th_myfunc_14___76 <= _th_myfunc_14___76 + 1; th_myfunc_14 <= th_myfunc_14_9; end th_myfunc_14_11: begin _th_myfunc_14_i_75 <= _th_myfunc_14_i_75 + 1; th_myfunc_14 <= th_myfunc_14_7; end th_myfunc_14_12: begin th_myfunc_14 <= th_myfunc_14_13; end th_myfunc_14_13: begin $display("Thread %d count = %d", _th_myfunc_14_tid_73, count); th_myfunc_14 <= th_myfunc_14_14; end th_myfunc_14_14: begin th_myfunc_14 <= th_myfunc_14_15; end th_myfunc_14_15: begin $display("Thread %d Unlock", _th_myfunc_14_tid_73); th_myfunc_14 <= th_myfunc_14_16; end th_myfunc_14_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 14)) begin _th_myfunc_14_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 14)) begin th_myfunc_14 <= th_myfunc_14_init; end end endcase end end localparam th_myfunc_15_1 = 1; localparam th_myfunc_15_2 = 2; localparam th_myfunc_15_3 = 3; localparam th_myfunc_15_4 = 4; localparam th_myfunc_15_5 = 5; localparam th_myfunc_15_6 = 6; localparam th_myfunc_15_7 = 7; localparam th_myfunc_15_8 = 8; localparam th_myfunc_15_9 = 9; localparam th_myfunc_15_10 = 10; localparam th_myfunc_15_11 = 11; localparam th_myfunc_15_12 = 12; localparam th_myfunc_15_13 = 13; localparam th_myfunc_15_14 = 14; localparam th_myfunc_15_15 = 15; localparam th_myfunc_15_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_15 <= th_myfunc_15_init; _th_myfunc_15_called <= 0; _th_myfunc_15_tid_77 <= 0; _th_myfunc_15_tid_78 <= 0; _th_myfunc_15_time_79 <= 0; _th_myfunc_15_i_80 <= 0; _th_myfunc_15___81 <= 0; end else begin case(th_myfunc_15) th_myfunc_15_init: begin if(_th_myfunc_start[15] && (th_blink == 10)) begin _th_myfunc_15_called <= 1; end if(_th_myfunc_start[15] && (th_blink == 10)) begin _th_myfunc_15_tid_77 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[15]) begin th_myfunc_15 <= th_myfunc_15_1; end end th_myfunc_15_1: begin _th_myfunc_15_tid_78 <= _th_myfunc_15_tid_77; th_myfunc_15 <= th_myfunc_15_2; end th_myfunc_15_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 15)) begin th_myfunc_15 <= th_myfunc_15_3; end end th_myfunc_15_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 15))) begin th_myfunc_15 <= th_myfunc_15_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 15)) begin th_myfunc_15 <= th_myfunc_15_4; end end th_myfunc_15_4: begin $display("Thread %d Lock", _th_myfunc_15_tid_78); th_myfunc_15 <= th_myfunc_15_5; end th_myfunc_15_5: begin _th_myfunc_15_time_79 <= sw; th_myfunc_15 <= th_myfunc_15_6; end th_myfunc_15_6: begin _th_myfunc_15_i_80 <= 0; th_myfunc_15 <= th_myfunc_15_7; end th_myfunc_15_7: begin if(_th_myfunc_15_i_80 < _th_myfunc_15_time_79) begin th_myfunc_15 <= th_myfunc_15_8; end else begin th_myfunc_15 <= th_myfunc_15_12; end end th_myfunc_15_8: begin _th_myfunc_15___81 <= 0; th_myfunc_15 <= th_myfunc_15_9; end th_myfunc_15_9: begin if(_th_myfunc_15___81 < 1024) begin th_myfunc_15 <= th_myfunc_15_10; end else begin th_myfunc_15 <= th_myfunc_15_11; end end th_myfunc_15_10: begin _th_myfunc_15___81 <= _th_myfunc_15___81 + 1; th_myfunc_15 <= th_myfunc_15_9; end th_myfunc_15_11: begin _th_myfunc_15_i_80 <= _th_myfunc_15_i_80 + 1; th_myfunc_15 <= th_myfunc_15_7; end th_myfunc_15_12: begin th_myfunc_15 <= th_myfunc_15_13; end th_myfunc_15_13: begin $display("Thread %d count = %d", _th_myfunc_15_tid_78, count); th_myfunc_15 <= th_myfunc_15_14; end th_myfunc_15_14: begin th_myfunc_15 <= th_myfunc_15_15; end th_myfunc_15_15: begin $display("Thread %d Unlock", _th_myfunc_15_tid_78); th_myfunc_15 <= th_myfunc_15_16; end th_myfunc_15_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 15)) begin _th_myfunc_15_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 15)) begin th_myfunc_15 <= th_myfunc_15_init; end end endcase end end localparam th_myfunc_16_1 = 1; localparam th_myfunc_16_2 = 2; localparam th_myfunc_16_3 = 3; localparam th_myfunc_16_4 = 4; localparam th_myfunc_16_5 = 5; localparam th_myfunc_16_6 = 6; localparam th_myfunc_16_7 = 7; localparam th_myfunc_16_8 = 8; localparam th_myfunc_16_9 = 9; localparam th_myfunc_16_10 = 10; localparam th_myfunc_16_11 = 11; localparam th_myfunc_16_12 = 12; localparam th_myfunc_16_13 = 13; localparam th_myfunc_16_14 = 14; localparam th_myfunc_16_15 = 15; localparam th_myfunc_16_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_16 <= th_myfunc_16_init; _th_myfunc_16_called <= 0; _th_myfunc_16_tid_82 <= 0; _th_myfunc_16_tid_83 <= 0; _th_myfunc_16_time_84 <= 0; _th_myfunc_16_i_85 <= 0; _th_myfunc_16___86 <= 0; end else begin case(th_myfunc_16) th_myfunc_16_init: begin if(_th_myfunc_start[16] && (th_blink == 10)) begin _th_myfunc_16_called <= 1; end if(_th_myfunc_start[16] && (th_blink == 10)) begin _th_myfunc_16_tid_82 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[16]) begin th_myfunc_16 <= th_myfunc_16_1; end end th_myfunc_16_1: begin _th_myfunc_16_tid_83 <= _th_myfunc_16_tid_82; th_myfunc_16 <= th_myfunc_16_2; end th_myfunc_16_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 16)) begin th_myfunc_16 <= th_myfunc_16_3; end end th_myfunc_16_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 16))) begin th_myfunc_16 <= th_myfunc_16_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 16)) begin th_myfunc_16 <= th_myfunc_16_4; end end th_myfunc_16_4: begin $display("Thread %d Lock", _th_myfunc_16_tid_83); th_myfunc_16 <= th_myfunc_16_5; end th_myfunc_16_5: begin _th_myfunc_16_time_84 <= sw; th_myfunc_16 <= th_myfunc_16_6; end th_myfunc_16_6: begin _th_myfunc_16_i_85 <= 0; th_myfunc_16 <= th_myfunc_16_7; end th_myfunc_16_7: begin if(_th_myfunc_16_i_85 < _th_myfunc_16_time_84) begin th_myfunc_16 <= th_myfunc_16_8; end else begin th_myfunc_16 <= th_myfunc_16_12; end end th_myfunc_16_8: begin _th_myfunc_16___86 <= 0; th_myfunc_16 <= th_myfunc_16_9; end th_myfunc_16_9: begin if(_th_myfunc_16___86 < 1024) begin th_myfunc_16 <= th_myfunc_16_10; end else begin th_myfunc_16 <= th_myfunc_16_11; end end th_myfunc_16_10: begin _th_myfunc_16___86 <= _th_myfunc_16___86 + 1; th_myfunc_16 <= th_myfunc_16_9; end th_myfunc_16_11: begin _th_myfunc_16_i_85 <= _th_myfunc_16_i_85 + 1; th_myfunc_16 <= th_myfunc_16_7; end th_myfunc_16_12: begin th_myfunc_16 <= th_myfunc_16_13; end th_myfunc_16_13: begin $display("Thread %d count = %d", _th_myfunc_16_tid_83, count); th_myfunc_16 <= th_myfunc_16_14; end th_myfunc_16_14: begin th_myfunc_16 <= th_myfunc_16_15; end th_myfunc_16_15: begin $display("Thread %d Unlock", _th_myfunc_16_tid_83); th_myfunc_16 <= th_myfunc_16_16; end th_myfunc_16_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 16)) begin _th_myfunc_16_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 16)) begin th_myfunc_16 <= th_myfunc_16_init; end end endcase end end localparam th_myfunc_17_1 = 1; localparam th_myfunc_17_2 = 2; localparam th_myfunc_17_3 = 3; localparam th_myfunc_17_4 = 4; localparam th_myfunc_17_5 = 5; localparam th_myfunc_17_6 = 6; localparam th_myfunc_17_7 = 7; localparam th_myfunc_17_8 = 8; localparam th_myfunc_17_9 = 9; localparam th_myfunc_17_10 = 10; localparam th_myfunc_17_11 = 11; localparam th_myfunc_17_12 = 12; localparam th_myfunc_17_13 = 13; localparam th_myfunc_17_14 = 14; localparam th_myfunc_17_15 = 15; localparam th_myfunc_17_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_17 <= th_myfunc_17_init; _th_myfunc_17_called <= 0; _th_myfunc_17_tid_87 <= 0; _th_myfunc_17_tid_88 <= 0; _th_myfunc_17_time_89 <= 0; _th_myfunc_17_i_90 <= 0; _th_myfunc_17___91 <= 0; end else begin case(th_myfunc_17) th_myfunc_17_init: begin if(_th_myfunc_start[17] && (th_blink == 10)) begin _th_myfunc_17_called <= 1; end if(_th_myfunc_start[17] && (th_blink == 10)) begin _th_myfunc_17_tid_87 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[17]) begin th_myfunc_17 <= th_myfunc_17_1; end end th_myfunc_17_1: begin _th_myfunc_17_tid_88 <= _th_myfunc_17_tid_87; th_myfunc_17 <= th_myfunc_17_2; end th_myfunc_17_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 17)) begin th_myfunc_17 <= th_myfunc_17_3; end end th_myfunc_17_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 17))) begin th_myfunc_17 <= th_myfunc_17_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 17)) begin th_myfunc_17 <= th_myfunc_17_4; end end th_myfunc_17_4: begin $display("Thread %d Lock", _th_myfunc_17_tid_88); th_myfunc_17 <= th_myfunc_17_5; end th_myfunc_17_5: begin _th_myfunc_17_time_89 <= sw; th_myfunc_17 <= th_myfunc_17_6; end th_myfunc_17_6: begin _th_myfunc_17_i_90 <= 0; th_myfunc_17 <= th_myfunc_17_7; end th_myfunc_17_7: begin if(_th_myfunc_17_i_90 < _th_myfunc_17_time_89) begin th_myfunc_17 <= th_myfunc_17_8; end else begin th_myfunc_17 <= th_myfunc_17_12; end end th_myfunc_17_8: begin _th_myfunc_17___91 <= 0; th_myfunc_17 <= th_myfunc_17_9; end th_myfunc_17_9: begin if(_th_myfunc_17___91 < 1024) begin th_myfunc_17 <= th_myfunc_17_10; end else begin th_myfunc_17 <= th_myfunc_17_11; end end th_myfunc_17_10: begin _th_myfunc_17___91 <= _th_myfunc_17___91 + 1; th_myfunc_17 <= th_myfunc_17_9; end th_myfunc_17_11: begin _th_myfunc_17_i_90 <= _th_myfunc_17_i_90 + 1; th_myfunc_17 <= th_myfunc_17_7; end th_myfunc_17_12: begin th_myfunc_17 <= th_myfunc_17_13; end th_myfunc_17_13: begin $display("Thread %d count = %d", _th_myfunc_17_tid_88, count); th_myfunc_17 <= th_myfunc_17_14; end th_myfunc_17_14: begin th_myfunc_17 <= th_myfunc_17_15; end th_myfunc_17_15: begin $display("Thread %d Unlock", _th_myfunc_17_tid_88); th_myfunc_17 <= th_myfunc_17_16; end th_myfunc_17_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 17)) begin _th_myfunc_17_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 17)) begin th_myfunc_17 <= th_myfunc_17_init; end end endcase end end localparam th_myfunc_18_1 = 1; localparam th_myfunc_18_2 = 2; localparam th_myfunc_18_3 = 3; localparam th_myfunc_18_4 = 4; localparam th_myfunc_18_5 = 5; localparam th_myfunc_18_6 = 6; localparam th_myfunc_18_7 = 7; localparam th_myfunc_18_8 = 8; localparam th_myfunc_18_9 = 9; localparam th_myfunc_18_10 = 10; localparam th_myfunc_18_11 = 11; localparam th_myfunc_18_12 = 12; localparam th_myfunc_18_13 = 13; localparam th_myfunc_18_14 = 14; localparam th_myfunc_18_15 = 15; localparam th_myfunc_18_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_18 <= th_myfunc_18_init; _th_myfunc_18_called <= 0; _th_myfunc_18_tid_92 <= 0; _th_myfunc_18_tid_93 <= 0; _th_myfunc_18_time_94 <= 0; _th_myfunc_18_i_95 <= 0; _th_myfunc_18___96 <= 0; end else begin case(th_myfunc_18) th_myfunc_18_init: begin if(_th_myfunc_start[18] && (th_blink == 10)) begin _th_myfunc_18_called <= 1; end if(_th_myfunc_start[18] && (th_blink == 10)) begin _th_myfunc_18_tid_92 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[18]) begin th_myfunc_18 <= th_myfunc_18_1; end end th_myfunc_18_1: begin _th_myfunc_18_tid_93 <= _th_myfunc_18_tid_92; th_myfunc_18 <= th_myfunc_18_2; end th_myfunc_18_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 18)) begin th_myfunc_18 <= th_myfunc_18_3; end end th_myfunc_18_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 18))) begin th_myfunc_18 <= th_myfunc_18_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 18)) begin th_myfunc_18 <= th_myfunc_18_4; end end th_myfunc_18_4: begin $display("Thread %d Lock", _th_myfunc_18_tid_93); th_myfunc_18 <= th_myfunc_18_5; end th_myfunc_18_5: begin _th_myfunc_18_time_94 <= sw; th_myfunc_18 <= th_myfunc_18_6; end th_myfunc_18_6: begin _th_myfunc_18_i_95 <= 0; th_myfunc_18 <= th_myfunc_18_7; end th_myfunc_18_7: begin if(_th_myfunc_18_i_95 < _th_myfunc_18_time_94) begin th_myfunc_18 <= th_myfunc_18_8; end else begin th_myfunc_18 <= th_myfunc_18_12; end end th_myfunc_18_8: begin _th_myfunc_18___96 <= 0; th_myfunc_18 <= th_myfunc_18_9; end th_myfunc_18_9: begin if(_th_myfunc_18___96 < 1024) begin th_myfunc_18 <= th_myfunc_18_10; end else begin th_myfunc_18 <= th_myfunc_18_11; end end th_myfunc_18_10: begin _th_myfunc_18___96 <= _th_myfunc_18___96 + 1; th_myfunc_18 <= th_myfunc_18_9; end th_myfunc_18_11: begin _th_myfunc_18_i_95 <= _th_myfunc_18_i_95 + 1; th_myfunc_18 <= th_myfunc_18_7; end th_myfunc_18_12: begin th_myfunc_18 <= th_myfunc_18_13; end th_myfunc_18_13: begin $display("Thread %d count = %d", _th_myfunc_18_tid_93, count); th_myfunc_18 <= th_myfunc_18_14; end th_myfunc_18_14: begin th_myfunc_18 <= th_myfunc_18_15; end th_myfunc_18_15: begin $display("Thread %d Unlock", _th_myfunc_18_tid_93); th_myfunc_18 <= th_myfunc_18_16; end th_myfunc_18_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 18)) begin _th_myfunc_18_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 18)) begin th_myfunc_18 <= th_myfunc_18_init; end end endcase end end localparam th_myfunc_19_1 = 1; localparam th_myfunc_19_2 = 2; localparam th_myfunc_19_3 = 3; localparam th_myfunc_19_4 = 4; localparam th_myfunc_19_5 = 5; localparam th_myfunc_19_6 = 6; localparam th_myfunc_19_7 = 7; localparam th_myfunc_19_8 = 8; localparam th_myfunc_19_9 = 9; localparam th_myfunc_19_10 = 10; localparam th_myfunc_19_11 = 11; localparam th_myfunc_19_12 = 12; localparam th_myfunc_19_13 = 13; localparam th_myfunc_19_14 = 14; localparam th_myfunc_19_15 = 15; localparam th_myfunc_19_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_19 <= th_myfunc_19_init; _th_myfunc_19_called <= 0; _th_myfunc_19_tid_97 <= 0; _th_myfunc_19_tid_98 <= 0; _th_myfunc_19_time_99 <= 0; _th_myfunc_19_i_100 <= 0; _th_myfunc_19___101 <= 0; end else begin case(th_myfunc_19) th_myfunc_19_init: begin if(_th_myfunc_start[19] && (th_blink == 10)) begin _th_myfunc_19_called <= 1; end if(_th_myfunc_start[19] && (th_blink == 10)) begin _th_myfunc_19_tid_97 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[19]) begin th_myfunc_19 <= th_myfunc_19_1; end end th_myfunc_19_1: begin _th_myfunc_19_tid_98 <= _th_myfunc_19_tid_97; th_myfunc_19 <= th_myfunc_19_2; end th_myfunc_19_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 19)) begin th_myfunc_19 <= th_myfunc_19_3; end end th_myfunc_19_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 19))) begin th_myfunc_19 <= th_myfunc_19_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 19)) begin th_myfunc_19 <= th_myfunc_19_4; end end th_myfunc_19_4: begin $display("Thread %d Lock", _th_myfunc_19_tid_98); th_myfunc_19 <= th_myfunc_19_5; end th_myfunc_19_5: begin _th_myfunc_19_time_99 <= sw; th_myfunc_19 <= th_myfunc_19_6; end th_myfunc_19_6: begin _th_myfunc_19_i_100 <= 0; th_myfunc_19 <= th_myfunc_19_7; end th_myfunc_19_7: begin if(_th_myfunc_19_i_100 < _th_myfunc_19_time_99) begin th_myfunc_19 <= th_myfunc_19_8; end else begin th_myfunc_19 <= th_myfunc_19_12; end end th_myfunc_19_8: begin _th_myfunc_19___101 <= 0; th_myfunc_19 <= th_myfunc_19_9; end th_myfunc_19_9: begin if(_th_myfunc_19___101 < 1024) begin th_myfunc_19 <= th_myfunc_19_10; end else begin th_myfunc_19 <= th_myfunc_19_11; end end th_myfunc_19_10: begin _th_myfunc_19___101 <= _th_myfunc_19___101 + 1; th_myfunc_19 <= th_myfunc_19_9; end th_myfunc_19_11: begin _th_myfunc_19_i_100 <= _th_myfunc_19_i_100 + 1; th_myfunc_19 <= th_myfunc_19_7; end th_myfunc_19_12: begin th_myfunc_19 <= th_myfunc_19_13; end th_myfunc_19_13: begin $display("Thread %d count = %d", _th_myfunc_19_tid_98, count); th_myfunc_19 <= th_myfunc_19_14; end th_myfunc_19_14: begin th_myfunc_19 <= th_myfunc_19_15; end th_myfunc_19_15: begin $display("Thread %d Unlock", _th_myfunc_19_tid_98); th_myfunc_19 <= th_myfunc_19_16; end th_myfunc_19_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 19)) begin _th_myfunc_19_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 19)) begin th_myfunc_19 <= th_myfunc_19_init; end end endcase end end localparam th_myfunc_20_1 = 1; localparam th_myfunc_20_2 = 2; localparam th_myfunc_20_3 = 3; localparam th_myfunc_20_4 = 4; localparam th_myfunc_20_5 = 5; localparam th_myfunc_20_6 = 6; localparam th_myfunc_20_7 = 7; localparam th_myfunc_20_8 = 8; localparam th_myfunc_20_9 = 9; localparam th_myfunc_20_10 = 10; localparam th_myfunc_20_11 = 11; localparam th_myfunc_20_12 = 12; localparam th_myfunc_20_13 = 13; localparam th_myfunc_20_14 = 14; localparam th_myfunc_20_15 = 15; localparam th_myfunc_20_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_20 <= th_myfunc_20_init; _th_myfunc_20_called <= 0; _th_myfunc_20_tid_102 <= 0; _th_myfunc_20_tid_103 <= 0; _th_myfunc_20_time_104 <= 0; _th_myfunc_20_i_105 <= 0; _th_myfunc_20___106 <= 0; end else begin case(th_myfunc_20) th_myfunc_20_init: begin if(_th_myfunc_start[20] && (th_blink == 10)) begin _th_myfunc_20_called <= 1; end if(_th_myfunc_start[20] && (th_blink == 10)) begin _th_myfunc_20_tid_102 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[20]) begin th_myfunc_20 <= th_myfunc_20_1; end end th_myfunc_20_1: begin _th_myfunc_20_tid_103 <= _th_myfunc_20_tid_102; th_myfunc_20 <= th_myfunc_20_2; end th_myfunc_20_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 20)) begin th_myfunc_20 <= th_myfunc_20_3; end end th_myfunc_20_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 20))) begin th_myfunc_20 <= th_myfunc_20_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 20)) begin th_myfunc_20 <= th_myfunc_20_4; end end th_myfunc_20_4: begin $display("Thread %d Lock", _th_myfunc_20_tid_103); th_myfunc_20 <= th_myfunc_20_5; end th_myfunc_20_5: begin _th_myfunc_20_time_104 <= sw; th_myfunc_20 <= th_myfunc_20_6; end th_myfunc_20_6: begin _th_myfunc_20_i_105 <= 0; th_myfunc_20 <= th_myfunc_20_7; end th_myfunc_20_7: begin if(_th_myfunc_20_i_105 < _th_myfunc_20_time_104) begin th_myfunc_20 <= th_myfunc_20_8; end else begin th_myfunc_20 <= th_myfunc_20_12; end end th_myfunc_20_8: begin _th_myfunc_20___106 <= 0; th_myfunc_20 <= th_myfunc_20_9; end th_myfunc_20_9: begin if(_th_myfunc_20___106 < 1024) begin th_myfunc_20 <= th_myfunc_20_10; end else begin th_myfunc_20 <= th_myfunc_20_11; end end th_myfunc_20_10: begin _th_myfunc_20___106 <= _th_myfunc_20___106 + 1; th_myfunc_20 <= th_myfunc_20_9; end th_myfunc_20_11: begin _th_myfunc_20_i_105 <= _th_myfunc_20_i_105 + 1; th_myfunc_20 <= th_myfunc_20_7; end th_myfunc_20_12: begin th_myfunc_20 <= th_myfunc_20_13; end th_myfunc_20_13: begin $display("Thread %d count = %d", _th_myfunc_20_tid_103, count); th_myfunc_20 <= th_myfunc_20_14; end th_myfunc_20_14: begin th_myfunc_20 <= th_myfunc_20_15; end th_myfunc_20_15: begin $display("Thread %d Unlock", _th_myfunc_20_tid_103); th_myfunc_20 <= th_myfunc_20_16; end th_myfunc_20_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 20)) begin _th_myfunc_20_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 20)) begin th_myfunc_20 <= th_myfunc_20_init; end end endcase end end localparam th_myfunc_21_1 = 1; localparam th_myfunc_21_2 = 2; localparam th_myfunc_21_3 = 3; localparam th_myfunc_21_4 = 4; localparam th_myfunc_21_5 = 5; localparam th_myfunc_21_6 = 6; localparam th_myfunc_21_7 = 7; localparam th_myfunc_21_8 = 8; localparam th_myfunc_21_9 = 9; localparam th_myfunc_21_10 = 10; localparam th_myfunc_21_11 = 11; localparam th_myfunc_21_12 = 12; localparam th_myfunc_21_13 = 13; localparam th_myfunc_21_14 = 14; localparam th_myfunc_21_15 = 15; localparam th_myfunc_21_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_21 <= th_myfunc_21_init; _th_myfunc_21_called <= 0; _th_myfunc_21_tid_107 <= 0; _th_myfunc_21_tid_108 <= 0; _th_myfunc_21_time_109 <= 0; _th_myfunc_21_i_110 <= 0; _th_myfunc_21___111 <= 0; end else begin case(th_myfunc_21) th_myfunc_21_init: begin if(_th_myfunc_start[21] && (th_blink == 10)) begin _th_myfunc_21_called <= 1; end if(_th_myfunc_start[21] && (th_blink == 10)) begin _th_myfunc_21_tid_107 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[21]) begin th_myfunc_21 <= th_myfunc_21_1; end end th_myfunc_21_1: begin _th_myfunc_21_tid_108 <= _th_myfunc_21_tid_107; th_myfunc_21 <= th_myfunc_21_2; end th_myfunc_21_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 21)) begin th_myfunc_21 <= th_myfunc_21_3; end end th_myfunc_21_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 21))) begin th_myfunc_21 <= th_myfunc_21_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 21)) begin th_myfunc_21 <= th_myfunc_21_4; end end th_myfunc_21_4: begin $display("Thread %d Lock", _th_myfunc_21_tid_108); th_myfunc_21 <= th_myfunc_21_5; end th_myfunc_21_5: begin _th_myfunc_21_time_109 <= sw; th_myfunc_21 <= th_myfunc_21_6; end th_myfunc_21_6: begin _th_myfunc_21_i_110 <= 0; th_myfunc_21 <= th_myfunc_21_7; end th_myfunc_21_7: begin if(_th_myfunc_21_i_110 < _th_myfunc_21_time_109) begin th_myfunc_21 <= th_myfunc_21_8; end else begin th_myfunc_21 <= th_myfunc_21_12; end end th_myfunc_21_8: begin _th_myfunc_21___111 <= 0; th_myfunc_21 <= th_myfunc_21_9; end th_myfunc_21_9: begin if(_th_myfunc_21___111 < 1024) begin th_myfunc_21 <= th_myfunc_21_10; end else begin th_myfunc_21 <= th_myfunc_21_11; end end th_myfunc_21_10: begin _th_myfunc_21___111 <= _th_myfunc_21___111 + 1; th_myfunc_21 <= th_myfunc_21_9; end th_myfunc_21_11: begin _th_myfunc_21_i_110 <= _th_myfunc_21_i_110 + 1; th_myfunc_21 <= th_myfunc_21_7; end th_myfunc_21_12: begin th_myfunc_21 <= th_myfunc_21_13; end th_myfunc_21_13: begin $display("Thread %d count = %d", _th_myfunc_21_tid_108, count); th_myfunc_21 <= th_myfunc_21_14; end th_myfunc_21_14: begin th_myfunc_21 <= th_myfunc_21_15; end th_myfunc_21_15: begin $display("Thread %d Unlock", _th_myfunc_21_tid_108); th_myfunc_21 <= th_myfunc_21_16; end th_myfunc_21_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 21)) begin _th_myfunc_21_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 21)) begin th_myfunc_21 <= th_myfunc_21_init; end end endcase end end localparam th_myfunc_22_1 = 1; localparam th_myfunc_22_2 = 2; localparam th_myfunc_22_3 = 3; localparam th_myfunc_22_4 = 4; localparam th_myfunc_22_5 = 5; localparam th_myfunc_22_6 = 6; localparam th_myfunc_22_7 = 7; localparam th_myfunc_22_8 = 8; localparam th_myfunc_22_9 = 9; localparam th_myfunc_22_10 = 10; localparam th_myfunc_22_11 = 11; localparam th_myfunc_22_12 = 12; localparam th_myfunc_22_13 = 13; localparam th_myfunc_22_14 = 14; localparam th_myfunc_22_15 = 15; localparam th_myfunc_22_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_22 <= th_myfunc_22_init; _th_myfunc_22_called <= 0; _th_myfunc_22_tid_112 <= 0; _th_myfunc_22_tid_113 <= 0; _th_myfunc_22_time_114 <= 0; _th_myfunc_22_i_115 <= 0; _th_myfunc_22___116 <= 0; end else begin case(th_myfunc_22) th_myfunc_22_init: begin if(_th_myfunc_start[22] && (th_blink == 10)) begin _th_myfunc_22_called <= 1; end if(_th_myfunc_start[22] && (th_blink == 10)) begin _th_myfunc_22_tid_112 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[22]) begin th_myfunc_22 <= th_myfunc_22_1; end end th_myfunc_22_1: begin _th_myfunc_22_tid_113 <= _th_myfunc_22_tid_112; th_myfunc_22 <= th_myfunc_22_2; end th_myfunc_22_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 22)) begin th_myfunc_22 <= th_myfunc_22_3; end end th_myfunc_22_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 22))) begin th_myfunc_22 <= th_myfunc_22_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 22)) begin th_myfunc_22 <= th_myfunc_22_4; end end th_myfunc_22_4: begin $display("Thread %d Lock", _th_myfunc_22_tid_113); th_myfunc_22 <= th_myfunc_22_5; end th_myfunc_22_5: begin _th_myfunc_22_time_114 <= sw; th_myfunc_22 <= th_myfunc_22_6; end th_myfunc_22_6: begin _th_myfunc_22_i_115 <= 0; th_myfunc_22 <= th_myfunc_22_7; end th_myfunc_22_7: begin if(_th_myfunc_22_i_115 < _th_myfunc_22_time_114) begin th_myfunc_22 <= th_myfunc_22_8; end else begin th_myfunc_22 <= th_myfunc_22_12; end end th_myfunc_22_8: begin _th_myfunc_22___116 <= 0; th_myfunc_22 <= th_myfunc_22_9; end th_myfunc_22_9: begin if(_th_myfunc_22___116 < 1024) begin th_myfunc_22 <= th_myfunc_22_10; end else begin th_myfunc_22 <= th_myfunc_22_11; end end th_myfunc_22_10: begin _th_myfunc_22___116 <= _th_myfunc_22___116 + 1; th_myfunc_22 <= th_myfunc_22_9; end th_myfunc_22_11: begin _th_myfunc_22_i_115 <= _th_myfunc_22_i_115 + 1; th_myfunc_22 <= th_myfunc_22_7; end th_myfunc_22_12: begin th_myfunc_22 <= th_myfunc_22_13; end th_myfunc_22_13: begin $display("Thread %d count = %d", _th_myfunc_22_tid_113, count); th_myfunc_22 <= th_myfunc_22_14; end th_myfunc_22_14: begin th_myfunc_22 <= th_myfunc_22_15; end th_myfunc_22_15: begin $display("Thread %d Unlock", _th_myfunc_22_tid_113); th_myfunc_22 <= th_myfunc_22_16; end th_myfunc_22_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 22)) begin _th_myfunc_22_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 22)) begin th_myfunc_22 <= th_myfunc_22_init; end end endcase end end localparam th_myfunc_23_1 = 1; localparam th_myfunc_23_2 = 2; localparam th_myfunc_23_3 = 3; localparam th_myfunc_23_4 = 4; localparam th_myfunc_23_5 = 5; localparam th_myfunc_23_6 = 6; localparam th_myfunc_23_7 = 7; localparam th_myfunc_23_8 = 8; localparam th_myfunc_23_9 = 9; localparam th_myfunc_23_10 = 10; localparam th_myfunc_23_11 = 11; localparam th_myfunc_23_12 = 12; localparam th_myfunc_23_13 = 13; localparam th_myfunc_23_14 = 14; localparam th_myfunc_23_15 = 15; localparam th_myfunc_23_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_23 <= th_myfunc_23_init; _th_myfunc_23_called <= 0; _th_myfunc_23_tid_117 <= 0; _th_myfunc_23_tid_118 <= 0; _th_myfunc_23_time_119 <= 0; _th_myfunc_23_i_120 <= 0; _th_myfunc_23___121 <= 0; end else begin case(th_myfunc_23) th_myfunc_23_init: begin if(_th_myfunc_start[23] && (th_blink == 10)) begin _th_myfunc_23_called <= 1; end if(_th_myfunc_start[23] && (th_blink == 10)) begin _th_myfunc_23_tid_117 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[23]) begin th_myfunc_23 <= th_myfunc_23_1; end end th_myfunc_23_1: begin _th_myfunc_23_tid_118 <= _th_myfunc_23_tid_117; th_myfunc_23 <= th_myfunc_23_2; end th_myfunc_23_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 23)) begin th_myfunc_23 <= th_myfunc_23_3; end end th_myfunc_23_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 23))) begin th_myfunc_23 <= th_myfunc_23_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 23)) begin th_myfunc_23 <= th_myfunc_23_4; end end th_myfunc_23_4: begin $display("Thread %d Lock", _th_myfunc_23_tid_118); th_myfunc_23 <= th_myfunc_23_5; end th_myfunc_23_5: begin _th_myfunc_23_time_119 <= sw; th_myfunc_23 <= th_myfunc_23_6; end th_myfunc_23_6: begin _th_myfunc_23_i_120 <= 0; th_myfunc_23 <= th_myfunc_23_7; end th_myfunc_23_7: begin if(_th_myfunc_23_i_120 < _th_myfunc_23_time_119) begin th_myfunc_23 <= th_myfunc_23_8; end else begin th_myfunc_23 <= th_myfunc_23_12; end end th_myfunc_23_8: begin _th_myfunc_23___121 <= 0; th_myfunc_23 <= th_myfunc_23_9; end th_myfunc_23_9: begin if(_th_myfunc_23___121 < 1024) begin th_myfunc_23 <= th_myfunc_23_10; end else begin th_myfunc_23 <= th_myfunc_23_11; end end th_myfunc_23_10: begin _th_myfunc_23___121 <= _th_myfunc_23___121 + 1; th_myfunc_23 <= th_myfunc_23_9; end th_myfunc_23_11: begin _th_myfunc_23_i_120 <= _th_myfunc_23_i_120 + 1; th_myfunc_23 <= th_myfunc_23_7; end th_myfunc_23_12: begin th_myfunc_23 <= th_myfunc_23_13; end th_myfunc_23_13: begin $display("Thread %d count = %d", _th_myfunc_23_tid_118, count); th_myfunc_23 <= th_myfunc_23_14; end th_myfunc_23_14: begin th_myfunc_23 <= th_myfunc_23_15; end th_myfunc_23_15: begin $display("Thread %d Unlock", _th_myfunc_23_tid_118); th_myfunc_23 <= th_myfunc_23_16; end th_myfunc_23_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 23)) begin _th_myfunc_23_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 23)) begin th_myfunc_23 <= th_myfunc_23_init; end end endcase end end localparam th_myfunc_24_1 = 1; localparam th_myfunc_24_2 = 2; localparam th_myfunc_24_3 = 3; localparam th_myfunc_24_4 = 4; localparam th_myfunc_24_5 = 5; localparam th_myfunc_24_6 = 6; localparam th_myfunc_24_7 = 7; localparam th_myfunc_24_8 = 8; localparam th_myfunc_24_9 = 9; localparam th_myfunc_24_10 = 10; localparam th_myfunc_24_11 = 11; localparam th_myfunc_24_12 = 12; localparam th_myfunc_24_13 = 13; localparam th_myfunc_24_14 = 14; localparam th_myfunc_24_15 = 15; localparam th_myfunc_24_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_24 <= th_myfunc_24_init; _th_myfunc_24_called <= 0; _th_myfunc_24_tid_122 <= 0; _th_myfunc_24_tid_123 <= 0; _th_myfunc_24_time_124 <= 0; _th_myfunc_24_i_125 <= 0; _th_myfunc_24___126 <= 0; end else begin case(th_myfunc_24) th_myfunc_24_init: begin if(_th_myfunc_start[24] && (th_blink == 10)) begin _th_myfunc_24_called <= 1; end if(_th_myfunc_start[24] && (th_blink == 10)) begin _th_myfunc_24_tid_122 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[24]) begin th_myfunc_24 <= th_myfunc_24_1; end end th_myfunc_24_1: begin _th_myfunc_24_tid_123 <= _th_myfunc_24_tid_122; th_myfunc_24 <= th_myfunc_24_2; end th_myfunc_24_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 24)) begin th_myfunc_24 <= th_myfunc_24_3; end end th_myfunc_24_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 24))) begin th_myfunc_24 <= th_myfunc_24_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 24)) begin th_myfunc_24 <= th_myfunc_24_4; end end th_myfunc_24_4: begin $display("Thread %d Lock", _th_myfunc_24_tid_123); th_myfunc_24 <= th_myfunc_24_5; end th_myfunc_24_5: begin _th_myfunc_24_time_124 <= sw; th_myfunc_24 <= th_myfunc_24_6; end th_myfunc_24_6: begin _th_myfunc_24_i_125 <= 0; th_myfunc_24 <= th_myfunc_24_7; end th_myfunc_24_7: begin if(_th_myfunc_24_i_125 < _th_myfunc_24_time_124) begin th_myfunc_24 <= th_myfunc_24_8; end else begin th_myfunc_24 <= th_myfunc_24_12; end end th_myfunc_24_8: begin _th_myfunc_24___126 <= 0; th_myfunc_24 <= th_myfunc_24_9; end th_myfunc_24_9: begin if(_th_myfunc_24___126 < 1024) begin th_myfunc_24 <= th_myfunc_24_10; end else begin th_myfunc_24 <= th_myfunc_24_11; end end th_myfunc_24_10: begin _th_myfunc_24___126 <= _th_myfunc_24___126 + 1; th_myfunc_24 <= th_myfunc_24_9; end th_myfunc_24_11: begin _th_myfunc_24_i_125 <= _th_myfunc_24_i_125 + 1; th_myfunc_24 <= th_myfunc_24_7; end th_myfunc_24_12: begin th_myfunc_24 <= th_myfunc_24_13; end th_myfunc_24_13: begin $display("Thread %d count = %d", _th_myfunc_24_tid_123, count); th_myfunc_24 <= th_myfunc_24_14; end th_myfunc_24_14: begin th_myfunc_24 <= th_myfunc_24_15; end th_myfunc_24_15: begin $display("Thread %d Unlock", _th_myfunc_24_tid_123); th_myfunc_24 <= th_myfunc_24_16; end th_myfunc_24_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 24)) begin _th_myfunc_24_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 24)) begin th_myfunc_24 <= th_myfunc_24_init; end end endcase end end localparam th_myfunc_25_1 = 1; localparam th_myfunc_25_2 = 2; localparam th_myfunc_25_3 = 3; localparam th_myfunc_25_4 = 4; localparam th_myfunc_25_5 = 5; localparam th_myfunc_25_6 = 6; localparam th_myfunc_25_7 = 7; localparam th_myfunc_25_8 = 8; localparam th_myfunc_25_9 = 9; localparam th_myfunc_25_10 = 10; localparam th_myfunc_25_11 = 11; localparam th_myfunc_25_12 = 12; localparam th_myfunc_25_13 = 13; localparam th_myfunc_25_14 = 14; localparam th_myfunc_25_15 = 15; localparam th_myfunc_25_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_25 <= th_myfunc_25_init; _th_myfunc_25_called <= 0; _th_myfunc_25_tid_127 <= 0; _th_myfunc_25_tid_128 <= 0; _th_myfunc_25_time_129 <= 0; _th_myfunc_25_i_130 <= 0; _th_myfunc_25___131 <= 0; end else begin case(th_myfunc_25) th_myfunc_25_init: begin if(_th_myfunc_start[25] && (th_blink == 10)) begin _th_myfunc_25_called <= 1; end if(_th_myfunc_start[25] && (th_blink == 10)) begin _th_myfunc_25_tid_127 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[25]) begin th_myfunc_25 <= th_myfunc_25_1; end end th_myfunc_25_1: begin _th_myfunc_25_tid_128 <= _th_myfunc_25_tid_127; th_myfunc_25 <= th_myfunc_25_2; end th_myfunc_25_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 25)) begin th_myfunc_25 <= th_myfunc_25_3; end end th_myfunc_25_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 25))) begin th_myfunc_25 <= th_myfunc_25_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 25)) begin th_myfunc_25 <= th_myfunc_25_4; end end th_myfunc_25_4: begin $display("Thread %d Lock", _th_myfunc_25_tid_128); th_myfunc_25 <= th_myfunc_25_5; end th_myfunc_25_5: begin _th_myfunc_25_time_129 <= sw; th_myfunc_25 <= th_myfunc_25_6; end th_myfunc_25_6: begin _th_myfunc_25_i_130 <= 0; th_myfunc_25 <= th_myfunc_25_7; end th_myfunc_25_7: begin if(_th_myfunc_25_i_130 < _th_myfunc_25_time_129) begin th_myfunc_25 <= th_myfunc_25_8; end else begin th_myfunc_25 <= th_myfunc_25_12; end end th_myfunc_25_8: begin _th_myfunc_25___131 <= 0; th_myfunc_25 <= th_myfunc_25_9; end th_myfunc_25_9: begin if(_th_myfunc_25___131 < 1024) begin th_myfunc_25 <= th_myfunc_25_10; end else begin th_myfunc_25 <= th_myfunc_25_11; end end th_myfunc_25_10: begin _th_myfunc_25___131 <= _th_myfunc_25___131 + 1; th_myfunc_25 <= th_myfunc_25_9; end th_myfunc_25_11: begin _th_myfunc_25_i_130 <= _th_myfunc_25_i_130 + 1; th_myfunc_25 <= th_myfunc_25_7; end th_myfunc_25_12: begin th_myfunc_25 <= th_myfunc_25_13; end th_myfunc_25_13: begin $display("Thread %d count = %d", _th_myfunc_25_tid_128, count); th_myfunc_25 <= th_myfunc_25_14; end th_myfunc_25_14: begin th_myfunc_25 <= th_myfunc_25_15; end th_myfunc_25_15: begin $display("Thread %d Unlock", _th_myfunc_25_tid_128); th_myfunc_25 <= th_myfunc_25_16; end th_myfunc_25_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 25)) begin _th_myfunc_25_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 25)) begin th_myfunc_25 <= th_myfunc_25_init; end end endcase end end localparam th_myfunc_26_1 = 1; localparam th_myfunc_26_2 = 2; localparam th_myfunc_26_3 = 3; localparam th_myfunc_26_4 = 4; localparam th_myfunc_26_5 = 5; localparam th_myfunc_26_6 = 6; localparam th_myfunc_26_7 = 7; localparam th_myfunc_26_8 = 8; localparam th_myfunc_26_9 = 9; localparam th_myfunc_26_10 = 10; localparam th_myfunc_26_11 = 11; localparam th_myfunc_26_12 = 12; localparam th_myfunc_26_13 = 13; localparam th_myfunc_26_14 = 14; localparam th_myfunc_26_15 = 15; localparam th_myfunc_26_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_26 <= th_myfunc_26_init; _th_myfunc_26_called <= 0; _th_myfunc_26_tid_132 <= 0; _th_myfunc_26_tid_133 <= 0; _th_myfunc_26_time_134 <= 0; _th_myfunc_26_i_135 <= 0; _th_myfunc_26___136 <= 0; end else begin case(th_myfunc_26) th_myfunc_26_init: begin if(_th_myfunc_start[26] && (th_blink == 10)) begin _th_myfunc_26_called <= 1; end if(_th_myfunc_start[26] && (th_blink == 10)) begin _th_myfunc_26_tid_132 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[26]) begin th_myfunc_26 <= th_myfunc_26_1; end end th_myfunc_26_1: begin _th_myfunc_26_tid_133 <= _th_myfunc_26_tid_132; th_myfunc_26 <= th_myfunc_26_2; end th_myfunc_26_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 26)) begin th_myfunc_26 <= th_myfunc_26_3; end end th_myfunc_26_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 26))) begin th_myfunc_26 <= th_myfunc_26_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 26)) begin th_myfunc_26 <= th_myfunc_26_4; end end th_myfunc_26_4: begin $display("Thread %d Lock", _th_myfunc_26_tid_133); th_myfunc_26 <= th_myfunc_26_5; end th_myfunc_26_5: begin _th_myfunc_26_time_134 <= sw; th_myfunc_26 <= th_myfunc_26_6; end th_myfunc_26_6: begin _th_myfunc_26_i_135 <= 0; th_myfunc_26 <= th_myfunc_26_7; end th_myfunc_26_7: begin if(_th_myfunc_26_i_135 < _th_myfunc_26_time_134) begin th_myfunc_26 <= th_myfunc_26_8; end else begin th_myfunc_26 <= th_myfunc_26_12; end end th_myfunc_26_8: begin _th_myfunc_26___136 <= 0; th_myfunc_26 <= th_myfunc_26_9; end th_myfunc_26_9: begin if(_th_myfunc_26___136 < 1024) begin th_myfunc_26 <= th_myfunc_26_10; end else begin th_myfunc_26 <= th_myfunc_26_11; end end th_myfunc_26_10: begin _th_myfunc_26___136 <= _th_myfunc_26___136 + 1; th_myfunc_26 <= th_myfunc_26_9; end th_myfunc_26_11: begin _th_myfunc_26_i_135 <= _th_myfunc_26_i_135 + 1; th_myfunc_26 <= th_myfunc_26_7; end th_myfunc_26_12: begin th_myfunc_26 <= th_myfunc_26_13; end th_myfunc_26_13: begin $display("Thread %d count = %d", _th_myfunc_26_tid_133, count); th_myfunc_26 <= th_myfunc_26_14; end th_myfunc_26_14: begin th_myfunc_26 <= th_myfunc_26_15; end th_myfunc_26_15: begin $display("Thread %d Unlock", _th_myfunc_26_tid_133); th_myfunc_26 <= th_myfunc_26_16; end th_myfunc_26_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 26)) begin _th_myfunc_26_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 26)) begin th_myfunc_26 <= th_myfunc_26_init; end end endcase end end localparam th_myfunc_27_1 = 1; localparam th_myfunc_27_2 = 2; localparam th_myfunc_27_3 = 3; localparam th_myfunc_27_4 = 4; localparam th_myfunc_27_5 = 5; localparam th_myfunc_27_6 = 6; localparam th_myfunc_27_7 = 7; localparam th_myfunc_27_8 = 8; localparam th_myfunc_27_9 = 9; localparam th_myfunc_27_10 = 10; localparam th_myfunc_27_11 = 11; localparam th_myfunc_27_12 = 12; localparam th_myfunc_27_13 = 13; localparam th_myfunc_27_14 = 14; localparam th_myfunc_27_15 = 15; localparam th_myfunc_27_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_27 <= th_myfunc_27_init; _th_myfunc_27_called <= 0; _th_myfunc_27_tid_137 <= 0; _th_myfunc_27_tid_138 <= 0; _th_myfunc_27_time_139 <= 0; _th_myfunc_27_i_140 <= 0; _th_myfunc_27___141 <= 0; end else begin case(th_myfunc_27) th_myfunc_27_init: begin if(_th_myfunc_start[27] && (th_blink == 10)) begin _th_myfunc_27_called <= 1; end if(_th_myfunc_start[27] && (th_blink == 10)) begin _th_myfunc_27_tid_137 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[27]) begin th_myfunc_27 <= th_myfunc_27_1; end end th_myfunc_27_1: begin _th_myfunc_27_tid_138 <= _th_myfunc_27_tid_137; th_myfunc_27 <= th_myfunc_27_2; end th_myfunc_27_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 27)) begin th_myfunc_27 <= th_myfunc_27_3; end end th_myfunc_27_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 27))) begin th_myfunc_27 <= th_myfunc_27_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 27)) begin th_myfunc_27 <= th_myfunc_27_4; end end th_myfunc_27_4: begin $display("Thread %d Lock", _th_myfunc_27_tid_138); th_myfunc_27 <= th_myfunc_27_5; end th_myfunc_27_5: begin _th_myfunc_27_time_139 <= sw; th_myfunc_27 <= th_myfunc_27_6; end th_myfunc_27_6: begin _th_myfunc_27_i_140 <= 0; th_myfunc_27 <= th_myfunc_27_7; end th_myfunc_27_7: begin if(_th_myfunc_27_i_140 < _th_myfunc_27_time_139) begin th_myfunc_27 <= th_myfunc_27_8; end else begin th_myfunc_27 <= th_myfunc_27_12; end end th_myfunc_27_8: begin _th_myfunc_27___141 <= 0; th_myfunc_27 <= th_myfunc_27_9; end th_myfunc_27_9: begin if(_th_myfunc_27___141 < 1024) begin th_myfunc_27 <= th_myfunc_27_10; end else begin th_myfunc_27 <= th_myfunc_27_11; end end th_myfunc_27_10: begin _th_myfunc_27___141 <= _th_myfunc_27___141 + 1; th_myfunc_27 <= th_myfunc_27_9; end th_myfunc_27_11: begin _th_myfunc_27_i_140 <= _th_myfunc_27_i_140 + 1; th_myfunc_27 <= th_myfunc_27_7; end th_myfunc_27_12: begin th_myfunc_27 <= th_myfunc_27_13; end th_myfunc_27_13: begin $display("Thread %d count = %d", _th_myfunc_27_tid_138, count); th_myfunc_27 <= th_myfunc_27_14; end th_myfunc_27_14: begin th_myfunc_27 <= th_myfunc_27_15; end th_myfunc_27_15: begin $display("Thread %d Unlock", _th_myfunc_27_tid_138); th_myfunc_27 <= th_myfunc_27_16; end th_myfunc_27_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 27)) begin _th_myfunc_27_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 27)) begin th_myfunc_27 <= th_myfunc_27_init; end end endcase end end localparam th_myfunc_28_1 = 1; localparam th_myfunc_28_2 = 2; localparam th_myfunc_28_3 = 3; localparam th_myfunc_28_4 = 4; localparam th_myfunc_28_5 = 5; localparam th_myfunc_28_6 = 6; localparam th_myfunc_28_7 = 7; localparam th_myfunc_28_8 = 8; localparam th_myfunc_28_9 = 9; localparam th_myfunc_28_10 = 10; localparam th_myfunc_28_11 = 11; localparam th_myfunc_28_12 = 12; localparam th_myfunc_28_13 = 13; localparam th_myfunc_28_14 = 14; localparam th_myfunc_28_15 = 15; localparam th_myfunc_28_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_28 <= th_myfunc_28_init; _th_myfunc_28_called <= 0; _th_myfunc_28_tid_142 <= 0; _th_myfunc_28_tid_143 <= 0; _th_myfunc_28_time_144 <= 0; _th_myfunc_28_i_145 <= 0; _th_myfunc_28___146 <= 0; end else begin case(th_myfunc_28) th_myfunc_28_init: begin if(_th_myfunc_start[28] && (th_blink == 10)) begin _th_myfunc_28_called <= 1; end if(_th_myfunc_start[28] && (th_blink == 10)) begin _th_myfunc_28_tid_142 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[28]) begin th_myfunc_28 <= th_myfunc_28_1; end end th_myfunc_28_1: begin _th_myfunc_28_tid_143 <= _th_myfunc_28_tid_142; th_myfunc_28 <= th_myfunc_28_2; end th_myfunc_28_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 28)) begin th_myfunc_28 <= th_myfunc_28_3; end end th_myfunc_28_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 28))) begin th_myfunc_28 <= th_myfunc_28_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 28)) begin th_myfunc_28 <= th_myfunc_28_4; end end th_myfunc_28_4: begin $display("Thread %d Lock", _th_myfunc_28_tid_143); th_myfunc_28 <= th_myfunc_28_5; end th_myfunc_28_5: begin _th_myfunc_28_time_144 <= sw; th_myfunc_28 <= th_myfunc_28_6; end th_myfunc_28_6: begin _th_myfunc_28_i_145 <= 0; th_myfunc_28 <= th_myfunc_28_7; end th_myfunc_28_7: begin if(_th_myfunc_28_i_145 < _th_myfunc_28_time_144) begin th_myfunc_28 <= th_myfunc_28_8; end else begin th_myfunc_28 <= th_myfunc_28_12; end end th_myfunc_28_8: begin _th_myfunc_28___146 <= 0; th_myfunc_28 <= th_myfunc_28_9; end th_myfunc_28_9: begin if(_th_myfunc_28___146 < 1024) begin th_myfunc_28 <= th_myfunc_28_10; end else begin th_myfunc_28 <= th_myfunc_28_11; end end th_myfunc_28_10: begin _th_myfunc_28___146 <= _th_myfunc_28___146 + 1; th_myfunc_28 <= th_myfunc_28_9; end th_myfunc_28_11: begin _th_myfunc_28_i_145 <= _th_myfunc_28_i_145 + 1; th_myfunc_28 <= th_myfunc_28_7; end th_myfunc_28_12: begin th_myfunc_28 <= th_myfunc_28_13; end th_myfunc_28_13: begin $display("Thread %d count = %d", _th_myfunc_28_tid_143, count); th_myfunc_28 <= th_myfunc_28_14; end th_myfunc_28_14: begin th_myfunc_28 <= th_myfunc_28_15; end th_myfunc_28_15: begin $display("Thread %d Unlock", _th_myfunc_28_tid_143); th_myfunc_28 <= th_myfunc_28_16; end th_myfunc_28_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 28)) begin _th_myfunc_28_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 28)) begin th_myfunc_28 <= th_myfunc_28_init; end end endcase end end localparam th_myfunc_29_1 = 1; localparam th_myfunc_29_2 = 2; localparam th_myfunc_29_3 = 3; localparam th_myfunc_29_4 = 4; localparam th_myfunc_29_5 = 5; localparam th_myfunc_29_6 = 6; localparam th_myfunc_29_7 = 7; localparam th_myfunc_29_8 = 8; localparam th_myfunc_29_9 = 9; localparam th_myfunc_29_10 = 10; localparam th_myfunc_29_11 = 11; localparam th_myfunc_29_12 = 12; localparam th_myfunc_29_13 = 13; localparam th_myfunc_29_14 = 14; localparam th_myfunc_29_15 = 15; localparam th_myfunc_29_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_29 <= th_myfunc_29_init; _th_myfunc_29_called <= 0; _th_myfunc_29_tid_147 <= 0; _th_myfunc_29_tid_148 <= 0; _th_myfunc_29_time_149 <= 0; _th_myfunc_29_i_150 <= 0; _th_myfunc_29___151 <= 0; end else begin case(th_myfunc_29) th_myfunc_29_init: begin if(_th_myfunc_start[29] && (th_blink == 10)) begin _th_myfunc_29_called <= 1; end if(_th_myfunc_start[29] && (th_blink == 10)) begin _th_myfunc_29_tid_147 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[29]) begin th_myfunc_29 <= th_myfunc_29_1; end end th_myfunc_29_1: begin _th_myfunc_29_tid_148 <= _th_myfunc_29_tid_147; th_myfunc_29 <= th_myfunc_29_2; end th_myfunc_29_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 29)) begin th_myfunc_29 <= th_myfunc_29_3; end end th_myfunc_29_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 29))) begin th_myfunc_29 <= th_myfunc_29_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 29)) begin th_myfunc_29 <= th_myfunc_29_4; end end th_myfunc_29_4: begin $display("Thread %d Lock", _th_myfunc_29_tid_148); th_myfunc_29 <= th_myfunc_29_5; end th_myfunc_29_5: begin _th_myfunc_29_time_149 <= sw; th_myfunc_29 <= th_myfunc_29_6; end th_myfunc_29_6: begin _th_myfunc_29_i_150 <= 0; th_myfunc_29 <= th_myfunc_29_7; end th_myfunc_29_7: begin if(_th_myfunc_29_i_150 < _th_myfunc_29_time_149) begin th_myfunc_29 <= th_myfunc_29_8; end else begin th_myfunc_29 <= th_myfunc_29_12; end end th_myfunc_29_8: begin _th_myfunc_29___151 <= 0; th_myfunc_29 <= th_myfunc_29_9; end th_myfunc_29_9: begin if(_th_myfunc_29___151 < 1024) begin th_myfunc_29 <= th_myfunc_29_10; end else begin th_myfunc_29 <= th_myfunc_29_11; end end th_myfunc_29_10: begin _th_myfunc_29___151 <= _th_myfunc_29___151 + 1; th_myfunc_29 <= th_myfunc_29_9; end th_myfunc_29_11: begin _th_myfunc_29_i_150 <= _th_myfunc_29_i_150 + 1; th_myfunc_29 <= th_myfunc_29_7; end th_myfunc_29_12: begin th_myfunc_29 <= th_myfunc_29_13; end th_myfunc_29_13: begin $display("Thread %d count = %d", _th_myfunc_29_tid_148, count); th_myfunc_29 <= th_myfunc_29_14; end th_myfunc_29_14: begin th_myfunc_29 <= th_myfunc_29_15; end th_myfunc_29_15: begin $display("Thread %d Unlock", _th_myfunc_29_tid_148); th_myfunc_29 <= th_myfunc_29_16; end th_myfunc_29_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 29)) begin _th_myfunc_29_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 29)) begin th_myfunc_29 <= th_myfunc_29_init; end end endcase end end localparam th_myfunc_30_1 = 1; localparam th_myfunc_30_2 = 2; localparam th_myfunc_30_3 = 3; localparam th_myfunc_30_4 = 4; localparam th_myfunc_30_5 = 5; localparam th_myfunc_30_6 = 6; localparam th_myfunc_30_7 = 7; localparam th_myfunc_30_8 = 8; localparam th_myfunc_30_9 = 9; localparam th_myfunc_30_10 = 10; localparam th_myfunc_30_11 = 11; localparam th_myfunc_30_12 = 12; localparam th_myfunc_30_13 = 13; localparam th_myfunc_30_14 = 14; localparam th_myfunc_30_15 = 15; localparam th_myfunc_30_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_30 <= th_myfunc_30_init; _th_myfunc_30_called <= 0; _th_myfunc_30_tid_152 <= 0; _th_myfunc_30_tid_153 <= 0; _th_myfunc_30_time_154 <= 0; _th_myfunc_30_i_155 <= 0; _th_myfunc_30___156 <= 0; end else begin case(th_myfunc_30) th_myfunc_30_init: begin if(_th_myfunc_start[30] && (th_blink == 10)) begin _th_myfunc_30_called <= 1; end if(_th_myfunc_start[30] && (th_blink == 10)) begin _th_myfunc_30_tid_152 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[30]) begin th_myfunc_30 <= th_myfunc_30_1; end end th_myfunc_30_1: begin _th_myfunc_30_tid_153 <= _th_myfunc_30_tid_152; th_myfunc_30 <= th_myfunc_30_2; end th_myfunc_30_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 30)) begin th_myfunc_30 <= th_myfunc_30_3; end end th_myfunc_30_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 30))) begin th_myfunc_30 <= th_myfunc_30_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 30)) begin th_myfunc_30 <= th_myfunc_30_4; end end th_myfunc_30_4: begin $display("Thread %d Lock", _th_myfunc_30_tid_153); th_myfunc_30 <= th_myfunc_30_5; end th_myfunc_30_5: begin _th_myfunc_30_time_154 <= sw; th_myfunc_30 <= th_myfunc_30_6; end th_myfunc_30_6: begin _th_myfunc_30_i_155 <= 0; th_myfunc_30 <= th_myfunc_30_7; end th_myfunc_30_7: begin if(_th_myfunc_30_i_155 < _th_myfunc_30_time_154) begin th_myfunc_30 <= th_myfunc_30_8; end else begin th_myfunc_30 <= th_myfunc_30_12; end end th_myfunc_30_8: begin _th_myfunc_30___156 <= 0; th_myfunc_30 <= th_myfunc_30_9; end th_myfunc_30_9: begin if(_th_myfunc_30___156 < 1024) begin th_myfunc_30 <= th_myfunc_30_10; end else begin th_myfunc_30 <= th_myfunc_30_11; end end th_myfunc_30_10: begin _th_myfunc_30___156 <= _th_myfunc_30___156 + 1; th_myfunc_30 <= th_myfunc_30_9; end th_myfunc_30_11: begin _th_myfunc_30_i_155 <= _th_myfunc_30_i_155 + 1; th_myfunc_30 <= th_myfunc_30_7; end th_myfunc_30_12: begin th_myfunc_30 <= th_myfunc_30_13; end th_myfunc_30_13: begin $display("Thread %d count = %d", _th_myfunc_30_tid_153, count); th_myfunc_30 <= th_myfunc_30_14; end th_myfunc_30_14: begin th_myfunc_30 <= th_myfunc_30_15; end th_myfunc_30_15: begin $display("Thread %d Unlock", _th_myfunc_30_tid_153); th_myfunc_30 <= th_myfunc_30_16; end th_myfunc_30_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 30)) begin _th_myfunc_30_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 30)) begin th_myfunc_30 <= th_myfunc_30_init; end end endcase end end localparam th_myfunc_31_1 = 1; localparam th_myfunc_31_2 = 2; localparam th_myfunc_31_3 = 3; localparam th_myfunc_31_4 = 4; localparam th_myfunc_31_5 = 5; localparam th_myfunc_31_6 = 6; localparam th_myfunc_31_7 = 7; localparam th_myfunc_31_8 = 8; localparam th_myfunc_31_9 = 9; localparam th_myfunc_31_10 = 10; localparam th_myfunc_31_11 = 11; localparam th_myfunc_31_12 = 12; localparam th_myfunc_31_13 = 13; localparam th_myfunc_31_14 = 14; localparam th_myfunc_31_15 = 15; localparam th_myfunc_31_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_31 <= th_myfunc_31_init; _th_myfunc_31_called <= 0; _th_myfunc_31_tid_157 <= 0; _th_myfunc_31_tid_158 <= 0; _th_myfunc_31_time_159 <= 0; _th_myfunc_31_i_160 <= 0; _th_myfunc_31___161 <= 0; end else begin case(th_myfunc_31) th_myfunc_31_init: begin if(_th_myfunc_start[31] && (th_blink == 10)) begin _th_myfunc_31_called <= 1; end if(_th_myfunc_start[31] && (th_blink == 10)) begin _th_myfunc_31_tid_157 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[31]) begin th_myfunc_31 <= th_myfunc_31_1; end end th_myfunc_31_1: begin _th_myfunc_31_tid_158 <= _th_myfunc_31_tid_157; th_myfunc_31 <= th_myfunc_31_2; end th_myfunc_31_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 31)) begin th_myfunc_31 <= th_myfunc_31_3; end end th_myfunc_31_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 31))) begin th_myfunc_31 <= th_myfunc_31_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 31)) begin th_myfunc_31 <= th_myfunc_31_4; end end th_myfunc_31_4: begin $display("Thread %d Lock", _th_myfunc_31_tid_158); th_myfunc_31 <= th_myfunc_31_5; end th_myfunc_31_5: begin _th_myfunc_31_time_159 <= sw; th_myfunc_31 <= th_myfunc_31_6; end th_myfunc_31_6: begin _th_myfunc_31_i_160 <= 0; th_myfunc_31 <= th_myfunc_31_7; end th_myfunc_31_7: begin if(_th_myfunc_31_i_160 < _th_myfunc_31_time_159) begin th_myfunc_31 <= th_myfunc_31_8; end else begin th_myfunc_31 <= th_myfunc_31_12; end end th_myfunc_31_8: begin _th_myfunc_31___161 <= 0; th_myfunc_31 <= th_myfunc_31_9; end th_myfunc_31_9: begin if(_th_myfunc_31___161 < 1024) begin th_myfunc_31 <= th_myfunc_31_10; end else begin th_myfunc_31 <= th_myfunc_31_11; end end th_myfunc_31_10: begin _th_myfunc_31___161 <= _th_myfunc_31___161 + 1; th_myfunc_31 <= th_myfunc_31_9; end th_myfunc_31_11: begin _th_myfunc_31_i_160 <= _th_myfunc_31_i_160 + 1; th_myfunc_31 <= th_myfunc_31_7; end th_myfunc_31_12: begin th_myfunc_31 <= th_myfunc_31_13; end th_myfunc_31_13: begin $display("Thread %d count = %d", _th_myfunc_31_tid_158, count); th_myfunc_31 <= th_myfunc_31_14; end th_myfunc_31_14: begin th_myfunc_31 <= th_myfunc_31_15; end th_myfunc_31_15: begin $display("Thread %d Unlock", _th_myfunc_31_tid_158); th_myfunc_31 <= th_myfunc_31_16; end th_myfunc_31_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 31)) begin _th_myfunc_31_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 31)) begin th_myfunc_31 <= th_myfunc_31_init; end end endcase end end localparam th_myfunc_32_1 = 1; localparam th_myfunc_32_2 = 2; localparam th_myfunc_32_3 = 3; localparam th_myfunc_32_4 = 4; localparam th_myfunc_32_5 = 5; localparam th_myfunc_32_6 = 6; localparam th_myfunc_32_7 = 7; localparam th_myfunc_32_8 = 8; localparam th_myfunc_32_9 = 9; localparam th_myfunc_32_10 = 10; localparam th_myfunc_32_11 = 11; localparam th_myfunc_32_12 = 12; localparam th_myfunc_32_13 = 13; localparam th_myfunc_32_14 = 14; localparam th_myfunc_32_15 = 15; localparam th_myfunc_32_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_32 <= th_myfunc_32_init; _th_myfunc_32_called <= 0; _th_myfunc_32_tid_162 <= 0; _th_myfunc_32_tid_163 <= 0; _th_myfunc_32_time_164 <= 0; _th_myfunc_32_i_165 <= 0; _th_myfunc_32___166 <= 0; end else begin case(th_myfunc_32) th_myfunc_32_init: begin if(_th_myfunc_start[32] && (th_blink == 10)) begin _th_myfunc_32_called <= 1; end if(_th_myfunc_start[32] && (th_blink == 10)) begin _th_myfunc_32_tid_162 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[32]) begin th_myfunc_32 <= th_myfunc_32_1; end end th_myfunc_32_1: begin _th_myfunc_32_tid_163 <= _th_myfunc_32_tid_162; th_myfunc_32 <= th_myfunc_32_2; end th_myfunc_32_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 32)) begin th_myfunc_32 <= th_myfunc_32_3; end end th_myfunc_32_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 32))) begin th_myfunc_32 <= th_myfunc_32_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 32)) begin th_myfunc_32 <= th_myfunc_32_4; end end th_myfunc_32_4: begin $display("Thread %d Lock", _th_myfunc_32_tid_163); th_myfunc_32 <= th_myfunc_32_5; end th_myfunc_32_5: begin _th_myfunc_32_time_164 <= sw; th_myfunc_32 <= th_myfunc_32_6; end th_myfunc_32_6: begin _th_myfunc_32_i_165 <= 0; th_myfunc_32 <= th_myfunc_32_7; end th_myfunc_32_7: begin if(_th_myfunc_32_i_165 < _th_myfunc_32_time_164) begin th_myfunc_32 <= th_myfunc_32_8; end else begin th_myfunc_32 <= th_myfunc_32_12; end end th_myfunc_32_8: begin _th_myfunc_32___166 <= 0; th_myfunc_32 <= th_myfunc_32_9; end th_myfunc_32_9: begin if(_th_myfunc_32___166 < 1024) begin th_myfunc_32 <= th_myfunc_32_10; end else begin th_myfunc_32 <= th_myfunc_32_11; end end th_myfunc_32_10: begin _th_myfunc_32___166 <= _th_myfunc_32___166 + 1; th_myfunc_32 <= th_myfunc_32_9; end th_myfunc_32_11: begin _th_myfunc_32_i_165 <= _th_myfunc_32_i_165 + 1; th_myfunc_32 <= th_myfunc_32_7; end th_myfunc_32_12: begin th_myfunc_32 <= th_myfunc_32_13; end th_myfunc_32_13: begin $display("Thread %d count = %d", _th_myfunc_32_tid_163, count); th_myfunc_32 <= th_myfunc_32_14; end th_myfunc_32_14: begin th_myfunc_32 <= th_myfunc_32_15; end th_myfunc_32_15: begin $display("Thread %d Unlock", _th_myfunc_32_tid_163); th_myfunc_32 <= th_myfunc_32_16; end th_myfunc_32_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 32)) begin _th_myfunc_32_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 32)) begin th_myfunc_32 <= th_myfunc_32_init; end end endcase end end localparam th_myfunc_33_1 = 1; localparam th_myfunc_33_2 = 2; localparam th_myfunc_33_3 = 3; localparam th_myfunc_33_4 = 4; localparam th_myfunc_33_5 = 5; localparam th_myfunc_33_6 = 6; localparam th_myfunc_33_7 = 7; localparam th_myfunc_33_8 = 8; localparam th_myfunc_33_9 = 9; localparam th_myfunc_33_10 = 10; localparam th_myfunc_33_11 = 11; localparam th_myfunc_33_12 = 12; localparam th_myfunc_33_13 = 13; localparam th_myfunc_33_14 = 14; localparam th_myfunc_33_15 = 15; localparam th_myfunc_33_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_33 <= th_myfunc_33_init; _th_myfunc_33_called <= 0; _th_myfunc_33_tid_167 <= 0; _th_myfunc_33_tid_168 <= 0; _th_myfunc_33_time_169 <= 0; _th_myfunc_33_i_170 <= 0; _th_myfunc_33___171 <= 0; end else begin case(th_myfunc_33) th_myfunc_33_init: begin if(_th_myfunc_start[33] && (th_blink == 10)) begin _th_myfunc_33_called <= 1; end if(_th_myfunc_start[33] && (th_blink == 10)) begin _th_myfunc_33_tid_167 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[33]) begin th_myfunc_33 <= th_myfunc_33_1; end end th_myfunc_33_1: begin _th_myfunc_33_tid_168 <= _th_myfunc_33_tid_167; th_myfunc_33 <= th_myfunc_33_2; end th_myfunc_33_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 33)) begin th_myfunc_33 <= th_myfunc_33_3; end end th_myfunc_33_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 33))) begin th_myfunc_33 <= th_myfunc_33_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 33)) begin th_myfunc_33 <= th_myfunc_33_4; end end th_myfunc_33_4: begin $display("Thread %d Lock", _th_myfunc_33_tid_168); th_myfunc_33 <= th_myfunc_33_5; end th_myfunc_33_5: begin _th_myfunc_33_time_169 <= sw; th_myfunc_33 <= th_myfunc_33_6; end th_myfunc_33_6: begin _th_myfunc_33_i_170 <= 0; th_myfunc_33 <= th_myfunc_33_7; end th_myfunc_33_7: begin if(_th_myfunc_33_i_170 < _th_myfunc_33_time_169) begin th_myfunc_33 <= th_myfunc_33_8; end else begin th_myfunc_33 <= th_myfunc_33_12; end end th_myfunc_33_8: begin _th_myfunc_33___171 <= 0; th_myfunc_33 <= th_myfunc_33_9; end th_myfunc_33_9: begin if(_th_myfunc_33___171 < 1024) begin th_myfunc_33 <= th_myfunc_33_10; end else begin th_myfunc_33 <= th_myfunc_33_11; end end th_myfunc_33_10: begin _th_myfunc_33___171 <= _th_myfunc_33___171 + 1; th_myfunc_33 <= th_myfunc_33_9; end th_myfunc_33_11: begin _th_myfunc_33_i_170 <= _th_myfunc_33_i_170 + 1; th_myfunc_33 <= th_myfunc_33_7; end th_myfunc_33_12: begin th_myfunc_33 <= th_myfunc_33_13; end th_myfunc_33_13: begin $display("Thread %d count = %d", _th_myfunc_33_tid_168, count); th_myfunc_33 <= th_myfunc_33_14; end th_myfunc_33_14: begin th_myfunc_33 <= th_myfunc_33_15; end th_myfunc_33_15: begin $display("Thread %d Unlock", _th_myfunc_33_tid_168); th_myfunc_33 <= th_myfunc_33_16; end th_myfunc_33_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 33)) begin _th_myfunc_33_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 33)) begin th_myfunc_33 <= th_myfunc_33_init; end end endcase end end localparam th_myfunc_34_1 = 1; localparam th_myfunc_34_2 = 2; localparam th_myfunc_34_3 = 3; localparam th_myfunc_34_4 = 4; localparam th_myfunc_34_5 = 5; localparam th_myfunc_34_6 = 6; localparam th_myfunc_34_7 = 7; localparam th_myfunc_34_8 = 8; localparam th_myfunc_34_9 = 9; localparam th_myfunc_34_10 = 10; localparam th_myfunc_34_11 = 11; localparam th_myfunc_34_12 = 12; localparam th_myfunc_34_13 = 13; localparam th_myfunc_34_14 = 14; localparam th_myfunc_34_15 = 15; localparam th_myfunc_34_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_34 <= th_myfunc_34_init; _th_myfunc_34_called <= 0; _th_myfunc_34_tid_172 <= 0; _th_myfunc_34_tid_173 <= 0; _th_myfunc_34_time_174 <= 0; _th_myfunc_34_i_175 <= 0; _th_myfunc_34___176 <= 0; end else begin case(th_myfunc_34) th_myfunc_34_init: begin if(_th_myfunc_start[34] && (th_blink == 10)) begin _th_myfunc_34_called <= 1; end if(_th_myfunc_start[34] && (th_blink == 10)) begin _th_myfunc_34_tid_172 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[34]) begin th_myfunc_34 <= th_myfunc_34_1; end end th_myfunc_34_1: begin _th_myfunc_34_tid_173 <= _th_myfunc_34_tid_172; th_myfunc_34 <= th_myfunc_34_2; end th_myfunc_34_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 34)) begin th_myfunc_34 <= th_myfunc_34_3; end end th_myfunc_34_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 34))) begin th_myfunc_34 <= th_myfunc_34_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 34)) begin th_myfunc_34 <= th_myfunc_34_4; end end th_myfunc_34_4: begin $display("Thread %d Lock", _th_myfunc_34_tid_173); th_myfunc_34 <= th_myfunc_34_5; end th_myfunc_34_5: begin _th_myfunc_34_time_174 <= sw; th_myfunc_34 <= th_myfunc_34_6; end th_myfunc_34_6: begin _th_myfunc_34_i_175 <= 0; th_myfunc_34 <= th_myfunc_34_7; end th_myfunc_34_7: begin if(_th_myfunc_34_i_175 < _th_myfunc_34_time_174) begin th_myfunc_34 <= th_myfunc_34_8; end else begin th_myfunc_34 <= th_myfunc_34_12; end end th_myfunc_34_8: begin _th_myfunc_34___176 <= 0; th_myfunc_34 <= th_myfunc_34_9; end th_myfunc_34_9: begin if(_th_myfunc_34___176 < 1024) begin th_myfunc_34 <= th_myfunc_34_10; end else begin th_myfunc_34 <= th_myfunc_34_11; end end th_myfunc_34_10: begin _th_myfunc_34___176 <= _th_myfunc_34___176 + 1; th_myfunc_34 <= th_myfunc_34_9; end th_myfunc_34_11: begin _th_myfunc_34_i_175 <= _th_myfunc_34_i_175 + 1; th_myfunc_34 <= th_myfunc_34_7; end th_myfunc_34_12: begin th_myfunc_34 <= th_myfunc_34_13; end th_myfunc_34_13: begin $display("Thread %d count = %d", _th_myfunc_34_tid_173, count); th_myfunc_34 <= th_myfunc_34_14; end th_myfunc_34_14: begin th_myfunc_34 <= th_myfunc_34_15; end th_myfunc_34_15: begin $display("Thread %d Unlock", _th_myfunc_34_tid_173); th_myfunc_34 <= th_myfunc_34_16; end th_myfunc_34_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 34)) begin _th_myfunc_34_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 34)) begin th_myfunc_34 <= th_myfunc_34_init; end end endcase end end localparam th_myfunc_35_1 = 1; localparam th_myfunc_35_2 = 2; localparam th_myfunc_35_3 = 3; localparam th_myfunc_35_4 = 4; localparam th_myfunc_35_5 = 5; localparam th_myfunc_35_6 = 6; localparam th_myfunc_35_7 = 7; localparam th_myfunc_35_8 = 8; localparam th_myfunc_35_9 = 9; localparam th_myfunc_35_10 = 10; localparam th_myfunc_35_11 = 11; localparam th_myfunc_35_12 = 12; localparam th_myfunc_35_13 = 13; localparam th_myfunc_35_14 = 14; localparam th_myfunc_35_15 = 15; localparam th_myfunc_35_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_35 <= th_myfunc_35_init; _th_myfunc_35_called <= 0; _th_myfunc_35_tid_177 <= 0; _th_myfunc_35_tid_178 <= 0; _th_myfunc_35_time_179 <= 0; _th_myfunc_35_i_180 <= 0; _th_myfunc_35___181 <= 0; end else begin case(th_myfunc_35) th_myfunc_35_init: begin if(_th_myfunc_start[35] && (th_blink == 10)) begin _th_myfunc_35_called <= 1; end if(_th_myfunc_start[35] && (th_blink == 10)) begin _th_myfunc_35_tid_177 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[35]) begin th_myfunc_35 <= th_myfunc_35_1; end end th_myfunc_35_1: begin _th_myfunc_35_tid_178 <= _th_myfunc_35_tid_177; th_myfunc_35 <= th_myfunc_35_2; end th_myfunc_35_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 35)) begin th_myfunc_35 <= th_myfunc_35_3; end end th_myfunc_35_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 35))) begin th_myfunc_35 <= th_myfunc_35_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 35)) begin th_myfunc_35 <= th_myfunc_35_4; end end th_myfunc_35_4: begin $display("Thread %d Lock", _th_myfunc_35_tid_178); th_myfunc_35 <= th_myfunc_35_5; end th_myfunc_35_5: begin _th_myfunc_35_time_179 <= sw; th_myfunc_35 <= th_myfunc_35_6; end th_myfunc_35_6: begin _th_myfunc_35_i_180 <= 0; th_myfunc_35 <= th_myfunc_35_7; end th_myfunc_35_7: begin if(_th_myfunc_35_i_180 < _th_myfunc_35_time_179) begin th_myfunc_35 <= th_myfunc_35_8; end else begin th_myfunc_35 <= th_myfunc_35_12; end end th_myfunc_35_8: begin _th_myfunc_35___181 <= 0; th_myfunc_35 <= th_myfunc_35_9; end th_myfunc_35_9: begin if(_th_myfunc_35___181 < 1024) begin th_myfunc_35 <= th_myfunc_35_10; end else begin th_myfunc_35 <= th_myfunc_35_11; end end th_myfunc_35_10: begin _th_myfunc_35___181 <= _th_myfunc_35___181 + 1; th_myfunc_35 <= th_myfunc_35_9; end th_myfunc_35_11: begin _th_myfunc_35_i_180 <= _th_myfunc_35_i_180 + 1; th_myfunc_35 <= th_myfunc_35_7; end th_myfunc_35_12: begin th_myfunc_35 <= th_myfunc_35_13; end th_myfunc_35_13: begin $display("Thread %d count = %d", _th_myfunc_35_tid_178, count); th_myfunc_35 <= th_myfunc_35_14; end th_myfunc_35_14: begin th_myfunc_35 <= th_myfunc_35_15; end th_myfunc_35_15: begin $display("Thread %d Unlock", _th_myfunc_35_tid_178); th_myfunc_35 <= th_myfunc_35_16; end th_myfunc_35_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 35)) begin _th_myfunc_35_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 35)) begin th_myfunc_35 <= th_myfunc_35_init; end end endcase end end localparam th_myfunc_36_1 = 1; localparam th_myfunc_36_2 = 2; localparam th_myfunc_36_3 = 3; localparam th_myfunc_36_4 = 4; localparam th_myfunc_36_5 = 5; localparam th_myfunc_36_6 = 6; localparam th_myfunc_36_7 = 7; localparam th_myfunc_36_8 = 8; localparam th_myfunc_36_9 = 9; localparam th_myfunc_36_10 = 10; localparam th_myfunc_36_11 = 11; localparam th_myfunc_36_12 = 12; localparam th_myfunc_36_13 = 13; localparam th_myfunc_36_14 = 14; localparam th_myfunc_36_15 = 15; localparam th_myfunc_36_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_36 <= th_myfunc_36_init; _th_myfunc_36_called <= 0; _th_myfunc_36_tid_182 <= 0; _th_myfunc_36_tid_183 <= 0; _th_myfunc_36_time_184 <= 0; _th_myfunc_36_i_185 <= 0; _th_myfunc_36___186 <= 0; end else begin case(th_myfunc_36) th_myfunc_36_init: begin if(_th_myfunc_start[36] && (th_blink == 10)) begin _th_myfunc_36_called <= 1; end if(_th_myfunc_start[36] && (th_blink == 10)) begin _th_myfunc_36_tid_182 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[36]) begin th_myfunc_36 <= th_myfunc_36_1; end end th_myfunc_36_1: begin _th_myfunc_36_tid_183 <= _th_myfunc_36_tid_182; th_myfunc_36 <= th_myfunc_36_2; end th_myfunc_36_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 36)) begin th_myfunc_36 <= th_myfunc_36_3; end end th_myfunc_36_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 36))) begin th_myfunc_36 <= th_myfunc_36_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 36)) begin th_myfunc_36 <= th_myfunc_36_4; end end th_myfunc_36_4: begin $display("Thread %d Lock", _th_myfunc_36_tid_183); th_myfunc_36 <= th_myfunc_36_5; end th_myfunc_36_5: begin _th_myfunc_36_time_184 <= sw; th_myfunc_36 <= th_myfunc_36_6; end th_myfunc_36_6: begin _th_myfunc_36_i_185 <= 0; th_myfunc_36 <= th_myfunc_36_7; end th_myfunc_36_7: begin if(_th_myfunc_36_i_185 < _th_myfunc_36_time_184) begin th_myfunc_36 <= th_myfunc_36_8; end else begin th_myfunc_36 <= th_myfunc_36_12; end end th_myfunc_36_8: begin _th_myfunc_36___186 <= 0; th_myfunc_36 <= th_myfunc_36_9; end th_myfunc_36_9: begin if(_th_myfunc_36___186 < 1024) begin th_myfunc_36 <= th_myfunc_36_10; end else begin th_myfunc_36 <= th_myfunc_36_11; end end th_myfunc_36_10: begin _th_myfunc_36___186 <= _th_myfunc_36___186 + 1; th_myfunc_36 <= th_myfunc_36_9; end th_myfunc_36_11: begin _th_myfunc_36_i_185 <= _th_myfunc_36_i_185 + 1; th_myfunc_36 <= th_myfunc_36_7; end th_myfunc_36_12: begin th_myfunc_36 <= th_myfunc_36_13; end th_myfunc_36_13: begin $display("Thread %d count = %d", _th_myfunc_36_tid_183, count); th_myfunc_36 <= th_myfunc_36_14; end th_myfunc_36_14: begin th_myfunc_36 <= th_myfunc_36_15; end th_myfunc_36_15: begin $display("Thread %d Unlock", _th_myfunc_36_tid_183); th_myfunc_36 <= th_myfunc_36_16; end th_myfunc_36_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 36)) begin _th_myfunc_36_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 36)) begin th_myfunc_36 <= th_myfunc_36_init; end end endcase end end localparam th_myfunc_37_1 = 1; localparam th_myfunc_37_2 = 2; localparam th_myfunc_37_3 = 3; localparam th_myfunc_37_4 = 4; localparam th_myfunc_37_5 = 5; localparam th_myfunc_37_6 = 6; localparam th_myfunc_37_7 = 7; localparam th_myfunc_37_8 = 8; localparam th_myfunc_37_9 = 9; localparam th_myfunc_37_10 = 10; localparam th_myfunc_37_11 = 11; localparam th_myfunc_37_12 = 12; localparam th_myfunc_37_13 = 13; localparam th_myfunc_37_14 = 14; localparam th_myfunc_37_15 = 15; localparam th_myfunc_37_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_37 <= th_myfunc_37_init; _th_myfunc_37_called <= 0; _th_myfunc_37_tid_187 <= 0; _th_myfunc_37_tid_188 <= 0; _th_myfunc_37_time_189 <= 0; _th_myfunc_37_i_190 <= 0; _th_myfunc_37___191 <= 0; end else begin case(th_myfunc_37) th_myfunc_37_init: begin if(_th_myfunc_start[37] && (th_blink == 10)) begin _th_myfunc_37_called <= 1; end if(_th_myfunc_start[37] && (th_blink == 10)) begin _th_myfunc_37_tid_187 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[37]) begin th_myfunc_37 <= th_myfunc_37_1; end end th_myfunc_37_1: begin _th_myfunc_37_tid_188 <= _th_myfunc_37_tid_187; th_myfunc_37 <= th_myfunc_37_2; end th_myfunc_37_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 37)) begin th_myfunc_37 <= th_myfunc_37_3; end end th_myfunc_37_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 37))) begin th_myfunc_37 <= th_myfunc_37_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 37)) begin th_myfunc_37 <= th_myfunc_37_4; end end th_myfunc_37_4: begin $display("Thread %d Lock", _th_myfunc_37_tid_188); th_myfunc_37 <= th_myfunc_37_5; end th_myfunc_37_5: begin _th_myfunc_37_time_189 <= sw; th_myfunc_37 <= th_myfunc_37_6; end th_myfunc_37_6: begin _th_myfunc_37_i_190 <= 0; th_myfunc_37 <= th_myfunc_37_7; end th_myfunc_37_7: begin if(_th_myfunc_37_i_190 < _th_myfunc_37_time_189) begin th_myfunc_37 <= th_myfunc_37_8; end else begin th_myfunc_37 <= th_myfunc_37_12; end end th_myfunc_37_8: begin _th_myfunc_37___191 <= 0; th_myfunc_37 <= th_myfunc_37_9; end th_myfunc_37_9: begin if(_th_myfunc_37___191 < 1024) begin th_myfunc_37 <= th_myfunc_37_10; end else begin th_myfunc_37 <= th_myfunc_37_11; end end th_myfunc_37_10: begin _th_myfunc_37___191 <= _th_myfunc_37___191 + 1; th_myfunc_37 <= th_myfunc_37_9; end th_myfunc_37_11: begin _th_myfunc_37_i_190 <= _th_myfunc_37_i_190 + 1; th_myfunc_37 <= th_myfunc_37_7; end th_myfunc_37_12: begin th_myfunc_37 <= th_myfunc_37_13; end th_myfunc_37_13: begin $display("Thread %d count = %d", _th_myfunc_37_tid_188, count); th_myfunc_37 <= th_myfunc_37_14; end th_myfunc_37_14: begin th_myfunc_37 <= th_myfunc_37_15; end th_myfunc_37_15: begin $display("Thread %d Unlock", _th_myfunc_37_tid_188); th_myfunc_37 <= th_myfunc_37_16; end th_myfunc_37_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 37)) begin _th_myfunc_37_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 37)) begin th_myfunc_37 <= th_myfunc_37_init; end end endcase end end localparam th_myfunc_38_1 = 1; localparam th_myfunc_38_2 = 2; localparam th_myfunc_38_3 = 3; localparam th_myfunc_38_4 = 4; localparam th_myfunc_38_5 = 5; localparam th_myfunc_38_6 = 6; localparam th_myfunc_38_7 = 7; localparam th_myfunc_38_8 = 8; localparam th_myfunc_38_9 = 9; localparam th_myfunc_38_10 = 10; localparam th_myfunc_38_11 = 11; localparam th_myfunc_38_12 = 12; localparam th_myfunc_38_13 = 13; localparam th_myfunc_38_14 = 14; localparam th_myfunc_38_15 = 15; localparam th_myfunc_38_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_38 <= th_myfunc_38_init; _th_myfunc_38_called <= 0; _th_myfunc_38_tid_192 <= 0; _th_myfunc_38_tid_193 <= 0; _th_myfunc_38_time_194 <= 0; _th_myfunc_38_i_195 <= 0; _th_myfunc_38___196 <= 0; end else begin case(th_myfunc_38) th_myfunc_38_init: begin if(_th_myfunc_start[38] && (th_blink == 10)) begin _th_myfunc_38_called <= 1; end if(_th_myfunc_start[38] && (th_blink == 10)) begin _th_myfunc_38_tid_192 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[38]) begin th_myfunc_38 <= th_myfunc_38_1; end end th_myfunc_38_1: begin _th_myfunc_38_tid_193 <= _th_myfunc_38_tid_192; th_myfunc_38 <= th_myfunc_38_2; end th_myfunc_38_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 38)) begin th_myfunc_38 <= th_myfunc_38_3; end end th_myfunc_38_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 38))) begin th_myfunc_38 <= th_myfunc_38_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 38)) begin th_myfunc_38 <= th_myfunc_38_4; end end th_myfunc_38_4: begin $display("Thread %d Lock", _th_myfunc_38_tid_193); th_myfunc_38 <= th_myfunc_38_5; end th_myfunc_38_5: begin _th_myfunc_38_time_194 <= sw; th_myfunc_38 <= th_myfunc_38_6; end th_myfunc_38_6: begin _th_myfunc_38_i_195 <= 0; th_myfunc_38 <= th_myfunc_38_7; end th_myfunc_38_7: begin if(_th_myfunc_38_i_195 < _th_myfunc_38_time_194) begin th_myfunc_38 <= th_myfunc_38_8; end else begin th_myfunc_38 <= th_myfunc_38_12; end end th_myfunc_38_8: begin _th_myfunc_38___196 <= 0; th_myfunc_38 <= th_myfunc_38_9; end th_myfunc_38_9: begin if(_th_myfunc_38___196 < 1024) begin th_myfunc_38 <= th_myfunc_38_10; end else begin th_myfunc_38 <= th_myfunc_38_11; end end th_myfunc_38_10: begin _th_myfunc_38___196 <= _th_myfunc_38___196 + 1; th_myfunc_38 <= th_myfunc_38_9; end th_myfunc_38_11: begin _th_myfunc_38_i_195 <= _th_myfunc_38_i_195 + 1; th_myfunc_38 <= th_myfunc_38_7; end th_myfunc_38_12: begin th_myfunc_38 <= th_myfunc_38_13; end th_myfunc_38_13: begin $display("Thread %d count = %d", _th_myfunc_38_tid_193, count); th_myfunc_38 <= th_myfunc_38_14; end th_myfunc_38_14: begin th_myfunc_38 <= th_myfunc_38_15; end th_myfunc_38_15: begin $display("Thread %d Unlock", _th_myfunc_38_tid_193); th_myfunc_38 <= th_myfunc_38_16; end th_myfunc_38_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 38)) begin _th_myfunc_38_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 38)) begin th_myfunc_38 <= th_myfunc_38_init; end end endcase end end localparam th_myfunc_39_1 = 1; localparam th_myfunc_39_2 = 2; localparam th_myfunc_39_3 = 3; localparam th_myfunc_39_4 = 4; localparam th_myfunc_39_5 = 5; localparam th_myfunc_39_6 = 6; localparam th_myfunc_39_7 = 7; localparam th_myfunc_39_8 = 8; localparam th_myfunc_39_9 = 9; localparam th_myfunc_39_10 = 10; localparam th_myfunc_39_11 = 11; localparam th_myfunc_39_12 = 12; localparam th_myfunc_39_13 = 13; localparam th_myfunc_39_14 = 14; localparam th_myfunc_39_15 = 15; localparam th_myfunc_39_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_39 <= th_myfunc_39_init; _th_myfunc_39_called <= 0; _th_myfunc_39_tid_197 <= 0; _th_myfunc_39_tid_198 <= 0; _th_myfunc_39_time_199 <= 0; _th_myfunc_39_i_200 <= 0; _th_myfunc_39___201 <= 0; end else begin case(th_myfunc_39) th_myfunc_39_init: begin if(_th_myfunc_start[39] && (th_blink == 10)) begin _th_myfunc_39_called <= 1; end if(_th_myfunc_start[39] && (th_blink == 10)) begin _th_myfunc_39_tid_197 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[39]) begin th_myfunc_39 <= th_myfunc_39_1; end end th_myfunc_39_1: begin _th_myfunc_39_tid_198 <= _th_myfunc_39_tid_197; th_myfunc_39 <= th_myfunc_39_2; end th_myfunc_39_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 39)) begin th_myfunc_39 <= th_myfunc_39_3; end end th_myfunc_39_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 39))) begin th_myfunc_39 <= th_myfunc_39_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 39)) begin th_myfunc_39 <= th_myfunc_39_4; end end th_myfunc_39_4: begin $display("Thread %d Lock", _th_myfunc_39_tid_198); th_myfunc_39 <= th_myfunc_39_5; end th_myfunc_39_5: begin _th_myfunc_39_time_199 <= sw; th_myfunc_39 <= th_myfunc_39_6; end th_myfunc_39_6: begin _th_myfunc_39_i_200 <= 0; th_myfunc_39 <= th_myfunc_39_7; end th_myfunc_39_7: begin if(_th_myfunc_39_i_200 < _th_myfunc_39_time_199) begin th_myfunc_39 <= th_myfunc_39_8; end else begin th_myfunc_39 <= th_myfunc_39_12; end end th_myfunc_39_8: begin _th_myfunc_39___201 <= 0; th_myfunc_39 <= th_myfunc_39_9; end th_myfunc_39_9: begin if(_th_myfunc_39___201 < 1024) begin th_myfunc_39 <= th_myfunc_39_10; end else begin th_myfunc_39 <= th_myfunc_39_11; end end th_myfunc_39_10: begin _th_myfunc_39___201 <= _th_myfunc_39___201 + 1; th_myfunc_39 <= th_myfunc_39_9; end th_myfunc_39_11: begin _th_myfunc_39_i_200 <= _th_myfunc_39_i_200 + 1; th_myfunc_39 <= th_myfunc_39_7; end th_myfunc_39_12: begin th_myfunc_39 <= th_myfunc_39_13; end th_myfunc_39_13: begin $display("Thread %d count = %d", _th_myfunc_39_tid_198, count); th_myfunc_39 <= th_myfunc_39_14; end th_myfunc_39_14: begin th_myfunc_39 <= th_myfunc_39_15; end th_myfunc_39_15: begin $display("Thread %d Unlock", _th_myfunc_39_tid_198); th_myfunc_39 <= th_myfunc_39_16; end th_myfunc_39_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 39)) begin _th_myfunc_39_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 39)) begin th_myfunc_39 <= th_myfunc_39_init; end end endcase end end localparam th_myfunc_40_1 = 1; localparam th_myfunc_40_2 = 2; localparam th_myfunc_40_3 = 3; localparam th_myfunc_40_4 = 4; localparam th_myfunc_40_5 = 5; localparam th_myfunc_40_6 = 6; localparam th_myfunc_40_7 = 7; localparam th_myfunc_40_8 = 8; localparam th_myfunc_40_9 = 9; localparam th_myfunc_40_10 = 10; localparam th_myfunc_40_11 = 11; localparam th_myfunc_40_12 = 12; localparam th_myfunc_40_13 = 13; localparam th_myfunc_40_14 = 14; localparam th_myfunc_40_15 = 15; localparam th_myfunc_40_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_40 <= th_myfunc_40_init; _th_myfunc_40_called <= 0; _th_myfunc_40_tid_202 <= 0; _th_myfunc_40_tid_203 <= 0; _th_myfunc_40_time_204 <= 0; _th_myfunc_40_i_205 <= 0; _th_myfunc_40___206 <= 0; end else begin case(th_myfunc_40) th_myfunc_40_init: begin if(_th_myfunc_start[40] && (th_blink == 10)) begin _th_myfunc_40_called <= 1; end if(_th_myfunc_start[40] && (th_blink == 10)) begin _th_myfunc_40_tid_202 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[40]) begin th_myfunc_40 <= th_myfunc_40_1; end end th_myfunc_40_1: begin _th_myfunc_40_tid_203 <= _th_myfunc_40_tid_202; th_myfunc_40 <= th_myfunc_40_2; end th_myfunc_40_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 40)) begin th_myfunc_40 <= th_myfunc_40_3; end end th_myfunc_40_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 40))) begin th_myfunc_40 <= th_myfunc_40_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 40)) begin th_myfunc_40 <= th_myfunc_40_4; end end th_myfunc_40_4: begin $display("Thread %d Lock", _th_myfunc_40_tid_203); th_myfunc_40 <= th_myfunc_40_5; end th_myfunc_40_5: begin _th_myfunc_40_time_204 <= sw; th_myfunc_40 <= th_myfunc_40_6; end th_myfunc_40_6: begin _th_myfunc_40_i_205 <= 0; th_myfunc_40 <= th_myfunc_40_7; end th_myfunc_40_7: begin if(_th_myfunc_40_i_205 < _th_myfunc_40_time_204) begin th_myfunc_40 <= th_myfunc_40_8; end else begin th_myfunc_40 <= th_myfunc_40_12; end end th_myfunc_40_8: begin _th_myfunc_40___206 <= 0; th_myfunc_40 <= th_myfunc_40_9; end th_myfunc_40_9: begin if(_th_myfunc_40___206 < 1024) begin th_myfunc_40 <= th_myfunc_40_10; end else begin th_myfunc_40 <= th_myfunc_40_11; end end th_myfunc_40_10: begin _th_myfunc_40___206 <= _th_myfunc_40___206 + 1; th_myfunc_40 <= th_myfunc_40_9; end th_myfunc_40_11: begin _th_myfunc_40_i_205 <= _th_myfunc_40_i_205 + 1; th_myfunc_40 <= th_myfunc_40_7; end th_myfunc_40_12: begin th_myfunc_40 <= th_myfunc_40_13; end th_myfunc_40_13: begin $display("Thread %d count = %d", _th_myfunc_40_tid_203, count); th_myfunc_40 <= th_myfunc_40_14; end th_myfunc_40_14: begin th_myfunc_40 <= th_myfunc_40_15; end th_myfunc_40_15: begin $display("Thread %d Unlock", _th_myfunc_40_tid_203); th_myfunc_40 <= th_myfunc_40_16; end th_myfunc_40_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 40)) begin _th_myfunc_40_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 40)) begin th_myfunc_40 <= th_myfunc_40_init; end end endcase end end localparam th_myfunc_41_1 = 1; localparam th_myfunc_41_2 = 2; localparam th_myfunc_41_3 = 3; localparam th_myfunc_41_4 = 4; localparam th_myfunc_41_5 = 5; localparam th_myfunc_41_6 = 6; localparam th_myfunc_41_7 = 7; localparam th_myfunc_41_8 = 8; localparam th_myfunc_41_9 = 9; localparam th_myfunc_41_10 = 10; localparam th_myfunc_41_11 = 11; localparam th_myfunc_41_12 = 12; localparam th_myfunc_41_13 = 13; localparam th_myfunc_41_14 = 14; localparam th_myfunc_41_15 = 15; localparam th_myfunc_41_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_41 <= th_myfunc_41_init; _th_myfunc_41_called <= 0; _th_myfunc_41_tid_207 <= 0; _th_myfunc_41_tid_208 <= 0; _th_myfunc_41_time_209 <= 0; _th_myfunc_41_i_210 <= 0; _th_myfunc_41___211 <= 0; end else begin case(th_myfunc_41) th_myfunc_41_init: begin if(_th_myfunc_start[41] && (th_blink == 10)) begin _th_myfunc_41_called <= 1; end if(_th_myfunc_start[41] && (th_blink == 10)) begin _th_myfunc_41_tid_207 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[41]) begin th_myfunc_41 <= th_myfunc_41_1; end end th_myfunc_41_1: begin _th_myfunc_41_tid_208 <= _th_myfunc_41_tid_207; th_myfunc_41 <= th_myfunc_41_2; end th_myfunc_41_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 41)) begin th_myfunc_41 <= th_myfunc_41_3; end end th_myfunc_41_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 41))) begin th_myfunc_41 <= th_myfunc_41_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 41)) begin th_myfunc_41 <= th_myfunc_41_4; end end th_myfunc_41_4: begin $display("Thread %d Lock", _th_myfunc_41_tid_208); th_myfunc_41 <= th_myfunc_41_5; end th_myfunc_41_5: begin _th_myfunc_41_time_209 <= sw; th_myfunc_41 <= th_myfunc_41_6; end th_myfunc_41_6: begin _th_myfunc_41_i_210 <= 0; th_myfunc_41 <= th_myfunc_41_7; end th_myfunc_41_7: begin if(_th_myfunc_41_i_210 < _th_myfunc_41_time_209) begin th_myfunc_41 <= th_myfunc_41_8; end else begin th_myfunc_41 <= th_myfunc_41_12; end end th_myfunc_41_8: begin _th_myfunc_41___211 <= 0; th_myfunc_41 <= th_myfunc_41_9; end th_myfunc_41_9: begin if(_th_myfunc_41___211 < 1024) begin th_myfunc_41 <= th_myfunc_41_10; end else begin th_myfunc_41 <= th_myfunc_41_11; end end th_myfunc_41_10: begin _th_myfunc_41___211 <= _th_myfunc_41___211 + 1; th_myfunc_41 <= th_myfunc_41_9; end th_myfunc_41_11: begin _th_myfunc_41_i_210 <= _th_myfunc_41_i_210 + 1; th_myfunc_41 <= th_myfunc_41_7; end th_myfunc_41_12: begin th_myfunc_41 <= th_myfunc_41_13; end th_myfunc_41_13: begin $display("Thread %d count = %d", _th_myfunc_41_tid_208, count); th_myfunc_41 <= th_myfunc_41_14; end th_myfunc_41_14: begin th_myfunc_41 <= th_myfunc_41_15; end th_myfunc_41_15: begin $display("Thread %d Unlock", _th_myfunc_41_tid_208); th_myfunc_41 <= th_myfunc_41_16; end th_myfunc_41_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 41)) begin _th_myfunc_41_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 41)) begin th_myfunc_41 <= th_myfunc_41_init; end end endcase end end localparam th_myfunc_42_1 = 1; localparam th_myfunc_42_2 = 2; localparam th_myfunc_42_3 = 3; localparam th_myfunc_42_4 = 4; localparam th_myfunc_42_5 = 5; localparam th_myfunc_42_6 = 6; localparam th_myfunc_42_7 = 7; localparam th_myfunc_42_8 = 8; localparam th_myfunc_42_9 = 9; localparam th_myfunc_42_10 = 10; localparam th_myfunc_42_11 = 11; localparam th_myfunc_42_12 = 12; localparam th_myfunc_42_13 = 13; localparam th_myfunc_42_14 = 14; localparam th_myfunc_42_15 = 15; localparam th_myfunc_42_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_42 <= th_myfunc_42_init; _th_myfunc_42_called <= 0; _th_myfunc_42_tid_212 <= 0; _th_myfunc_42_tid_213 <= 0; _th_myfunc_42_time_214 <= 0; _th_myfunc_42_i_215 <= 0; _th_myfunc_42___216 <= 0; end else begin case(th_myfunc_42) th_myfunc_42_init: begin if(_th_myfunc_start[42] && (th_blink == 10)) begin _th_myfunc_42_called <= 1; end if(_th_myfunc_start[42] && (th_blink == 10)) begin _th_myfunc_42_tid_212 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[42]) begin th_myfunc_42 <= th_myfunc_42_1; end end th_myfunc_42_1: begin _th_myfunc_42_tid_213 <= _th_myfunc_42_tid_212; th_myfunc_42 <= th_myfunc_42_2; end th_myfunc_42_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 42)) begin th_myfunc_42 <= th_myfunc_42_3; end end th_myfunc_42_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 42))) begin th_myfunc_42 <= th_myfunc_42_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 42)) begin th_myfunc_42 <= th_myfunc_42_4; end end th_myfunc_42_4: begin $display("Thread %d Lock", _th_myfunc_42_tid_213); th_myfunc_42 <= th_myfunc_42_5; end th_myfunc_42_5: begin _th_myfunc_42_time_214 <= sw; th_myfunc_42 <= th_myfunc_42_6; end th_myfunc_42_6: begin _th_myfunc_42_i_215 <= 0; th_myfunc_42 <= th_myfunc_42_7; end th_myfunc_42_7: begin if(_th_myfunc_42_i_215 < _th_myfunc_42_time_214) begin th_myfunc_42 <= th_myfunc_42_8; end else begin th_myfunc_42 <= th_myfunc_42_12; end end th_myfunc_42_8: begin _th_myfunc_42___216 <= 0; th_myfunc_42 <= th_myfunc_42_9; end th_myfunc_42_9: begin if(_th_myfunc_42___216 < 1024) begin th_myfunc_42 <= th_myfunc_42_10; end else begin th_myfunc_42 <= th_myfunc_42_11; end end th_myfunc_42_10: begin _th_myfunc_42___216 <= _th_myfunc_42___216 + 1; th_myfunc_42 <= th_myfunc_42_9; end th_myfunc_42_11: begin _th_myfunc_42_i_215 <= _th_myfunc_42_i_215 + 1; th_myfunc_42 <= th_myfunc_42_7; end th_myfunc_42_12: begin th_myfunc_42 <= th_myfunc_42_13; end th_myfunc_42_13: begin $display("Thread %d count = %d", _th_myfunc_42_tid_213, count); th_myfunc_42 <= th_myfunc_42_14; end th_myfunc_42_14: begin th_myfunc_42 <= th_myfunc_42_15; end th_myfunc_42_15: begin $display("Thread %d Unlock", _th_myfunc_42_tid_213); th_myfunc_42 <= th_myfunc_42_16; end th_myfunc_42_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 42)) begin _th_myfunc_42_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 42)) begin th_myfunc_42 <= th_myfunc_42_init; end end endcase end end localparam th_myfunc_43_1 = 1; localparam th_myfunc_43_2 = 2; localparam th_myfunc_43_3 = 3; localparam th_myfunc_43_4 = 4; localparam th_myfunc_43_5 = 5; localparam th_myfunc_43_6 = 6; localparam th_myfunc_43_7 = 7; localparam th_myfunc_43_8 = 8; localparam th_myfunc_43_9 = 9; localparam th_myfunc_43_10 = 10; localparam th_myfunc_43_11 = 11; localparam th_myfunc_43_12 = 12; localparam th_myfunc_43_13 = 13; localparam th_myfunc_43_14 = 14; localparam th_myfunc_43_15 = 15; localparam th_myfunc_43_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_43 <= th_myfunc_43_init; _th_myfunc_43_called <= 0; _th_myfunc_43_tid_217 <= 0; _th_myfunc_43_tid_218 <= 0; _th_myfunc_43_time_219 <= 0; _th_myfunc_43_i_220 <= 0; _th_myfunc_43___221 <= 0; end else begin case(th_myfunc_43) th_myfunc_43_init: begin if(_th_myfunc_start[43] && (th_blink == 10)) begin _th_myfunc_43_called <= 1; end if(_th_myfunc_start[43] && (th_blink == 10)) begin _th_myfunc_43_tid_217 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[43]) begin th_myfunc_43 <= th_myfunc_43_1; end end th_myfunc_43_1: begin _th_myfunc_43_tid_218 <= _th_myfunc_43_tid_217; th_myfunc_43 <= th_myfunc_43_2; end th_myfunc_43_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 43)) begin th_myfunc_43 <= th_myfunc_43_3; end end th_myfunc_43_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 43))) begin th_myfunc_43 <= th_myfunc_43_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 43)) begin th_myfunc_43 <= th_myfunc_43_4; end end th_myfunc_43_4: begin $display("Thread %d Lock", _th_myfunc_43_tid_218); th_myfunc_43 <= th_myfunc_43_5; end th_myfunc_43_5: begin _th_myfunc_43_time_219 <= sw; th_myfunc_43 <= th_myfunc_43_6; end th_myfunc_43_6: begin _th_myfunc_43_i_220 <= 0; th_myfunc_43 <= th_myfunc_43_7; end th_myfunc_43_7: begin if(_th_myfunc_43_i_220 < _th_myfunc_43_time_219) begin th_myfunc_43 <= th_myfunc_43_8; end else begin th_myfunc_43 <= th_myfunc_43_12; end end th_myfunc_43_8: begin _th_myfunc_43___221 <= 0; th_myfunc_43 <= th_myfunc_43_9; end th_myfunc_43_9: begin if(_th_myfunc_43___221 < 1024) begin th_myfunc_43 <= th_myfunc_43_10; end else begin th_myfunc_43 <= th_myfunc_43_11; end end th_myfunc_43_10: begin _th_myfunc_43___221 <= _th_myfunc_43___221 + 1; th_myfunc_43 <= th_myfunc_43_9; end th_myfunc_43_11: begin _th_myfunc_43_i_220 <= _th_myfunc_43_i_220 + 1; th_myfunc_43 <= th_myfunc_43_7; end th_myfunc_43_12: begin th_myfunc_43 <= th_myfunc_43_13; end th_myfunc_43_13: begin $display("Thread %d count = %d", _th_myfunc_43_tid_218, count); th_myfunc_43 <= th_myfunc_43_14; end th_myfunc_43_14: begin th_myfunc_43 <= th_myfunc_43_15; end th_myfunc_43_15: begin $display("Thread %d Unlock", _th_myfunc_43_tid_218); th_myfunc_43 <= th_myfunc_43_16; end th_myfunc_43_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 43)) begin _th_myfunc_43_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 43)) begin th_myfunc_43 <= th_myfunc_43_init; end end endcase end end localparam th_myfunc_44_1 = 1; localparam th_myfunc_44_2 = 2; localparam th_myfunc_44_3 = 3; localparam th_myfunc_44_4 = 4; localparam th_myfunc_44_5 = 5; localparam th_myfunc_44_6 = 6; localparam th_myfunc_44_7 = 7; localparam th_myfunc_44_8 = 8; localparam th_myfunc_44_9 = 9; localparam th_myfunc_44_10 = 10; localparam th_myfunc_44_11 = 11; localparam th_myfunc_44_12 = 12; localparam th_myfunc_44_13 = 13; localparam th_myfunc_44_14 = 14; localparam th_myfunc_44_15 = 15; localparam th_myfunc_44_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_44 <= th_myfunc_44_init; _th_myfunc_44_called <= 0; _th_myfunc_44_tid_222 <= 0; _th_myfunc_44_tid_223 <= 0; _th_myfunc_44_time_224 <= 0; _th_myfunc_44_i_225 <= 0; _th_myfunc_44___226 <= 0; end else begin case(th_myfunc_44) th_myfunc_44_init: begin if(_th_myfunc_start[44] && (th_blink == 10)) begin _th_myfunc_44_called <= 1; end if(_th_myfunc_start[44] && (th_blink == 10)) begin _th_myfunc_44_tid_222 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[44]) begin th_myfunc_44 <= th_myfunc_44_1; end end th_myfunc_44_1: begin _th_myfunc_44_tid_223 <= _th_myfunc_44_tid_222; th_myfunc_44 <= th_myfunc_44_2; end th_myfunc_44_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 44)) begin th_myfunc_44 <= th_myfunc_44_3; end end th_myfunc_44_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 44))) begin th_myfunc_44 <= th_myfunc_44_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 44)) begin th_myfunc_44 <= th_myfunc_44_4; end end th_myfunc_44_4: begin $display("Thread %d Lock", _th_myfunc_44_tid_223); th_myfunc_44 <= th_myfunc_44_5; end th_myfunc_44_5: begin _th_myfunc_44_time_224 <= sw; th_myfunc_44 <= th_myfunc_44_6; end th_myfunc_44_6: begin _th_myfunc_44_i_225 <= 0; th_myfunc_44 <= th_myfunc_44_7; end th_myfunc_44_7: begin if(_th_myfunc_44_i_225 < _th_myfunc_44_time_224) begin th_myfunc_44 <= th_myfunc_44_8; end else begin th_myfunc_44 <= th_myfunc_44_12; end end th_myfunc_44_8: begin _th_myfunc_44___226 <= 0; th_myfunc_44 <= th_myfunc_44_9; end th_myfunc_44_9: begin if(_th_myfunc_44___226 < 1024) begin th_myfunc_44 <= th_myfunc_44_10; end else begin th_myfunc_44 <= th_myfunc_44_11; end end th_myfunc_44_10: begin _th_myfunc_44___226 <= _th_myfunc_44___226 + 1; th_myfunc_44 <= th_myfunc_44_9; end th_myfunc_44_11: begin _th_myfunc_44_i_225 <= _th_myfunc_44_i_225 + 1; th_myfunc_44 <= th_myfunc_44_7; end th_myfunc_44_12: begin th_myfunc_44 <= th_myfunc_44_13; end th_myfunc_44_13: begin $display("Thread %d count = %d", _th_myfunc_44_tid_223, count); th_myfunc_44 <= th_myfunc_44_14; end th_myfunc_44_14: begin th_myfunc_44 <= th_myfunc_44_15; end th_myfunc_44_15: begin $display("Thread %d Unlock", _th_myfunc_44_tid_223); th_myfunc_44 <= th_myfunc_44_16; end th_myfunc_44_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 44)) begin _th_myfunc_44_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 44)) begin th_myfunc_44 <= th_myfunc_44_init; end end endcase end end localparam th_myfunc_45_1 = 1; localparam th_myfunc_45_2 = 2; localparam th_myfunc_45_3 = 3; localparam th_myfunc_45_4 = 4; localparam th_myfunc_45_5 = 5; localparam th_myfunc_45_6 = 6; localparam th_myfunc_45_7 = 7; localparam th_myfunc_45_8 = 8; localparam th_myfunc_45_9 = 9; localparam th_myfunc_45_10 = 10; localparam th_myfunc_45_11 = 11; localparam th_myfunc_45_12 = 12; localparam th_myfunc_45_13 = 13; localparam th_myfunc_45_14 = 14; localparam th_myfunc_45_15 = 15; localparam th_myfunc_45_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_45 <= th_myfunc_45_init; _th_myfunc_45_called <= 0; _th_myfunc_45_tid_227 <= 0; _th_myfunc_45_tid_228 <= 0; _th_myfunc_45_time_229 <= 0; _th_myfunc_45_i_230 <= 0; _th_myfunc_45___231 <= 0; end else begin case(th_myfunc_45) th_myfunc_45_init: begin if(_th_myfunc_start[45] && (th_blink == 10)) begin _th_myfunc_45_called <= 1; end if(_th_myfunc_start[45] && (th_blink == 10)) begin _th_myfunc_45_tid_227 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[45]) begin th_myfunc_45 <= th_myfunc_45_1; end end th_myfunc_45_1: begin _th_myfunc_45_tid_228 <= _th_myfunc_45_tid_227; th_myfunc_45 <= th_myfunc_45_2; end th_myfunc_45_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 45)) begin th_myfunc_45 <= th_myfunc_45_3; end end th_myfunc_45_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 45))) begin th_myfunc_45 <= th_myfunc_45_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 45)) begin th_myfunc_45 <= th_myfunc_45_4; end end th_myfunc_45_4: begin $display("Thread %d Lock", _th_myfunc_45_tid_228); th_myfunc_45 <= th_myfunc_45_5; end th_myfunc_45_5: begin _th_myfunc_45_time_229 <= sw; th_myfunc_45 <= th_myfunc_45_6; end th_myfunc_45_6: begin _th_myfunc_45_i_230 <= 0; th_myfunc_45 <= th_myfunc_45_7; end th_myfunc_45_7: begin if(_th_myfunc_45_i_230 < _th_myfunc_45_time_229) begin th_myfunc_45 <= th_myfunc_45_8; end else begin th_myfunc_45 <= th_myfunc_45_12; end end th_myfunc_45_8: begin _th_myfunc_45___231 <= 0; th_myfunc_45 <= th_myfunc_45_9; end th_myfunc_45_9: begin if(_th_myfunc_45___231 < 1024) begin th_myfunc_45 <= th_myfunc_45_10; end else begin th_myfunc_45 <= th_myfunc_45_11; end end th_myfunc_45_10: begin _th_myfunc_45___231 <= _th_myfunc_45___231 + 1; th_myfunc_45 <= th_myfunc_45_9; end th_myfunc_45_11: begin _th_myfunc_45_i_230 <= _th_myfunc_45_i_230 + 1; th_myfunc_45 <= th_myfunc_45_7; end th_myfunc_45_12: begin th_myfunc_45 <= th_myfunc_45_13; end th_myfunc_45_13: begin $display("Thread %d count = %d", _th_myfunc_45_tid_228, count); th_myfunc_45 <= th_myfunc_45_14; end th_myfunc_45_14: begin th_myfunc_45 <= th_myfunc_45_15; end th_myfunc_45_15: begin $display("Thread %d Unlock", _th_myfunc_45_tid_228); th_myfunc_45 <= th_myfunc_45_16; end th_myfunc_45_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 45)) begin _th_myfunc_45_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 45)) begin th_myfunc_45 <= th_myfunc_45_init; end end endcase end end localparam th_myfunc_46_1 = 1; localparam th_myfunc_46_2 = 2; localparam th_myfunc_46_3 = 3; localparam th_myfunc_46_4 = 4; localparam th_myfunc_46_5 = 5; localparam th_myfunc_46_6 = 6; localparam th_myfunc_46_7 = 7; localparam th_myfunc_46_8 = 8; localparam th_myfunc_46_9 = 9; localparam th_myfunc_46_10 = 10; localparam th_myfunc_46_11 = 11; localparam th_myfunc_46_12 = 12; localparam th_myfunc_46_13 = 13; localparam th_myfunc_46_14 = 14; localparam th_myfunc_46_15 = 15; localparam th_myfunc_46_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_46 <= th_myfunc_46_init; _th_myfunc_46_called <= 0; _th_myfunc_46_tid_232 <= 0; _th_myfunc_46_tid_233 <= 0; _th_myfunc_46_time_234 <= 0; _th_myfunc_46_i_235 <= 0; _th_myfunc_46___236 <= 0; end else begin case(th_myfunc_46) th_myfunc_46_init: begin if(_th_myfunc_start[46] && (th_blink == 10)) begin _th_myfunc_46_called <= 1; end if(_th_myfunc_start[46] && (th_blink == 10)) begin _th_myfunc_46_tid_232 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[46]) begin th_myfunc_46 <= th_myfunc_46_1; end end th_myfunc_46_1: begin _th_myfunc_46_tid_233 <= _th_myfunc_46_tid_232; th_myfunc_46 <= th_myfunc_46_2; end th_myfunc_46_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 46)) begin th_myfunc_46 <= th_myfunc_46_3; end end th_myfunc_46_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 46))) begin th_myfunc_46 <= th_myfunc_46_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 46)) begin th_myfunc_46 <= th_myfunc_46_4; end end th_myfunc_46_4: begin $display("Thread %d Lock", _th_myfunc_46_tid_233); th_myfunc_46 <= th_myfunc_46_5; end th_myfunc_46_5: begin _th_myfunc_46_time_234 <= sw; th_myfunc_46 <= th_myfunc_46_6; end th_myfunc_46_6: begin _th_myfunc_46_i_235 <= 0; th_myfunc_46 <= th_myfunc_46_7; end th_myfunc_46_7: begin if(_th_myfunc_46_i_235 < _th_myfunc_46_time_234) begin th_myfunc_46 <= th_myfunc_46_8; end else begin th_myfunc_46 <= th_myfunc_46_12; end end th_myfunc_46_8: begin _th_myfunc_46___236 <= 0; th_myfunc_46 <= th_myfunc_46_9; end th_myfunc_46_9: begin if(_th_myfunc_46___236 < 1024) begin th_myfunc_46 <= th_myfunc_46_10; end else begin th_myfunc_46 <= th_myfunc_46_11; end end th_myfunc_46_10: begin _th_myfunc_46___236 <= _th_myfunc_46___236 + 1; th_myfunc_46 <= th_myfunc_46_9; end th_myfunc_46_11: begin _th_myfunc_46_i_235 <= _th_myfunc_46_i_235 + 1; th_myfunc_46 <= th_myfunc_46_7; end th_myfunc_46_12: begin th_myfunc_46 <= th_myfunc_46_13; end th_myfunc_46_13: begin $display("Thread %d count = %d", _th_myfunc_46_tid_233, count); th_myfunc_46 <= th_myfunc_46_14; end th_myfunc_46_14: begin th_myfunc_46 <= th_myfunc_46_15; end th_myfunc_46_15: begin $display("Thread %d Unlock", _th_myfunc_46_tid_233); th_myfunc_46 <= th_myfunc_46_16; end th_myfunc_46_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 46)) begin _th_myfunc_46_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 46)) begin th_myfunc_46 <= th_myfunc_46_init; end end endcase end end localparam th_myfunc_47_1 = 1; localparam th_myfunc_47_2 = 2; localparam th_myfunc_47_3 = 3; localparam th_myfunc_47_4 = 4; localparam th_myfunc_47_5 = 5; localparam th_myfunc_47_6 = 6; localparam th_myfunc_47_7 = 7; localparam th_myfunc_47_8 = 8; localparam th_myfunc_47_9 = 9; localparam th_myfunc_47_10 = 10; localparam th_myfunc_47_11 = 11; localparam th_myfunc_47_12 = 12; localparam th_myfunc_47_13 = 13; localparam th_myfunc_47_14 = 14; localparam th_myfunc_47_15 = 15; localparam th_myfunc_47_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_47 <= th_myfunc_47_init; _th_myfunc_47_called <= 0; _th_myfunc_47_tid_237 <= 0; _th_myfunc_47_tid_238 <= 0; _th_myfunc_47_time_239 <= 0; _th_myfunc_47_i_240 <= 0; _th_myfunc_47___241 <= 0; end else begin case(th_myfunc_47) th_myfunc_47_init: begin if(_th_myfunc_start[47] && (th_blink == 10)) begin _th_myfunc_47_called <= 1; end if(_th_myfunc_start[47] && (th_blink == 10)) begin _th_myfunc_47_tid_237 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[47]) begin th_myfunc_47 <= th_myfunc_47_1; end end th_myfunc_47_1: begin _th_myfunc_47_tid_238 <= _th_myfunc_47_tid_237; th_myfunc_47 <= th_myfunc_47_2; end th_myfunc_47_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 47)) begin th_myfunc_47 <= th_myfunc_47_3; end end th_myfunc_47_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 47))) begin th_myfunc_47 <= th_myfunc_47_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 47)) begin th_myfunc_47 <= th_myfunc_47_4; end end th_myfunc_47_4: begin $display("Thread %d Lock", _th_myfunc_47_tid_238); th_myfunc_47 <= th_myfunc_47_5; end th_myfunc_47_5: begin _th_myfunc_47_time_239 <= sw; th_myfunc_47 <= th_myfunc_47_6; end th_myfunc_47_6: begin _th_myfunc_47_i_240 <= 0; th_myfunc_47 <= th_myfunc_47_7; end th_myfunc_47_7: begin if(_th_myfunc_47_i_240 < _th_myfunc_47_time_239) begin th_myfunc_47 <= th_myfunc_47_8; end else begin th_myfunc_47 <= th_myfunc_47_12; end end th_myfunc_47_8: begin _th_myfunc_47___241 <= 0; th_myfunc_47 <= th_myfunc_47_9; end th_myfunc_47_9: begin if(_th_myfunc_47___241 < 1024) begin th_myfunc_47 <= th_myfunc_47_10; end else begin th_myfunc_47 <= th_myfunc_47_11; end end th_myfunc_47_10: begin _th_myfunc_47___241 <= _th_myfunc_47___241 + 1; th_myfunc_47 <= th_myfunc_47_9; end th_myfunc_47_11: begin _th_myfunc_47_i_240 <= _th_myfunc_47_i_240 + 1; th_myfunc_47 <= th_myfunc_47_7; end th_myfunc_47_12: begin th_myfunc_47 <= th_myfunc_47_13; end th_myfunc_47_13: begin $display("Thread %d count = %d", _th_myfunc_47_tid_238, count); th_myfunc_47 <= th_myfunc_47_14; end th_myfunc_47_14: begin th_myfunc_47 <= th_myfunc_47_15; end th_myfunc_47_15: begin $display("Thread %d Unlock", _th_myfunc_47_tid_238); th_myfunc_47 <= th_myfunc_47_16; end th_myfunc_47_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 47)) begin _th_myfunc_47_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 47)) begin th_myfunc_47 <= th_myfunc_47_init; end end endcase end end localparam th_myfunc_48_1 = 1; localparam th_myfunc_48_2 = 2; localparam th_myfunc_48_3 = 3; localparam th_myfunc_48_4 = 4; localparam th_myfunc_48_5 = 5; localparam th_myfunc_48_6 = 6; localparam th_myfunc_48_7 = 7; localparam th_myfunc_48_8 = 8; localparam th_myfunc_48_9 = 9; localparam th_myfunc_48_10 = 10; localparam th_myfunc_48_11 = 11; localparam th_myfunc_48_12 = 12; localparam th_myfunc_48_13 = 13; localparam th_myfunc_48_14 = 14; localparam th_myfunc_48_15 = 15; localparam th_myfunc_48_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_48 <= th_myfunc_48_init; _th_myfunc_48_called <= 0; _th_myfunc_48_tid_242 <= 0; _th_myfunc_48_tid_243 <= 0; _th_myfunc_48_time_244 <= 0; _th_myfunc_48_i_245 <= 0; _th_myfunc_48___246 <= 0; end else begin case(th_myfunc_48) th_myfunc_48_init: begin if(_th_myfunc_start[48] && (th_blink == 10)) begin _th_myfunc_48_called <= 1; end if(_th_myfunc_start[48] && (th_blink == 10)) begin _th_myfunc_48_tid_242 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[48]) begin th_myfunc_48 <= th_myfunc_48_1; end end th_myfunc_48_1: begin _th_myfunc_48_tid_243 <= _th_myfunc_48_tid_242; th_myfunc_48 <= th_myfunc_48_2; end th_myfunc_48_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 48)) begin th_myfunc_48 <= th_myfunc_48_3; end end th_myfunc_48_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 48))) begin th_myfunc_48 <= th_myfunc_48_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 48)) begin th_myfunc_48 <= th_myfunc_48_4; end end th_myfunc_48_4: begin $display("Thread %d Lock", _th_myfunc_48_tid_243); th_myfunc_48 <= th_myfunc_48_5; end th_myfunc_48_5: begin _th_myfunc_48_time_244 <= sw; th_myfunc_48 <= th_myfunc_48_6; end th_myfunc_48_6: begin _th_myfunc_48_i_245 <= 0; th_myfunc_48 <= th_myfunc_48_7; end th_myfunc_48_7: begin if(_th_myfunc_48_i_245 < _th_myfunc_48_time_244) begin th_myfunc_48 <= th_myfunc_48_8; end else begin th_myfunc_48 <= th_myfunc_48_12; end end th_myfunc_48_8: begin _th_myfunc_48___246 <= 0; th_myfunc_48 <= th_myfunc_48_9; end th_myfunc_48_9: begin if(_th_myfunc_48___246 < 1024) begin th_myfunc_48 <= th_myfunc_48_10; end else begin th_myfunc_48 <= th_myfunc_48_11; end end th_myfunc_48_10: begin _th_myfunc_48___246 <= _th_myfunc_48___246 + 1; th_myfunc_48 <= th_myfunc_48_9; end th_myfunc_48_11: begin _th_myfunc_48_i_245 <= _th_myfunc_48_i_245 + 1; th_myfunc_48 <= th_myfunc_48_7; end th_myfunc_48_12: begin th_myfunc_48 <= th_myfunc_48_13; end th_myfunc_48_13: begin $display("Thread %d count = %d", _th_myfunc_48_tid_243, count); th_myfunc_48 <= th_myfunc_48_14; end th_myfunc_48_14: begin th_myfunc_48 <= th_myfunc_48_15; end th_myfunc_48_15: begin $display("Thread %d Unlock", _th_myfunc_48_tid_243); th_myfunc_48 <= th_myfunc_48_16; end th_myfunc_48_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 48)) begin _th_myfunc_48_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 48)) begin th_myfunc_48 <= th_myfunc_48_init; end end endcase end end localparam th_myfunc_49_1 = 1; localparam th_myfunc_49_2 = 2; localparam th_myfunc_49_3 = 3; localparam th_myfunc_49_4 = 4; localparam th_myfunc_49_5 = 5; localparam th_myfunc_49_6 = 6; localparam th_myfunc_49_7 = 7; localparam th_myfunc_49_8 = 8; localparam th_myfunc_49_9 = 9; localparam th_myfunc_49_10 = 10; localparam th_myfunc_49_11 = 11; localparam th_myfunc_49_12 = 12; localparam th_myfunc_49_13 = 13; localparam th_myfunc_49_14 = 14; localparam th_myfunc_49_15 = 15; localparam th_myfunc_49_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_49 <= th_myfunc_49_init; _th_myfunc_49_called <= 0; _th_myfunc_49_tid_247 <= 0; _th_myfunc_49_tid_248 <= 0; _th_myfunc_49_time_249 <= 0; _th_myfunc_49_i_250 <= 0; _th_myfunc_49___251 <= 0; end else begin case(th_myfunc_49) th_myfunc_49_init: begin if(_th_myfunc_start[49] && (th_blink == 10)) begin _th_myfunc_49_called <= 1; end if(_th_myfunc_start[49] && (th_blink == 10)) begin _th_myfunc_49_tid_247 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[49]) begin th_myfunc_49 <= th_myfunc_49_1; end end th_myfunc_49_1: begin _th_myfunc_49_tid_248 <= _th_myfunc_49_tid_247; th_myfunc_49 <= th_myfunc_49_2; end th_myfunc_49_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 49)) begin th_myfunc_49 <= th_myfunc_49_3; end end th_myfunc_49_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 49))) begin th_myfunc_49 <= th_myfunc_49_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 49)) begin th_myfunc_49 <= th_myfunc_49_4; end end th_myfunc_49_4: begin $display("Thread %d Lock", _th_myfunc_49_tid_248); th_myfunc_49 <= th_myfunc_49_5; end th_myfunc_49_5: begin _th_myfunc_49_time_249 <= sw; th_myfunc_49 <= th_myfunc_49_6; end th_myfunc_49_6: begin _th_myfunc_49_i_250 <= 0; th_myfunc_49 <= th_myfunc_49_7; end th_myfunc_49_7: begin if(_th_myfunc_49_i_250 < _th_myfunc_49_time_249) begin th_myfunc_49 <= th_myfunc_49_8; end else begin th_myfunc_49 <= th_myfunc_49_12; end end th_myfunc_49_8: begin _th_myfunc_49___251 <= 0; th_myfunc_49 <= th_myfunc_49_9; end th_myfunc_49_9: begin if(_th_myfunc_49___251 < 1024) begin th_myfunc_49 <= th_myfunc_49_10; end else begin th_myfunc_49 <= th_myfunc_49_11; end end th_myfunc_49_10: begin _th_myfunc_49___251 <= _th_myfunc_49___251 + 1; th_myfunc_49 <= th_myfunc_49_9; end th_myfunc_49_11: begin _th_myfunc_49_i_250 <= _th_myfunc_49_i_250 + 1; th_myfunc_49 <= th_myfunc_49_7; end th_myfunc_49_12: begin th_myfunc_49 <= th_myfunc_49_13; end th_myfunc_49_13: begin $display("Thread %d count = %d", _th_myfunc_49_tid_248, count); th_myfunc_49 <= th_myfunc_49_14; end th_myfunc_49_14: begin th_myfunc_49 <= th_myfunc_49_15; end th_myfunc_49_15: begin $display("Thread %d Unlock", _th_myfunc_49_tid_248); th_myfunc_49 <= th_myfunc_49_16; end th_myfunc_49_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 49)) begin _th_myfunc_49_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 49)) begin th_myfunc_49 <= th_myfunc_49_init; end end endcase end end localparam th_myfunc_50_1 = 1; localparam th_myfunc_50_2 = 2; localparam th_myfunc_50_3 = 3; localparam th_myfunc_50_4 = 4; localparam th_myfunc_50_5 = 5; localparam th_myfunc_50_6 = 6; localparam th_myfunc_50_7 = 7; localparam th_myfunc_50_8 = 8; localparam th_myfunc_50_9 = 9; localparam th_myfunc_50_10 = 10; localparam th_myfunc_50_11 = 11; localparam th_myfunc_50_12 = 12; localparam th_myfunc_50_13 = 13; localparam th_myfunc_50_14 = 14; localparam th_myfunc_50_15 = 15; localparam th_myfunc_50_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_50 <= th_myfunc_50_init; _th_myfunc_50_called <= 0; _th_myfunc_50_tid_252 <= 0; _th_myfunc_50_tid_253 <= 0; _th_myfunc_50_time_254 <= 0; _th_myfunc_50_i_255 <= 0; _th_myfunc_50___256 <= 0; end else begin case(th_myfunc_50) th_myfunc_50_init: begin if(_th_myfunc_start[50] && (th_blink == 10)) begin _th_myfunc_50_called <= 1; end if(_th_myfunc_start[50] && (th_blink == 10)) begin _th_myfunc_50_tid_252 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[50]) begin th_myfunc_50 <= th_myfunc_50_1; end end th_myfunc_50_1: begin _th_myfunc_50_tid_253 <= _th_myfunc_50_tid_252; th_myfunc_50 <= th_myfunc_50_2; end th_myfunc_50_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 50)) begin th_myfunc_50 <= th_myfunc_50_3; end end th_myfunc_50_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 50))) begin th_myfunc_50 <= th_myfunc_50_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 50)) begin th_myfunc_50 <= th_myfunc_50_4; end end th_myfunc_50_4: begin $display("Thread %d Lock", _th_myfunc_50_tid_253); th_myfunc_50 <= th_myfunc_50_5; end th_myfunc_50_5: begin _th_myfunc_50_time_254 <= sw; th_myfunc_50 <= th_myfunc_50_6; end th_myfunc_50_6: begin _th_myfunc_50_i_255 <= 0; th_myfunc_50 <= th_myfunc_50_7; end th_myfunc_50_7: begin if(_th_myfunc_50_i_255 < _th_myfunc_50_time_254) begin th_myfunc_50 <= th_myfunc_50_8; end else begin th_myfunc_50 <= th_myfunc_50_12; end end th_myfunc_50_8: begin _th_myfunc_50___256 <= 0; th_myfunc_50 <= th_myfunc_50_9; end th_myfunc_50_9: begin if(_th_myfunc_50___256 < 1024) begin th_myfunc_50 <= th_myfunc_50_10; end else begin th_myfunc_50 <= th_myfunc_50_11; end end th_myfunc_50_10: begin _th_myfunc_50___256 <= _th_myfunc_50___256 + 1; th_myfunc_50 <= th_myfunc_50_9; end th_myfunc_50_11: begin _th_myfunc_50_i_255 <= _th_myfunc_50_i_255 + 1; th_myfunc_50 <= th_myfunc_50_7; end th_myfunc_50_12: begin th_myfunc_50 <= th_myfunc_50_13; end th_myfunc_50_13: begin $display("Thread %d count = %d", _th_myfunc_50_tid_253, count); th_myfunc_50 <= th_myfunc_50_14; end th_myfunc_50_14: begin th_myfunc_50 <= th_myfunc_50_15; end th_myfunc_50_15: begin $display("Thread %d Unlock", _th_myfunc_50_tid_253); th_myfunc_50 <= th_myfunc_50_16; end th_myfunc_50_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 50)) begin _th_myfunc_50_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 50)) begin th_myfunc_50 <= th_myfunc_50_init; end end endcase end end localparam th_myfunc_51_1 = 1; localparam th_myfunc_51_2 = 2; localparam th_myfunc_51_3 = 3; localparam th_myfunc_51_4 = 4; localparam th_myfunc_51_5 = 5; localparam th_myfunc_51_6 = 6; localparam th_myfunc_51_7 = 7; localparam th_myfunc_51_8 = 8; localparam th_myfunc_51_9 = 9; localparam th_myfunc_51_10 = 10; localparam th_myfunc_51_11 = 11; localparam th_myfunc_51_12 = 12; localparam th_myfunc_51_13 = 13; localparam th_myfunc_51_14 = 14; localparam th_myfunc_51_15 = 15; localparam th_myfunc_51_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_51 <= th_myfunc_51_init; _th_myfunc_51_called <= 0; _th_myfunc_51_tid_257 <= 0; _th_myfunc_51_tid_258 <= 0; _th_myfunc_51_time_259 <= 0; _th_myfunc_51_i_260 <= 0; _th_myfunc_51___261 <= 0; end else begin case(th_myfunc_51) th_myfunc_51_init: begin if(_th_myfunc_start[51] && (th_blink == 10)) begin _th_myfunc_51_called <= 1; end if(_th_myfunc_start[51] && (th_blink == 10)) begin _th_myfunc_51_tid_257 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[51]) begin th_myfunc_51 <= th_myfunc_51_1; end end th_myfunc_51_1: begin _th_myfunc_51_tid_258 <= _th_myfunc_51_tid_257; th_myfunc_51 <= th_myfunc_51_2; end th_myfunc_51_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 51)) begin th_myfunc_51 <= th_myfunc_51_3; end end th_myfunc_51_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 51))) begin th_myfunc_51 <= th_myfunc_51_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 51)) begin th_myfunc_51 <= th_myfunc_51_4; end end th_myfunc_51_4: begin $display("Thread %d Lock", _th_myfunc_51_tid_258); th_myfunc_51 <= th_myfunc_51_5; end th_myfunc_51_5: begin _th_myfunc_51_time_259 <= sw; th_myfunc_51 <= th_myfunc_51_6; end th_myfunc_51_6: begin _th_myfunc_51_i_260 <= 0; th_myfunc_51 <= th_myfunc_51_7; end th_myfunc_51_7: begin if(_th_myfunc_51_i_260 < _th_myfunc_51_time_259) begin th_myfunc_51 <= th_myfunc_51_8; end else begin th_myfunc_51 <= th_myfunc_51_12; end end th_myfunc_51_8: begin _th_myfunc_51___261 <= 0; th_myfunc_51 <= th_myfunc_51_9; end th_myfunc_51_9: begin if(_th_myfunc_51___261 < 1024) begin th_myfunc_51 <= th_myfunc_51_10; end else begin th_myfunc_51 <= th_myfunc_51_11; end end th_myfunc_51_10: begin _th_myfunc_51___261 <= _th_myfunc_51___261 + 1; th_myfunc_51 <= th_myfunc_51_9; end th_myfunc_51_11: begin _th_myfunc_51_i_260 <= _th_myfunc_51_i_260 + 1; th_myfunc_51 <= th_myfunc_51_7; end th_myfunc_51_12: begin th_myfunc_51 <= th_myfunc_51_13; end th_myfunc_51_13: begin $display("Thread %d count = %d", _th_myfunc_51_tid_258, count); th_myfunc_51 <= th_myfunc_51_14; end th_myfunc_51_14: begin th_myfunc_51 <= th_myfunc_51_15; end th_myfunc_51_15: begin $display("Thread %d Unlock", _th_myfunc_51_tid_258); th_myfunc_51 <= th_myfunc_51_16; end th_myfunc_51_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 51)) begin _th_myfunc_51_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 51)) begin th_myfunc_51 <= th_myfunc_51_init; end end endcase end end localparam th_myfunc_52_1 = 1; localparam th_myfunc_52_2 = 2; localparam th_myfunc_52_3 = 3; localparam th_myfunc_52_4 = 4; localparam th_myfunc_52_5 = 5; localparam th_myfunc_52_6 = 6; localparam th_myfunc_52_7 = 7; localparam th_myfunc_52_8 = 8; localparam th_myfunc_52_9 = 9; localparam th_myfunc_52_10 = 10; localparam th_myfunc_52_11 = 11; localparam th_myfunc_52_12 = 12; localparam th_myfunc_52_13 = 13; localparam th_myfunc_52_14 = 14; localparam th_myfunc_52_15 = 15; localparam th_myfunc_52_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_52 <= th_myfunc_52_init; _th_myfunc_52_called <= 0; _th_myfunc_52_tid_262 <= 0; _th_myfunc_52_tid_263 <= 0; _th_myfunc_52_time_264 <= 0; _th_myfunc_52_i_265 <= 0; _th_myfunc_52___266 <= 0; end else begin case(th_myfunc_52) th_myfunc_52_init: begin if(_th_myfunc_start[52] && (th_blink == 10)) begin _th_myfunc_52_called <= 1; end if(_th_myfunc_start[52] && (th_blink == 10)) begin _th_myfunc_52_tid_262 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[52]) begin th_myfunc_52 <= th_myfunc_52_1; end end th_myfunc_52_1: begin _th_myfunc_52_tid_263 <= _th_myfunc_52_tid_262; th_myfunc_52 <= th_myfunc_52_2; end th_myfunc_52_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 52)) begin th_myfunc_52 <= th_myfunc_52_3; end end th_myfunc_52_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 52))) begin th_myfunc_52 <= th_myfunc_52_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 52)) begin th_myfunc_52 <= th_myfunc_52_4; end end th_myfunc_52_4: begin $display("Thread %d Lock", _th_myfunc_52_tid_263); th_myfunc_52 <= th_myfunc_52_5; end th_myfunc_52_5: begin _th_myfunc_52_time_264 <= sw; th_myfunc_52 <= th_myfunc_52_6; end th_myfunc_52_6: begin _th_myfunc_52_i_265 <= 0; th_myfunc_52 <= th_myfunc_52_7; end th_myfunc_52_7: begin if(_th_myfunc_52_i_265 < _th_myfunc_52_time_264) begin th_myfunc_52 <= th_myfunc_52_8; end else begin th_myfunc_52 <= th_myfunc_52_12; end end th_myfunc_52_8: begin _th_myfunc_52___266 <= 0; th_myfunc_52 <= th_myfunc_52_9; end th_myfunc_52_9: begin if(_th_myfunc_52___266 < 1024) begin th_myfunc_52 <= th_myfunc_52_10; end else begin th_myfunc_52 <= th_myfunc_52_11; end end th_myfunc_52_10: begin _th_myfunc_52___266 <= _th_myfunc_52___266 + 1; th_myfunc_52 <= th_myfunc_52_9; end th_myfunc_52_11: begin _th_myfunc_52_i_265 <= _th_myfunc_52_i_265 + 1; th_myfunc_52 <= th_myfunc_52_7; end th_myfunc_52_12: begin th_myfunc_52 <= th_myfunc_52_13; end th_myfunc_52_13: begin $display("Thread %d count = %d", _th_myfunc_52_tid_263, count); th_myfunc_52 <= th_myfunc_52_14; end th_myfunc_52_14: begin th_myfunc_52 <= th_myfunc_52_15; end th_myfunc_52_15: begin $display("Thread %d Unlock", _th_myfunc_52_tid_263); th_myfunc_52 <= th_myfunc_52_16; end th_myfunc_52_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 52)) begin _th_myfunc_52_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 52)) begin th_myfunc_52 <= th_myfunc_52_init; end end endcase end end localparam th_myfunc_53_1 = 1; localparam th_myfunc_53_2 = 2; localparam th_myfunc_53_3 = 3; localparam th_myfunc_53_4 = 4; localparam th_myfunc_53_5 = 5; localparam th_myfunc_53_6 = 6; localparam th_myfunc_53_7 = 7; localparam th_myfunc_53_8 = 8; localparam th_myfunc_53_9 = 9; localparam th_myfunc_53_10 = 10; localparam th_myfunc_53_11 = 11; localparam th_myfunc_53_12 = 12; localparam th_myfunc_53_13 = 13; localparam th_myfunc_53_14 = 14; localparam th_myfunc_53_15 = 15; localparam th_myfunc_53_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_53 <= th_myfunc_53_init; _th_myfunc_53_called <= 0; _th_myfunc_53_tid_267 <= 0; _th_myfunc_53_tid_268 <= 0; _th_myfunc_53_time_269 <= 0; _th_myfunc_53_i_270 <= 0; _th_myfunc_53___271 <= 0; end else begin case(th_myfunc_53) th_myfunc_53_init: begin if(_th_myfunc_start[53] && (th_blink == 10)) begin _th_myfunc_53_called <= 1; end if(_th_myfunc_start[53] && (th_blink == 10)) begin _th_myfunc_53_tid_267 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[53]) begin th_myfunc_53 <= th_myfunc_53_1; end end th_myfunc_53_1: begin _th_myfunc_53_tid_268 <= _th_myfunc_53_tid_267; th_myfunc_53 <= th_myfunc_53_2; end th_myfunc_53_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 53)) begin th_myfunc_53 <= th_myfunc_53_3; end end th_myfunc_53_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 53))) begin th_myfunc_53 <= th_myfunc_53_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 53)) begin th_myfunc_53 <= th_myfunc_53_4; end end th_myfunc_53_4: begin $display("Thread %d Lock", _th_myfunc_53_tid_268); th_myfunc_53 <= th_myfunc_53_5; end th_myfunc_53_5: begin _th_myfunc_53_time_269 <= sw; th_myfunc_53 <= th_myfunc_53_6; end th_myfunc_53_6: begin _th_myfunc_53_i_270 <= 0; th_myfunc_53 <= th_myfunc_53_7; end th_myfunc_53_7: begin if(_th_myfunc_53_i_270 < _th_myfunc_53_time_269) begin th_myfunc_53 <= th_myfunc_53_8; end else begin th_myfunc_53 <= th_myfunc_53_12; end end th_myfunc_53_8: begin _th_myfunc_53___271 <= 0; th_myfunc_53 <= th_myfunc_53_9; end th_myfunc_53_9: begin if(_th_myfunc_53___271 < 1024) begin th_myfunc_53 <= th_myfunc_53_10; end else begin th_myfunc_53 <= th_myfunc_53_11; end end th_myfunc_53_10: begin _th_myfunc_53___271 <= _th_myfunc_53___271 + 1; th_myfunc_53 <= th_myfunc_53_9; end th_myfunc_53_11: begin _th_myfunc_53_i_270 <= _th_myfunc_53_i_270 + 1; th_myfunc_53 <= th_myfunc_53_7; end th_myfunc_53_12: begin th_myfunc_53 <= th_myfunc_53_13; end th_myfunc_53_13: begin $display("Thread %d count = %d", _th_myfunc_53_tid_268, count); th_myfunc_53 <= th_myfunc_53_14; end th_myfunc_53_14: begin th_myfunc_53 <= th_myfunc_53_15; end th_myfunc_53_15: begin $display("Thread %d Unlock", _th_myfunc_53_tid_268); th_myfunc_53 <= th_myfunc_53_16; end th_myfunc_53_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 53)) begin _th_myfunc_53_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 53)) begin th_myfunc_53 <= th_myfunc_53_init; end end endcase end end localparam th_myfunc_54_1 = 1; localparam th_myfunc_54_2 = 2; localparam th_myfunc_54_3 = 3; localparam th_myfunc_54_4 = 4; localparam th_myfunc_54_5 = 5; localparam th_myfunc_54_6 = 6; localparam th_myfunc_54_7 = 7; localparam th_myfunc_54_8 = 8; localparam th_myfunc_54_9 = 9; localparam th_myfunc_54_10 = 10; localparam th_myfunc_54_11 = 11; localparam th_myfunc_54_12 = 12; localparam th_myfunc_54_13 = 13; localparam th_myfunc_54_14 = 14; localparam th_myfunc_54_15 = 15; localparam th_myfunc_54_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_54 <= th_myfunc_54_init; _th_myfunc_54_called <= 0; _th_myfunc_54_tid_272 <= 0; _th_myfunc_54_tid_273 <= 0; _th_myfunc_54_time_274 <= 0; _th_myfunc_54_i_275 <= 0; _th_myfunc_54___276 <= 0; end else begin case(th_myfunc_54) th_myfunc_54_init: begin if(_th_myfunc_start[54] && (th_blink == 10)) begin _th_myfunc_54_called <= 1; end if(_th_myfunc_start[54] && (th_blink == 10)) begin _th_myfunc_54_tid_272 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[54]) begin th_myfunc_54 <= th_myfunc_54_1; end end th_myfunc_54_1: begin _th_myfunc_54_tid_273 <= _th_myfunc_54_tid_272; th_myfunc_54 <= th_myfunc_54_2; end th_myfunc_54_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 54)) begin th_myfunc_54 <= th_myfunc_54_3; end end th_myfunc_54_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 54))) begin th_myfunc_54 <= th_myfunc_54_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 54)) begin th_myfunc_54 <= th_myfunc_54_4; end end th_myfunc_54_4: begin $display("Thread %d Lock", _th_myfunc_54_tid_273); th_myfunc_54 <= th_myfunc_54_5; end th_myfunc_54_5: begin _th_myfunc_54_time_274 <= sw; th_myfunc_54 <= th_myfunc_54_6; end th_myfunc_54_6: begin _th_myfunc_54_i_275 <= 0; th_myfunc_54 <= th_myfunc_54_7; end th_myfunc_54_7: begin if(_th_myfunc_54_i_275 < _th_myfunc_54_time_274) begin th_myfunc_54 <= th_myfunc_54_8; end else begin th_myfunc_54 <= th_myfunc_54_12; end end th_myfunc_54_8: begin _th_myfunc_54___276 <= 0; th_myfunc_54 <= th_myfunc_54_9; end th_myfunc_54_9: begin if(_th_myfunc_54___276 < 1024) begin th_myfunc_54 <= th_myfunc_54_10; end else begin th_myfunc_54 <= th_myfunc_54_11; end end th_myfunc_54_10: begin _th_myfunc_54___276 <= _th_myfunc_54___276 + 1; th_myfunc_54 <= th_myfunc_54_9; end th_myfunc_54_11: begin _th_myfunc_54_i_275 <= _th_myfunc_54_i_275 + 1; th_myfunc_54 <= th_myfunc_54_7; end th_myfunc_54_12: begin th_myfunc_54 <= th_myfunc_54_13; end th_myfunc_54_13: begin $display("Thread %d count = %d", _th_myfunc_54_tid_273, count); th_myfunc_54 <= th_myfunc_54_14; end th_myfunc_54_14: begin th_myfunc_54 <= th_myfunc_54_15; end th_myfunc_54_15: begin $display("Thread %d Unlock", _th_myfunc_54_tid_273); th_myfunc_54 <= th_myfunc_54_16; end th_myfunc_54_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 54)) begin _th_myfunc_54_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 54)) begin th_myfunc_54 <= th_myfunc_54_init; end end endcase end end localparam th_myfunc_55_1 = 1; localparam th_myfunc_55_2 = 2; localparam th_myfunc_55_3 = 3; localparam th_myfunc_55_4 = 4; localparam th_myfunc_55_5 = 5; localparam th_myfunc_55_6 = 6; localparam th_myfunc_55_7 = 7; localparam th_myfunc_55_8 = 8; localparam th_myfunc_55_9 = 9; localparam th_myfunc_55_10 = 10; localparam th_myfunc_55_11 = 11; localparam th_myfunc_55_12 = 12; localparam th_myfunc_55_13 = 13; localparam th_myfunc_55_14 = 14; localparam th_myfunc_55_15 = 15; localparam th_myfunc_55_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_55 <= th_myfunc_55_init; _th_myfunc_55_called <= 0; _th_myfunc_55_tid_277 <= 0; _th_myfunc_55_tid_278 <= 0; _th_myfunc_55_time_279 <= 0; _th_myfunc_55_i_280 <= 0; _th_myfunc_55___281 <= 0; end else begin case(th_myfunc_55) th_myfunc_55_init: begin if(_th_myfunc_start[55] && (th_blink == 10)) begin _th_myfunc_55_called <= 1; end if(_th_myfunc_start[55] && (th_blink == 10)) begin _th_myfunc_55_tid_277 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[55]) begin th_myfunc_55 <= th_myfunc_55_1; end end th_myfunc_55_1: begin _th_myfunc_55_tid_278 <= _th_myfunc_55_tid_277; th_myfunc_55 <= th_myfunc_55_2; end th_myfunc_55_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 55)) begin th_myfunc_55 <= th_myfunc_55_3; end end th_myfunc_55_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 55))) begin th_myfunc_55 <= th_myfunc_55_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 55)) begin th_myfunc_55 <= th_myfunc_55_4; end end th_myfunc_55_4: begin $display("Thread %d Lock", _th_myfunc_55_tid_278); th_myfunc_55 <= th_myfunc_55_5; end th_myfunc_55_5: begin _th_myfunc_55_time_279 <= sw; th_myfunc_55 <= th_myfunc_55_6; end th_myfunc_55_6: begin _th_myfunc_55_i_280 <= 0; th_myfunc_55 <= th_myfunc_55_7; end th_myfunc_55_7: begin if(_th_myfunc_55_i_280 < _th_myfunc_55_time_279) begin th_myfunc_55 <= th_myfunc_55_8; end else begin th_myfunc_55 <= th_myfunc_55_12; end end th_myfunc_55_8: begin _th_myfunc_55___281 <= 0; th_myfunc_55 <= th_myfunc_55_9; end th_myfunc_55_9: begin if(_th_myfunc_55___281 < 1024) begin th_myfunc_55 <= th_myfunc_55_10; end else begin th_myfunc_55 <= th_myfunc_55_11; end end th_myfunc_55_10: begin _th_myfunc_55___281 <= _th_myfunc_55___281 + 1; th_myfunc_55 <= th_myfunc_55_9; end th_myfunc_55_11: begin _th_myfunc_55_i_280 <= _th_myfunc_55_i_280 + 1; th_myfunc_55 <= th_myfunc_55_7; end th_myfunc_55_12: begin th_myfunc_55 <= th_myfunc_55_13; end th_myfunc_55_13: begin $display("Thread %d count = %d", _th_myfunc_55_tid_278, count); th_myfunc_55 <= th_myfunc_55_14; end th_myfunc_55_14: begin th_myfunc_55 <= th_myfunc_55_15; end th_myfunc_55_15: begin $display("Thread %d Unlock", _th_myfunc_55_tid_278); th_myfunc_55 <= th_myfunc_55_16; end th_myfunc_55_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 55)) begin _th_myfunc_55_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 55)) begin th_myfunc_55 <= th_myfunc_55_init; end end endcase end end localparam th_myfunc_56_1 = 1; localparam th_myfunc_56_2 = 2; localparam th_myfunc_56_3 = 3; localparam th_myfunc_56_4 = 4; localparam th_myfunc_56_5 = 5; localparam th_myfunc_56_6 = 6; localparam th_myfunc_56_7 = 7; localparam th_myfunc_56_8 = 8; localparam th_myfunc_56_9 = 9; localparam th_myfunc_56_10 = 10; localparam th_myfunc_56_11 = 11; localparam th_myfunc_56_12 = 12; localparam th_myfunc_56_13 = 13; localparam th_myfunc_56_14 = 14; localparam th_myfunc_56_15 = 15; localparam th_myfunc_56_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_56 <= th_myfunc_56_init; _th_myfunc_56_called <= 0; _th_myfunc_56_tid_282 <= 0; _th_myfunc_56_tid_283 <= 0; _th_myfunc_56_time_284 <= 0; _th_myfunc_56_i_285 <= 0; _th_myfunc_56___286 <= 0; end else begin case(th_myfunc_56) th_myfunc_56_init: begin if(_th_myfunc_start[56] && (th_blink == 10)) begin _th_myfunc_56_called <= 1; end if(_th_myfunc_start[56] && (th_blink == 10)) begin _th_myfunc_56_tid_282 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[56]) begin th_myfunc_56 <= th_myfunc_56_1; end end th_myfunc_56_1: begin _th_myfunc_56_tid_283 <= _th_myfunc_56_tid_282; th_myfunc_56 <= th_myfunc_56_2; end th_myfunc_56_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 56)) begin th_myfunc_56 <= th_myfunc_56_3; end end th_myfunc_56_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 56))) begin th_myfunc_56 <= th_myfunc_56_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 56)) begin th_myfunc_56 <= th_myfunc_56_4; end end th_myfunc_56_4: begin $display("Thread %d Lock", _th_myfunc_56_tid_283); th_myfunc_56 <= th_myfunc_56_5; end th_myfunc_56_5: begin _th_myfunc_56_time_284 <= sw; th_myfunc_56 <= th_myfunc_56_6; end th_myfunc_56_6: begin _th_myfunc_56_i_285 <= 0; th_myfunc_56 <= th_myfunc_56_7; end th_myfunc_56_7: begin if(_th_myfunc_56_i_285 < _th_myfunc_56_time_284) begin th_myfunc_56 <= th_myfunc_56_8; end else begin th_myfunc_56 <= th_myfunc_56_12; end end th_myfunc_56_8: begin _th_myfunc_56___286 <= 0; th_myfunc_56 <= th_myfunc_56_9; end th_myfunc_56_9: begin if(_th_myfunc_56___286 < 1024) begin th_myfunc_56 <= th_myfunc_56_10; end else begin th_myfunc_56 <= th_myfunc_56_11; end end th_myfunc_56_10: begin _th_myfunc_56___286 <= _th_myfunc_56___286 + 1; th_myfunc_56 <= th_myfunc_56_9; end th_myfunc_56_11: begin _th_myfunc_56_i_285 <= _th_myfunc_56_i_285 + 1; th_myfunc_56 <= th_myfunc_56_7; end th_myfunc_56_12: begin th_myfunc_56 <= th_myfunc_56_13; end th_myfunc_56_13: begin $display("Thread %d count = %d", _th_myfunc_56_tid_283, count); th_myfunc_56 <= th_myfunc_56_14; end th_myfunc_56_14: begin th_myfunc_56 <= th_myfunc_56_15; end th_myfunc_56_15: begin $display("Thread %d Unlock", _th_myfunc_56_tid_283); th_myfunc_56 <= th_myfunc_56_16; end th_myfunc_56_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 56)) begin _th_myfunc_56_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 56)) begin th_myfunc_56 <= th_myfunc_56_init; end end endcase end end localparam th_myfunc_57_1 = 1; localparam th_myfunc_57_2 = 2; localparam th_myfunc_57_3 = 3; localparam th_myfunc_57_4 = 4; localparam th_myfunc_57_5 = 5; localparam th_myfunc_57_6 = 6; localparam th_myfunc_57_7 = 7; localparam th_myfunc_57_8 = 8; localparam th_myfunc_57_9 = 9; localparam th_myfunc_57_10 = 10; localparam th_myfunc_57_11 = 11; localparam th_myfunc_57_12 = 12; localparam th_myfunc_57_13 = 13; localparam th_myfunc_57_14 = 14; localparam th_myfunc_57_15 = 15; localparam th_myfunc_57_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_57 <= th_myfunc_57_init; _th_myfunc_57_called <= 0; _th_myfunc_57_tid_287 <= 0; _th_myfunc_57_tid_288 <= 0; _th_myfunc_57_time_289 <= 0; _th_myfunc_57_i_290 <= 0; _th_myfunc_57___291 <= 0; end else begin case(th_myfunc_57) th_myfunc_57_init: begin if(_th_myfunc_start[57] && (th_blink == 10)) begin _th_myfunc_57_called <= 1; end if(_th_myfunc_start[57] && (th_blink == 10)) begin _th_myfunc_57_tid_287 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[57]) begin th_myfunc_57 <= th_myfunc_57_1; end end th_myfunc_57_1: begin _th_myfunc_57_tid_288 <= _th_myfunc_57_tid_287; th_myfunc_57 <= th_myfunc_57_2; end th_myfunc_57_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 57)) begin th_myfunc_57 <= th_myfunc_57_3; end end th_myfunc_57_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 57))) begin th_myfunc_57 <= th_myfunc_57_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 57)) begin th_myfunc_57 <= th_myfunc_57_4; end end th_myfunc_57_4: begin $display("Thread %d Lock", _th_myfunc_57_tid_288); th_myfunc_57 <= th_myfunc_57_5; end th_myfunc_57_5: begin _th_myfunc_57_time_289 <= sw; th_myfunc_57 <= th_myfunc_57_6; end th_myfunc_57_6: begin _th_myfunc_57_i_290 <= 0; th_myfunc_57 <= th_myfunc_57_7; end th_myfunc_57_7: begin if(_th_myfunc_57_i_290 < _th_myfunc_57_time_289) begin th_myfunc_57 <= th_myfunc_57_8; end else begin th_myfunc_57 <= th_myfunc_57_12; end end th_myfunc_57_8: begin _th_myfunc_57___291 <= 0; th_myfunc_57 <= th_myfunc_57_9; end th_myfunc_57_9: begin if(_th_myfunc_57___291 < 1024) begin th_myfunc_57 <= th_myfunc_57_10; end else begin th_myfunc_57 <= th_myfunc_57_11; end end th_myfunc_57_10: begin _th_myfunc_57___291 <= _th_myfunc_57___291 + 1; th_myfunc_57 <= th_myfunc_57_9; end th_myfunc_57_11: begin _th_myfunc_57_i_290 <= _th_myfunc_57_i_290 + 1; th_myfunc_57 <= th_myfunc_57_7; end th_myfunc_57_12: begin th_myfunc_57 <= th_myfunc_57_13; end th_myfunc_57_13: begin $display("Thread %d count = %d", _th_myfunc_57_tid_288, count); th_myfunc_57 <= th_myfunc_57_14; end th_myfunc_57_14: begin th_myfunc_57 <= th_myfunc_57_15; end th_myfunc_57_15: begin $display("Thread %d Unlock", _th_myfunc_57_tid_288); th_myfunc_57 <= th_myfunc_57_16; end th_myfunc_57_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 57)) begin _th_myfunc_57_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 57)) begin th_myfunc_57 <= th_myfunc_57_init; end end endcase end end localparam th_myfunc_58_1 = 1; localparam th_myfunc_58_2 = 2; localparam th_myfunc_58_3 = 3; localparam th_myfunc_58_4 = 4; localparam th_myfunc_58_5 = 5; localparam th_myfunc_58_6 = 6; localparam th_myfunc_58_7 = 7; localparam th_myfunc_58_8 = 8; localparam th_myfunc_58_9 = 9; localparam th_myfunc_58_10 = 10; localparam th_myfunc_58_11 = 11; localparam th_myfunc_58_12 = 12; localparam th_myfunc_58_13 = 13; localparam th_myfunc_58_14 = 14; localparam th_myfunc_58_15 = 15; localparam th_myfunc_58_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_58 <= th_myfunc_58_init; _th_myfunc_58_called <= 0; _th_myfunc_58_tid_292 <= 0; _th_myfunc_58_tid_293 <= 0; _th_myfunc_58_time_294 <= 0; _th_myfunc_58_i_295 <= 0; _th_myfunc_58___296 <= 0; end else begin case(th_myfunc_58) th_myfunc_58_init: begin if(_th_myfunc_start[58] && (th_blink == 10)) begin _th_myfunc_58_called <= 1; end if(_th_myfunc_start[58] && (th_blink == 10)) begin _th_myfunc_58_tid_292 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[58]) begin th_myfunc_58 <= th_myfunc_58_1; end end th_myfunc_58_1: begin _th_myfunc_58_tid_293 <= _th_myfunc_58_tid_292; th_myfunc_58 <= th_myfunc_58_2; end th_myfunc_58_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 58)) begin th_myfunc_58 <= th_myfunc_58_3; end end th_myfunc_58_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 58))) begin th_myfunc_58 <= th_myfunc_58_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 58)) begin th_myfunc_58 <= th_myfunc_58_4; end end th_myfunc_58_4: begin $display("Thread %d Lock", _th_myfunc_58_tid_293); th_myfunc_58 <= th_myfunc_58_5; end th_myfunc_58_5: begin _th_myfunc_58_time_294 <= sw; th_myfunc_58 <= th_myfunc_58_6; end th_myfunc_58_6: begin _th_myfunc_58_i_295 <= 0; th_myfunc_58 <= th_myfunc_58_7; end th_myfunc_58_7: begin if(_th_myfunc_58_i_295 < _th_myfunc_58_time_294) begin th_myfunc_58 <= th_myfunc_58_8; end else begin th_myfunc_58 <= th_myfunc_58_12; end end th_myfunc_58_8: begin _th_myfunc_58___296 <= 0; th_myfunc_58 <= th_myfunc_58_9; end th_myfunc_58_9: begin if(_th_myfunc_58___296 < 1024) begin th_myfunc_58 <= th_myfunc_58_10; end else begin th_myfunc_58 <= th_myfunc_58_11; end end th_myfunc_58_10: begin _th_myfunc_58___296 <= _th_myfunc_58___296 + 1; th_myfunc_58 <= th_myfunc_58_9; end th_myfunc_58_11: begin _th_myfunc_58_i_295 <= _th_myfunc_58_i_295 + 1; th_myfunc_58 <= th_myfunc_58_7; end th_myfunc_58_12: begin th_myfunc_58 <= th_myfunc_58_13; end th_myfunc_58_13: begin $display("Thread %d count = %d", _th_myfunc_58_tid_293, count); th_myfunc_58 <= th_myfunc_58_14; end th_myfunc_58_14: begin th_myfunc_58 <= th_myfunc_58_15; end th_myfunc_58_15: begin $display("Thread %d Unlock", _th_myfunc_58_tid_293); th_myfunc_58 <= th_myfunc_58_16; end th_myfunc_58_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 58)) begin _th_myfunc_58_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 58)) begin th_myfunc_58 <= th_myfunc_58_init; end end endcase end end localparam th_myfunc_59_1 = 1; localparam th_myfunc_59_2 = 2; localparam th_myfunc_59_3 = 3; localparam th_myfunc_59_4 = 4; localparam th_myfunc_59_5 = 5; localparam th_myfunc_59_6 = 6; localparam th_myfunc_59_7 = 7; localparam th_myfunc_59_8 = 8; localparam th_myfunc_59_9 = 9; localparam th_myfunc_59_10 = 10; localparam th_myfunc_59_11 = 11; localparam th_myfunc_59_12 = 12; localparam th_myfunc_59_13 = 13; localparam th_myfunc_59_14 = 14; localparam th_myfunc_59_15 = 15; localparam th_myfunc_59_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_59 <= th_myfunc_59_init; _th_myfunc_59_called <= 0; _th_myfunc_59_tid_297 <= 0; _th_myfunc_59_tid_298 <= 0; _th_myfunc_59_time_299 <= 0; _th_myfunc_59_i_300 <= 0; _th_myfunc_59___301 <= 0; end else begin case(th_myfunc_59) th_myfunc_59_init: begin if(_th_myfunc_start[59] && (th_blink == 10)) begin _th_myfunc_59_called <= 1; end if(_th_myfunc_start[59] && (th_blink == 10)) begin _th_myfunc_59_tid_297 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[59]) begin th_myfunc_59 <= th_myfunc_59_1; end end th_myfunc_59_1: begin _th_myfunc_59_tid_298 <= _th_myfunc_59_tid_297; th_myfunc_59 <= th_myfunc_59_2; end th_myfunc_59_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 59)) begin th_myfunc_59 <= th_myfunc_59_3; end end th_myfunc_59_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 59))) begin th_myfunc_59 <= th_myfunc_59_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 59)) begin th_myfunc_59 <= th_myfunc_59_4; end end th_myfunc_59_4: begin $display("Thread %d Lock", _th_myfunc_59_tid_298); th_myfunc_59 <= th_myfunc_59_5; end th_myfunc_59_5: begin _th_myfunc_59_time_299 <= sw; th_myfunc_59 <= th_myfunc_59_6; end th_myfunc_59_6: begin _th_myfunc_59_i_300 <= 0; th_myfunc_59 <= th_myfunc_59_7; end th_myfunc_59_7: begin if(_th_myfunc_59_i_300 < _th_myfunc_59_time_299) begin th_myfunc_59 <= th_myfunc_59_8; end else begin th_myfunc_59 <= th_myfunc_59_12; end end th_myfunc_59_8: begin _th_myfunc_59___301 <= 0; th_myfunc_59 <= th_myfunc_59_9; end th_myfunc_59_9: begin if(_th_myfunc_59___301 < 1024) begin th_myfunc_59 <= th_myfunc_59_10; end else begin th_myfunc_59 <= th_myfunc_59_11; end end th_myfunc_59_10: begin _th_myfunc_59___301 <= _th_myfunc_59___301 + 1; th_myfunc_59 <= th_myfunc_59_9; end th_myfunc_59_11: begin _th_myfunc_59_i_300 <= _th_myfunc_59_i_300 + 1; th_myfunc_59 <= th_myfunc_59_7; end th_myfunc_59_12: begin th_myfunc_59 <= th_myfunc_59_13; end th_myfunc_59_13: begin $display("Thread %d count = %d", _th_myfunc_59_tid_298, count); th_myfunc_59 <= th_myfunc_59_14; end th_myfunc_59_14: begin th_myfunc_59 <= th_myfunc_59_15; end th_myfunc_59_15: begin $display("Thread %d Unlock", _th_myfunc_59_tid_298); th_myfunc_59 <= th_myfunc_59_16; end th_myfunc_59_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 59)) begin _th_myfunc_59_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 59)) begin th_myfunc_59 <= th_myfunc_59_init; end end endcase end end localparam th_myfunc_60_1 = 1; localparam th_myfunc_60_2 = 2; localparam th_myfunc_60_3 = 3; localparam th_myfunc_60_4 = 4; localparam th_myfunc_60_5 = 5; localparam th_myfunc_60_6 = 6; localparam th_myfunc_60_7 = 7; localparam th_myfunc_60_8 = 8; localparam th_myfunc_60_9 = 9; localparam th_myfunc_60_10 = 10; localparam th_myfunc_60_11 = 11; localparam th_myfunc_60_12 = 12; localparam th_myfunc_60_13 = 13; localparam th_myfunc_60_14 = 14; localparam th_myfunc_60_15 = 15; localparam th_myfunc_60_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_60 <= th_myfunc_60_init; _th_myfunc_60_called <= 0; _th_myfunc_60_tid_302 <= 0; _th_myfunc_60_tid_303 <= 0; _th_myfunc_60_time_304 <= 0; _th_myfunc_60_i_305 <= 0; _th_myfunc_60___306 <= 0; end else begin case(th_myfunc_60) th_myfunc_60_init: begin if(_th_myfunc_start[60] && (th_blink == 10)) begin _th_myfunc_60_called <= 1; end if(_th_myfunc_start[60] && (th_blink == 10)) begin _th_myfunc_60_tid_302 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[60]) begin th_myfunc_60 <= th_myfunc_60_1; end end th_myfunc_60_1: begin _th_myfunc_60_tid_303 <= _th_myfunc_60_tid_302; th_myfunc_60 <= th_myfunc_60_2; end th_myfunc_60_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 60)) begin th_myfunc_60 <= th_myfunc_60_3; end end th_myfunc_60_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 60))) begin th_myfunc_60 <= th_myfunc_60_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 60)) begin th_myfunc_60 <= th_myfunc_60_4; end end th_myfunc_60_4: begin $display("Thread %d Lock", _th_myfunc_60_tid_303); th_myfunc_60 <= th_myfunc_60_5; end th_myfunc_60_5: begin _th_myfunc_60_time_304 <= sw; th_myfunc_60 <= th_myfunc_60_6; end th_myfunc_60_6: begin _th_myfunc_60_i_305 <= 0; th_myfunc_60 <= th_myfunc_60_7; end th_myfunc_60_7: begin if(_th_myfunc_60_i_305 < _th_myfunc_60_time_304) begin th_myfunc_60 <= th_myfunc_60_8; end else begin th_myfunc_60 <= th_myfunc_60_12; end end th_myfunc_60_8: begin _th_myfunc_60___306 <= 0; th_myfunc_60 <= th_myfunc_60_9; end th_myfunc_60_9: begin if(_th_myfunc_60___306 < 1024) begin th_myfunc_60 <= th_myfunc_60_10; end else begin th_myfunc_60 <= th_myfunc_60_11; end end th_myfunc_60_10: begin _th_myfunc_60___306 <= _th_myfunc_60___306 + 1; th_myfunc_60 <= th_myfunc_60_9; end th_myfunc_60_11: begin _th_myfunc_60_i_305 <= _th_myfunc_60_i_305 + 1; th_myfunc_60 <= th_myfunc_60_7; end th_myfunc_60_12: begin th_myfunc_60 <= th_myfunc_60_13; end th_myfunc_60_13: begin $display("Thread %d count = %d", _th_myfunc_60_tid_303, count); th_myfunc_60 <= th_myfunc_60_14; end th_myfunc_60_14: begin th_myfunc_60 <= th_myfunc_60_15; end th_myfunc_60_15: begin $display("Thread %d Unlock", _th_myfunc_60_tid_303); th_myfunc_60 <= th_myfunc_60_16; end th_myfunc_60_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 60)) begin _th_myfunc_60_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 60)) begin th_myfunc_60 <= th_myfunc_60_init; end end endcase end end localparam th_myfunc_61_1 = 1; localparam th_myfunc_61_2 = 2; localparam th_myfunc_61_3 = 3; localparam th_myfunc_61_4 = 4; localparam th_myfunc_61_5 = 5; localparam th_myfunc_61_6 = 6; localparam th_myfunc_61_7 = 7; localparam th_myfunc_61_8 = 8; localparam th_myfunc_61_9 = 9; localparam th_myfunc_61_10 = 10; localparam th_myfunc_61_11 = 11; localparam th_myfunc_61_12 = 12; localparam th_myfunc_61_13 = 13; localparam th_myfunc_61_14 = 14; localparam th_myfunc_61_15 = 15; localparam th_myfunc_61_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_61 <= th_myfunc_61_init; _th_myfunc_61_called <= 0; _th_myfunc_61_tid_307 <= 0; _th_myfunc_61_tid_308 <= 0; _th_myfunc_61_time_309 <= 0; _th_myfunc_61_i_310 <= 0; _th_myfunc_61___311 <= 0; end else begin case(th_myfunc_61) th_myfunc_61_init: begin if(_th_myfunc_start[61] && (th_blink == 10)) begin _th_myfunc_61_called <= 1; end if(_th_myfunc_start[61] && (th_blink == 10)) begin _th_myfunc_61_tid_307 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[61]) begin th_myfunc_61 <= th_myfunc_61_1; end end th_myfunc_61_1: begin _th_myfunc_61_tid_308 <= _th_myfunc_61_tid_307; th_myfunc_61 <= th_myfunc_61_2; end th_myfunc_61_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 61)) begin th_myfunc_61 <= th_myfunc_61_3; end end th_myfunc_61_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 61))) begin th_myfunc_61 <= th_myfunc_61_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 61)) begin th_myfunc_61 <= th_myfunc_61_4; end end th_myfunc_61_4: begin $display("Thread %d Lock", _th_myfunc_61_tid_308); th_myfunc_61 <= th_myfunc_61_5; end th_myfunc_61_5: begin _th_myfunc_61_time_309 <= sw; th_myfunc_61 <= th_myfunc_61_6; end th_myfunc_61_6: begin _th_myfunc_61_i_310 <= 0; th_myfunc_61 <= th_myfunc_61_7; end th_myfunc_61_7: begin if(_th_myfunc_61_i_310 < _th_myfunc_61_time_309) begin th_myfunc_61 <= th_myfunc_61_8; end else begin th_myfunc_61 <= th_myfunc_61_12; end end th_myfunc_61_8: begin _th_myfunc_61___311 <= 0; th_myfunc_61 <= th_myfunc_61_9; end th_myfunc_61_9: begin if(_th_myfunc_61___311 < 1024) begin th_myfunc_61 <= th_myfunc_61_10; end else begin th_myfunc_61 <= th_myfunc_61_11; end end th_myfunc_61_10: begin _th_myfunc_61___311 <= _th_myfunc_61___311 + 1; th_myfunc_61 <= th_myfunc_61_9; end th_myfunc_61_11: begin _th_myfunc_61_i_310 <= _th_myfunc_61_i_310 + 1; th_myfunc_61 <= th_myfunc_61_7; end th_myfunc_61_12: begin th_myfunc_61 <= th_myfunc_61_13; end th_myfunc_61_13: begin $display("Thread %d count = %d", _th_myfunc_61_tid_308, count); th_myfunc_61 <= th_myfunc_61_14; end th_myfunc_61_14: begin th_myfunc_61 <= th_myfunc_61_15; end th_myfunc_61_15: begin $display("Thread %d Unlock", _th_myfunc_61_tid_308); th_myfunc_61 <= th_myfunc_61_16; end th_myfunc_61_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 61)) begin _th_myfunc_61_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 61)) begin th_myfunc_61 <= th_myfunc_61_init; end end endcase end end localparam th_myfunc_62_1 = 1; localparam th_myfunc_62_2 = 2; localparam th_myfunc_62_3 = 3; localparam th_myfunc_62_4 = 4; localparam th_myfunc_62_5 = 5; localparam th_myfunc_62_6 = 6; localparam th_myfunc_62_7 = 7; localparam th_myfunc_62_8 = 8; localparam th_myfunc_62_9 = 9; localparam th_myfunc_62_10 = 10; localparam th_myfunc_62_11 = 11; localparam th_myfunc_62_12 = 12; localparam th_myfunc_62_13 = 13; localparam th_myfunc_62_14 = 14; localparam th_myfunc_62_15 = 15; localparam th_myfunc_62_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_62 <= th_myfunc_62_init; _th_myfunc_62_called <= 0; _th_myfunc_62_tid_312 <= 0; _th_myfunc_62_tid_313 <= 0; _th_myfunc_62_time_314 <= 0; _th_myfunc_62_i_315 <= 0; _th_myfunc_62___316 <= 0; end else begin case(th_myfunc_62) th_myfunc_62_init: begin if(_th_myfunc_start[62] && (th_blink == 10)) begin _th_myfunc_62_called <= 1; end if(_th_myfunc_start[62] && (th_blink == 10)) begin _th_myfunc_62_tid_312 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[62]) begin th_myfunc_62 <= th_myfunc_62_1; end end th_myfunc_62_1: begin _th_myfunc_62_tid_313 <= _th_myfunc_62_tid_312; th_myfunc_62 <= th_myfunc_62_2; end th_myfunc_62_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 62)) begin th_myfunc_62 <= th_myfunc_62_3; end end th_myfunc_62_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 62))) begin th_myfunc_62 <= th_myfunc_62_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 62)) begin th_myfunc_62 <= th_myfunc_62_4; end end th_myfunc_62_4: begin $display("Thread %d Lock", _th_myfunc_62_tid_313); th_myfunc_62 <= th_myfunc_62_5; end th_myfunc_62_5: begin _th_myfunc_62_time_314 <= sw; th_myfunc_62 <= th_myfunc_62_6; end th_myfunc_62_6: begin _th_myfunc_62_i_315 <= 0; th_myfunc_62 <= th_myfunc_62_7; end th_myfunc_62_7: begin if(_th_myfunc_62_i_315 < _th_myfunc_62_time_314) begin th_myfunc_62 <= th_myfunc_62_8; end else begin th_myfunc_62 <= th_myfunc_62_12; end end th_myfunc_62_8: begin _th_myfunc_62___316 <= 0; th_myfunc_62 <= th_myfunc_62_9; end th_myfunc_62_9: begin if(_th_myfunc_62___316 < 1024) begin th_myfunc_62 <= th_myfunc_62_10; end else begin th_myfunc_62 <= th_myfunc_62_11; end end th_myfunc_62_10: begin _th_myfunc_62___316 <= _th_myfunc_62___316 + 1; th_myfunc_62 <= th_myfunc_62_9; end th_myfunc_62_11: begin _th_myfunc_62_i_315 <= _th_myfunc_62_i_315 + 1; th_myfunc_62 <= th_myfunc_62_7; end th_myfunc_62_12: begin th_myfunc_62 <= th_myfunc_62_13; end th_myfunc_62_13: begin $display("Thread %d count = %d", _th_myfunc_62_tid_313, count); th_myfunc_62 <= th_myfunc_62_14; end th_myfunc_62_14: begin th_myfunc_62 <= th_myfunc_62_15; end th_myfunc_62_15: begin $display("Thread %d Unlock", _th_myfunc_62_tid_313); th_myfunc_62 <= th_myfunc_62_16; end th_myfunc_62_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 62)) begin _th_myfunc_62_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 62)) begin th_myfunc_62 <= th_myfunc_62_init; end end endcase end end localparam th_myfunc_63_1 = 1; localparam th_myfunc_63_2 = 2; localparam th_myfunc_63_3 = 3; localparam th_myfunc_63_4 = 4; localparam th_myfunc_63_5 = 5; localparam th_myfunc_63_6 = 6; localparam th_myfunc_63_7 = 7; localparam th_myfunc_63_8 = 8; localparam th_myfunc_63_9 = 9; localparam th_myfunc_63_10 = 10; localparam th_myfunc_63_11 = 11; localparam th_myfunc_63_12 = 12; localparam th_myfunc_63_13 = 13; localparam th_myfunc_63_14 = 14; localparam th_myfunc_63_15 = 15; localparam th_myfunc_63_16 = 16; always @(posedge CLK) begin if(RST) begin th_myfunc_63 <= th_myfunc_63_init; _th_myfunc_63_called <= 0; _th_myfunc_63_tid_317 <= 0; _th_myfunc_63_tid_318 <= 0; _th_myfunc_63_time_319 <= 0; _th_myfunc_63_i_320 <= 0; _th_myfunc_63___321 <= 0; end else begin case(th_myfunc_63) th_myfunc_63_init: begin if(_th_myfunc_start[63] && (th_blink == 10)) begin _th_myfunc_63_called <= 1; end if(_th_myfunc_start[63] && (th_blink == 10)) begin _th_myfunc_63_tid_317 <= _th_blink_tid_1; end if((th_blink == 10) && _th_myfunc_start[63]) begin th_myfunc_63 <= th_myfunc_63_1; end end th_myfunc_63_1: begin _th_myfunc_63_tid_318 <= _th_myfunc_63_tid_317; th_myfunc_63 <= th_myfunc_63_2; end th_myfunc_63_2: begin if(!_mymutex_lock_reg || (_mymutex_lock_id == 63)) begin th_myfunc_63 <= th_myfunc_63_3; end end th_myfunc_63_3: begin if(!(_mymutex_lock_reg && (_mymutex_lock_id == 63))) begin th_myfunc_63 <= th_myfunc_63_2; end if(_mymutex_lock_reg && (_mymutex_lock_id == 63)) begin th_myfunc_63 <= th_myfunc_63_4; end end th_myfunc_63_4: begin $display("Thread %d Lock", _th_myfunc_63_tid_318); th_myfunc_63 <= th_myfunc_63_5; end th_myfunc_63_5: begin _th_myfunc_63_time_319 <= sw; th_myfunc_63 <= th_myfunc_63_6; end th_myfunc_63_6: begin _th_myfunc_63_i_320 <= 0; th_myfunc_63 <= th_myfunc_63_7; end th_myfunc_63_7: begin if(_th_myfunc_63_i_320 < _th_myfunc_63_time_319) begin th_myfunc_63 <= th_myfunc_63_8; end else begin th_myfunc_63 <= th_myfunc_63_12; end end th_myfunc_63_8: begin _th_myfunc_63___321 <= 0; th_myfunc_63 <= th_myfunc_63_9; end th_myfunc_63_9: begin if(_th_myfunc_63___321 < 1024) begin th_myfunc_63 <= th_myfunc_63_10; end else begin th_myfunc_63 <= th_myfunc_63_11; end end th_myfunc_63_10: begin _th_myfunc_63___321 <= _th_myfunc_63___321 + 1; th_myfunc_63 <= th_myfunc_63_9; end th_myfunc_63_11: begin _th_myfunc_63_i_320 <= _th_myfunc_63_i_320 + 1; th_myfunc_63 <= th_myfunc_63_7; end th_myfunc_63_12: begin th_myfunc_63 <= th_myfunc_63_13; end th_myfunc_63_13: begin $display("Thread %d count = %d", _th_myfunc_63_tid_318, count); th_myfunc_63 <= th_myfunc_63_14; end th_myfunc_63_14: begin th_myfunc_63 <= th_myfunc_63_15; end th_myfunc_63_15: begin $display("Thread %d Unlock", _th_myfunc_63_tid_318); th_myfunc_63 <= th_myfunc_63_16; end th_myfunc_63_16: begin if((th_blink == 19) && (_th_blink_tid_1 == 63)) begin _th_myfunc_63_called <= 0; end if((th_blink == 19) && (_th_blink_tid_1 == 63)) begin th_myfunc_63 <= th_myfunc_63_init; end end endcase end end endmodule """ def test(): veriloggen.reset() test_module = thread_multithread_top.mkTest() code = test_module.to_verilog() from pyverilog.vparser.parser import VerilogParser from pyverilog.ast_code_generator.codegen import ASTCodeGenerator parser = VerilogParser() expected_ast = parser.parse(expected_verilog) codegen = ASTCodeGenerator() expected_code = codegen.visit(expected_ast) assert(expected_code == code)
c0aaef63aeb8626fe7e42cbdf0af5ae2fff40490
f305f84ea6f721c2391300f0a60e21d2ce14f2a5
/9_排序和搜索/经典题/自定义比较函数/1996. 游戏中弱角色的数量.py
6fcc75af1ffbc773cf61c7a018cc69573c39871a
[]
no_license
981377660LMT/algorithm-study
f2ada3e6959338ae1bc21934a84f7314a8ecff82
7e79e26bb8f641868561b186e34c1127ed63c9e0
refs/heads/master
2023-09-01T18:26:16.525579
2023-09-01T12:21:58
2023-09-01T12:21:58
385,861,235
225
24
null
null
null
null
UTF-8
Python
false
false
868
py
1996. 游戏中弱角色的数量.py
from typing import List # 2 <= properties.length <= 105 # 如果存在一个其他角色的攻击和防御等级 都`严格高于` 该角色的攻击和防御等级,则认为该角色为 弱角色 # 一个降序,一个升序排列即可 class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(key=lambda x: (x[0], -x[1])) res = 0 preMax = -int(1e20) # 这里从后往前遍历,因为要获取最大的防御值 for _, cur in reversed(properties): if preMax > cur: res += 1 preMax = max(preMax, cur) return res print(Solution().numberOfWeakCharacters([[1, 5], [10, 4], [4, 3]])) # 输出:1 # 解释:第三个角色是弱角色,因为第二个角色的攻击和防御严格大于该角色。