content stringlengths 0 1.55M |
|---|
"""The ripple component."""<line_sep> |
<import_stmt>os<import_stmt>json<import_stmt>shlex<import_stmt>pprint<import_stmt>asyncio<import_stmt>tempfile<import_stmt>functools<import_stmt>subprocess<import_stmt>synapse.exc<as>s_exc<import_stmt>synapse.common<as>s_common<import_stmt>synapse.lib.cmd<as>s_cmd<import_stmt>synapse.lib.cli<as>s_cli<line_sep>ListHelp='''
Lists all the keys underneath a particular key in the hive.
Syntax:
hive ls|list [path]
Notes:
If path is not specified, the root is listed.
'''<line_sep>GetHelp='''
Display or save to file the contents of a key in the hive.
Syntax:
hive get [--file] [--json] {path}
'''<line_sep>DelHelp='''
Deletes a key in the cell's hive.
Syntax:
hive rm|del {path}
Notes:
Delete will recursively delete all subkeys underneath path if they exist.
'''<line_sep>EditHelp='''
Edits or creates a key in the cell's hive.
Syntax:
hive edit|mod {path} [--string] ({value} | --editor | -f {filename})
Notes:
One may specify the value directly on the command line, from a file, or use an editor. For the --editor option,
the environment variable VISUAL or EDITOR must be set.
'''<class_stmt>HiveCmd(s_cli.Cmd)<block_start>'''
Manipulates values in a cell's Hive.
A Hive is a hierarchy persistent storage mechanism typically used for configuration data.
'''<line_sep>_cmd_name='hive'<line_sep>_cmd_syntax=(('line' {'type':'glob'}) # type: ignore
)<def_stmt>_make_argparser self<block_start>parser=s_cmd.Parser(prog='hive' outp=self description=self.__doc__)<line_sep>subparsers=parser.add_subparsers(title='subcommands' required=<true> dest='cmd' parser_class=functools.partial(s_cmd.Parser outp=self))<line_sep>parser_ls=subparsers.add_parser('list' aliases=['ls'] help="List entries in the hive" usage=ListHelp)<line_sep>parser_ls.add_argument('path' nargs='?' help='Hive path')<line_sep>parser_get=subparsers.add_parser('get' help="Get any entry in the hive" usage=GetHelp)<line_sep>parser_get.add_argument('path' help='Hive path')<line_sep>parser_get.add_argument('-f' '--file' default=<false> action='store' help='Save the data to a file.')<line_sep>parser_get.add_argument('--json' default=<false> action='store_true' help='Emit output as json')<line_sep>parser_rm=subparsers.add_parser('del' aliases=['rm'] help='Delete a key in the hive' usage=DelHelp)<line_sep>parser_rm.add_argument('path' help='Hive path')<line_sep>parser_edit=subparsers.add_parser('edit' aliases=['mod'] help='Sets/creates a key' usage=EditHelp)<line_sep>parser_edit.add_argument('--string' action='store_true' help="Edit value as a single string")<line_sep>parser_edit.add_argument('path' help='Hive path')<line_sep>group=parser_edit.add_mutually_exclusive_group(required=<true>)<line_sep>group.add_argument('value' nargs='?' help='Value to set')<line_sep>group.add_argument('--editor' default=<false> action='store_true' help='Opens an editor to set the value')<line_sep>group.add_argument('--file' '-f' help='Copies the contents of the file to the path')<line_sep><return>parser<block_end><async_keyword><def_stmt>runCmdOpts self opts<block_start>line=opts.get('line')<if_stmt>line<is><none><block_start>self.printf(self.__doc__)<line_sep><return><block_end>core=self.getCmdItem()<try_stmt><block_start>opts=self._make_argparser().parse_args(shlex.split(line))<block_end><except_stmt>s_exc.ParserExit<block_start><return><block_end>handlers={'list':self._handle_ls 'ls':self._handle_ls 'del':self._handle_rm 'rm':self._handle_rm 'get':self._handle_get 'edit':self._handle_edit 'mod':self._handle_edit }<line_sep><await>handlers[opts.cmd](core opts)<block_end>@staticmethod<def_stmt>parsepath path<block_start>''' Turn a slash-delimited path into a list that hive takes '''<line_sep><return>path.split('/')<block_end><async_keyword><def_stmt>_handle_ls self core opts<block_start>path=self.parsepath(opts.path)<if>opts.path<is><not><none><else><none><line_sep>keys=<await>core.listHiveKey(path=path)<if_stmt>keys<is><none><block_start>self.printf('Path not found')<line_sep><return><block_end><for_stmt>key keys<block_start>self.printf(key)<block_end><block_end><async_keyword><def_stmt>_handle_get self core opts<block_start>path=self.parsepath(opts.path)<line_sep>valu=<await>core.getHiveKey(path)<if_stmt>valu<is><none><block_start>self.printf(f'{opts.path} not present')<line_sep><return><block_end><if_stmt>opts.json<block_start>prend=json.dumps(valu indent=4 sort_keys=<true>)<line_sep>rend=prend.encode()<block_end><elif_stmt>isinstance(valu str)<block_start>rend=valu.encode()<line_sep>prend=valu<block_end><elif_stmt>isinstance(valu bytes)<block_start>rend=valu<line_sep>prend=pprint.pformat(valu)<block_end><else_stmt><block_start>rend=json.dumps(valu indent=4 sort_keys=<true>).encode()<line_sep>prend=pprint.pformat(valu)<block_end><if_stmt>opts.file<block_start><with_stmt>s_common.genfile(opts.file)<as>fd<block_start>fd.truncate(0)<line_sep>fd.write(rend)<block_end>self.printf(f'Saved the hive entry [{opts.path}] to {opts.file}')<line_sep><return><block_end>self.printf(f'{opts.path}:\n{prend}')<block_end><async_keyword><def_stmt>_handle_rm self core opts<block_start>path=self.parsepath(opts.path)<line_sep><await>core.popHiveKey(path)<block_end><async_keyword><def_stmt>_handle_edit self core opts<block_start>path=self.parsepath(opts.path)<if_stmt>opts.value<is><not><none><block_start><if_stmt>opts.value[0]<not><in>'([{"'<block_start>data=opts.value<block_end><else_stmt><block_start>data=json.loads(opts.value)<block_end><await>core.setHiveKey(path data)<line_sep><return><block_end><elif_stmt>opts.file<is><not><none><block_start><with_stmt>open(opts.file)<as>fh<block_start>s=fh.read()<if_stmt>len(s)<eq>0<block_start>self.printf('Empty file. Not writing key.')<line_sep><return><block_end>data=s<if>opts.string<else>json.loads(s)<line_sep><await>core.setHiveKey(path data)<line_sep><return><block_end><block_end>editor=os.getenv('VISUAL' (os.getenv('EDITOR' <none>)))<if_stmt>editor<is><none><or>editor<eq>''<block_start>self.printf('Environment variable VISUAL or EDITOR must be set for --editor')<line_sep><return><block_end>tnam=<none><try_stmt><block_start><with_stmt>tempfile.NamedTemporaryFile(mode='w' delete=<false>)<as>fh<block_start>old_valu=<await>core.getHiveKey(path)<if_stmt>old_valu<is><not><none><block_start><if_stmt>opts.string<block_start><if_stmt><not>isinstance(old_valu str)<block_start>self.printf('Existing value is not a string, therefore not editable as a string')<line_sep><return><block_end>data=old_valu<block_end><else_stmt><block_start><try_stmt><block_start>data=json.dumps(old_valu indent=4 sort_keys=<true>)<block_end><except_stmt>(ValueError TypeError)<block_start>self.printf('Value is not JSON-encodable, therefore not editable.')<line_sep><return><block_end><block_end>fh.write(data)<block_end>tnam=fh.name<block_end><while_stmt><true><block_start>retn=subprocess.call(f'{editor} {tnam}' shell=<true>)<if_stmt>retn<ne>0# pragma: no cover
<block_start>self.printf('Editor failed with non-zero code. Aborting.')<line_sep><return><block_end><with_stmt>open(tnam)<as>fh<block_start>rawval=fh.read()<if_stmt>len(rawval)<eq>0# pragma: no cover
<block_start>self.printf('Empty file. Not writing key.')<line_sep><return><block_end><try_stmt><block_start>valu=rawval<if>opts.string<else>json.loads(rawval)<block_end><except_stmt>json.JSONDecodeError<as>e# pragma: no cover
<block_start>self.printf(f'JSON decode failure: [{e}]. Reopening.')<line_sep><await>asyncio.sleep(1)<line_sep><continue><block_end># We lose the tuple/list distinction in the telepath round trip, so tuplify everything to compare
<if_stmt>(opts.string<and>valu<eq>old_valu)<or>(<not>opts.string<and>s_common.tuplify(valu)<eq>old_valu)<block_start>self.printf('Valu not changed. Not writing key.')<line_sep><return><block_end><await>core.setHiveKey(path valu)<line_sep><break><block_end><block_end><block_end><finally_stmt><block_start><if_stmt>tnam<is><not><none><block_start>os.unlink(tnam)<block_end><block_end><block_end><block_end> |
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-USB-USBHUB
GUID : 7426a56b-e2d5-4b30-bdef-b31815c1a74a
"""<import_from_stmt>construct Int8sl Int8ul Int16ul Int16sl Int32sl Int32ul Int64sl Int64ul Bytes Double Float32l Struct<import_from_stmt>etl.utils WString CString SystemTime Guid<import_from_stmt>etl.dtyp Sid<import_from_stmt>etl.parsers.etw.core Etw declare guid<line_sep>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=1 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_1_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_USB_HubDescriptor"/Int64ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=2 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_2_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/CString "fid_USBHUB_Hub"/Int32sl)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=3 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_3_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_USB_HubDescriptor"/Int64ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=10 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_10_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=11 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_11_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=12 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_12_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=13 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_13_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=14 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_14_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=15 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_15_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=16 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_16_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=17 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_17_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=18 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_18_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=19 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_19_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=20 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_20_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=21 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_21_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=22 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_22_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=23 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_23_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=24 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_24_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=25 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_25_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=26 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_26_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=27 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_27_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=28 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_28_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=29 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_29_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=30 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_30_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=31 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_31_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=32 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_32_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=33 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_33_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=34 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_34_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=35 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_35_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=36 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_36_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=37 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_37_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=39 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_39_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=40 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_40_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=41 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_41_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=49 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_49_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=50 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_50_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=51 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_51_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=59 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_59_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=60 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_60_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=61 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_61_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=62 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_62_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=63 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_63_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=64 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_64_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=70 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_70_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=71 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_71_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=80 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_80_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_PortAttributes"/Int16ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=81 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_81_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=82 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_82_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=83 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_83_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=84 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_84_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=100 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_100_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Device"/Int64sl "fid_USBHUB_Device_State"/Guid "fid_DeviceDescriptor"/Int64ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=101 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_101_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/CString "fid_USBHUB_Device"/Int32sl)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=102 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_102_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Device"/Int64sl "fid_USBHUB_Device_State"/Guid "fid_DeviceDescriptor"/Int64ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=103 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_103_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_DeviceDescription"/WString)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=110 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_110_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=111 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_111_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=112 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_112_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=113 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_113_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=114 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_114_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_DeviceDescription"/WString)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=119 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_119_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=120 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_120_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Device"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=121 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_121_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Device"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=122 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_122_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Device"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=123 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_123_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Device"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=130 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_130_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=139 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_139_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=140 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_140_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=149 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_149_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=150 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_150_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=151 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_151_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=159 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_159_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=160 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_160_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=161 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_161_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=169 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_169_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=170 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_170_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=171 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_171_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=172 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_172_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=173 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_173_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=174 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_174_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=175 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_175_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=176 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_176_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=177 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_177_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=178 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_178_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=179 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_179_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=180 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_180_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=181 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_181_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=183 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_183_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=184 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_184_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=185 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_185_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=189 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_189_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=190 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_190_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=199 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_199_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=200 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_200_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=209 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_209_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PowerState"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=210 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_210_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int32sl "fid_USBHUB_Hub"/Double "fid_PortNumber"/Int32ul "fid_Class"/Int32ul "fid_NtStatus"/Int32ul "fid_UsbdStatus"/Int32ul "fid_DebugText"/CString)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=211 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_211_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_PortStatusChange"/Int16ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=212 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_212_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_TimerTag"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=213 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_213_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_TimerTag"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=214 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_214_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_TimerTag"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=220 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_220_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=229 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_229_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=230 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_230_0(Etw)<block_start>pattern=Struct("fid_TimeElapsedBeforeLogStart"/Int64ul "fid_USBHUB_HC"/Int32ul "fid_USBHUB_Hub"/Int8ul "fid_PortNumber"/Int32ul "fid_Class"/Int32ul "fid_NtStatus"/Int32ul "fid_UsbdStatus"/Int32ul "fid_DebugText"/CString)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=231 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_231_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=232 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_232_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8sl "fid_USBHUB_Device"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=233 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_233_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end>@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a") event_id=234 version=0)<class_stmt>Microsoft_Windows_USB_USBHUB_234_0(Etw)<block_start>pattern=Struct("fid_USBHUB_HC"/Int8ul "fid_USBHUB_Hub"/Int64sl "fid_PortNumber"/Int32ul "fid_Status"/Int32ul)<block_end> |
<import_stmt>enum<import_from_stmt>django.db models<import_from_stmt>care.facility.models FacilityBaseModel<import_from_stmt>care.users.models User<import_from_stmt>django.contrib.postgres.fields JSONField<class_stmt>Notification(FacilityBaseModel)<block_start><class_stmt>EventType(enum.Enum)<block_start>SYSTEM_GENERATED=50<line_sep>CUSTOM_MESSAGE=100<block_end>EventTypeChoices=[(e.value e.name)<for>e EventType]<class_stmt>Medium(enum.Enum)<block_start>SYSTEM=0<line_sep>SMS=100<line_sep>WHATSAPP=200<block_end>MediumChoices=[(e.value e.name)<for>e Medium]<class_stmt>Event(enum.Enum)<block_start>MESSAGE=0<line_sep>PATIENT_CREATED=20<line_sep>PATIENT_UPDATED=30<line_sep>PATIENT_DELETED=40<line_sep>PATIENT_CONSULTATION_CREATED=50<line_sep>PATIENT_CONSULTATION_UPDATED=60<line_sep>PATIENT_CONSULTATION_DELETED=70<line_sep>INVESTIGATION_SESSION_CREATED=80<line_sep>INVESTIGATION_UPDATED=90<line_sep>PATIENT_FILE_UPLOAD_CREATED=100<line_sep>CONSULTATION_FILE_UPLOAD_CREATED=110<line_sep>PATIENT_CONSULTATION_UPDATE_CREATED=120<line_sep>PATIENT_CONSULTATION_UPDATE_UPDATED=130<line_sep>PATIENT_CONSULTATION_ASSIGNMENT=140<line_sep>SHIFTING_UPDATED=200<block_end>EventChoices=[(e.value e.name)<for>e Event]<line_sep>intended_for=models.ForeignKey(User on_delete=models.SET_NULL null=<true> related_name="notification_intended_for" )<line_sep>medium_sent=models.IntegerField(choices=MediumChoices default=Medium.SYSTEM.value)<line_sep>caused_by=models.ForeignKey(User on_delete=models.SET_NULL null=<true> related_name="notification_caused_by" )<line_sep>read_at=models.DateTimeField(null=<true> blank=<true>)<line_sep>event_type=models.IntegerField(choices=EventTypeChoices default=EventType.SYSTEM_GENERATED.value)<line_sep>event=models.IntegerField(choices=EventChoices default=Event.MESSAGE.value)<line_sep>message=models.TextField(max_length=2000 null=<true> default=<none>)<line_sep>caused_objects=JSONField(null=<true> blank=<true> default=dict)<block_end> |
<import_stmt>pytest<import_from_stmt>django.urls reverse<class_stmt>TestHealthCheck<block_start><def_stmt>test_return_success_when_accessing_health_check self api_client url<block_start>response=api_client.get(url format="json")<assert_stmt>response.status_code<eq>200<assert_stmt>list(response.json().keys())<eq>["status" "time"]<assert_stmt>response.json().get("status")<eq>"available"<block_end><def_stmt>test_return_forbidden_when_trying_to_anonymously_access_a_restricted_route self api_client<block_start>url=reverse("gazettes-list")<line_sep>response=api_client.get(url)<assert_stmt>response.status_code<eq>403<block_end>@pytest.mark.django_db<def_stmt>test_return_success_when_accessing_a_restricted_route_with_credentials self api_client_authenticated<block_start>url=reverse("gazettes-list")<line_sep>response=api_client_authenticated.get(url)<assert_stmt>response.status_code<eq>200<block_end><block_end> |
<import_stmt>os<import_from_stmt>kids.cache cache<import_from_stmt>datetime datetime<import_from_stmt>datmo.core.util.i18n get<as>__<import_from_stmt>datmo.core.entity.model Model<import_from_stmt>datmo.core.entity.code Code<import_from_stmt>datmo.core.entity.environment Environment<import_from_stmt>datmo.core.entity.file_collection FileCollection<import_from_stmt>datmo.core.entity.task Task<import_from_stmt>datmo.core.entity.snapshot Snapshot<import_from_stmt>datmo.core.entity.user User<import_from_stmt>datmo.core.util.exceptions InputError EntityNotFound MoreThanOneEntityFound DALNotInitialized<import_from_stmt>datmo.core.util.misc_functions create_unique_hash<import_from_stmt>datmo.core.storage.driver.blitzdb_dal_driver BlitzDBDALDriver<class_stmt>LocalDAL()<block_start>"""
LocalDAL is a local DAL object that stores info locally. DAL stands for 'data access layer' and serves as a storage for
all entities.
Parameters
----------
driver_type : str
type of driver to pull from
driver_options : dict
options for the DALdriver class
driver : datmo.core.storage.driver.DALDriver, optional
Instantiated DAL driver used for backend storage for entities
Attributes
----------
driver_type : str
driver_options : dict
driver : datmo.core.storage.driver.DALDriver
Instantiated DAL driver used for backend storage for entities
is_initialized : bool
model : ModelMethods
code : CodeMethods
environment : EnvironmentMethods
file_collection : FileCollectionMethods
task : TaskMethods
snapshot : SnapshotMethods
user : UserMethods
Methods
-------
init()
initialize the dal
"""<def_stmt>__init__ self driver_type driver_options driver=<none><block_start>self.driver_type=driver_type<line_sep>self.driver_options=driver_options<line_sep>self.driver=driver<line_sep>self._is_initialized=self.is_initialized<block_end>@property<def_stmt>is_initialized self<block_start><if_stmt>os.path.isdir(self.driver_options['connection_string'])<block_start>self._is_initialized=<true><line_sep># set the driver so it is available
<if_stmt><not>self.driver<block_start><if_stmt>self.driver_type<eq>"blitzdb"<block_start>self.driver=BlitzDBDALDriver(**self.driver_options)<block_end><block_end><return>self._is_initialized<block_end>self._is_initialized=<false><line_sep><return>self._is_initialized<block_end>@property<def_stmt>model self<block_start>"""Model CRUD methods
Returns
-------
ModelMethods
Specific set of CRUD functions for model
Raises
------
DALNotInitialized
"""<if_stmt><not>self.is_initialized<block_start><raise>DALNotInitialized()<block_end><return>ModelMethods(self.driver)<block_end>@property<def_stmt>code self<block_start>"""Code CRUD methods
Returns
-------
CodeMethods
Specific set of CRUD functions for code
Raises
------
DALNotInitialized
"""<if_stmt><not>self.is_initialized<block_start><raise>DALNotInitialized()<block_end><return>CodeMethods(self.driver)<block_end>@property<def_stmt>environment self<block_start>"""Environment CRUD methods
Returns
-------
EnvironmentMethods
Specific set of CRUD functions for environment
Raises
------
DALNotInitialized
"""<if_stmt><not>self.is_initialized<block_start><raise>DALNotInitialized()<block_end><return>EnvironmentMethods(self.driver)<block_end>@property<def_stmt>file_collection self<block_start>"""FileCollection CRUD methods
Returns
-------
FileCollectionMethods
Specific set of CRUD functions for file collection
Raises
------
DALNotInitialized
"""<if_stmt><not>self.is_initialized<block_start><raise>DALNotInitialized()<block_end><return>FileCollectionMethods(self.driver)<block_end>@cache@property<def_stmt>task self<block_start>"""Task CRUD methods
Returns
-------
TaskMethods
Specific set of CRUD functions for task
Raises
------
DALNotInitialized
"""<if_stmt><not>self.is_initialized<block_start><raise>DALNotInitialized()<block_end><return>TaskMethods(self.driver)<block_end>@cache@property<def_stmt>snapshot self<block_start>"""Snapshot CRUD methods
Returns
-------
SnapshotMethods
Specific set of CRUD functions for snapshot
Raises
------
DALNotInitialized
"""<if_stmt><not>self.is_initialized<block_start><raise>DALNotInitialized()<block_end><return>SnapshotMethods(self.driver)<block_end>@cache@property<def_stmt>user self<block_start>"""User CRUD methods
Returns
-------
UserMethods
Specific set of CRUD functions for user
Raises
------
DALNotInitialized
"""<if_stmt><not>self.is_initialized<block_start><raise>DALNotInitialized()<block_end><return>UserMethods(self.driver)<block_end><def_stmt>init self<block_start><if_stmt><not>self.driver<block_start><if_stmt>self.driver_type<eq>"blitzdb"<block_start>self.driver=BlitzDBDALDriver(**self.driver_options)<block_end><block_end><block_end><block_end><class_stmt>EntityMethodsCRUD(object)<block_start><def_stmt>__init__ self collection entity_class driver<block_start>self.collection=collection<line_sep>self.entity_class=entity_class<line_sep>self.driver=driver<block_end><def_stmt>get_by_id self entity_id<block_start>obj=self.driver.get(self.collection entity_id)<line_sep><return>self.entity_class(obj)<block_end><def_stmt>get_by_shortened_id self shortened_entity_id<block_start>obj=self.driver.get_by_shortened_id(self.collection shortened_entity_id)<line_sep><return>self.entity_class(obj)<block_end><def_stmt>create self datmo_entity# translate datmo_entity to a standard dictionary (document) to be stored
<block_start><if_stmt>hasattr(datmo_entity 'to_dictionary')<block_start>dict_obj=datmo_entity.to_dictionary()<block_end><else_stmt><block_start>dict_obj=self.entity_class(datmo_entity).to_dictionary()<block_end># create a unique hash from misc_functions.py
# TODO: find efficient way to get previous hash for entity
# latest_entity = self.query({"id": latest})
# dict_obj['id'] = create_unique_hash(base_hash=latest_entity['id'])
dict_obj['id']=dict_obj['id']<if>'id'<in>dict_obj.keys()<and>dict_obj['id']<else>create_unique_hash()<line_sep>response=self.driver.set(self.collection dict_obj)<line_sep>entity_instance=self.entity_class(response)<line_sep><return>entity_instance<block_end><def_stmt>update self datmo_entity# translate datmo_entity to a standard dictionary (document) to be stored
<block_start><if_stmt>hasattr(datmo_entity 'to_dictionary')<block_start>dict_obj=datmo_entity.to_dictionary()<block_end><else_stmt><block_start><if_stmt>'id'<not><in>list(datmo_entity)<or><not>datmo_entity['id']<block_start><raise>InputError(__("error" "storage.local.dal.update"))<block_end># Aggregate original object and new object into dict_obj var
new_dict_obj=datmo_entity<line_sep>original_datmo_entity=self.get_by_id(datmo_entity['id'])<line_sep>dict_obj={}<for_stmt>key,value original_datmo_entity.to_dictionary().items()<block_start><if_stmt>key<in>list(new_dict_obj)<block_start>dict_obj[key]=new_dict_obj[key]<block_end><else_stmt><block_start>dict_obj[key]=getattr(original_datmo_entity key)<block_end><block_end><block_end># set updated_at always
dict_obj['updated_at']=datetime.utcnow()<line_sep>response=self.driver.set(self.collection dict_obj)<line_sep>entity_instance=self.entity_class(response)<line_sep><return>entity_instance<block_end><def_stmt>delete self entity_id<block_start><return>self.driver.delete(self.collection entity_id)<block_end><def_stmt>query self query_params sort_key=<none> sort_order=<none><block_start><return>[self.entity_class(item)<for>item self.driver.query(self.collection query_params sort_key sort_order)]<block_end><def_stmt>findOne self query_params<block_start>results=self.query(query_params)<if_stmt>len(results)<eq>0<block_start><raise>EntityNotFound()<block_end><if_stmt>len(results)<g>1<block_start><raise>MoreThanOneEntityFound()<block_end><return>results[0]<block_end><block_end>#
# https://stackoverflow.com/questions/1713038/super-fails-with-error-typeerror-argument-1-must-be-type-not-classobj
#
#
# Datmo Entity methods
#
<class_stmt>ModelMethods(EntityMethodsCRUD)<block_start><def_stmt>__init__ self driver<block_start>super(ModelMethods self).__init__('model' Model driver)<block_end><block_end><class_stmt>CodeMethods(EntityMethodsCRUD)<block_start><def_stmt>__init__ self driver<block_start>super(CodeMethods self).__init__('code' Code driver)<block_end><block_end><class_stmt>EnvironmentMethods(EntityMethodsCRUD)<block_start><def_stmt>__init__ self driver<block_start>super(EnvironmentMethods self).__init__('environment' Environment driver)<block_end><block_end><class_stmt>FileCollectionMethods(EntityMethodsCRUD)<block_start><def_stmt>__init__ self driver<block_start>super(FileCollectionMethods self).__init__('file_collection' FileCollection driver)<block_end><block_end><class_stmt>TaskMethods(EntityMethodsCRUD)<block_start><def_stmt>__init__ self driver<block_start>super(TaskMethods self).__init__('task' Task driver)<block_end><block_end><class_stmt>SnapshotMethods(EntityMethodsCRUD)<block_start><def_stmt>__init__ self driver<block_start>super(SnapshotMethods self).__init__('snapshot' Snapshot driver)<block_end><block_end><class_stmt>UserMethods(EntityMethodsCRUD)<block_start><def_stmt>__init__ self driver<block_start>super(UserMethods self).__init__('user' User driver)<block_end><block_end> |
<import_stmt>collections.abc<as>collections_abc<import_stmt>os.path<as>osp<import_from_stmt>addict Dict<import_stmt>yaml<class_stmt>ConfigDict(Dict)<block_start><def_stmt>__missing__ self name<block_start><raise>KeyError(name)<block_end><def_stmt>__getattr__ self name<block_start><try_stmt><block_start>value=super(ConfigDict self).__getattr__(name)<block_end><except_stmt>KeyError<block_start>ex=AttributeError("'{}' object has no attribute '{}'".format(self.__class__.__name__ name))<block_end><except_stmt>Exception<as>e<block_start>ex=e<block_end><else_stmt><block_start><return>value<block_end><raise>ex<block_end><def_stmt>__setitem__ self name value<block_start><if_stmt>isinstance(value dict)<block_start>value=ConfigDict(value)<block_end>super(ConfigDict self).__setitem__(name value)<block_end><block_end><def_stmt>add_args parser cfg prefix=""<block_start><for_stmt>k,v cfg.items()<block_start><if_stmt>isinstance(v str)<block_start>parser.add_argument("--"+prefix+k)<block_end><elif_stmt>isinstance(v int)<block_start>parser.add_argument("--"+prefix+k type=int)<block_end><elif_stmt>isinstance(v float)<block_start>parser.add_argument("--"+prefix+k type=float)<block_end><elif_stmt>isinstance(v bool)<block_start>parser.add_argument("--"+prefix+k action="store_true")<block_end><elif_stmt>isinstance(v dict)<block_start>add_args(parser v k+".")<block_end><elif_stmt>isinstance(v collections_abc.Iterable)<block_start>parser.add_argument("--"+prefix+k type=type(v[0]) nargs="+")<block_end><else_stmt><block_start>print("connot parse key {} of type {}".format(prefix+k type(v)))<block_end><block_end><return>parser<block_end><class_stmt>YamlConfig<block_start>"""Manager of ConfigDict from yaml."""<def_stmt>__init__ self config_paths:dict<block_start>"""Make ConfigDict from yaml path."""<line_sep>self.cfg=ConfigDict()<for_stmt>key,path config_paths.items()<block_start>self.cfg[key]=self._yaml_to_config_dict(path)<block_end><block_end>@staticmethod<def_stmt>_yaml_to_config_dict path:str<arrow>ConfigDict<block_start>"""Return ConfigDict from yaml."""<try_stmt><block_start><with_stmt>open(path)<as>f<block_start>data=yaml.load(f Loader=yaml.FullLoader)<block_end><block_end><except_stmt>FileNotFoundError<block_start><with_stmt>open(osp.expanduser(path))<as>f<block_start>data=yaml.load(f Loader=yaml.FullLoader)<block_end><block_end><return>ConfigDict(data)<block_end><def_stmt>get_config_dict self<block_start><return>self.cfg<block_end><block_end> |
<import_stmt>pickle<import_stmt>numpy<as>np<import_from_stmt>numpy.testing assert_array_almost_equal assert_array_equal<import_stmt>pytest<import_from_stmt>oddt.scoring.models classifiers regressors<line_sep>@pytest.mark.filterwarnings('ignore:Stochastic Optimizer')@pytest.mark.parametrize('cls' [classifiers.svm(probability=<true>) classifiers.neuralnetwork(random_state=42)])<def_stmt>test_classifiers cls# toy data
<block_start>X=np.concatenate((np.zeros((5 2)) np.ones((5 2))))<line_sep>Y=np.concatenate((np.ones(5) np.zeros(5)))<line_sep>np.random.seed(42)<line_sep>cls.fit(X Y)<line_sep>assert_array_equal(cls.predict(X) Y)<assert_stmt>cls.score(X Y)<eq>1.0<line_sep>prob=cls.predict_proba(X)<line_sep>assert_array_almost_equal(prob [[0 1]]<times>5+[[1 0]]<times>5 decimal=1)<line_sep>log_prob=cls.predict_log_proba(X)<line_sep>assert_array_almost_equal(np.log(prob) log_prob)<line_sep>pickled=pickle.dumps(cls)<line_sep>reloaded=pickle.loads(pickled)<line_sep>prob_reloaded=reloaded.predict_proba(X)<line_sep>assert_array_almost_equal(prob prob_reloaded)<block_end>@pytest.mark.parametrize('reg' [regressors.svm(C=10) regressors.randomforest(random_state=42) regressors.neuralnetwork(solver='lbfgs' random_state=42 hidden_layer_sizes=(20 20)) regressors.mlr()])<def_stmt>test_regressors reg<block_start>X=np.vstack((np.arange(30 10 -2 dtype='float64') np.arange(100 90 -1 dtype='float64'))).T<line_sep>Y=np.arange(10 dtype='float64')<line_sep>np.random.seed(42)<line_sep>reg.fit(X Y)<line_sep>pred=reg.predict(X)<assert_stmt>(np.abs(pred.flatten()-Y)<l>1).all()<assert_stmt>reg.score(X Y)<g>0.9<line_sep>pickled=pickle.dumps(reg)<line_sep>reloaded=pickle.loads(pickled)<line_sep>pred_reloaded=reloaded.predict(X)<line_sep>assert_array_almost_equal(pred pred_reloaded)<block_end> |
<import_stmt>logging<def_stmt>create_app config=<none> testing=<false><block_start><import_from_stmt>airflow.www_rbac app<as>airflow_app<line_sep>app,appbuilder=airflow_app.create_app(config=config testing=testing)<line_sep># only now we can load view..
# this import might causes circular dependency if placed above
<import_from_stmt>dbnd_airflow.airflow_override.dbnd_aiflow_webserver use_databand_airflow_dagbag <line_sep>use_databand_airflow_dagbag()<line_sep>logging.info("Airflow applications has been created")<line_sep><return>app appbuilder<block_end><def_stmt>cached_appbuilder config=<none> testing=<false><block_start>_,appbuilder=create_app(config testing)<line_sep><return>appbuilder<block_end> |
"""Generate a random string."""<line_sep># pyright: reportIncompatibleMethodOverride=none
<import_from_future_stmt> annotations<import_stmt>logging<import_stmt>secrets<import_stmt>string<import_from_stmt>typing TYPE_CHECKING Any Callable List Sequence Union<import_from_stmt>typing_extensions Final Literal<import_from_stmt>...utils BaseModel<import_from_stmt>.base LookupHandler<if_stmt>TYPE_CHECKING<block_start><import_from_stmt>...context CfnginContext RunwayContext<block_end>LOGGER=logging.getLogger(__name__)<class_stmt>ArgsDataModel(BaseModel)<block_start>"""Arguments data model."""<line_sep>digits:bool=<true><line_sep>lowercase:bool=<true><line_sep>punctuation:bool=<false><line_sep>uppercase:bool=<true><block_end><class_stmt>RandomStringLookup(LookupHandler)<block_start>"""Random string lookup."""<line_sep>TYPE_NAME:Final[Literal["random.string"]]="random.string"<line_sep>"""Name that the Lookup is registered as."""<line_sep>@staticmethod<def_stmt>calculate_char_set args:ArgsDataModel<arrow>str<block_start>"""Calculate character set from the provided arguments."""<line_sep>char_set=""<if_stmt>args.digits<block_start>char_set<augadd>string.digits<block_end><if_stmt>args.lowercase<block_start>char_set<augadd>string.ascii_lowercase<block_end><if_stmt>args.punctuation<block_start>char_set<augadd>string.punctuation<block_end><if_stmt>args.uppercase<block_start>char_set<augadd>string.ascii_uppercase<block_end>LOGGER.debug("character set: %s" char_set)<line_sep><return>char_set<block_end>@staticmethod<def_stmt>generate_random_string char_set:Sequence[str] length:int<arrow>str<block_start>"""Generate a random string of a set length from a set of characters."""<line_sep><return>"".join(secrets.choice(char_set)<for>_ range(length))<block_end>@staticmethod<def_stmt>has_digit value:str<arrow>bool<block_start>"""Check if value contains a digit."""<line_sep><return>any(v.isdigit()<for>v value)<block_end>@staticmethod<def_stmt>has_lowercase value:str<arrow>bool<block_start>"""Check if value contains lowercase."""<line_sep><return>any(v.islower()<for>v value)<block_end>@staticmethod<def_stmt>has_punctuation value:str<arrow>bool<block_start>"""Check if value contains uppercase."""<line_sep><return>any(v<in>string.punctuation<for>v value)<block_end>@staticmethod<def_stmt>has_uppercase value:str<arrow>bool<block_start>"""Check if value contains uppercase."""<line_sep><return>any(v.isupper()<for>v value)<block_end>@classmethod<def_stmt>ensure_has_one_of cls args:ArgsDataModel value:str<arrow>bool<block_start>"""Ensure value has at least one of each required character.
Args:
args: Hook args.
value: Value to check.
"""<line_sep>checks:List[Callable[[str] bool]]=[]<if_stmt>args.digits<block_start>checks.append(cls.has_digit)<block_end><if_stmt>args.lowercase<block_start>checks.append(cls.has_lowercase)<block_end><if_stmt>args.punctuation<block_start>checks.append(cls.has_punctuation)<block_end><if_stmt>args.uppercase<block_start>checks.append(cls.has_uppercase)<block_end><return>sum(c(value)<for>c checks)<eq>len(checks)<block_end>@classmethod<def_stmt>handle # pylint: disable=arguments-differ
cls value:str context:Union[CfnginContext RunwayContext] *__args:Any **__kwargs:Any <arrow>Any<block_start>"""Generate a random string.
Args:
value: The value passed to the Lookup.
context: The current context object.
Raises:
ValueError: Unable to find a value for the provided query and
a default value was not provided.
"""<line_sep>raw_length,raw_args=cls.parse(value)<line_sep>length=int(raw_length)<line_sep>args=ArgsDataModel.parse_obj(raw_args)<line_sep>char_set=cls.calculate_char_set(args)<while_stmt><true><block_start>result=cls.generate_random_string(char_set length)<if_stmt>cls.ensure_has_one_of(args result)<block_start><break><block_end><block_end><return>cls.format_results(result **raw_args)<block_end><block_end> |
<import_stmt>pywintypes<import_stmt>struct<import_stmt>win32event win32api<import_stmt>os<import_stmt>win32com.directsound.directsound<as>ds<def_stmt>wav_header_pack wfx datasize<block_start><return>struct.pack("<4sl4s4slhhllhh4sl" "RIFF" 36+datasize "WAVE" "fmt " 16 wfx.wFormatTag wfx.nChannels wfx.nSamplesPerSec wfx.nAvgBytesPerSec wfx.nBlockAlign wfx.wBitsPerSample "data" datasize )<block_end>d=ds.DirectSoundCaptureCreate(<none> <none>)<line_sep>sdesc=ds.DSCBUFFERDESC()<line_sep>sdesc.dwBufferBytes=352800# 2 seconds
sdesc.lpwfxFormat=pywintypes.WAVEFORMATEX()<line_sep>sdesc.lpwfxFormat.wFormatTag=pywintypes.WAVE_FORMAT_PCM<line_sep>sdesc.lpwfxFormat.nChannels=2<line_sep>sdesc.lpwfxFormat.nSamplesPerSec=44100<line_sep>sdesc.lpwfxFormat.nAvgBytesPerSec=176400<line_sep>sdesc.lpwfxFormat.nBlockAlign=4<line_sep>sdesc.lpwfxFormat.wBitsPerSample=16<line_sep>print(sdesc)<line_sep>print(d)<line_sep>buffer=d.CreateCaptureBuffer(sdesc)<line_sep>event=win32event.CreateEvent(<none> 0 0 <none>)<line_sep>notify=buffer.QueryInterface(ds.IID_IDirectSoundNotify)<line_sep>notify.SetNotificationPositions((ds.DSBPN_OFFSETSTOP event))<line_sep>buffer.Start(0)<line_sep>win32event.WaitForSingleObject(event -1)<line_sep>data=buffer.Update(0 352800)<line_sep>fname=os.path.join(win32api.GetTempPath() "test_directsound_record.wav")<line_sep>f=open(fname "wb")<line_sep>f.write(wav_header_pack(sdesc.lpwfxFormat 352800))<line_sep>f.write(data)<line_sep>f.close()<line_sep> |
<import_stmt>json<import_stmt>pytest<import_from_stmt>indy_common.constants JSON_LD_CONTEXT RS_CONTEXT_TYPE_VALUE RS_ID GET_RICH_SCHEMA_OBJECT_BY_ID GET_RICH_SCHEMA_OBJECT_BY_METADATA RS_NAME RS_VERSION RS_TYPE<import_from_stmt>indy_node.test.api.helper sdk_build_rich_schema_request sdk_write_rich_schema_object_and_check<import_from_stmt>indy_node.test.helper rich_schemas_enabled_scope<import_from_stmt>indy_node.test.rich_schema.templates W3C_BASE_CONTEXT<import_from_stmt>indy_node.test.rich_schema.test_send_get_rich_schema_obj PARAMS<import_from_stmt>indy_node.test.state_proof.helper sdk_submit_operation_and_get_result<import_from_stmt>plenum.common.constants TXN_TYPE<import_from_stmt>plenum.common.exceptions RequestNackedException<import_from_stmt>plenum.common.util randomString<import_from_stmt>plenum.test.helper sdk_sign_and_submit_req sdk_get_and_check_replies<line_sep>@pytest.fixture(scope='module')<def_stmt>write_rich_schema looper sdk_pool_handle sdk_wallet_endorser tconf<block_start><with_stmt>rich_schemas_enabled_scope(tconf)<block_start><for_stmt>txn_type,rs_type,content,rs_id,rs_name,rs_version PARAMS<block_start>sdk_write_rich_schema_object_and_check(looper sdk_wallet_endorser sdk_pool_handle txn_type=txn_type rs_id=rs_id rs_name=rs_name rs_version=rs_version rs_type=rs_type rs_content=content)<block_end><block_end><block_end>@pytest.mark.parametrize('txn_type, rs_type, content, rs_id' [(JSON_LD_CONTEXT RS_CONTEXT_TYPE_VALUE W3C_BASE_CONTEXT randomString())])<def_stmt>test_send_rich_schema_obj_disabled_by_default looper sdk_pool_handle sdk_wallet_endorser txn_type rs_type content rs_id<block_start>request=sdk_build_rich_schema_request(looper sdk_wallet_endorser txn_type rs_id=rs_id rs_name=randomString() rs_version='1.0' rs_type=rs_type rs_content=json.dumps(content))<line_sep>req=sdk_sign_and_submit_req(sdk_pool_handle sdk_wallet_endorser request)<with_stmt>pytest.raises(RequestNackedException match='RichSchema transactions are disabled')<block_start>sdk_get_and_check_replies(looper [req])<block_end><block_end>@pytest.mark.parametrize('txn_type, rs_type, content, rs_id, rs_name, rs_version' PARAMS)<def_stmt>test_send_get_rich_schema_obj_by_id_disabled_by_default looper sdk_pool_handle sdk_wallet_endorser txn_type rs_type content rs_id rs_name rs_version write_rich_schema<block_start>get_rich_schema_by_id_operation={TXN_TYPE:GET_RICH_SCHEMA_OBJECT_BY_ID RS_ID:rs_id }<with_stmt>pytest.raises(RequestNackedException match='RichSchema queries are disabled')<block_start>sdk_submit_operation_and_get_result(looper sdk_pool_handle sdk_wallet_endorser get_rich_schema_by_id_operation)<block_end><block_end>@pytest.mark.parametrize('txn_type, rs_type, content, rs_id, rs_name, rs_version' PARAMS)<def_stmt>test_send_get_rich_schema_obj_by_metadata_disabled_by_default looper sdk_pool_handle sdk_wallet_endorser txn_type rs_type content rs_id rs_name rs_version write_rich_schema<block_start>get_rich_schema_by_metadata_operation={TXN_TYPE:GET_RICH_SCHEMA_OBJECT_BY_METADATA RS_NAME:rs_name RS_VERSION:rs_version RS_TYPE:rs_type}<with_stmt>pytest.raises(RequestNackedException match='RichSchema queries are disabled')<block_start>sdk_submit_operation_and_get_result(looper sdk_pool_handle sdk_wallet_endorser get_rich_schema_by_metadata_operation)<block_end><block_end> |
<import_from_stmt>. configure core draw io interp retrieve qc<line_sep>__all__=["configure" "core" "draw" "io" "interp" "qc" "retrieve"]<line_sep> |
# -*- coding: utf-8 -*-
<import_from_stmt>amplify.agent.common.context context<import_from_stmt>amplify.agent.common.util subp<line_sep>__author__="<NAME>"<line_sep>__copyright__="Copyright (C) Nginx, Inc. All rights reserved."<line_sep>__license__=""<line_sep>__maintainer__="<NAME>"<line_sep>__email__="<EMAIL>"<line_sep>VERSION_CMD="%s --version"<def_stmt>VERSION_PARSER bin_path<block_start><try_stmt><block_start>raw_stdout,_=subp.call(VERSION_CMD%bin_path)<block_end><except_stmt>Exception<as>e<block_start>exc_name=e.__class__.__name__<line_sep># this is being logged as debug only since we will rely on bin_path
# collection error to tip off support as to what is going wrong with
# version detection
context.log.debug('failed to get version info from "%s" due to %s'%(bin_path exc_name))<line_sep>context.log.debug('additional info:' exc_info=<true>)<block_end><else_stmt># first line is all that we are interested in::
# PHP 5.5.9-1ubuntu4.17 (fpm-fcgi) (built: May 19 2016 19:08:26)
<block_start>raw_line=raw_stdout[0]<line_sep>raw_version=raw_line.split()[1]# 5.5.9-1ubuntu4.17
version=[]<for_stmt>char raw_version<block_start><if_stmt>char.isdigit()<or>char<in>('.' '-')<block_start>version.append(char)<block_end><else_stmt><block_start><break><block_end><block_end># version = ['5', '.', '5', '.', '9', '-', '1']
# '5.5.9-1',
# 'PHP 5.5.9-1ubuntu4.17 (fpm-fcgi) (built: May 19 2016 19:08:26)'
<return>''.join(version) raw_line<block_end><block_end> |
# flake8: noqa
<import_stmt>json<import_stmt>time<import_stmt>requests<import_from_stmt>django.conf settings<import_from_stmt>websocket create_connection<import_from_stmt>open.core.scripts.swarm_ml_services get_random_prompt<import_from_stmt>open.core.writeup.constants TEXT_GENERATION_URL<line_sep>"""
this script's design was to compare performance behind django channels
and how much overhead it added versus directly hitting the microservice
output:
1.8620352506637574 was the average time in seconds to run.
1.8132854890823364 was the average time in seconds to run directly.
amazingly enough, django channels ... has almost zero overhead wow.
"""<def_stmt>run # dpy runscript writeup_profile_prompt_generate_view
<block_start>url=f"wss://open.senrigan.io/ws/async/writeup/{TEXT_GENERATION_URL}/session/a-cool-test-session/"<line_sep>ws=create_connection(url)<line_sep>start=time.time()<line_sep>intervals=50<for_stmt>_ range(intervals)<block_start>data=get_random_prompt()<line_sep>ws_msg=json.dumps(data)<line_sep>ws.send(ws_msg)<line_sep>result=ws.recv()<block_end>end=time.time()<line_sep>websocket_difference=end-start<line_sep>print(f"{websocket_difference/intervals} was the average time in seconds to run.")<line_sep>url=settings.GPT2_MEDUM_API_ENDPOINT<line_sep>token_key=f"Token {settings.ML_SERVICE_ENDPOINT_API_KEY}"<line_sep>headers={"Authorization":token_key}<line_sep>api_start=time.time()<for_stmt>_ range(intervals)<block_start>data=get_random_prompt()<line_sep>response=requests.post(url json=data headers=headers)<assert_stmt>response.status_code<eq>200<block_end>api_end=time.time()<line_sep>api_difference=api_end-api_start<line_sep>print(f"{api_difference/intervals} was the average time in seconds to run directly.")<block_end> |
#!/usr/bin/env python
<import_stmt>sys<import_stmt>argparse<import_stmt>os<import_stmt>subprocess<import_stmt>platform<import_stmt>io<import_stmt>string<try_stmt># For Python >= 3.0
<block_start><import_from_stmt>urllib.request urlopen<block_end><except_stmt>ImportError# For Python < 3.0
<block_start><import_from_stmt>urllib2 urlopen<block_end><import_stmt>shutil<import_stmt>stat<def_stmt>run args<block_start>nugetFolder=os.path.join(args.target ".nuget")<line_sep>print("\nEnsuring folder: %s"%nugetFolder)<if_stmt><not>os.path.exists(nugetFolder)<block_start>os.makedirs(nugetFolder)<block_end>nugetExe=os.path.join(nugetFolder "nuget.exe")<if_stmt><not>os.path.exists(nugetExe)<block_start>nugetOrg="http://nuget.org/nuget.exe"<line_sep>print("Downloading... %s"%nugetOrg)<line_sep>response=urlopen(nugetOrg)<line_sep>output=open(nugetExe 'wb')<line_sep>output.write(response.read())<line_sep>output.close()<line_sep># Ensure it's executable
st=os.stat(nugetExe)<line_sep>os.chmod(nugetExe st.st_mode|stat.S_IEXEC)<block_end><if_stmt>(sys.platform<ne>"win32")# shutil.which can be used for python 3.3 or later, instead.
<block_start><for_stmt>mono ["/usr/bin/mono" "/usr/local/bin/mono"]<block_start><if_stmt>os.path.exists(mono)<block_start>monopath=mono<block_end><block_end><if_stmt><not>monopath<block_start><raise>"mono is required to run nuget.exe"<block_end>nugetExe=monopath+" "+nugetExe<block_end>nugetSpec=os.path.join(nugetFolder os.path.basename(args.nuspec))<if_stmt>args.nuspec<ne>nugetSpec<block_start>print("\nCopying "+args.nuspec+" to "+nugetSpec)<line_sep>shutil.copyfile(args.nuspec nugetSpec)<block_end><if_stmt>args.json<ne><none><block_start>nugetJson=os.path.join(nugetFolder os.path.basename(args.json))<if_stmt>args.json<ne>nugetJson<block_start>print("\nCopying "+args.json+" to "+nugetJson)<line_sep>shutil.copyfile(args.json nugetJson)<block_end><block_end>nugetCommand=nugetExe+" pack "+nugetSpec+" -NoPackageAnalysis -NoDefaultExcludes"<concat>" -OutputDirectory %s"%nugetFolder<line_sep>ret=os.system(nugetCommand)<line_sep><return>ret<block_end><def_stmt>main argv<block_start>parser=argparse.ArgumentParser(description="Download nuget and run it to create a package using the given nuspec. "<concat>"Example: make_package.py "<concat>"--target f:\llilc-rel\\bin\Release "<concat>"--nuspec f:\llilc\lib\ObjWriter\.nuget\Microsoft.Dotnet.ObjectWriter.nuspec" formatter_class=argparse.ArgumentDefaultsHelpFormatter)<line_sep>parser.add_argument("--target" metavar="PATH" default=<none> help="path to a target directory that contains files that will "<concat>"packaged")<line_sep>parser.add_argument("--nuspec" metavar="PATH" default=<none> help="path to a nuspec file. This file is assumed to be under "<concat>"a child directory (.nuget) of the target by convetion")<line_sep>parser.add_argument("--json" metavar="PATH" default=<none> help="path to a json file. This file is used to create "<concat>"a redirection package")<line_sep>args,unknown=parser.parse_known_args(argv)<if_stmt>unknown<block_start>print("Unknown argument(s): " ", ".join(unknown))<line_sep><return>-3<block_end>returncode=0<if_stmt>args.target<eq><none><block_start>print("--target is not specified.")<line_sep><return>-3<block_end><if_stmt>args.nuspec<eq><none><block_start>print("--nuspec is not specified")<line_sep><return>-3<block_end>returncode=run(args)<line_sep><return>returncode<block_end><if_stmt>__name__<eq>"__main__"<block_start>returncode=main(sys.argv[1:])<line_sep>sys.exit(returncode)<block_end> |
<import_from_stmt>avatar2 *<import_stmt>sys<import_stmt>os<import_stmt>logging<import_stmt>serial<import_stmt>time<import_stmt>argparse<import_stmt>pyudev<import_stmt>struct<import_stmt>ctypes<import_from_stmt>random randint<line_sep># For profiling
<import_stmt>pstats<line_sep>logging.basicConfig(filename='/tmp/inception-tests.log' level=logging.INFO)<line_sep># ****************************************************************************
<def_stmt>single_step target nb_test<block_start>print("[*] Single step target %d times"%nb_test)<for_stmt>i range(nb_test)<block_start>pc=target.protocols.execution.read_pc()<line_sep>print(pc)<line_sep>target.step()<line_sep>print('stepped')<line_sep>next_pc=target.protocols.execution.read_pc()<line_sep>print(next_pc)<block_end><block_end># ****************************************************************************
<def_stmt>read_full_mem target nb_test raw=<true> summary=<true><block_start>print(" - Read the full memory")<line_sep>nb_test=1<line_sep>average_read=0<for_stmt>i range(nb_test)<block_start>t0=time.time()<line_sep>target.read_memory(ram.address 1 ram.size raw=raw)<line_sep>t1=time.time()<line_sep>average_read<augadd>t1-t0<block_end><if_stmt>summary<block_start>average_read=average_read/nb_test<line_sep>speed_read=ram.size/average_read/1024<line_sep>print(" -> On average raw read of %s bytes takes %.2f sec, speed: %.2f KB/sec"%(ram.size average_read speed_read))<block_end><block_end># ****************************************************************************
<def_stmt>write_full_mem target nb_test raw=<true> summary=<true><block_start>print(" - Write the full memory")<line_sep>nb_test=1<line_sep>average_write=0<line_sep>buf=ctypes.create_string_buffer(ram.size)<for_stmt>i range(int(ram.size/4))<block_start>struct.pack_into(">I" buf i<times>4 randint(0 0xffffffff))<block_end><for_stmt>i range(nb_test)<block_start>t0=time.time()<line_sep>target.write_memory(ram.address 1 buf raw=raw)<line_sep>t1=time.time()<line_sep>average_write<augadd>t1-t0<block_end><if_stmt>summary<block_start>average_write=average_write/nb_test<line_sep>speed_write=ram.size/average_write/1024<line_sep>print(" -> On average raw write of %s bytes takes %.2f sec, speed: %.2f KB/sec"%(ram.size average_write speed_write))<block_end><block_end># ****************************************************************************
<def_stmt>read_write_full_mem target nb_test raw=<true> summary=<true><block_start>print(" - Read and write the full memory")<line_sep>reads=[]<line_sep>average_read_write=0<for_stmt>i range(nb_test)<block_start><if_stmt>raw<block_start>t0=time.time()<line_sep>reads.append(target.read_memory(ram.address 1 ram.size raw=raw))<line_sep>target.write_memory(ram.address 1 reads[i] raw=raw)<line_sep>t1=time.time()<block_end><else_stmt><block_start>t0=time.time()<line_sep>reads.append(target.read_memory(ram.address 1 ram.size raw=raw))<line_sep>target.write_memory(ram.address 1 reads[i] len(reads[i]) raw=raw)<line_sep>t1=time.time()<block_end>average_read_write<augadd>t1-t0<block_end><if_stmt>summary<block_start>average_read_write=average_read_write/nb_test<line_sep>speed_read_write=ram.size/average_read_write/1024<line_sep>print(" -> On average raw read&write of %s bytes takes %.2f sec, speed: %.2f KB/sec"%(ram.size average_read_write speed_read_write))<block_end># Verify all reads are identical
<for_stmt>i range(len(reads)-1)<block_start><assert_stmt>(reads[i]<eq>reads[i+1])<line_sep>#print("[!] Multiple reads produce different values !")
<block_end><block_end># ****************************************************************************
<def_stmt>random_read_write target nb_test raw=<true><block_start>print(" - Random read / writes of random size in the ram")<for_stmt>i range(0 nb_test)<block_start>size=randint(0 int(ram.size/8))<times>8<line_sep>#size = 2**4
# Reset the board and wait to reach the breakpoint
target.reset()<line_sep>target.wait()<if_stmt>raw<block_start>m1=ctypes.create_string_buffer(size)<for_stmt>j range(int(size/4))<block_start>struct.pack_into(">I" m1 j<times>4 randint(0 0xFFFFFFFF))<block_end>target.write_memory(ram.address 1 m1 raw=<true>)<line_sep>m2=target.read_memory(ram.address 1 size raw=<true>)<line_sep>n1,n2=([]<for>i range(2))<for_stmt>j range(int(size/4))<block_start>n1.append(struct.unpack_from(">I" m1 j)[0])<line_sep>n2.append(struct.unpack_from(">I" m2 j)[0])<block_end><assert_stmt>(n1<eq>n2)<line_sep>#print("i=%s m1: %s m2: %s" % (i, m1.raw, m2))
#print("[!] Multiple random reads produce different values !")
<block_end><else_stmt><block_start>m1=[]<for_stmt>j range(int(size/4))<block_start>m1.append(randint(0 0xFFFFFFFF))<block_end>target.write_memory(ram.address 1 m1 size raw=<false>)<line_sep>m2=target.read_memory(ram.address 1 size raw=<false>)<for_stmt>j range(int(size/4))<block_start><assert_stmt>(m1[j]<eq>m2[j])<line_sep>#print("[!] Multiple random reads produce different values !")
#print("i=%s j=%s m1[j]: %s m2[j]: %s" % (i, j, m1[j], m2[j]))
<block_end><block_end><block_end><block_end># ****************************************************************************
<def_stmt>random_4bytes_read_write target nb_test<block_start>print(" - Random read / writes of 4 bytes in the ram")<for_stmt>i range(nb_test)<block_start>written_word=randint(0 0xFFFFFFFF)<line_sep>address=randint(ram.address ram.address+ram.size-4)<line_sep>target.write_memory(address 4 written_word 1 raw=<false>)<line_sep>read_word=target.read_memory(address 4 1 raw=<false>)<assert_stmt>(written_word<eq>read_word)<block_end><block_end># ****************************************************************************
<def_stmt>read_write_registers target nb_test<block_start>print(" - Read / write registers")<line_sep>regs=['R0' 'R1' 'R2' 'R3' 'R4' 'R5' 'R6' 'R7' 'R8' 'R9' 'R10' 'R11' 'R12' 'SP' 'LR' 'PC' 'CPSR']<for_stmt>i range(nb_test)<block_start><for_stmt>j range(17)<block_start>written_reg=randint(0 0xFFFFFFFF)<line_sep>saved_reg=target.read_register(regs[j])<line_sep>target.write_register(regs[j] written_reg)<line_sep>read_reg=target.read_register(regs[j])<line_sep>'''
if read_reg != written_reg:
print(i)
print(j)
print(hex(read_reg))
print(hex(written_reg))
'''<line_sep>target.write_register(regs[j] saved_reg)<block_end><block_end><block_end># ****************************************************************************
<def_stmt>transfer_state av target_from target_to nb_test summary=<true><block_start>print(" - Transfer state")<line_sep>average=0<for_stmt>i range(nb_test)<block_start>t0=time.time()<line_sep>av.transfer_state(target_from target_to synced_ranges=[ram])<line_sep>t1=time.time()<line_sep>average<augadd>t1-t0<block_end><if_stmt>summary<block_start>average=average/nb_test<line_sep>speed=ram.size/average/1024<line_sep>print(" -> On average transfer state from %s to %s of %s bytes takes %.2f sec, speed: %.2f KB/sec"%(target_from.name target_to.name ram.size average speed))<block_end><block_end><if_stmt>__name__<eq>'__main__'# Number each test is repeated
<block_start>n=2<line_sep>avatar=Avatar(arch=ARMV7M output_directory='/tmp/inception-tests')<line_sep>nucleo=avatar.add_target(InceptionTarget name='nucleo')<line_sep>dum=avatar.add_target(DummyTarget name='dum')<line_sep>#qemu = avatar.add_target(QemuTarget, gdb_port=1236)
# Memory mapping of NUCLEO-L152RE
rom=avatar.add_memory_range(0x08000000 0x1000000 'rom' file=firmware)<line_sep>ram=avatar.add_memory_range(0x20000000 0x14000 'ram')<line_sep>mmio=avatar.add_memory_range(0x40000000 0x1000000 forwarded=<true> forwarded_to=nucleo)<line_sep>ram=avatar.get_memory_range(0x20000000)<line_sep>avatar.init_targets()<line_sep>print("Targets initialized")<line_sep>nucleo.reset()<line_sep>nucleo.cont()<line_sep>nucleo.stop()<line_sep>print("Targets stopped, start tests for n = %s"%n)<line_sep>print("[*] Raw read / writes tests")<line_sep>read_full_mem(nucleo n)<line_sep>write_full_mem(nucleo n)<line_sep>read_write_full_mem(nucleo n)<line_sep>random_read_write(nucleo n)<line_sep>print("[*] !raw read / writes tests")<line_sep>read_full_mem(nucleo n raw=<false> summary=<false>)<line_sep>write_full_mem(nucleo n raw=<false> summary=<false>)<line_sep>read_write_full_mem(nucleo n raw=<false> summary=<false>)<line_sep>random_read_write(nucleo n raw=<false>)<line_sep>random_4bytes_read_write(nucleo 100<times>n)<line_sep>print("[*] Read / Write registers")<line_sep>read_write_registers(nucleo n)<line_sep>print("[*] Transfer state to dummy target")<line_sep>transfer_state(avatar nucleo dum n)<line_sep>#Stop all threads for the profiler
print("[*] Test completed")<line_sep>avatar.stop()<block_end> |
# paura_lite:
# An ultra-simple command-line audio recorder with real-time
# spectrogram visualization
<import_stmt>numpy<as>np<import_stmt>pyaudio<import_stmt>struct<import_stmt>scipy.fftpack<as>scp<import_stmt>termplotlib<as>tpl<import_stmt>os<line_sep># get window's dimensions
rows,columns=os.popen('stty size' 'r').read().split()<line_sep>buff_size=0.2# window size in seconds
wanted_num_of_bins=40# number of frequency bins to display
# initialize soundcard for recording:
fs=8000<line_sep>pa=pyaudio.PyAudio()<line_sep>stream=pa.open(format=pyaudio.paInt16 channels=1 rate=fs input=<true> frames_per_buffer=int(fs<times>buff_size))<while_stmt>1# for each recorded window (until ctr+c) is pressed
# get current block and convert to list of short ints,
<block_start>block=stream.read(int(fs<times>buff_size))<line_sep>format="%dh"%(len(block)/2)<line_sep>shorts=struct.unpack(format block)<line_sep># then normalize and convert to numpy array:
x=np.double(list(shorts))/(2<power>15)<line_sep>seg_len=len(x)<line_sep># get total energy of the current window and compute a normalization
# factor (to be used for visualizing the maximum spectrogram value)
energy=np.mean(x<power>2)<line_sep>max_energy=0.01# energy for which the bars are set to max
max_width_from_energy=int((energy/max_energy)<times>int(columns))+1<if_stmt>max_width_from_energy<g>int(columns)-10<block_start>max_width_from_energy=int(columns)-10<block_end># get the magnitude of the FFT and the corresponding frequencies
X=np.abs(scp.fft(x))[0:int(seg_len/2)]<line_sep>freqs=(np.arange(0 1+1.0/len(X) 1.0/len(X))<times>fs/2)<line_sep># ... and resample to a fix number of frequency bins (to visualize)
wanted_step=(int(freqs.shape[0]/wanted_num_of_bins))<line_sep>freqs2=freqs[0::wanted_step].astype('int')<line_sep>X2=np.mean(X.reshape(-1 wanted_step) axis=1)<line_sep># plot (freqs, fft) as horizontal histogram:
fig=tpl.figure()<line_sep>fig.barh(X2 labels=[str(int(f))+" Hz"<for>f freqs2[0:-1]] show_vals=<false> max_width=max_width_from_energy)<line_sep>fig.show()<line_sep># add exactly as many new lines as they are needed to
# fill clear the screen in the next iteration:
print("\n"<times>(int(rows)-freqs2.shape[0]-1))<block_end> |
# -*- coding: utf-8 -*-
<import_from_stmt>flask Blueprint render_template g request make_response<import_from_stmt>dataviva.apps.general.views get_locale<import_from_stmt>dataviva.translations.dictionary dictionary<import_from_stmt>dataviva datavivadir<import_from_stmt>config GZIP_DATA<import_from_stmt>dataviva.utils.cached_query cached_query<import_from_stmt>dataviva.utils.graphs_services location_service<import_from_stmt>dataviva.apps.title.views get_title<import_from_stmt>dataviva.utils.graphs_services *<import_stmt>urllib<import_stmt>json<line_sep>mod=Blueprint('map' __name__ template_folder='templates' url_prefix='/<lang_code>/map' static_folder='static')<line_sep>@mod.url_value_preprocessor<def_stmt>pull_lang_code endpoint values<block_start>g.locale=values.pop('lang_code')<block_end>@mod.url_defaults<def_stmt>add_language_code endpoint values<block_start>values.setdefault('lang_code' get_locale())<block_end>@mod.before_request<def_stmt>before_request <block_start>g.page_type=mod.name<block_end>@mod.route('/<dataset>/<value>/' defaults={'id_ibge':''})@mod.route('/<dataset>/<value>/<id_ibge>')<def_stmt>index dataset value id_ibge<block_start>filters=[]<line_sep>title_attrs={}<line_sep>services={'product':product_service 'id_ibge':location_service 'wld':wld_service 'occupation':occupation_service 'industry':industry_service 'basic_course':sc_service }<for_stmt>k,v request.args.items()<block_start><if_stmt>k<not><in>['values' 'filters' 'count' 'year']<block_start><if_stmt>v<and>k<in>services<block_start>filters.append(services[k](v))<line_sep>title_attrs[services[k](v)[0]]=services[k](v)[1]<block_end><else_stmt><block_start><if_stmt>k<ne>'colors'<block_start>filters.append((k v))<line_sep>title_attrs[k]=v<block_end><block_end><block_end><block_end><if_stmt>id_ibge<block_start>location=location_service(id_ibge)[0]<line_sep>filters.append((location id_ibge))<line_sep>state=''<if>location<eq>'region'<else>id_ibge[:2]<line_sep>title_attrs[location]=id_ibge<block_end><else_stmt><block_start>state=id_ibge<line_sep>location='municipality'<block_end>filters=urllib.urlencode(filters)<line_sep>title,subtitle=get_title(dataset value 'map' title_attrs)<line_sep><return>render_template('map/index.html' dataset=dataset value=value state=state filters=filters title=title<or>'' subtitle=subtitle<or>'' dictionary=json.dumps(dictionary()))<block_end>@mod.route('/coords/' defaults={'id':'all'})@mod.route('/coords/<id>')<def_stmt>coords id<block_start><if_stmt>GZIP_DATA<block_start>fileext=".gz"<line_sep>filetype="gzip"<block_end><else_stmt><block_start>fileext=""<line_sep>filetype="json"<block_end><if_stmt>id<eq>"all"<block_start>file_name="bra_all_states.json"+fileext<block_end><else_stmt><block_start>file_name=("coords-{0}.json"+fileext).format(id)<block_end>cached_q=cached_query(file_name)<if_stmt>cached_q<block_start>ret=make_response(cached_q)<block_end><else_stmt><block_start>path=datavivadir+"/static/json/map/{0}".format(file_name)<line_sep>gzip_file=open(path).read()<line_sep>cached_query(file_name gzip_file)<line_sep>ret=make_response(gzip_file)<block_end>ret.headers['Content-Encoding']=filetype<line_sep>ret.headers['Content-Length']=str(len(ret.data))<line_sep><return>ret<block_end> |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2018, 8minutenergy / Kisensum.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Neither 8minutenergy nor Kisensum, nor any of their
# employees, nor any jurisdiction or organization that has cooperated in the
# development of these materials, makes any warranty, express or
# implied, or assumes any legal liability or responsibility for the accuracy,
# completeness, or usefulness or any information, apparatus, product,
# software, or process disclosed, or represents that its use would not infringe
# privately owned rights. Reference herein to any specific commercial product,
# process, or service by trade name, trademark, manufacturer, or otherwise
# does not necessarily constitute or imply its endorsement, recommendation, or
# favoring by 8minutenergy or Kisensum.
# }}}
<import_stmt>pytest<try_stmt><block_start><import_stmt>dnp3<block_end><except_stmt>ImportError<block_start>pytest.skip("pydnp3 not found!" allow_module_level=<true>)<block_end><import_from_stmt>dnp3.points ArrayHeadPointDefinition PointDefinitions PointValue<import_from_stmt>dnp3.mesa.agent MesaAgent<import_from_stmt>dnp3.mesa.functions FunctionDefinitions<import_from_stmt>test_mesa_agent POINT_DEFINITIONS_PATH FUNCTION_DEFINITIONS_PATH<def_stmt>test_point_definition_load <block_start>point_defs=PointDefinitions(point_definitions_path=POINT_DEFINITIONS_PATH)<import_stmt>pprint<line_sep>pprint.pprint(point_defs._points)<line_sep>pprint.pprint(point_defs._point_name_dict)<line_sep>print("_point_variations_dict")<line_sep>pprint.pprint(point_defs._point_variation_dict)<block_end><def_stmt>test_point_definition <block_start>test_dict={"name":"CurveStart-X" "type":"array" # Start of the curve's X/Y array
"array_times_repeated":100 "group":40 "variation":1 "index":207 "description":"Starting index for a curve of up to 99 X/Y points" "array_points":[{"name":"Curve-X"} {"name":"Curve-Y"}]}<line_sep>test_def=ArrayHeadPointDefinition(test_dict)<line_sep>print(test_def)<block_end><def_stmt>send_points mesa_agent some_points<block_start><for_stmt>name,value,index some_points<block_start>pdef=mesa_agent.point_definitions.get_point_named(name index)<line_sep>point_value=PointValue('Operate' <none> value pdef pdef.index <none>)<line_sep># What is op_type used for?
print(point_value)<line_sep>mesa_agent._process_point_value(point_value)<block_end><block_end><def_stmt>test_mesa_agent <block_start>mesa_agent=MesaAgent(point_topic='points_foobar' local_ip='127.0.0.1' port=8999 outstation_config={} function_topic='functions_foobar' outstation_status_topic='' local_point_definitions_path=POINT_DEFINITIONS_PATH local_function_definitions_path=FUNCTION_DEFINITIONS_PATH)<line_sep>mesa_agent._configure('' '' {})<line_sep>point_definitions=mesa_agent.point_definitions<line_sep>supported_pdef=point_definitions.get_point_named("Supports Charge/Discharge Mode")<line_sep>mesa_agent.update_input_point(supported_pdef <true>)<line_sep>test_points=(# ("DCHD.WinTms (out)", 1.0),
# ("DCHD.RmpTms (out)", 2.0),
# ("DCHD.RevtTms (out)", 3.0),
("CurveStart-X" 1.0 <none>) ("CurveStart-X" 2.0 208) )<line_sep>send_points(mesa_agent test_points)<block_end><def_stmt>test_mesa_agent_2 <block_start>mesa_agent=MesaAgent(point_topic='points_foobar' local_ip='127.0.0.1' port=8999 outstation_config={} function_topic='functions_foobar' outstation_status_topic='' local_point_definitions_path=POINT_DEFINITIONS_PATH local_function_definitions_path=FUNCTION_DEFINITIONS_PATH)<line_sep>mesa_agent._configure('' '' {})<line_sep>point_definitions=mesa_agent.point_definitions<line_sep>supported_pdef=point_definitions.get_point_named("Supports Charge/Discharge Mode")<line_sep>mesa_agent.update_input_point(supported_pdef <true>)<line_sep>test_points=(("DCHD.WinTms (out)" 1.0 <none>) #("DCHD.RmpTms (out)", 2.0, None),
("DCHD.RevtTms (out)" 3.0 <none>) )<line_sep>send_points(mesa_agent test_points)<block_end><def_stmt>test_function_definitions <block_start>point_definitions=PointDefinitions(point_definitions_path=POINT_DEFINITIONS_PATH)<line_sep>fdefs=FunctionDefinitions(point_definitions function_definitions_path=FUNCTION_DEFINITIONS_PATH)<line_sep>fd=fdefs.function_for_id("curve")<line_sep>print(fd)<line_sep>pdef=point_definitions.get_point_named("DCHD.WinTms (out)")<line_sep>print(pdef)<line_sep>print(fdefs.step_definition_for_point(pdef))<block_end><def_stmt>test_selector_block <block_start>"""
Test send a Curve function / selector block (including an array of points) to MesaAgent.
Get MesaAgent's selector block and confirm that it has the correct contents.
Do this for a variety of Edit Selectors and array contents.
"""<def_stmt>process_block_points agt block_points edit_selector<block_start>"""Send each point value in block_points to the MesaAgent."""<line_sep># print('Processing {}'.format(block_points))
<for_stmt>name,value,index block_points<block_start>point_definitions=agt.point_definitions<line_sep>pdef=point_definitions.get_point_named(name index)<line_sep>point_value=PointValue('Operate' <none> value pdef pdef.index <none>)<line_sep>agt._process_point_value(point_value)<block_end>returned_block=mesa_agent.get_selector_block('Curve Edit Selector' edit_selector)<line_sep># print('get_selector_block returned {}'.format(returned_block))
<return>returned_block<block_end>mesa_agent=MesaAgent(point_topic='points_foobar' local_ip='127.0.0.1' port=8999 outstation_config={} function_topic='functions_foobar' outstation_status_topic='' local_point_definitions_path=POINT_DEFINITIONS_PATH local_function_definitions_path=FUNCTION_DEFINITIONS_PATH)<line_sep>mesa_agent._configure('' '' {})<line_sep>block_1_points=[('Curve Edit Selector' 1 <none>) # index 191 - Function and SelectorBlock start
('CurveStart-X' 1.0 <none>) # Point #1-X: index 207 - Array start
('CurveStart-X' 2.0 208) # Point #1-Y
('Curve Number of Points' 1 <none>)]<line_sep># index 196 - Curve function end
block_2_points=[('Curve Edit Selector' 2 <none>) # index 191 - Function and SelectorBlock start
('CurveStart-X' 1.0 <none>) # Point #1-X: index 207 - Array start
('CurveStart-X' 2.0 208) # Point #1-Y
('CurveStart-X' 3.0 209) # Point #2-X
('CurveStart-X' 4.0 210) # Point #2-Y
('Curve Number of Points' 2 <none>)]<line_sep># index 196 - Curve function end
block_2a_points=[('Curve Edit Selector' 2 <none>) # index 191 - Function and SelectorBlock start
('CurveStart-X' 1.0 <none>) # Point #1-X: index 207 - Array start
('CurveStart-X' 2.0 208) # Point #1-Y
('CurveStart-X' 5.0 211) # Point #3-X
('CurveStart-X' 6.0 212) # Point #3-Y
('Curve Number of Points' 3 <none>)]<line_sep># index 196 - Curve function end
# Send block #1. Confirm that its array has a point with Y=2.0.
block=process_block_points(mesa_agent block_1_points 1)<assert_stmt>block['CurveStart-X'][0]['Curve-Y']<eq>2.0<line_sep># Send block #2. Confirm that its array has a point #2 with Y=4.0.
block=process_block_points(mesa_agent block_2_points 2)<assert_stmt>block['CurveStart-X'][1]['Curve-Y']<eq>4.0<line_sep># Send an updated block #2 with no point #2 and a new point #3.
block=process_block_points(mesa_agent block_2a_points 2)<line_sep># Confirm that its array still has a point #2 with Y=4.0, even though it wasn't just sent.
<assert_stmt>block['CurveStart-X'][1]['Curve-Y']<eq>4.0<line_sep># Confirm that its array now has a point #3 with Y=6.0.
<assert_stmt>block['CurveStart-X'][2]['Curve-Y']<eq>6.0<line_sep># Re-send block #1. Confirm that selector block initialization reset the point cache: the array has no second point.
block=process_block_points(mesa_agent block_1_points 1)<assert_stmt>len(block['CurveStart-X'])<eq>1<block_end><if_stmt>__name__<eq>"__main__"# test_mesa_agent()
# test_mesa_agent_2()
# test_function_definitions()
# test_point_definition()
<block_start>test_point_definition_load()<line_sep># test_selector_block()
<block_end> |
# -*- coding: utf-8 -*-
# python std lib
<import_stmt>logging<import_stmt>logging.config<line_sep>log=logging.getLogger()<line_sep># Set the root logger to be silent so all code that uses the python logger
# will not print anything unless we want it to, then it should be specified
# in each test and reseted after that test
<def_stmt>_set_log_lv level=1337 loggers=<none><block_start>""" If no level is set then level will be so high all logging is silenced
"""<if_stmt>loggers<is><none># If no additional loggers is specified then only apply to root logger
<block_start>log.setLevel(level)<for_stmt>handler log.handlers<block_start>handler.level=level<block_end><block_end><else_stmt># If we have other logging instances specified apply to root logger and them
<block_start><if_stmt>log<not><in>loggers<block_start>loggers.append(log)<block_end><for_stmt>log_instance loggers<block_start>log_instance.setLevel(level)<for_stmt>handler log_instance.handlers<block_start>handler.level=level<block_end><block_end><block_end><block_end># Initially silence all logging
_set_log_lv()<line_sep> |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-24 22:12
<import_from_stmt>. rules<def_stmt>ls_resource_in_module root<arrow>dict<block_start>res=dict()<for_stmt>k,v root.__dict__.items()<block_start><if_stmt>k.startswith('_')<or>v<eq>root<block_start><continue><block_end><if_stmt>isinstance(v str)<block_start><if_stmt>v.startswith('http')<and><not>v.endswith('/')<and><not>v.endswith('#')<and><not>v.startswith('_')<block_start>res[k]=v<block_end><block_end><elif_stmt>type(v).__name__<eq>'module'<block_start>res.update(ls_resource_in_module(v))<block_end><block_end><if_stmt>'ALL'<in>root.__dict__<and>isinstance(root.__dict__['ALL'] dict)<block_start>root.__dict__['ALL'].update(res)<block_end><return>res<block_end> |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""<import_stmt>time<import_stmt>struct<import_from_stmt>.. ivi<import_from_stmt>.. dmm<import_from_stmt>.. scpi<class_stmt>agilent34410A(scpi.dmm.Base)<block_start>"Agilent 34410A IVI DMM driver"<def_stmt>__init__ self *args **kwargs<block_start>self.__dict__.setdefault('_instrument_id' '34410A')<line_sep>super(agilent34410A self).__init__(*args **kwargs)<line_sep>self._memory_size=5<line_sep>self._identity_description="Agilent 34410A/11A IVI DMM driver"<line_sep>self._identity_identifier=""<line_sep>self._identity_revision=""<line_sep>self._identity_vendor=""<line_sep>self._identity_instrument_manufacturer="Agilent Technologies"<line_sep>self._identity_instrument_model=""<line_sep>self._identity_instrument_firmware_revision=""<line_sep>self._identity_specification_major_version=4<line_sep>self._identity_specification_minor_version=1<line_sep>self._identity_supported_instrument_models=['34410A' '34411A']<line_sep>self._add_method('memory.save' self._memory_save)<line_sep>self._add_method('memory.recall' self._memory_recall)<line_sep>self._add_method('memory.set_name' self._set_memory_name)<line_sep>self._add_method('memory.get_name' self._get_memory_name)<block_end><def_stmt>_initialize self resource=<none> id_query=<false> reset=<false> **keywargs<block_start>"Opens an I/O session to the instrument."<line_sep>super(agilent34410A self)._initialize(resource id_query reset **keywargs)<line_sep># interface clear
<if_stmt><not>self._driver_operation_simulate<block_start>self._clear()<block_end># check ID
<if_stmt>id_query<and><not>self._driver_operation_simulate<block_start>id=self.identity.instrument_model<line_sep>id_check=self._instrument_id<line_sep>id_short=id[:len(id_check)]<if_stmt>id_short<ne>id_check<block_start><raise>Exception("Instrument ID mismatch, expecting %s, got %s" id_check id_short)<block_end><block_end># reset
<if_stmt>reset<block_start>self.utility.reset()<block_end><block_end><def_stmt>_memory_save self index<block_start>index=int(index)<if_stmt>index<l>1<or>index<g>self._memory_size<block_start><raise>OutOfRangeException()<block_end><if_stmt><not>self._driver_operation_simulate<block_start>self._write("*sav %d"%index)<block_end><block_end><def_stmt>_memory_recall self index<block_start>index=int(index)<if_stmt>index<l>1<or>index<g>self._memory_size<block_start><raise>OutOfRangeException()<block_end><if_stmt><not>self._driver_operation_simulate<block_start>self._write("*rcl %d"%index)<block_end><block_end><def_stmt>_get_memory_name self index<block_start>index=int(index)<if_stmt>index<l>1<or>index<g>self._memory_size<block_start><raise>OutOfRangeException()<block_end><if_stmt><not>self._driver_operation_simulate<block_start><return>self._ask("memory:state:name? %d"%index).strip(' "')<block_end><block_end><def_stmt>_set_memory_name self index value<block_start>index=int(index)<line_sep>value=str(value)<if_stmt>index<l>1<or>index<g>self._memory_size<block_start><raise>OutOfRangeException()<block_end><if_stmt><not>self._driver_operation_simulate<block_start>self._write("memory:state:name %d, \"%s\""%(index value))<block_end><block_end><block_end> |
<import_from_stmt>hummingbot.client.config.config_var ConfigVar<import_from_stmt>hummingbot.client.config.config_methods using_exchange<line_sep>CENTRALIZED=<true><line_sep>EXAMPLE_PAIR="ZRX-ETH"<line_sep>DEFAULT_FEES=[0.25 0.25]<line_sep>KEYS={"bittrex_api_key":ConfigVar(key="bittrex_api_key" prompt="Enter your Bittrex API key >>> " required_if=using_exchange("bittrex") is_secure=<true> is_connect_key=<true>) "bittrex_secret_key":ConfigVar(key="bittrex_secret_key" prompt="Enter your Bittrex secret key >>> " required_if=using_exchange("bittrex") is_secure=<true> is_connect_key=<true>) }<line_sep> |
# Time: O(n)
# Space: O(h)
# Definition for a binary tree node.
<class_stmt>TreeNode(object)<block_start><def_stmt>__init__ self x<block_start>self.val=x<line_sep>self.left=<none><line_sep>self.right=<none><block_end><block_end># iterative stack solution
<class_stmt>Solution(object)<block_start><def_stmt>maxAncestorDiff self root<block_start>"""
:type root: TreeNode
:rtype: int
"""<line_sep>result=0<line_sep>stack=[(root 0 float("inf"))]<while_stmt>stack<block_start>node,mx,mn=stack.pop()<if_stmt><not>node<block_start><continue><block_end>result=max(result mx-node.val node.val-mn)<line_sep>mx=max(mx node.val)<line_sep>mn=min(mn node.val)<line_sep>stack.append((node.left mx mn))<line_sep>stack.append((node.right mx mn))<block_end><return>result<block_end><block_end># Time: O(n)
# Space: O(h)
# recursive solution
<class_stmt>Solution2(object)<block_start><def_stmt>maxAncestorDiff self root<block_start>"""
:type root: TreeNode
:rtype: int
"""<def_stmt>maxAncestorDiffHelper node mx mn<block_start><if_stmt><not>node<block_start><return>0<block_end>result=max(mx-node.val node.val-mn)<line_sep>mx=max(mx node.val)<line_sep>mn=min(mn node.val)<line_sep>result=max(result maxAncestorDiffHelper(node.left mx mn))<line_sep>result=max(result maxAncestorDiffHelper(node.right mx mn))<line_sep><return>result<block_end><return>maxAncestorDiffHelper(root 0 float("inf"))<block_end><block_end> |
# Generated by Django 3.0.6 on 2020-06-01 12:47
<import_from_stmt>django.db migrations models<class_stmt>Migration(migrations.Migration)<block_start>dependencies=[('blogs' '0011_auto_20200531_0915') ]<line_sep>operations=[migrations.RemoveField(model_name='post' name='tags' ) migrations.AddField(model_name='blog' name='hashtags' field=models.TextField(blank=<true>) ) ]<block_end> |
<import_from_stmt>tests.helper restricted_exec<def_stmt>test_RestrictingNodeTransformer__visit_Assert__1 <block_start>"""It allows assert statements."""<line_sep>restricted_exec('assert 1')<block_end> |
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is
# located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.
"""
This module defines middleware functions for command line operations.
This allows the ability to provide custom logic either before or after running
an operation by specifying the name of the operation, and then calling the
function that is provided as the first argument and passing the **kwargs
provided.
"""<import_stmt>logging<import_stmt>argparse<import_stmt>boto3<import_stmt>jmespath<import_from_stmt>botocore.exceptions WaiterError<import_stmt>pcluster.cli.model<import_from_stmt>pcluster.cli.exceptions APIOperationException ParameterException<line_sep>LOGGER=logging.getLogger(__name__)<def_stmt>_cluster_status cluster_name<block_start>controller="cluster_operations_controller"<line_sep>func_name="describe_cluster"<line_sep>full_func_name=f"pcluster.api.controllers.{controller}.{func_name}"<line_sep><return>pcluster.cli.model.call(full_func_name cluster_name=cluster_name)<block_end><def_stmt>add_additional_args parser_map<block_start>"""Add any additional arguments to parsers for individual operations.
NOTE: these additional arguments will also need to be removed before
calling the underlying function for the situation where they are not a part
of the specification.
"""<line_sep>parser_map["create-cluster"].add_argument("--wait" action="store_true" help=argparse.SUPPRESS)<line_sep>parser_map["delete-cluster"].add_argument("--wait" action="store_true" help=argparse.SUPPRESS)<line_sep>parser_map["update-cluster"].add_argument("--wait" action="store_true" help=argparse.SUPPRESS)<block_end><def_stmt>middleware_hooks <block_start>"""Return a map and from operation to middleware functions.
The map has operation names as the keys and functions as values.
"""<line_sep><return>{"create-cluster":create_cluster "delete-cluster":delete_cluster "update-cluster":update_cluster}<block_end><def_stmt>queryable func<block_start><def_stmt>wrapper dest_func _body kwargs<block_start>query=kwargs.pop("query" <none>)<line_sep>ret=func(dest_func _body kwargs)<try_stmt><block_start><return>jmespath.search(query ret)<if>query<else>ret<block_end><except_stmt>jmespath.exceptions.ParseError<block_start><raise>ParameterException({"message":"Invalid query string." "query":query})<block_end><block_end><return>wrapper<block_end>@queryable<def_stmt>update_cluster func _body kwargs<block_start>wait=kwargs.pop("wait" <false>)<line_sep>ret=func(**kwargs)<if_stmt>wait<and><not>kwargs.get("dryrun")<block_start>cloud_formation=boto3.client("cloudformation")<line_sep>waiter=cloud_formation.get_waiter("stack_update_complete")<try_stmt><block_start>waiter.wait(StackName=kwargs["cluster_name"])<block_end><except_stmt>WaiterError<as>e<block_start>LOGGER.error("Failed when waiting for cluster update with error: %s" e)<line_sep><raise>APIOperationException(_cluster_status(kwargs["cluster_name"]))<block_end>ret=_cluster_status(kwargs["cluster_name"])<block_end><return>ret<block_end>@queryable<def_stmt>create_cluster func body kwargs<block_start>wait=kwargs.pop("wait" <false>)<line_sep>ret=func(**kwargs)<if_stmt>wait<and><not>kwargs.get("dryrun")<block_start>cloud_formation=boto3.client("cloudformation")<line_sep>waiter=cloud_formation.get_waiter("stack_create_complete")<try_stmt><block_start>waiter.wait(StackName=body["clusterName"])<block_end><except_stmt>WaiterError<as>e<block_start>LOGGER.error("Failed when waiting for cluster creation with error: %s" e)<line_sep><raise>APIOperationException(_cluster_status(body["clusterName"]))<block_end>ret=_cluster_status(body["clusterName"])<block_end><return>ret<block_end>@queryable<def_stmt>delete_cluster func _body kwargs<block_start>wait=kwargs.pop("wait" <false>)<line_sep>ret=func(**kwargs)<if_stmt>wait<block_start>cloud_formation=boto3.client("cloudformation")<line_sep>waiter=cloud_formation.get_waiter("stack_delete_complete")<try_stmt><block_start>waiter.wait(StackName=kwargs["cluster_name"])<block_end><except_stmt>WaiterError<as>e<block_start>LOGGER.error("Failed when waiting for cluster deletion with error: %s" e)<line_sep><raise>APIOperationException({"message":f"Failed when deleting cluster '{kwargs['cluster_name']}'."})<block_end><return>{"message":f"Successfully deleted cluster '{kwargs['cluster_name']}'."}<block_end><else_stmt><block_start><return>ret<block_end><block_end> |
# Copyright (c) OpenMMLab. All rights reserved.
<import_stmt>pytest<import_stmt>torch<import_from_stmt>numpy.testing assert_almost_equal<import_from_stmt>mmpose.models build_loss<import_from_stmt>mmpose.models.utils.geometry batch_rodrigues<def_stmt>test_mesh_loss <block_start>"""test mesh loss."""<line_sep>loss_cfg=dict(type='MeshLoss' joints_2d_loss_weight=1 joints_3d_loss_weight=1 vertex_loss_weight=1 smpl_pose_loss_weight=1 smpl_beta_loss_weight=1 img_res=256 focal_length=5000)<line_sep>loss=build_loss(loss_cfg)<line_sep>smpl_pose=torch.zeros([1 72] dtype=torch.float32)<line_sep>smpl_rotmat=batch_rodrigues(smpl_pose.view(-1 3)).view(-1 24 3 3)<line_sep>smpl_beta=torch.zeros([1 10] dtype=torch.float32)<line_sep>camera=torch.tensor([[1 0 0]] dtype=torch.float32)<line_sep>vertices=torch.rand([1 6890 3] dtype=torch.float32)<line_sep>joints_3d=torch.ones([1 24 3] dtype=torch.float32)<line_sep>joints_2d=loss.project_points(joints_3d camera)+(256-1)/2<line_sep>fake_pred={}<line_sep>fake_pred['pose']=smpl_rotmat<line_sep>fake_pred['beta']=smpl_beta<line_sep>fake_pred['camera']=camera<line_sep>fake_pred['vertices']=vertices<line_sep>fake_pred['joints_3d']=joints_3d<line_sep>fake_gt={}<line_sep>fake_gt['pose']=smpl_pose<line_sep>fake_gt['beta']=smpl_beta<line_sep>fake_gt['vertices']=vertices<line_sep>fake_gt['has_smpl']=torch.ones(1 dtype=torch.float32)<line_sep>fake_gt['joints_3d']=joints_3d<line_sep>fake_gt['joints_3d_visible']=torch.ones([1 24 1] dtype=torch.float32)<line_sep>fake_gt['joints_2d']=joints_2d<line_sep>fake_gt['joints_2d_visible']=torch.ones([1 24 1] dtype=torch.float32)<line_sep>losses=loss(fake_pred fake_gt)<assert_stmt>torch.allclose(losses['vertex_loss'] torch.tensor(0.))<assert_stmt>torch.allclose(losses['smpl_pose_loss'] torch.tensor(0.))<assert_stmt>torch.allclose(losses['smpl_beta_loss'] torch.tensor(0.))<assert_stmt>torch.allclose(losses['joints_3d_loss'] torch.tensor(0.))<assert_stmt>torch.allclose(losses['joints_2d_loss'] torch.tensor(0.))<line_sep>fake_pred={}<line_sep>fake_pred['pose']=smpl_rotmat+1<line_sep>fake_pred['beta']=smpl_beta+1<line_sep>fake_pred['camera']=camera<line_sep>fake_pred['vertices']=vertices+1<line_sep>fake_pred['joints_3d']=joints_3d.clone()<line_sep>joints_3d_t=joints_3d.clone()<line_sep>joints_3d_t[: 0]=joints_3d_t[: 0]+1<line_sep>fake_gt={}<line_sep>fake_gt['pose']=smpl_pose<line_sep>fake_gt['beta']=smpl_beta<line_sep>fake_gt['vertices']=vertices<line_sep>fake_gt['has_smpl']=torch.ones(1 dtype=torch.float32)<line_sep>fake_gt['joints_3d']=joints_3d_t<line_sep>fake_gt['joints_3d_visible']=torch.ones([1 24 1] dtype=torch.float32)<line_sep>fake_gt['joints_2d']=joints_2d+(256-1)/2<line_sep>fake_gt['joints_2d_visible']=torch.ones([1 24 1] dtype=torch.float32)<line_sep>losses=loss(fake_pred fake_gt)<assert_stmt>torch.allclose(losses['vertex_loss'] torch.tensor(1.))<assert_stmt>torch.allclose(losses['smpl_pose_loss'] torch.tensor(1.))<assert_stmt>torch.allclose(losses['smpl_beta_loss'] torch.tensor(1.))<assert_stmt>torch.allclose(losses['joints_3d_loss'] torch.tensor(0.5/24))<assert_stmt>torch.allclose(losses['joints_2d_loss'] torch.tensor(0.5))<block_end><def_stmt>test_gan_loss <block_start>"""test gan loss."""<with_stmt>pytest.raises(NotImplementedError)<block_start>loss_cfg=dict(type='GANLoss' gan_type='test' real_label_val=1.0 fake_label_val=0.0 loss_weight=1)<line_sep>_=build_loss(loss_cfg)<block_end>input_1=torch.ones(1 1)<line_sep>input_2=torch.ones(1 3 6 6)<times>2<line_sep># vanilla
loss_cfg=dict(type='GANLoss' gan_type='vanilla' real_label_val=1.0 fake_label_val=0.0 loss_weight=2.0)<line_sep>gan_loss=build_loss(loss_cfg)<line_sep>loss=gan_loss(input_1 <true> is_disc=<false>)<line_sep>assert_almost_equal(loss.item() 0.6265233)<line_sep>loss=gan_loss(input_1 <false> is_disc=<false>)<line_sep>assert_almost_equal(loss.item() 2.6265232)<line_sep>loss=gan_loss(input_1 <true> is_disc=<true>)<line_sep>assert_almost_equal(loss.item() 0.3132616)<line_sep>loss=gan_loss(input_1 <false> is_disc=<true>)<line_sep>assert_almost_equal(loss.item() 1.3132616)<line_sep># lsgan
loss_cfg=dict(type='GANLoss' gan_type='lsgan' real_label_val=1.0 fake_label_val=0.0 loss_weight=2.0)<line_sep>gan_loss=build_loss(loss_cfg)<line_sep>loss=gan_loss(input_2 <true> is_disc=<false>)<line_sep>assert_almost_equal(loss.item() 2.0)<line_sep>loss=gan_loss(input_2 <false> is_disc=<false>)<line_sep>assert_almost_equal(loss.item() 8.0)<line_sep>loss=gan_loss(input_2 <true> is_disc=<true>)<line_sep>assert_almost_equal(loss.item() 1.0)<line_sep>loss=gan_loss(input_2 <false> is_disc=<true>)<line_sep>assert_almost_equal(loss.item() 4.0)<line_sep># wgan
loss_cfg=dict(type='GANLoss' gan_type='wgan' real_label_val=1.0 fake_label_val=0.0 loss_weight=2.0)<line_sep>gan_loss=build_loss(loss_cfg)<line_sep>loss=gan_loss(input_2 <true> is_disc=<false>)<line_sep>assert_almost_equal(loss.item() -4.0)<line_sep>loss=gan_loss(input_2 <false> is_disc=<false>)<line_sep>assert_almost_equal(loss.item() 4)<line_sep>loss=gan_loss(input_2 <true> is_disc=<true>)<line_sep>assert_almost_equal(loss.item() -2.0)<line_sep>loss=gan_loss(input_2 <false> is_disc=<true>)<line_sep>assert_almost_equal(loss.item() 2.0)<line_sep># hinge
loss_cfg=dict(type='GANLoss' gan_type='hinge' real_label_val=1.0 fake_label_val=0.0 loss_weight=2.0)<line_sep>gan_loss=build_loss(loss_cfg)<line_sep>loss=gan_loss(input_2 <true> is_disc=<false>)<line_sep>assert_almost_equal(loss.item() -4.0)<line_sep>loss=gan_loss(input_2 <false> is_disc=<false>)<line_sep>assert_almost_equal(loss.item() -4.0)<line_sep>loss=gan_loss(input_2 <true> is_disc=<true>)<line_sep>assert_almost_equal(loss.item() 0.0)<line_sep>loss=gan_loss(input_2 <false> is_disc=<true>)<line_sep>assert_almost_equal(loss.item() 3.0)<block_end> |
<import_stmt>boto3<import_stmt>json<import_stmt>datetime<import_stmt>logging<import_stmt>os<import_stmt>ipaddress<import_stmt>requests<line_sep>log=logging.getLogger()<line_sep>log.setLevel(logging.INFO)<line_sep>QUEUE_URL=os.environ['SQS_QUEUE_CLOUD_SNIPER']<line_sep>DYNAMO_TABLE=os.environ['DYNAMO_TABLE_CLOUD_SNIPER']<line_sep>WEBHOOK_URL=os.environ['WEBHOOK_URL_CLOUD_SNIPER']<line_sep>HUB_ACCOUNT_ID=os.environ['HUB_ACCOUNT_ID_CLOUD_SNIPER']<line_sep>ROLE_SPOKE=os.environ['ROLE_SPOKE_CLOUD_SNIPER']<line_sep>BUCKET_NAME=os.environ['BUCKET_NAME']<line_sep>IOCS_PATH=os.environ['IOCS_PATH']<line_sep>TOPIC_ARN=os.environ['TOPIC_ARN']<line_sep>message=[]<line_sep>json_a=[]<line_sep># hub account
s=boto3.session.Session(region_name=os.environ['AWS_REGION'])<line_sep>ec2=s.client('ec2')<line_sep>sqs=s.client('sqs')<line_sep>iam=s.client('iam')<line_sep>r_ec2=s.resource('ec2')<line_sep>dynamodb=s.resource('dynamodb')<line_sep>sns=s.client('sns')<line_sep># spoke account
sts_connection=boto3.client('sts')<line_sep>networkConnectionAction=["UnauthorizedAccess:EC2/SSHBruteForce" ]<line_sep>portProbeAction=["Recon:EC2/PortProbeUnprotectedPort" ]<line_sep>instanceDetails=["UnauthorizedAccess:EC2/TorIPCaller" ]<line_sep>awsApiCallAction=["Recon:IAMUser/TorIPCaller" ]<def_stmt>read_sqs <block_start>log.info("Processing queue")<line_sep>response=sqs.receive_message(QueueUrl=QUEUE_URL MaxNumberOfMessages=10 MessageAttributeNames=['All'] )<if_stmt>'Messages'<in>response<block_start><return>response['Messages']<block_end><else_stmt><block_start>log.info("There is no new message in the queue")<line_sep><return><block_end><block_end><def_stmt>search_ioc <block_start>log.info("Searching for IOC ...")<line_sep><global>json_a<for_stmt>b message<block_start>body=b['Body']<line_sep>data=json.loads(body)<try_stmt><block_start>flag=0<for_stmt>dt networkConnectionAction<block_start><if_stmt>data["detail"]["type"]<eq>dt<block_start>flag=1<line_sep><break><block_end><block_end><for_stmt>dt portProbeAction<block_start><if_stmt>data["detail"]["type"]<eq>dt<block_start>flag=2<line_sep><break><block_end><block_end><for_stmt>dt instanceDetails<block_start><if_stmt>data["detail"]["type"]<eq>dt<block_start>flag=3<line_sep><break><block_end><block_end><for_stmt>dt awsApiCallAction<block_start><if_stmt>data["detail"]["type"]<eq>dt<block_start>flag=4<line_sep><break><block_end><block_end><if_stmt>flag<eq>1<block_start>ioc=[]<line_sep>src_ip=(json.dumps(data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["ipAddressV4"])).strip('"')<line_sep>direction=data["detail"]["service"]["action"]["networkConnectionAction"]["connectionDirection"]<if_stmt>ipaddress.ip_address(src_ip).is_private<is><false><and>direction<eq>"INBOUND"<block_start>account_id=data["detail"]["accountId"]<line_sep>region=data["detail"]["region"]<line_sep>subnet_id=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["subnetId"]<line_sep>instance_id=data["detail"]["resource"]["instanceDetails"]["instanceId"]<line_sep>ttp=data["detail"]["type"]<line_sep>asn=data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["organization"]["asn"]<line_sep>asn_org=(data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["organization"]["asnOrg"]).replace("," " ")<line_sep>isp=(data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["organization"]["isp"]).replace("," " ")<line_sep>org=(data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["organization"]["org"]).replace("," " ")<line_sep>country=data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["country"]["countryName"]<line_sep>city=(data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["city"]["cityName"]).replace("," " ")<line_sep>nacl_id=get_netacl_id(subnet_id account_id)<line_sep>hits=str(data["detail"]["service"]["count"])<line_sep>vpc_id=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["vpcId"]<line_sep>sg_name=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["securityGroups"][0]["groupName"]<line_sep>sg_id=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["securityGroups"][0]["groupId"]<line_sep>tags=(str(data["detail"]["resource"]["instanceDetails"]["tags"])).replace("," "")<line_sep>account_alias=str(get_account_alias(account_id))<line_sep>event_first_seen=str(data["detail"]["service"]["eventFirstSeen"])<line_sep>ioc=ttp+","+hits+","+account_id+","+account_alias+","+region+","+subnet_id+","+src_ip+","+instance_id+","+nacl_id+","+country+","+city+","+asn_org+","+org+","+isp+","+asn+","+vpc_id+","+sg_name+","+sg_id+","+tags+","+event_first_seen<line_sep>log.info("IOCs: "+str(ioc))<line_sep>put_to_s3(ioc)<if_stmt>len(json_a)<eq>0<block_start>json_a.append(ioc)<block_end><else_stmt><block_start><for_stmt>e json_a<block_start><if_stmt>e<ne>ioc<block_start>json_a.append(ioc)<block_end><block_end><block_end><block_end><block_end><elif_stmt>flag<eq>2<block_start>ioc=[]<line_sep>src_ip=(json.dumps(data["detail"]["service"]["action"]["portProbeAction"]["portProbeDetails"][0]["remoteIpDetails"]["ipAddressV4"])).strip('"')<if_stmt>ipaddress.ip_address(src_ip).is_private<is><false><block_start>account_id=data["detail"]["accountId"]<line_sep>region=data["detail"]["region"]<line_sep>subnet_id=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["subnetId"]<line_sep>instance_id=data["detail"]["resource"]["instanceDetails"]["instanceId"]<line_sep>ttp=data["detail"]["type"]<line_sep>country=data["detail"]["service"]["action"]["portProbeAction"]["portProbeDetails"][0]["remoteIpDetails"]["country"]["countryName"]<line_sep>city=(data["detail"]["service"]["action"]["portProbeAction"]["portProbeDetails"][0]["remoteIpDetails"]["city"]["cityName"]).replace("," " ")<line_sep>asn_org=(data["detail"]["service"]["action"]["portProbeAction"]["portProbeDetails"][0]["remoteIpDetails"]["organization"]["asnOrg"]).replace("," " ")<line_sep>org=(data["detail"]["service"]["action"]["portProbeAction"]["portProbeDetails"][0]["remoteIpDetails"]["organization"]["org"]).replace("," " ")<line_sep>isp=(data["detail"]["service"]["action"]["portProbeAction"]["portProbeDetails"][0]["remoteIpDetails"]["organization"]["isp"]).replace("," " ")<line_sep>asn=data["detail"]["service"]["action"]["portProbeAction"]["portProbeDetails"][0]["remoteIpDetails"]["organization"]["asn"]<line_sep>nacl_id=get_netacl_id(subnet_id account_id)<line_sep>hits=str(data["detail"]["service"]["count"])<line_sep>vpc_id=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["vpcId"]<line_sep>sg_name=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["securityGroups"][0]["groupName"]<line_sep>sg_id=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["securityGroups"][0]["groupId"]<line_sep>tags=(str(data["detail"]["resource"]["instanceDetails"]["tags"])).replace("," "")<line_sep>account_alias=str(get_account_alias(account_id))<line_sep>event_first_seen=str(data["detail"]["service"]["eventFirstSeen"])<line_sep>ioc=ttp+","+hits+","+account_id+","+account_alias+","+region+","+subnet_id+","+src_ip+","+instance_id+","+nacl_id+","+country+","+city+","+asn_org+","+org+","+isp+","+asn+","+vpc_id+","+sg_name+","+sg_id+","+tags+","+event_first_seen<line_sep>log.info("IOCs: "+str(ioc))<line_sep>put_to_s3(ioc)<if_stmt>len(json_a)<eq>0<block_start>json_a.append(ioc)<block_end><else_stmt><block_start><for_stmt>e json_a<block_start><if_stmt>e<ne>ioc<block_start>json_a.append(ioc)<block_end><block_end><block_end><block_end><block_end><elif_stmt>flag<eq>3<block_start>ioc=[]<line_sep>src_ip=(json.dumps(data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["ipAddressV4"])).strip('"')<line_sep>direction=data["detail"]["service"]["action"]["networkConnectionAction"]["connectionDirection"]<if_stmt>ipaddress.ip_address(src_ip).is_private<is><false><and>direction<eq>"INBOUND"<block_start>account_id=data["detail"]["accountId"]<line_sep>region=data["detail"]["region"]<line_sep>subnet_id=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["subnetId"]<line_sep>instance_id=data["detail"]["resource"]["instanceDetails"]["instanceId"]<line_sep>ttp=data["detail"]["type"]<line_sep>asn=data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["organization"]["asn"]<line_sep>asn_org=(data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["organization"]["asnOrg"]).replace("," " ")<line_sep>isp=(data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["organization"]["isp"]).replace("," " ")<line_sep>org=(data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["organization"]["org"]).replace("," " ")<line_sep>country=data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["country"]["countryName"]<try_stmt><block_start>city=str((data["detail"]["service"]["action"]["networkConnectionAction"]["remoteIpDetails"]["city"]["cityName"]).replace("," " "))<block_end><except_stmt>Exception<as>e<block_start>city="NIA"<block_end>nacl_id=get_netacl_id(subnet_id account_id)<line_sep>hits=str(data["detail"]["service"]["count"])<line_sep>vpc_id=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["vpcId"]<line_sep>sg_name=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["securityGroups"][0]["groupName"]<line_sep>sg_id=data["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["securityGroups"][0]["groupId"]<line_sep>tags=(str(data["detail"]["resource"]["instanceDetails"]["tags"])).replace("," "")<line_sep>account_alias=str(get_account_alias(account_id))<line_sep>event_first_seen=str(data["detail"]["service"]["eventFirstSeen"])<line_sep>ioc=ttp+","+hits+","+account_id+","+account_alias+","+region+","+subnet_id+","+src_ip+","+instance_id+","+nacl_id+","+country+","+city+","+asn_org+","+org+","+isp+","+asn+","+vpc_id+","+sg_name+","+sg_id+","+tags+","+event_first_seen<line_sep>log.info("IOCs: "+str(ioc))<line_sep>put_to_s3(ioc)<if_stmt>len(json_a)<eq>0<block_start>json_a.append(ioc)<block_end><else_stmt><block_start><for_stmt>e json_a<block_start><if_stmt>e<ne>ioc<block_start>json_a.append(ioc)<block_end><block_end><block_end><block_end><block_end><elif_stmt>flag<eq>4<block_start>ioc=[]<line_sep>src_ip=(json.dumps(data["detail"]["service"]["action"]["awsApiCallAction"]["remoteIpDetails"]["ipAddressV4"])).strip('"')<line_sep>account_id=data["detail"]["accountId"]<line_sep>region=data["detail"]["region"]<line_sep>ttp=data["detail"]["type"]<line_sep>asn=data["detail"]["service"]["action"]["awsApiCallAction"]["remoteIpDetails"]["organization"]["asn"]<line_sep>asn_org=(data["detail"]["service"]["action"]["awsApiCallAction"]["remoteIpDetails"]["organization"]["asnOrg"]).replace("," " ")<line_sep>isp=(data["detail"]["service"]["action"]["awsApiCallAction"]["remoteIpDetails"]["organization"]["isp"]).replace("," " ")<line_sep>org=(data["detail"]["service"]["action"]["awsApiCallAction"]["remoteIpDetails"]["organization"]["org"]).replace("," " ")<line_sep>country=data["detail"]["service"]["action"]["awsApiCallAction"]["remoteIpDetails"]["country"]["countryName"]<try_stmt><block_start>city=str((data["detail"]["service"]["action"]["awsApiCallAction"]["remoteIpDetails"]["city"]["cityName"]).replace("," " "))<block_end><except_stmt>Exception<as>e<block_start>city="NIA"<block_end>hits=str(data["detail"]["service"]["count"])<line_sep>account_alias=str(get_account_alias(account_id))<line_sep>event_first_seen=str(data["detail"]["service"]["eventFirstSeen"])<line_sep>subnet_id=instance_id=nacl_id=vpc_id=sg_name=sg_id=tags=""<line_sep>principal_id=data["detail"]["resource"]["accessKeyDetails"]["principalId"]<line_sep>user_name=data["detail"]["resource"]["accessKeyDetails"]["userName"]<line_sep>ioc=ttp+","+hits+","+account_id+","+account_alias+","+region+","+subnet_id+","+src_ip+","+instance_id+","+nacl_id+","+country+","+city+","+asn_org+","+org+","+isp+","+asn+","+vpc_id+","+sg_name+","+sg_id+","+tags+","+event_first_seen+","+principal_id+","+user_name<line_sep>log.info("IOCs: "+str(ioc))<line_sep>put_to_s3(ioc)<if_stmt>len(json_a)<eq>0<block_start>json_a.append(ioc)<block_end><else_stmt><block_start><for_stmt>e json_a<block_start><if_stmt>e<ne>ioc<block_start>json_a.append(ioc)<block_end><block_end><block_end><block_end><block_end><except_stmt>Exception<as>e<block_start>log.info("JSON could not be parsed:"+str(e))<block_end><block_end><block_end><def_stmt>get_netacl_id subnet_id account_id<block_start>log.info("Getting NACL id for subnet: "+str(subnet_id)+" account: "+str(account_id))<line_sep><global>HUB_ACCOUNT_ID<try_stmt><block_start>nacl_id=""<if_stmt>account_id<ne>HUB_ACCOUNT_ID<block_start>client=assume_role(account_id "client")<line_sep>response=client.describe_network_acls(Filters=[{'Name':'association.subnet-id' 'Values':[subnet_id ]}])<block_end><else_stmt><block_start>response=ec2.describe_network_acls(Filters=[{'Name':'association.subnet-id' 'Values':[subnet_id ]}])<block_end>nacls=response['NetworkAcls'][0]['Associations']<for_stmt>n nacls<block_start><if_stmt>n['SubnetId']<eq>subnet_id<block_start>nacl_id=n['NetworkAclId']<line_sep>log.info("NACL found:"+str(nacl_id))<block_end><block_end><return>nacl_id<block_end><except_stmt>Exception<as>e<block_start>log.info("Failed to get NACL id:"+str(e))<block_end><block_end><def_stmt>incident_and_response <block_start>log.info("Incident and Response Automation ...")<line_sep>ts=str(datetime.datetime.now())<line_sep>ujsa=set(json_a)<for_stmt>jsa ujsa<block_start>lst=jsa.split(",")<line_sep>ioc=len(lst)<line_sep>rule_no="-1"<if_stmt>ioc<eq>20<block_start>ttp,hits,account_id,account_alias,region,subnet_id,src_ip,instance_id,nacl_id,country,city,asn_org,org,isp,asn,vpc_id,sg_name,sg_id,tags,event_first_seen=jsa.split(",")<line_sep>lst_nacl=get_nacl_rule(nacl_id account_id)<line_sep>rule_no=int(lst_nacl.pop())<line_sep>result=create_nacl_rule(nacl_id src_ip rule_no account_id set(lst_nacl))<if_stmt>result<block_start>update_ioc(src_ip ts ttp hits region account_id account_alias nacl_id subnet_id instance_id country city asn_org org isp asn rule_no vpc_id sg_name sg_id tags event_first_seen)<line_sep>message_to_slack(jsa)<block_end><block_end><elif_stmt>ioc<eq>22<block_start>ttp,hits,account_id,account_alias,region,subnet_id,src_ip,instance_id,nacl_id,country,city,asn_org,org,isp,asn,vpc_id,sg_name,sg_id,tags,event_first_seen,principal_id,user_name=jsa.split(",")<line_sep>message_to_slack(jsa)<block_end><else_stmt><block_start>country=city=asn_org=org=isp=asn="NIA"<line_sep>ttp,account_id,account_alias,region,subnet_id,src_ip,instance_id,nacl_id,vpc_id,sg_name,sg_id,tags,event_first_seen=jsa.split(",")<line_sep>lst_nacl=get_nacl_rule(nacl_id account_id)<line_sep>rule_no=int(lst_nacl.pop())<line_sep>result=create_nacl_rule(nacl_id src_ip rule_no account_id set(lst_nacl))<if_stmt>result<block_start>update_ioc(src_ip ts ttp hits region account_id account_alias nacl_id subnet_id instance_id country city asn_org org isp asn rule_no vpc_id sg_name sg_id tags event_first_seen)<line_sep>message_to_slack(jsa)<block_end><block_end><block_end><block_end><def_stmt>get_nacl_rule nacl_id account_id<block_start>rule=get_rules(nacl_id account_id)<line_sep>log.info("Getting rule number (entry) for NACL: "+str(nacl_id)+" account: "+str(account_id))<line_sep>lst_no=[]<line_sep>lst_cidr=[]<for_stmt>r rule<block_start>no,cidr=r.split(",")<line_sep>lst_no.append(int(no))<line_sep>lst_cidr.append(cidr)<block_end>i=int(min(lst_no))+1<if_stmt>int(min(lst_no))<eq>100<block_start>rule_no=1<block_end><else_stmt><block_start>count=1<while_stmt>count<l>98<block_start>count<augadd>1<if_stmt>i<l>100<and>i<not><in>lst_no<block_start>rule_no=i<line_sep><break><block_end><else_stmt><block_start>i<augadd>1<block_end><block_end><block_end>log.info("Rule number (entry): "+str(rule_no))<line_sep>log.info("CIDR already added: "+str(set(lst_cidr)))<line_sep>lst_cidr.append(str(rule_no))<line_sep><return>lst_cidr<block_end><def_stmt>get_rules nacl_id account_id<block_start>log.info("Getting rules for NACL: "+str(nacl_id)+" account: "+str(account_id))<line_sep><global>HUB_ACCOUNT_ID<line_sep>rules=[]<if_stmt>account_id<ne>HUB_ACCOUNT_ID<block_start>client=assume_role(account_id "client")<line_sep>response=client.describe_network_acls(NetworkAclIds=[nacl_id ] )<block_end><else_stmt><block_start>response=ec2.describe_network_acls(NetworkAclIds=[nacl_id ] )<block_end>data=response['NetworkAcls'][0]['Entries']<for_stmt>d data<block_start>entry=str(d['RuleNumber'])+","+str(d['CidrBlock'])<line_sep>rules.append(entry)<block_end><return>rules<block_end><def_stmt>create_nacl_rule nacl_id attacker_ip rule_no account_id lst_nacl<block_start><global>HUB_ACCOUNT_ID<line_sep>log.info("Creating NACL rule for attacker:"+str(attacker_ip))<if_stmt>attacker_ip+'/32'<not><in>lst_nacl<and>len(lst_nacl)<le>18<block_start><if_stmt>account_id<ne>HUB_ACCOUNT_ID<block_start>client=assume_role(account_id "resource")<line_sep>nacl=client.NetworkAcl(nacl_id)<block_end><else_stmt><block_start>nacl=r_ec2.NetworkAcl(nacl_id)<block_end>response=nacl.create_entry(CidrBlock=attacker_ip+'/32' Egress=<false> PortRange={'From':0 'To':65535} Protocol='-1' RuleAction='deny' RuleNumber=rule_no)<if_stmt>response['ResponseMetadata']['HTTPStatusCode']<eq>200<block_start><return><true><block_end><else_stmt><block_start><return><false><block_end><block_end><elif_stmt>len(lst_nacl)<eq>20<block_start>log.info("NACL is full, no more than 18 entries can be added")<block_end><else_stmt><block_start>log.info("Attacker is already blocked")<block_end><block_end><def_stmt>get_account_alias account_id<block_start>log.info("Getting alias for account: "+str(account_id))<line_sep><global>HUB_ACCOUNT_ID<line_sep>rules=[]<if_stmt>account_id<ne>HUB_ACCOUNT_ID<block_start>client=assume_role(account_id "iam")<line_sep>response=client.list_account_aliases()<block_end><else_stmt><block_start>response=iam.list_account_aliases()<block_end>alias=str(response['AccountAliases'])<line_sep>result=alias[2:-2]<line_sep><return>result<block_end><def_stmt>update_ioc attacker_ip timestamp ttp hits region account_id account_alias nacl_id subnet_id instance_id country city asn_org org isp asn rule_no vpc_id sg_name sg_id tags event_first_seen<block_start>log.info("Sending IOCs to DynamoDB ...")<try_stmt><block_start>table=dynamodb.Table(DYNAMO_TABLE)<line_sep>scan=table.scan()<if_stmt>scan['Items']<block_start>updated=0<for_stmt>s scan['Items']<block_start><if_stmt>s['attacker_ip']<eq>attacker_ip<block_start>update_entry_attackers(attacker_ip hits rule_no <false>)<line_sep>updated=1<block_end><block_end><if_stmt>updated<eq>0<block_start>create_entry_attackers(attacker_ip timestamp ttp hits region account_id account_alias nacl_id subnet_id instance_id country city asn_org org isp asn rule_no vpc_id sg_name sg_id tags event_first_seen)<block_end><block_end><else_stmt><block_start>create_entry_attackers(attacker_ip timestamp ttp hits region account_id account_alias nacl_id subnet_id instance_id country city asn_org org isp asn rule_no vpc_id sg_name sg_id tags event_first_seen)<block_end><block_end><except_stmt>Exception<as>e<block_start>log.info("DynamoDB entry could not be updated"+str(e))<block_end><block_end><def_stmt>update_entry_attackers attacker_ip hits rule_no deleted<block_start>table=dynamodb.Table(DYNAMO_TABLE)<try_stmt><block_start><if_stmt><not>deleted<block_start>log.info("Updating new DynamoDB entry for attacker: "+str(attacker_ip))<line_sep>response=table.update_item(Key={'attacker_ip':attacker_ip} UpdateExpression="set hits = :h, rule_no = :r_no" ExpressionAttributeValues={':h':hits ':r_no':rule_no} ReturnValues="UPDATED_NEW")<line_sep><return><block_end><else_stmt><block_start>log.info("Updating cleaned (NACL) DynamoDB entry for attacker: "+str(attacker_ip))<line_sep>response=table.update_item(Key={'attacker_ip':attacker_ip} UpdateExpression="set hits = :h, rule_no = :r_no" ExpressionAttributeValues={':h':hits ':r_no':rule_no} ReturnValues="UPDATED_NEW")<line_sep><return><block_end><block_end><except_stmt>Exception<as>e<block_start>log.info("DynamoDB could not be updated:"+str(e))<block_end><block_end><def_stmt>create_entry_attackers attacker_ip timestamp ttp hits region account_id account_alias nacl_id subnet_id instance_id country city asn_org org isp asn rule_no vpc_id sg_name sg_id tags event_first_seen<block_start><if_stmt><not>city<block_start>city="NIA"<block_end>log.info("Creating DynamoDB entry for attacker:"+str(attacker_ip))<try_stmt><block_start>table=dynamodb.Table(DYNAMO_TABLE)<line_sep>response=table.put_item(Item={'attacker_ip':str(attacker_ip) 'timestamp':str(timestamp) 'ttp':str(ttp) 'hits':str(hits) 'region':str(region) 'account_id':str(account_id) 'account_alias':str(account_alias) 'vpc_id':str(vpc_id) 'nacl_id':str(nacl_id) 'subnet_id':str(subnet_id) 'instance_id':str(instance_id) 'tags':str(tags) 'sg_name':str(sg_name) 'sg_id':str(sg_id) 'country':str(country) 'city':str(city) 'asn_org':str(asn_org) 'org':str(org) 'isp':str(isp) 'asn':str(asn) 'rule_no':str(rule_no) 'event_first_seen':str(event_first_seen)})<block_end><except_stmt>Exception<as>e<block_start>log.info("DynamoDB entry could not be created"+str(e))<block_end><block_end><def_stmt>assume_role account_id boto_type<block_start><global>ROLE_SPOKE<line_sep>log.info("Assuming role: "+str(ROLE_SPOKE)+" account: "+str(account_id))<try_stmt><block_start>sts=sts_connection.assume_role(RoleArn="arn:aws:iam::"+account_id+":role/"+ROLE_SPOKE RoleSessionName="cross_acct_lambda")<line_sep>ACCESS_KEY=sts['Credentials']['AccessKeyId']<line_sep>SECRET_KEY=sts['Credentials']['SecretAccessKey']<line_sep>SESSION_TOKEN=sts['Credentials']['SessionToken']<if_stmt>boto_type<eq>"resource"<block_start>client=boto3.resource('ec2' aws_access_key_id=ACCESS_KEY aws_secret_access_key=SECRET_KEY aws_session_token=SESSION_TOKEN )<block_end><elif_stmt>boto_type<eq>"client"<block_start>client=boto3.client('ec2' aws_access_key_id=ACCESS_KEY aws_secret_access_key=SECRET_KEY aws_session_token=SESSION_TOKEN )<block_end><elif_stmt>boto_type<eq>"iam"<block_start>client=boto3.client('iam' aws_access_key_id=ACCESS_KEY aws_secret_access_key=SECRET_KEY aws_session_token=SESSION_TOKEN )<block_end><return>client<block_end><except_stmt>Exception<as>e<block_start>log.info("Role could not be assumed"+str(e))<block_end><block_end><def_stmt>clean_nacls <block_start><global>HUB_ACCOUNT_ID<line_sep>log.info("Cleaning old NACLs entries ... ")<try_stmt><block_start>now=datetime.datetime.now()<line_sep>table=dynamodb.Table(DYNAMO_TABLE)<line_sep>response=table.scan()<for_stmt>r response['Items']<block_start><if_stmt>str(r['rule_no'])<ne>"0"<block_start>t=r['timestamp']<line_sep>account=r['account_id']<line_sep>log.info("Searching for oldest entries in the account: "+str(account)+" attacker: "+str(r['attacker_ip']))<line_sep>old=datetime.datetime.strptime(t '%Y-%m-%d %H:%M:%S.%f')<line_sep>difh=((now-old).days<times>24)+int((now-old).seconds/3600)<line_sep>log.info("Hours that remained blocked: "+str(difh))<if_stmt>difh<ge>6<block_start>log.info("Cleaning NACL entry: "+str(r['rule_no'])+" account: "+str(account))<try_stmt><block_start><if_stmt>account<ne>HUB_ACCOUNT_ID<block_start>client=assume_role(account "resource")<line_sep>network_acl=client.NetworkAcl(r['nacl_id'])<block_end><else_stmt><block_start>network_acl=r_ec2.NetworkAcl(r['nacl_id'])<block_end>response2=network_acl.delete_entry(Egress=<false> RuleNumber=int(r['rule_no']))<if_stmt>response2['ResponseMetadata']['HTTPStatusCode']<eq>200<block_start>log.info("NACL rule deleted for attacker: "+str(r['attacker_ip']))<line_sep>update_entry_attackers(str(r['attacker_ip']) str(r['hits']) "0" <true>)<line_sep><return><block_end><else_stmt><block_start>log.info("Failed to delete the entry")<block_end><block_end><except_stmt>Exception<as>e<block_start>log.info("Failed to instantiate resource NetworkAcl "+str(e))<line_sep>log.info("Updating IOCs db to keep consistency ... "+str(e))<try_stmt><block_start>update_entry_attackers(str(r['attacker_ip']) str(r['hits']) "0" <true>)<block_end><except_stmt>Exception<as>e<block_start>log.info("Updating IOCs db to keep consistency failed: "+str(e))<block_end><block_end><block_end><block_end><block_end><block_end><except_stmt>Exception<as>e<block_start>log.info("NACLs could not be deleted: "+str(e))<block_end><block_end><def_stmt>message_to_slack ioc<block_start>lst=ioc.split(",")<line_sep>ioc_len=len(lst)<try_stmt><block_start><if_stmt>ioc_len<eq>20<block_start>ttp,hits,account_id,account_alias,region,subnet_id,src_ip,instance_id,nacl_id,country,city,asn_org,org,isp,asn,vpc_id,sg_name,sg_id,tags,event_first_seen=ioc.split(",")<line_sep>nacl_url="https://console.aws.amazon.com/vpc/home?region="+region+"#acls:networkAclId="+nacl_id+";sort=networkAclId"<line_sep>data={'text':'***************************************************************\n\n'+'*ATTACKER IP:* '+src_ip+' *HITS:* '+hits+'\n'+'*TTP:* '+ttp+'\n'+'*ACCOUNT ID:* '+'`'+account_id+'`'+' *ACCOUNT ALIAS:* '+account_alias+' *INSTANCE ID:* '+'`'+instance_id+'`'+'\n'+'*TAGS:* '+tags+'\n'+'*NACL:* '+nacl_url+'\n'+'*VPC ID:* '+'`'+vpc_id+'`'+' *SUBNET ID:* '+'`'+subnet_id+'`'+'\n'+'*COUNTRY:* '+country+' *CITY:* '+city+'\n'+'*ASN ORG:* '+asn_org+' *ORG:* '+org+' *ISP:* '+isp+'\n'+'*FIRST SEEN:* '+event_first_seen+'\n'+'***************************************************************' 'username':'CLOUD SNIPER BUDDY' 'icon_emoji':':robot_face:'}<block_end><else_stmt><block_start>ttp,hits,account_id,account_alias,region,subnet_id,src_ip,instance_id,nacl_id,country,city,asn_org,org,isp,asn,vpc_id,sg_name,sg_id,tags,event_first_seen,principal_id,user_name=ioc.split(",")<line_sep>data={'text':'***************************************************************\n\n'+'*ATTACKER IP:* '+src_ip+' *HITS:* '+hits+'\n'+'*TTP:* '+ttp+'\n'+'*ACCOUNT ID:* '+'`'+account_id+'`'+' *ACCOUNT ALIAS:* '+account_alias+'\n'+'*COUNTRY:* '+country+' *CITY:* '+city+'\n'+'*ASN ORG:* '+asn_org+' *ORG:* '+org+' *ISP:* '+isp+'\n'+'*FIRST SEEN:* '+event_first_seen+'\n'+'*USER NAME:* '+user_name+' *PRINCIPAL ID:* '+principal_id+'\n'+'*DESCRIPTION:* API DescribeAlarms, commonly used in reconnaissance attacks, was invoked from a Tor exit node IP address. The threat intelligence feed does not provide resource details, so there is no automatic blocking. The user must be investigated'+'\n'+'***************************************************************' 'username':'CLOUD SNIPER BUDDY' 'icon_emoji':':robot_face:'}<block_end>response=requests.post(WEBHOOK_URL data=json.dumps(data) headers={'Content-Type':'application/json'})<line_sep>log.info('Sending message to Slack. Response: '+str(response.text)+' Response Code: '+str(response.status_code))<block_end><except_stmt>Exception<as>e<block_start>log.info("Message could not be send to Slack: "+str(e))<block_end><block_end><def_stmt>delete_sqs <block_start>log.info("Deleting queue ...")<try_stmt><block_start><for_stmt>rh message<block_start>receipt_handle=rh['ReceiptHandle']<line_sep>sqs.delete_message(QueueUrl=QUEUE_URL ReceiptHandle=receipt_handle)<line_sep>log.info('Processed and deleted message: %s'%receipt_handle)<block_end><block_end><except_stmt>Exception<as>e<block_start>log.info("SQS queue could not be deleted"+str(e))<block_end><block_end><def_stmt>put_to_s3 ioc<block_start>log.info("Sending findings to S3 ...")<line_sep>lst=ioc.split(",")<line_sep>ioc_len=len(lst)<if_stmt>ioc_len<eq>20<block_start>ttp,hits,account_id,account_alias,region,subnet_id,src_ip,instance_id,nacl_id,country,city,asn_org,org,isp,asn,vpc_id,sg_name,sg_id,tags,event_first_seen=ioc.split(",")<line_sep>dataset={'ttp':str(ttp) 'hits':str(hits) 'cloud.account.id':str(account_id) 'cloud.account.name':str(account_alias) 'cloud.region':str(region) 'interface.subnet.id':str(subnet_id) 'source.ip':str(src_ip) 'cloud.instance.id':str(instance_id) 'interface.nacl.id':str(nacl_id) 'country':str(country) 'city':str(city) 'asn_org':str(asn_org) 'org':str(org) 'isp':str(isp) 'asn':str(asn) 'interface.vpc.id':str(vpc_id) 'interface.security_group.name':str(sg_name) 'interface.security_group.id':str(sg_id) 'tags':str(tags) 'timestamp':str(event_first_seen) 'cloud.provider':'aws'}<block_end><else_stmt># 22
<block_start>ttp,hits,account_id,account_alias,region,subnet_id,src_ip,instance_id,nacl_id,country,city,asn_org,org,isp,asn,vpc_id,sg_name,sg_id,tags,event_first_seen,principal_id,user_name=ioc.split(",")<line_sep>dataset={'ttp':str(ttp) 'hits':str(hits) 'cloud.account.id':str(account_id) 'cloud.account.name':str(account_alias) 'cloud.region':str(region) 'source.ip':str(src_ip) 'country':str(country) 'city':str(city) 'asn_org':str(asn_org) 'org':str(org) 'isp':str(isp) 'asn':str(asn) 'timestamp':str(event_first_seen) 'cloud.provider':'aws' 'cloud.principal_id':str(principal_id) 'cloud.user_name':str(user_name)}<block_end>NOW=datetime.datetime.now().strftime("%Y%m%d_%H%M%S")<line_sep>s3_resource=boto3.resource('s3')<line_sep>bucket_name=BUCKET_NAME<line_sep>iocs_path=IOCS_PATH<line_sep>bucket=s3_resource.Bucket(name=bucket_name)<if_stmt>iocs_path.startswith("/")<block_start>iocs_path=iocs_path[1:]<block_end><if_stmt>iocs_path.endswith("/")<block_start>iocs_path=iocs_path[:-1]<block_end><try_stmt><block_start>(bucket.Object(key=f"{iocs_path}/iocs_{NOW}.json").put(Body=bytes(json.dumps(dataset).encode('UTF-8'))))<block_end><except_stmt>Exception<as>e<block_start>log.info("Could not put the object to S3"+str(e))<block_end><block_end><def_stmt>publish_to_sns <block_start>publish_object={"Message":"TOR"}<try_stmt><block_start>response=sns.publish(TopicArn=TOPIC_ARN Message=json.dumps(publish_object) Subject="IR")<line_sep>log.info("Publish to SNS: "+str(response['ResponseMetadata']['HTTPStatusCode']))<block_end><except_stmt>Exception<as>e<block_start>log.info("Could not publish to SNS "+str(e))<block_end><block_end><def_stmt>cloud_sniper_threat_intelligence event context<block_start><global>message<line_sep>log.info("Processing GuardDuty findings: %s"%json.dumps(event))<try_stmt><block_start>clean_nacls()<line_sep>message=read_sqs()<if_stmt>message<block_start>search_ioc()<line_sep>incident_and_response()<line_sep>delete_sqs()<line_sep>log.info("Findings properly processed")<block_end><block_end><except_stmt>Exception<as>e<block_start>log.error('Failure to process finding '+str(e))<block_end><block_end> |
<import_stmt>autograd.numpy<as>anp<import_stmt>numpy<as>np<import_from_stmt>autograd value_and_grad<import_from_stmt>pymoo.factory normalize<import_from_stmt>pymoo.util.ref_dirs.energy squared_dist<import_from_stmt>pymoo.util.ref_dirs.optimizer Adam<import_from_stmt>pymoo.util.reference_direction ReferenceDirectionFactory scale_reference_directions<class_stmt>LayerwiseRieszEnergyReferenceDirectionFactory(ReferenceDirectionFactory)<block_start><def_stmt>__init__ self n_dim partitions return_as_tuple=<false> n_max_iter=1000 verbose=<false> X=<none> **kwargs<block_start>super().__init__(n_dim **kwargs)<line_sep>self.scalings=<none><line_sep>self.n_max_iter=n_max_iter<line_sep>self.verbose=verbose<line_sep>self.return_as_tuple=return_as_tuple<line_sep>self.X=X<line_sep>self.partitions=partitions<block_end><def_stmt>_step self optimizer X scalings<block_start>obj,grad=value_and_grad(calc_potential_energy)(scalings X)<line_sep>scalings=optimizer.next(scalings np.array(grad))<line_sep>scalings=normalize(scalings xl=0 xu=scalings.max())<line_sep><return>scalings obj<block_end><def_stmt>_solve self X scalings# initialize the optimizer for the run
<block_start>optimizer=Adam()<line_sep># for each iteration of gradient descent
<for_stmt>i range(self.n_max_iter)# execute one optimization step
<block_start>_scalings,_obj=self._step(optimizer X scalings)<line_sep># evaluate how much the points have moved
delta=np.abs(_scalings-scalings).sum()<if_stmt>self.verbose<block_start>print(i "objective" _obj "delta" delta)<block_end># if there was only a little delta during the last iteration -> terminate
<if_stmt>delta<l>1e-5<block_start>scalings=_scalings<line_sep><break><block_end># otherwise use the new points for the next iteration
scalings=_scalings<block_end>self.scalings=scalings<line_sep><return>get_points(X scalings)<block_end><def_stmt>do self<block_start>X=[]<line_sep>scalings=[]<for_stmt>k,p enumerate(self.partitions)<block_start><if_stmt>p<g>1<block_start>val=np.linspace(0 1 p+1)[1:-1]<line_sep>_X=[]<for_stmt>i range(self.n_dim)<block_start><for_stmt>j range(i+1 self.n_dim)<block_start>x=np.zeros((len(val) self.n_dim))<line_sep>x[: i]=val<line_sep>x[: j]=1-val<line_sep>_X.append(x)<block_end><block_end>X.append(np.row_stack(_X+[np.eye(self.n_dim)]))<block_end><elif_stmt>p<eq>1<block_start>X.append(np.eye(self.n_dim))<block_end><else_stmt><block_start>X.append(np.full(self.n_dim 1/self.n_dim)[<none> :])<block_end>scalings.append(1-k/len(self.partitions))<block_end>scalings=np.array(scalings)<line_sep>X=self._solve(X scalings)<line_sep><return>X<block_end><block_end># ---------------------------------------------------------------------------------------------------------
# Energy Functions
# ---------------------------------------------------------------------------------------------------------
<def_stmt>get_points X scalings<block_start>vals=[]<for_stmt>i range(len(X))<block_start>vals.append(scale_reference_directions(X[i] scalings[i]))<block_end>X=anp.row_stack(vals)<line_sep><return>X<block_end><def_stmt>calc_potential_energy scalings X<block_start>X=get_points(X scalings)<line_sep>i,j=anp.triu_indices(len(X) 1)<line_sep>D=squared_dist(X X)[i j]<if_stmt>np.any(D<l>1e-12)<block_start><return>np.nan np.nan<block_end><return>(1/D).mean()<block_end> |
<import_stmt>torch<import_from_stmt>torch Tensor<import_from_stmt>torch.utils.data Dataset<import_from_stmt>torchvision io<import_from_stmt>pathlib Path<import_from_stmt>typing Tuple<import_from_stmt>torchvision transforms<as>T<class_stmt>CelebAMaskHQ(Dataset)<block_start>CLASSES=['background' 'skin' 'nose' 'eye_g' 'l_eye' 'r_eye' 'l_brow' 'r_brow' 'l_ear' 'r_ear' 'mouth' 'u_lip' 'l_lip' 'hair' 'hat' 'ear_r' 'neck_l' 'neck' 'cloth']<line_sep>PALETTE=torch.tensor([[0 0 0] [204 0 0] [76 153 0] [204 204 0] [51 51 255] [204 0 204] [0 255 255] [255 204 204] [102 51 0] [255 0 0] [102 204 0] [255 255 0] [0 0 153] [0 0 204] [255 51 153] [0 204 204] [0 51 0] [255 153 51] [0 204 0]])<def_stmt>__init__ self root:str split:str='train' transform=<none><arrow><none><block_start>super().__init__()<assert_stmt>split<in>['train' 'val' 'test']<line_sep>self.root=Path(root)<line_sep>self.transform=transform<line_sep>self.n_classes=len(self.CLASSES)<line_sep>self.ignore_label=255<line_sep>self.resize=T.Resize((512 512))<with_stmt>open(self.root/f'{split}_list.txt')<as>f<block_start>self.files=f.read().splitlines()<block_end><if_stmt><not>self.files<block_start><raise>Exception(f"No images found in {root}")<block_end>print(f"Found {len(self.files)} {split} images.")<block_end><def_stmt>__len__ self<arrow>int<block_start><return>len(self.files)<block_end><def_stmt>__getitem__ self index:int<arrow>Tuple[Tensor Tensor]<block_start>img_path=self.root/'CelebA-HQ-img'/f"{self.files[index]}.jpg"<line_sep>lbl_path=self.root/'CelebAMask-HQ-label'/f"{self.files[index]}.png"<line_sep>image=io.read_image(str(img_path))<line_sep>image=self.resize(image)<line_sep>label=io.read_image(str(lbl_path))<if_stmt>self.transform<block_start>image,label=self.transform(image label)<block_end><return>image label.squeeze().long()<block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start><import_from_stmt>semseg.utils.visualize visualize_dataset_sample<line_sep>visualize_dataset_sample(CelebAMaskHQ '/home/sithu/datasets/CelebAMask-HQ')<block_end> |
<import_from_stmt>mushroom_rl.utils.table Table<def_stmt>EligibilityTrace shape name='replacing'<block_start>"""
Factory method to create an eligibility trace of the provided type.
Args:
shape (list): shape of the eligibility trace table;
name (str, 'replacing'): type of the eligibility trace.
Returns:
The eligibility trace table of the provided shape and type.
"""<if_stmt>name<eq>'replacing'<block_start><return>ReplacingTrace(shape)<block_end><elif_stmt>name<eq>'accumulating'<block_start><return>AccumulatingTrace(shape)<block_end><else_stmt><block_start><raise>ValueError('Unknown type of trace.')<block_end><block_end><class_stmt>ReplacingTrace(Table)<block_start>"""
Replacing trace.
"""<def_stmt>reset self<block_start>self.table[:]=0.<block_end><def_stmt>update self state action<block_start>self.table[state action]=1.<block_end><block_end><class_stmt>AccumulatingTrace(Table)<block_start>"""
Accumulating trace.
"""<def_stmt>reset self<block_start>self.table[:]=0.<block_end><def_stmt>update self state action<block_start>self.table[state action]<augadd>1.<block_end><block_end> |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license.
<import_stmt>sys<import_stmt>iotc<import_from_stmt>iotc IOTConnectType IOTLogLevel<import_from_stmt>random randint<import_stmt>base64<import_stmt>hmac<import_stmt>hashlib<line_sep>gIsMicroPython=('implementation'<in>dir(sys))<and>('name'<in>dir(sys.implementation))<and>(sys.implementation.name<eq>'micropython')<def_stmt>computeKey secret regId<block_start><global>gIsMicroPython<try_stmt><block_start>secret=base64.b64decode(secret)<block_end><except_stmt><block_start>print("ERROR: broken base64 secret => `"+secret+"`")<line_sep>sys.exit()<block_end><if_stmt>gIsMicroPython<eq><false><block_start><return>base64.b64encode(hmac.new(secret msg=regId.encode('utf8') digestmod=hashlib.sha256).digest())<block_end><else_stmt><block_start><return>base64.b64encode(hmac.new(secret msg=regId.encode('utf8') digestmod=hashlib._sha256.sha256).digest())<block_end><block_end>deviceId="DEVICE_ID"<line_sep>scopeId="SCOPE_ID"<line_sep>masterKey="PRIMARY/SECONDARY master Key"<line_sep>deviceKey=computeKey(masterKey deviceId)<line_sep>iotc=iotc.Device(scopeId deviceKey deviceId IOTConnectType.IOTC_CONNECT_SYMM_KEY)<line_sep>iotc.setLogLevel(IOTLogLevel.IOTC_LOGGING_API_ONLY)<line_sep>gCanSend=<false><line_sep>gCounter=0<def_stmt>onconnect info<block_start><global>gCanSend<line_sep>print("- [onconnect] => status:"+str(info.getStatusCode()))<if_stmt>info.getStatusCode()<eq>0<block_start><if_stmt>iotc.isConnected()<block_start>gCanSend=<true><block_end><block_end><block_end><def_stmt>onmessagesent info<block_start>print("\t- [onmessagesent] => "+str(info.getPayload()))<block_end><def_stmt>oncommand info<block_start>print("- [oncommand] => "+info.getTag()+" => "+str(info.getPayload()))<block_end><def_stmt>onsettingsupdated info<block_start>print("- [onsettingsupdated] => "+info.getTag()+" => "+info.getPayload())<block_end>iotc.on("ConnectionStatus" onconnect)<line_sep>iotc.on("MessageSent" onmessagesent)<line_sep>iotc.on("Command" oncommand)<line_sep>iotc.on("SettingsUpdated" onsettingsupdated)<line_sep>iotc.connect()<while_stmt>iotc.isConnected()<block_start>iotc.doNext()# do the async work needed to be done for MQTT
<if_stmt>gCanSend<eq><true><block_start><if_stmt>gCounter%20<eq>0<block_start>gCounter=0<line_sep>print("Sending telemetry..")<line_sep>iotc.sendTelemetry("{ \
\"temp\": "+str(randint(20 45))+", \
\"accelerometerX\": "+str(randint(2 15))+", \
\"accelerometerY\": "+str(randint(3 9))+", \
\"accelerometerZ\": "+str(randint(1 4))+"}")<block_end>gCounter<augadd>1<block_end><block_end> |
"""
Experiments with infix operator dispatch
>>> kadd = KnowsAdd()
>>> kadd + 1
(<KnowsAdd object>, 1)
>>> kadd * 1
"""<class_stmt>KnowsAdd<block_start><def_stmt>__add__ self other<block_start><return>self other<block_end><def_stmt>__repr__ self<block_start><return>'<{} object>'.format(type(self).__name__)<block_end><block_end> |
# Copyright (c) 2014 OpenStack Foundation
#
# 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_stmt>abc<import_stmt>os<import_stmt>xml.dom.minidom<as>xml<import_from_stmt>oslo_config cfg<import_from_stmt>oslo_utils uuidutils<import_stmt>six<import_from_stmt>sahara conductor<as>c<import_from_stmt>sahara context<import_from_stmt>sahara.service.edp base_engine<import_from_stmt>sahara.service.edp hdfs_helper<as>h<import_from_stmt>sahara.service.edp.job_binaries manager<as>jb_manager<import_from_stmt>sahara.service.edp job_utils<import_from_stmt>sahara.service.edp.oozie oozie<as>o<import_from_stmt>sahara.service.edp.oozie.workflow_creator workflow_factory<import_from_stmt>sahara.service.validations.edp job_execution<as>j<import_from_stmt>sahara.utils edp<import_from_stmt>sahara.utils remote<import_from_stmt>sahara.utils xmlutils<as>x<line_sep>CONF=cfg.CONF<line_sep>conductor=c.API<line_sep>@six.add_metaclass(abc.ABCMeta)<class_stmt>OozieJobEngine(base_engine.JobEngine)<block_start><def_stmt>__init__ self cluster<block_start>self.cluster=cluster<line_sep>self.plugin=job_utils.get_plugin(self.cluster)<block_end><def_stmt>get_remote_client self<block_start><return>o.RemoteOozieClient(self.get_oozie_server_uri(self.cluster) self.get_oozie_server(self.cluster) self.get_hdfs_user())<block_end><def_stmt>get_client self# by default engine will return standard oozie client implementation
<block_start><return>o.OozieClient(self.get_oozie_server_uri(self.cluster) self.get_oozie_server(self.cluster))<block_end><def_stmt>_get_oozie_job_params self hdfs_user path_to_workflow oozie_params use_hbase_lib scheduled_params=<none> job_dir=<none> job_execution_type=<none><block_start>oozie_libpath_key="oozie.libpath"<line_sep>oozie_libpath=""<line_sep>rm_path=self.get_resource_manager_uri(self.cluster)<line_sep>nn_path=self.get_name_node_uri(self.cluster)<line_sep>hbase_common_lib_path="%s%s"%(nn_path h.HBASE_COMMON_LIB_PATH)<if_stmt>use_hbase_lib<block_start><if_stmt>oozie_libpath_key<in>oozie_params<block_start>oozie_libpath="%s,%s"%(oozie_params.get(oozie_libpath_key "") hbase_common_lib_path)<block_end><else_stmt><block_start>oozie_libpath=hbase_common_lib_path<block_end><block_end><if_stmt>job_execution_type<eq>"scheduled"<block_start>app_path="oozie.coord.application.path"<line_sep>job_parameters={"start":scheduled_params.get('start') "end":scheduled_params.get('end') "frequency":scheduled_params.get('frequency') "workflowAppUri":"%s%s"%(nn_path job_dir) app_path:"%s%s"%(nn_path job_dir)}<block_end><else_stmt><block_start>app_path="oozie.wf.application.path"<line_sep>job_parameters={app_path:"%s%s"%(nn_path path_to_workflow)}<block_end>job_parameters["nameNode"]=nn_path<line_sep>job_parameters["user.name"]=hdfs_user<line_sep>job_parameters["jobTracker"]=rm_path<line_sep>job_parameters[oozie_libpath_key]=oozie_libpath<line_sep>job_parameters["oozie.use.system.libpath"]="true"<line_sep># Don't let the application path be overwritten, that can't
# possibly make any sense
<if_stmt>app_path<in>oozie_params<block_start><del_stmt>oozie_params[app_path]<block_end><if_stmt>oozie_libpath_key<in>oozie_params<block_start><del_stmt>oozie_params[oozie_libpath_key]<block_end>job_parameters.update(oozie_params)<line_sep><return>job_parameters<block_end><def_stmt>_upload_workflow_file self where job_dir wf_xml hdfs_user<block_start><with_stmt>remote.get_remote(where)<as>r<block_start>h.put_file_to_hdfs(r wf_xml "workflow.xml" job_dir hdfs_user)<block_end><return>"%s/workflow.xml"%job_dir<block_end><def_stmt>_upload_coordinator_file self where job_dir wf_xml hdfs_user<block_start><with_stmt>remote.get_remote(where)<as>r<block_start>h.put_file_to_hdfs(r wf_xml "coordinator.xml" job_dir hdfs_user)<block_end><return>"%s/coordinator.xml"%job_dir<block_end><def_stmt>cancel_job self job_execution<block_start><if_stmt>job_execution.engine_job_id<is><not><none><block_start>client=self.get_client()<line_sep>client.kill_job(job_execution)<line_sep><return>client.get_job_info(job_execution)<block_end><block_end><def_stmt>get_job_status self job_execution<block_start><if_stmt>job_execution.engine_job_id<is><not><none><block_start><return>self.get_client().get_job_info(job_execution)<block_end><block_end><def_stmt>_prepare_run_job self job_execution<block_start>ctx=context.ctx()<line_sep># This will be a dictionary of tuples, (native_url, runtime_url)
# keyed by data_source id
data_source_urls={}<line_sep>prepared_job_params={}<line_sep>job=conductor.job_get(ctx job_execution.job_id)<line_sep>input_source,output_source=job_utils.get_input_output_data_sources(job_execution job data_source_urls self.cluster)<line_sep># Updated_job_configs will be a copy of job_execution.job_configs with
# any name or uuid references to data_sources resolved to paths
# assuming substitution is enabled.
# If substitution is not enabled then updated_job_configs will
# just be a reference to job_execution.job_configs to avoid a copy.
# Additional_sources will be a list of any data_sources found.
additional_sources,updated_job_configs=(job_utils.resolve_data_source_references(job_execution.job_configs job_execution.id data_source_urls self.cluster))<line_sep>job_execution=conductor.job_execution_update(ctx job_execution {"data_source_urls":job_utils.to_url_dict(data_source_urls)})<line_sep># Now that we've recorded the native urls, we can switch to the
# runtime urls
data_source_urls=job_utils.to_url_dict(data_source_urls runtime=<true>)<line_sep>data_sources=additional_sources+[input_source output_source]<line_sep>job_utils.prepare_cluster_for_ds(data_sources self.cluster updated_job_configs data_source_urls)<line_sep>proxy_configs=updated_job_configs.get('proxy_configs')<line_sep>configs=updated_job_configs.get('configs' {})<line_sep>use_hbase_lib=configs.get('edp.hbase_common_lib' {})<line_sep># Extract all the 'oozie.' configs so that they can be set in the
# job properties file. These are config values for Oozie itself,
# not the job code
oozie_params={}<for_stmt>k list(configs)<block_start><if_stmt>k.startswith('oozie.')<block_start>oozie_params[k]=configs[k]<block_end><block_end>external_hdfs_urls=self._resolve_external_hdfs_urls(job_execution.job_configs)<for_stmt>url external_hdfs_urls<block_start>h.configure_cluster_for_hdfs(self.cluster url)<block_end>hdfs_user=self.get_hdfs_user()<line_sep># TODO(tmckay): this should probably be "get_namenode"
# but that call does not exist in the oozie engine api now.
oozie_server=self.get_oozie_server(self.cluster)<line_sep>wf_dir=self._create_hdfs_workflow_dir(oozie_server job)<line_sep>self._upload_job_files_to_hdfs(oozie_server wf_dir job configs proxy_configs)<line_sep>wf_xml=workflow_factory.get_workflow_xml(job self.cluster updated_job_configs input_source output_source hdfs_user data_source_urls)<line_sep>path_to_workflow=self._upload_workflow_file(oozie_server wf_dir wf_xml hdfs_user)<line_sep>prepared_job_params['context']=ctx<line_sep>prepared_job_params['hdfs_user']=hdfs_user<line_sep>prepared_job_params['path_to_workflow']=path_to_workflow<line_sep>prepared_job_params['use_hbase_lib']=use_hbase_lib<line_sep>prepared_job_params['job_execution']=job_execution<line_sep>prepared_job_params['oozie_params']=oozie_params<line_sep>prepared_job_params['wf_dir']=wf_dir<line_sep>prepared_job_params['oozie_server']=oozie_server<line_sep><return>prepared_job_params<block_end><def_stmt>run_job self job_execution<block_start>prepared_job_params=self._prepare_run_job(job_execution)<line_sep>path_to_workflow=prepared_job_params['path_to_workflow']<line_sep>hdfs_user=prepared_job_params['hdfs_user']<line_sep>oozie_params=prepared_job_params['oozie_params']<line_sep>use_hbase_lib=prepared_job_params['use_hbase_lib']<line_sep>ctx=prepared_job_params['context']<line_sep>job_execution=prepared_job_params['job_execution']<line_sep>job_params=self._get_oozie_job_params(hdfs_user path_to_workflow oozie_params use_hbase_lib)<line_sep>client=self.get_client()<line_sep>oozie_job_id=client.add_job(x.create_hadoop_xml(job_params) job_execution)<line_sep>job_execution=conductor.job_execution_get(ctx job_execution.id)<if_stmt>job_execution.info['status']<eq>edp.JOB_STATUS_TOBEKILLED<block_start><return>(<none> edp.JOB_STATUS_KILLED <none>)<block_end>conductor.job_execution_update(context.ctx() job_execution.id {'info':{'status':edp.JOB_STATUS_READYTORUN} 'engine_job_id':oozie_job_id})<line_sep>client.run_job(job_execution oozie_job_id)<try_stmt><block_start>status=client.get_job_info(job_execution oozie_job_id)['status']<block_end><except_stmt>Exception<block_start>status=<none><block_end><return>(oozie_job_id status <none>)<block_end><def_stmt>run_scheduled_job self job_execution<block_start>prepared_job_params=self._prepare_run_job(job_execution)<line_sep>oozie_server=prepared_job_params['oozie_server']<line_sep>wf_dir=prepared_job_params['wf_dir']<line_sep>hdfs_user=prepared_job_params['hdfs_user']<line_sep>oozie_params=prepared_job_params['oozie_params']<line_sep>use_hbase_lib=prepared_job_params['use_hbase_lib']<line_sep>ctx=prepared_job_params['context']<line_sep>job_execution=prepared_job_params['job_execution']<line_sep>coord_configs={"jobTracker":"${jobTracker}" "nameNode":"${nameNode}"}<line_sep>coord_xml=self._create_coordinator_xml(coord_configs)<line_sep>self._upload_coordinator_file(oozie_server wf_dir coord_xml hdfs_user)<line_sep>job_params=self._get_oozie_job_params(hdfs_user <none> oozie_params use_hbase_lib job_execution.job_configs.job_execution_info wf_dir "scheduled")<line_sep>client=self.get_client()<line_sep>oozie_job_id=client.add_job(x.create_hadoop_xml(job_params) job_execution)<line_sep>job_execution=conductor.job_execution_get(ctx job_execution.id)<if_stmt>job_execution.info['status']<eq>edp.JOB_STATUS_TOBEKILLED<block_start><return>(<none> edp.JOB_STATUS_KILLED <none>)<block_end><try_stmt><block_start>status=client.get_job_status(job_execution oozie_job_id)['status']<block_end><except_stmt>Exception<block_start>status=<none><block_end><return>(oozie_job_id status <none>)<block_end>@abc.abstractmethod<def_stmt>get_hdfs_user self<block_start><pass><block_end>@abc.abstractmethod<def_stmt>create_hdfs_dir self remote dir_name<block_start><pass><block_end>@abc.abstractmethod<def_stmt>get_oozie_server_uri self cluster<block_start><pass><block_end>@abc.abstractmethod<def_stmt>get_oozie_server self cluster<block_start><pass><block_end>@abc.abstractmethod<def_stmt>get_name_node_uri self cluster<block_start><pass><block_end>@abc.abstractmethod<def_stmt>get_resource_manager_uri self cluster<block_start><pass><block_end><def_stmt>validate_job_execution self cluster job data# Shell job type requires no specific fields
<block_start><if_stmt>job.type<eq>edp.JOB_TYPE_SHELL<block_start><return><block_end># All other types except Java require input and output
# objects and Java require main class
<if_stmt>job.type<eq>edp.JOB_TYPE_JAVA<block_start>j.check_main_class_present(data job)<block_end><else_stmt><block_start>j.check_data_sources(data job)<line_sep>job_type,subtype=edp.split_job_type(job.type)<if_stmt>job_type<eq>edp.JOB_TYPE_MAPREDUCE<and>(subtype<eq>edp.JOB_SUBTYPE_STREAMING)<block_start>j.check_streaming_present(data job)<block_end><block_end><block_end>@staticmethod<def_stmt>get_possible_job_config job_type<block_start><return>workflow_factory.get_possible_job_config(job_type)<block_end>@staticmethod<def_stmt>get_supported_job_types <block_start><return>[edp.JOB_TYPE_HIVE edp.JOB_TYPE_JAVA edp.JOB_TYPE_MAPREDUCE edp.JOB_TYPE_MAPREDUCE_STREAMING edp.JOB_TYPE_PIG edp.JOB_TYPE_SHELL]<block_end><def_stmt>_prepare_job_binaries self job_binaries r<block_start><for_stmt>jb job_binaries<block_start>jb_manager.JOB_BINARIES.get_job_binary_by_url(jb.url).prepare_cluster(jb remote=r)<block_end><block_end><def_stmt>_upload_job_files_to_hdfs self where job_dir job configs proxy_configs=<none><block_start>mains=list(job.mains)<if>job.mains<else>[]<line_sep>libs=list(job.libs)<if>job.libs<else>[]<line_sep>builtin_libs=edp.get_builtin_binaries(job configs)<line_sep>uploaded_paths=[]<line_sep>hdfs_user=self.get_hdfs_user()<line_sep>job_dir_suffix='lib'<if>job.type<ne>edp.JOB_TYPE_SHELL<else>''<line_sep>lib_dir=os.path.join(job_dir job_dir_suffix)<with_stmt>remote.get_remote(where)<as>r<block_start>job_binaries=mains+libs<line_sep>self._prepare_job_binaries(job_binaries r)<line_sep># upload mains
uploaded_paths.extend(self._upload_job_binaries(r mains proxy_configs hdfs_user job_dir))<line_sep># upload libs
<if_stmt>len(libs)<and>job_dir_suffix# HDFS 2.2.0 fails to put file if the lib dir does not exist
<block_start>self.create_hdfs_dir(r lib_dir)<block_end>uploaded_paths.extend(self._upload_job_binaries(r libs proxy_configs hdfs_user lib_dir))<line_sep># upload buitin_libs
<for_stmt>lib builtin_libs<block_start>h.put_file_to_hdfs(r lib['raw'] lib['name'] lib_dir hdfs_user)<line_sep>uploaded_paths.append(lib_dir+lib['name'])<block_end><block_end><return>uploaded_paths<block_end><def_stmt>_upload_job_binaries self r job_binaries proxy_configs hdfs_user job_dir<block_start>uploaded_paths=[]<for_stmt>jb job_binaries<block_start>path=jb_manager.JOB_BINARIES.get_job_binary_by_url(jb.url).copy_binary_to_cluster(jb proxy_configs=proxy_configs remote=r context=context.ctx())<line_sep>h.copy_from_local(r path job_dir hdfs_user)<line_sep>uploaded_paths.append(path)<block_end><return>uploaded_paths<block_end><def_stmt>_create_hdfs_workflow_dir self where job<block_start>constructed_dir='/user/%s/'%self.get_hdfs_user()<line_sep>constructed_dir=self._add_postfix(constructed_dir)<line_sep>constructed_dir<augadd>'%s/%s'%(job.name uuidutils.generate_uuid())<with_stmt>remote.get_remote(where)<as>r<block_start>self.create_hdfs_dir(r constructed_dir)<block_end><return>constructed_dir<block_end><def_stmt>_create_coordinator_xml self coord_configs config_filter=<none> appname='coord'<block_start>doc=xml.Document()<line_sep># Create the <coordinator-app> base element
coord=doc.createElement('coordinator-app')<line_sep>coord.attributes['name']=appname<line_sep>coord.attributes['start']="${start}"<line_sep>coord.attributes['end']="${end}"<line_sep>coord.attributes['frequency']="${frequency}"<line_sep>coord.attributes['timezone']='UTC'<line_sep>coord.attributes['xmlns']='uri:oozie:coordinator:0.2'<line_sep>doc.appendChild(coord)<line_sep>action=doc.createElement('action')<line_sep>workflow=doc.createElement('workflow')<line_sep>coord.appendChild(action)<line_sep>action.appendChild(workflow)<line_sep>x.add_text_element_to_tag(doc "workflow" 'app-path' "${workflowAppUri}")<line_sep>configuration=doc.createElement('configuration')<line_sep>workflow.appendChild(configuration)<line_sep>default_configs=[]<if_stmt>config_filter<is><not><none><block_start>default_configs=[cfg['name']<for>cfg config_filter]<block_end><for_stmt>name sorted(coord_configs)<block_start><if_stmt>name<in>default_configs<or>config_filter<is><none><block_start>x.add_property_to_configuration(doc name coord_configs[name])<block_end><block_end># Return newly created XML
<return>doc.toprettyxml(indent=" ")<block_end><def_stmt>_add_postfix self constructed_dir<block_start><def_stmt>_append_slash_if_needed path<block_start><if_stmt>path[-1]<ne>'/'<block_start>path<augadd>'/'<block_end><return>path<block_end>constructed_dir=_append_slash_if_needed(constructed_dir)<if_stmt>CONF.job_workflow_postfix<block_start>constructed_dir=''.join([str(constructed_dir) str(CONF.job_workflow_postfix)])<block_end><return>_append_slash_if_needed(constructed_dir)<block_end><def_stmt>_resolve_external_hdfs_urls self job_configs<block_start>external_hdfs_urls=[]<for_stmt>k,v six.iteritems(job_configs.get('configs' {}))<block_start><if_stmt>isinstance(v six.string_types)<and>v.startswith("hdfs://")<block_start>external_hdfs_urls.append(v)<block_end><block_end><for_stmt>k,v six.iteritems(job_configs.get('params' {}))<block_start><if_stmt>isinstance(v six.string_types)<and>v.startswith("hdfs://")<block_start>external_hdfs_urls.append(v)<block_end><block_end><for_stmt>v job_configs.get('args' [])<block_start><if_stmt>isinstance(v six.string_types)<and>v.startswith("hdfs://")<block_start>external_hdfs_urls.append(v)<block_end><block_end><return>external_hdfs_urls<block_end><def_stmt>suspend_job self job_execution<block_start><return>self._manage_job(job_execution edp.JOB_ACTION_SUSPEND)<block_end><def_stmt>_manage_job self job_execution action<block_start><if_stmt>job_execution.oozie_job_id<is><not><none><block_start>client=self.get_client()<if_stmt>action<eq>edp.JOB_ACTION_SUSPEND<block_start>client.suspend_job(job_execution)<block_end><return>client.get_job_status(job_execution)<block_end><block_end><block_end> |
<import_stmt>rclpy<import_from_stmt>rclpy.action ActionClient<import_from_stmt>rclpy.node Node<import_from_stmt>action_tutorials_interfaces.action Fibonacci<class_stmt>FibonacciActionClient(Node)<block_start><def_stmt>__init__ self<block_start>super().__init__('fibonacci_action_client')<line_sep>self._action_client=ActionClient(self Fibonacci 'fibonacci')<block_end><def_stmt>send_goal self order<block_start>goal_msg=Fibonacci.Goal()<line_sep>goal_msg.order=order<line_sep>self._action_client.wait_for_server()<line_sep><return>self._action_client.send_goal_async(goal_msg)<block_end><block_end><def_stmt>main args=<none><block_start>rclpy.init(args=args)<line_sep>action_client=FibonacciActionClient()<line_sep>future=action_client.send_goal(10)<line_sep>rclpy.spin_until_future_complete(action_client future)<block_end><if_stmt>__name__<eq>'__main__'<block_start>main()<block_end> |
"""
Tests the DQM Server class
"""<import_stmt>json<import_stmt>os<import_stmt>threading<import_stmt>pytest<import_stmt>requests<import_stmt>qcfractal.interface<as>ptl<import_from_stmt>qcfractal FractalServer FractalSnowflake FractalSnowflakeHandler<import_from_stmt>qcfractal.testing await_true find_open_port pristine_loop test_server using_geometric using_rdkit using_torsiondrive <line_sep>meta_set={"errors" "n_inserted" "success" "duplicates" "error_description" "validation_errors"}<def_stmt>test_server_information test_server<block_start>client=ptl.FractalClient(test_server)<line_sep>server_info=client.server_information()<assert_stmt>{"name" "heartbeat_frequency" "counts"}<le>server_info.keys()<assert_stmt>server_info["counts"].keys()<ge>{"molecule" "kvstore" "result" "collection"}<block_end><def_stmt>test_storage_socket test_server<block_start>storage_api_addr=test_server.get_address()+"collection"# Targets and endpoint in the FractalServer
storage={"collection":"TorsionDriveRecord" "name":"Torsion123" "something":"else" "array":["54321"] "visibility":<true> "view_available":<false> "group":"default" }<line_sep># Cast collection type to lower since the server-side does it anyways
storage["collection"]=storage["collection"].lower()<line_sep>r=requests.post(storage_api_addr json={"meta":{} "data":storage})<assert_stmt>r.status_code<eq>200 r.reason<line_sep>pdata=r.json()<assert_stmt>pdata["meta"].keys()<eq>meta_set<assert_stmt>pdata["meta"]["n_inserted"]<eq>1<line_sep>r=requests.get(storage_api_addr json={"meta":{} "data":{"collection":storage["collection"] "name":storage["name"]}})<line_sep>print(r.content)<assert_stmt>r.status_code<eq>200 r.reason<line_sep>pdata=r.json()<line_sep>col_id=pdata["data"][0].pop("id")<line_sep># got a default values when created
pdata["data"][0].pop("tags" <none>)<line_sep>pdata["data"][0].pop("tagline" <none>)<line_sep>pdata["data"][0].pop("provenance" <none>)<line_sep>pdata["data"][0].pop("view_url_hdf5" <none>)<line_sep>pdata["data"][0].pop("view_url_plaintext" <none>)<line_sep>pdata["data"][0].pop("view_metadata" <none>)<line_sep>pdata["data"][0].pop("description" <none>)<assert_stmt>pdata["data"][0]<eq>storage<line_sep># Test collection id sub-resource
r=requests.get(f"{storage_api_addr}/{col_id}" json={"meta":{} "data":{}}).json()<assert_stmt>r["meta"]["success"]<is><true><assert_stmt>len(r["data"])<eq>1<assert_stmt>r["data"][0]["id"]<eq>col_id<line_sep>r=requests.get(f"{storage_api_addr}/{col_id}" json={"meta":{} "data":{"name":"wrong name"}}).json()<assert_stmt>r["meta"]["success"]<is><true><assert_stmt>len(r["data"])<eq>0<block_end><def_stmt>test_bad_collection_get test_server<block_start><for_stmt>storage_api_addr [test_server.get_address()+"collection/1234/entry" test_server.get_address()+"collection/1234/value" test_server.get_address()+"collection/1234/list" test_server.get_address()+"collection/1234/molecule" ]<block_start>r=requests.get(storage_api_addr json={"meta":{} "data":{}})<assert_stmt>r.status_code<eq>200 f"{r.reason} {storage_api_addr}"<assert_stmt>r.json()["meta"]["success"]<is><false> storage_api_addr<block_end><block_end><def_stmt>test_bad_collection_post test_server<block_start>storage={"collection":"TorsionDriveRecord" "name":"Torsion123" "something":"else" "array":["54321"] "visibility":<true> "view_available":<false> }<line_sep># Cast collection type to lower since the server-side does it anyways
storage["collection"]=storage["collection"].lower()<for_stmt>storage_api_addr [test_server.get_address()+"collection/1234" test_server.get_address()+"collection/1234/value" test_server.get_address()+"collection/1234/entry" test_server.get_address()+"collection/1234/list" test_server.get_address()+"collection/1234/molecule" ]<block_start>r=requests.post(storage_api_addr json={"meta":{} "data":storage})<assert_stmt>r.status_code<eq>200 r.reason<assert_stmt>r.json()["meta"]["success"]<is><false><block_end><block_end><def_stmt>test_bad_view_endpoints test_server<block_start>"""Tests that certain misspellings of the view endpoints result in 404s"""<line_sep>addr=test_server.get_address()<assert_stmt>requests.get(addr+"collection//value").status_code<eq>404<assert_stmt>requests.get(addr+"collection/234/values").status_code<eq>404<assert_stmt>requests.get(addr+"collections/234/value").status_code<eq>404<assert_stmt>requests.get(addr+"collection/234/view/value").status_code<eq>404<assert_stmt>requests.get(addr+"collection/value").status_code<eq>404<assert_stmt>requests.get(addr+"collection/S22").status_code<eq>404<block_end>@pytest.mark.slow<def_stmt>test_snowflakehandler_restart <block_start><with_stmt>FractalSnowflakeHandler()<as>server<block_start>server.client()<line_sep>proc1=server._qcfractal_proc<line_sep>server.restart()<line_sep>server.client()<line_sep>proc2=server._qcfractal_proc<block_end><assert_stmt>proc1<ne>proc2<assert_stmt>proc1.poll()<is><not><none><assert_stmt>proc2.poll()<is><not><none><block_end><def_stmt>test_snowflakehandler_log <block_start><with_stmt>FractalSnowflakeHandler()<as>server<block_start>proc=server._qcfractal_proc<assert_stmt>"No SSL files passed in"<in>server.show_log(show=<false> nlines=100)<assert_stmt>"0 task"<not><in>server.show_log(show=<false> nlines=100)<block_end><assert_stmt>proc.poll()<is><not><none><block_end>@pytest.mark.slow@using_geometric@using_torsiondrive@using_rdkit<def_stmt>test_snowflake_service <block_start><with_stmt>FractalSnowflakeHandler()<as>server<block_start>client=server.client()<line_sep>hooh=ptl.data.get_molecule("hooh.json")<line_sep># Geometric options
tdinput={"initial_molecule":[hooh] "keywords":{"dihedrals":[[0 1 2 3]] "grid_spacing":[90]} "optimization_spec":{"program":"geometric" "keywords":{"coordsys":"tric"}} "qc_spec":{"driver":"gradient" "method":"UFF" "basis":<none> "keywords":<none> "program":"rdkit"} }<line_sep>ret=client.add_service([tdinput])<def_stmt>geometric_await <block_start>td=client.query_procedures(id=ret.ids)[0]<line_sep><return>td.status<eq>"COMPLETE"<block_end><assert_stmt>await_true(60 geometric_await period=2) client.query_procedures(id=ret.ids)[0]<block_end><block_end> |
<import_from_stmt>collections namedtuple<import_stmt>json logging socket re struct time<import_from_stmt>typing Tuple Iterator<import_from_stmt>urllib.parse urlparse parse_qs<import_from_stmt>backend Backend Change<import_from_stmt>protocol PacketType recvall PKT_CHANGE_TYPES change_from_packet packet_from_change send_packet recv_packet<line_sep># Total number of reconnection tries
RECONNECT_TRIES=5<line_sep># Delay in seconds between reconnections (initial)
RECONNECT_DELAY=5<line_sep># Scale delay factor after each failure
RECONNECT_DELAY_BACKOFF=1.5<line_sep>HostPortInfo=namedtuple('HostPortInfo' ['host' 'port' 'addrtype'])<line_sep>SocketURLInfo=namedtuple('SocketURLInfo' ['target' 'proxytype' 'proxytarget'])<line_sep># Network address type.
<class_stmt>AddrType<block_start>IPv4=0<line_sep>IPv6=1<line_sep>NAME=2<block_end># Proxy type. Only SOCKS5 supported at the moment as this is sufficient for Tor.
<class_stmt>ProxyType<block_start>DIRECT=0<line_sep>SOCKS5=1<block_end><def_stmt>parse_host_port path:str<arrow>HostPortInfo<block_start>'''Parse a host:port pair.'''<if_stmt>path.startswith('[')# bracketed IPv6 address
<block_start>eidx=path.find(']')<if_stmt>eidx<eq>-1<block_start><raise>ValueError('Unterminated bracketed host address.')<block_end>host=path[1:eidx]<line_sep>addrtype=AddrType.IPv6<line_sep>eidx<augadd>1<if_stmt>eidx<ge>len(path)<or>path[eidx]<ne>':'<block_start><raise>ValueError('Port number missing.')<block_end>eidx<augadd>1<block_end><else_stmt><block_start>eidx=path.find(':')<if_stmt>eidx<eq>-1<block_start><raise>ValueError('Port number missing.')<block_end>host=path[0:eidx]<if_stmt>re.match('\d+\.\d+\.\d+\.\d+$' host)# matches IPv4 address format
<block_start>addrtype=AddrType.IPv4<block_end><else_stmt><block_start>addrtype=AddrType.NAME<block_end>eidx<augadd>1<block_end><try_stmt><block_start>port=int(path[eidx:])<block_end><except_stmt>ValueError<block_start><raise>ValueError('Invalid port number')<block_end><return>HostPortInfo(host=host port=port addrtype=addrtype)<block_end><def_stmt>parse_socket_url destination:str<arrow>SocketURLInfo<block_start>'''Parse a socket: URL to extract the information contained in it.'''<line_sep>url=urlparse(destination)<if_stmt>url.scheme<ne>'socket'<block_start><raise>ValueError('Scheme for socket backend must be socket:...')<block_end>target=parse_host_port(url.path)<line_sep>proxytype=ProxyType.DIRECT<line_sep>proxytarget=<none><line_sep># parse query parameters
# reject unknown parameters (currently all of them)
qs=parse_qs(url.query)<for_stmt>(key values) qs.items()<block_start><if_stmt>key<eq>'proxy'# proxy=socks5:127.0.0.1:9050
<block_start><if_stmt>len(values)<ne>1<block_start><raise>ValueError('Proxy can only have one value')<block_end>(ptype ptarget)=values[0].split(':' 1)<if_stmt>ptype<ne>'socks5'<block_start><raise>ValueError('Unknown proxy type '+ptype)<block_end>proxytype=ProxyType.SOCKS5<line_sep>proxytarget=parse_host_port(ptarget)<block_end><else_stmt><block_start><raise>ValueError('Unknown query string parameter '+key)<block_end><block_end><return>SocketURLInfo(target=target proxytype=proxytype proxytarget=proxytarget)<block_end><class_stmt>SocketBackend(Backend)<block_start><def_stmt>__init__ self destination:str create:bool<block_start>self.version=<none><line_sep>self.prev_version=<none><line_sep>self.destination=destination<line_sep>self.url=parse_socket_url(destination)<line_sep>self.connect()<block_end><def_stmt>connect self<block_start><if_stmt>self.url.proxytype<eq>ProxyType.DIRECT<block_start><if_stmt>self.url.target.addrtype<eq>AddrType.IPv6<block_start>self.sock=socket.socket(socket.AF_INET6 socket.SOCK_STREAM)<block_end><else_stmt># TODO NAME is assumed to be IPv4 for now
<block_start>self.sock=socket.socket(socket.AF_INET socket.SOCK_STREAM)<block_end><block_end><else_stmt><block_start><assert_stmt>(self.url.proxytype<eq>ProxyType.SOCKS5)<import_stmt>socks<line_sep>self.sock=socks.socksocket()<line_sep>self.sock.set_proxy(socks.SOCKS5 self.url.proxytarget.host self.url.proxytarget.port)<block_end>logging.info('Connecting to {}:{} (addrtype {}, proxytype {}, proxytarget {})...'.format(self.url.target.host self.url.target.port self.url.target.addrtype self.url.proxytype self.url.proxytarget))<line_sep>self.sock.connect((self.url.target.host self.url.target.port))<line_sep>logging.info('Connected to {}'.format(self.destination))<block_end><def_stmt>_send_packet self typ:int payload:bytes<arrow><none><block_start>send_packet(self.sock typ payload)<block_end><def_stmt>_recv_packet self<arrow>Tuple[int bytes]<block_start><return>recv_packet(self.sock)<block_end><def_stmt>initialize self<arrow>bool<block_start>'''
Initialize socket backend by request current metadata from server.
'''<line_sep>logging.info('Initializing backend')<line_sep>self._request_metadata()<line_sep>logging.info('Initialized SocketBackend: protocol={}, version={}, prev_version={}, version_count={}'.format(self.protocol self.version self.prev_version self.version_count))<line_sep><return><true><block_end><def_stmt>_request_metadata self<arrow><none><block_start>self._send_packet(PacketType.REQ_METADATA b'')<line_sep>(typ payload)=self._recv_packet()<assert_stmt>(typ<eq>PacketType.METADATA)<line_sep>self.protocol,self.version,self.prev_version,self.version_count=struct.unpack("!IIIQ" payload)<block_end><def_stmt>add_change self entry:Change<arrow>bool<block_start>typ,payload=packet_from_change(entry)<line_sep>base_version=self.version<line_sep>retry=0<line_sep>retry_delay=RECONNECT_DELAY<line_sep>need_connect=<false><while_stmt><true># Retry loop
<block_start><try_stmt><block_start><if_stmt>need_connect<block_start>self.connect()<line_sep># Request metadata, to know where we stand
self._request_metadata()<if_stmt>self.version<eq>entry.version# If the current version at the server side matches the version of the
# entry, the packet was succesfully sent and processed and the error
# happened afterward. Nothing left to do.
<block_start><return><true><block_end><elif_stmt>base_version<eq>self.version# The other acceptable option is that the current version still matches
# that on the server side. Then we retry.
<block_start><pass><block_end><else_stmt><block_start><raise>Exception('Unexpected backup version {} after reconnect'.format(self.version))<block_end><block_end>self._send_packet(typ payload)<line_sep># Wait for change to be acknowledged before continuing.
(typ _)=self._recv_packet()<assert_stmt>(typ<eq>PacketType.ACK)<block_end><except_stmt>(BrokenPipeError OSError)<block_start><pass><block_end><else_stmt><block_start><break><block_end><if_stmt>retry<eq>RECONNECT_TRIES<block_start>logging.error('Connection was lost while sending change (giving up after {} retries)'.format(retry))<line_sep><raise>IOError('Connection was lost while sending change')<block_end>retry<augadd>1<line_sep>logging.warning('Connection was lost while sending change (retry {} of {}, will try again after {} seconds)'.format(retry RECONNECT_TRIES retry_delay))<line_sep>time.sleep(retry_delay)<line_sep>retry_delay<augmul>RECONNECT_DELAY_BACKOFF<line_sep>need_connect=<true><block_end>self.prev_version=self.version<line_sep>self.version=entry.version<line_sep><return><true><block_end><def_stmt>rewind self<arrow>bool<block_start>'''Rewind to previous version.'''<line_sep>version=struct.pack("!I" self.prev_version)<line_sep>self._send_packet(PacketType.REWIND version)<line_sep># Wait for change to be acknowledged before continuing.
(typ _)=self._recv_packet()<assert_stmt>(typ<eq>PacketType.ACK)<line_sep><return><true><block_end><def_stmt>stream_changes self<arrow>Iterator[Change]<block_start>self._send_packet(PacketType.RESTORE b'')<line_sep>version=-1<while_stmt><true><block_start>(typ payload)=self._recv_packet()<if_stmt>typ<in>PKT_CHANGE_TYPES<block_start>change=change_from_packet(typ payload)<line_sep>version=change.version<line_sep><yield>change<block_end><elif_stmt>typ<eq>PacketType.DONE<block_start><break><block_end><else_stmt><block_start><raise>ValueError("Unknown entry type {}".format(typ))<block_end><block_end><if_stmt>version<ne>self.version<block_start><raise>ValueError("Versions do not match up: restored version {}, backend version {}".format(version self.version))<block_end><assert_stmt>(version<eq>self.version)<block_end><def_stmt>compact self<block_start>self._send_packet(PacketType.COMPACT b'')<line_sep>(typ payload)=self._recv_packet()<assert_stmt>(typ<eq>PacketType.COMPACT_RES)<line_sep><return>json.loads(payload.decode())<block_end><block_end> |
<import_stmt>os<import_from_stmt>conans ConanFile CMake tools<line_sep>required_conan_version=">=1.28.0"<class_stmt>OneDplConan(ConanFile)<block_start>name="onedpl"<line_sep>description=("OneDPL (Formerly Parallel STL) is an implementation of "<concat>"the C++ standard library algorithms"<concat>"with support for execution policies, as specified in "<concat>"ISO/IEC 14882:2017 standard, commonly called C++17")<line_sep>license=("Apache-2.0" "LLVM-exception")<line_sep>url="https://github.com/conan-io/conan-center-index"<line_sep>homepage="https://github.com/oneapi-src/oneDPL"<line_sep>topics=("stl" "parallelism")<line_sep>settings="os" "arch" "build_type" "compiler"<line_sep>options={"backend":["tbb" "serial"]}<line_sep>default_options={"backend":"tbb"}<line_sep>generators=["cmake" "cmake_find_package"]<line_sep>exports=["CMakeLists.txt"]<line_sep>no_copy_source=<true><line_sep>@property<def_stmt>_source_subfolder self<block_start><return>"source_subfolder"<block_end><def_stmt>configure self<block_start><if_stmt>self.settings.compiler.cppstd<block_start>tools.check_min_cppstd(self 11)<block_end><block_end><def_stmt>requirements self<block_start><if_stmt>self.options.backend<eq>"tbb"<block_start>self.requires("tbb/2020.2")<block_end><block_end><def_stmt>package_id self<block_start>self.info.header_only()<block_end><def_stmt>source self<block_start>tools.get(**self.conan_data["sources"][self.version])<line_sep>os.rename("oneDPL-"+self.version self._source_subfolder)<block_end><def_stmt>_configure_cmake self<block_start>cmake=CMake(self)<line_sep>cmake.definitions["PARALLELSTL_BACKEND"]=self.options.backend<line_sep>cmake.configure()<line_sep><return>cmake<block_end><def_stmt>package self<block_start>cmake=self._configure_cmake()<line_sep>cmake.install()<line_sep>self.copy("*" src=os.path.join(self._source_subfolder "stdlib") dst=os.path.join("lib" "stdlib"))<line_sep>self.copy("LICENSE.txt" src=self._source_subfolder dst="licenses")<line_sep>tools.rmdir(os.path.join(self.package_folder "lib" "cmake"))<block_end><def_stmt>package_info self<block_start>self.cpp_info.filenames["cmake_find_package"]="ParallelSTL"<line_sep>self.cpp_info.filenames["cmake_find_package_multi"]="ParallelSTL"<line_sep>self.cpp_info.names["cmake_find_package"]="pstl"<line_sep>self.cpp_info.names["cmake_find_package_multi"]="pstl"<line_sep>self.cpp_info.components["_onedpl"].names["cmake_find_package"]="ParallelSTL"<line_sep>self.cpp_info.components["_onedpl"].names["cmake_find_package_multi"]="ParallelSTL"<line_sep>self.cpp_info.components["_onedpl"].includedirs=["include" os.path.join("lib" "stdlib")]<if_stmt>self.options.backend<eq>"tbb"<block_start>self.cpp_info.components["_onedpl"].requires=["tbb::tbb"]<block_end><block_end><block_end> |
##########################################################################
#
# Copyright (c) 2019, <NAME>. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * 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.
#
# * Neither the name of <NAME> nor the names of
# any other contributors to this software 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 OWNER 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.
#
##########################################################################
<import_stmt>os<import_stmt>sys<import_stmt>unittest<import_stmt>functools<import_stmt>Gaffer<import_stmt>GafferTest<class_stmt>ExtensionAlgoTest(GafferTest.TestCase)<block_start><def_stmt>setUp self<block_start>GafferTest.TestCase.setUp(self)<line_sep>self.addCleanup(functools.partial(setattr sys "path" sys.path[:]))<block_end><def_stmt>testExport self# Export
<block_start>box=Gaffer.Box("AddOne")<line_sep>box["__add"]=GafferTest.AddNode()<line_sep>box["__add"]["op2"].setValue(1)<line_sep>Gaffer.PlugAlgo.promote(box["__add"]["op1"]).setName("in")<line_sep>Gaffer.PlugAlgo.promote(box["__add"]["sum"]).setName("out")<line_sep>Gaffer.Metadata.registerValue(box "description" "Test")<line_sep>Gaffer.Metadata.registerValue(box["in"] "description" "The input")<line_sep>Gaffer.Metadata.registerValue(box["out"] "description" "The output")<line_sep>Gaffer.Metadata.registerValue(box["in"] "test" 1)<line_sep>Gaffer.ExtensionAlgo.exportExtension("TestExtension" [box] self.temporaryDirectory())<line_sep>self.assertTrue(os.path.exists(os.path.join(self.temporaryDirectory() "python" "TestExtension")))<line_sep>sys.path.append(os.path.join(self.temporaryDirectory() "python"))<line_sep># Import and test
<import_stmt>TestExtension<line_sep>script=Gaffer.ScriptNode()<line_sep>script["node"]=TestExtension.AddOne()<line_sep>script["node"]["in"].setValue(2)<line_sep>self.assertEqual(script["node"]["out"].getValue() 3)<import_stmt>TestExtensionUI<def_stmt>assertExpectedMetadata node<block_start>self.assertEqual(Gaffer.Metadata.registeredValues(node instanceOnly=<true>) [])<line_sep>self.assertEqual(Gaffer.Metadata.registeredValues(node["in"] instanceOnly=<true>) [])<line_sep>self.assertEqual(Gaffer.Metadata.registeredValues(node["out"] instanceOnly=<true>) [])<line_sep>self.assertEqual(Gaffer.Metadata.value(node "description") "Test")<line_sep>self.assertEqual(Gaffer.Metadata.value(node["in"] "description") "The input")<line_sep>self.assertEqual(Gaffer.Metadata.value(node["out"] "description") "The output")<line_sep>self.assertEqual(Gaffer.Metadata.value(node["in"] "test") 1)<block_end>assertExpectedMetadata(script["node"])<line_sep># Copy/paste and test
script.execute(script.serialise(filter=Gaffer.StandardSet({script["node"]})))<line_sep>self.assertEqual(script["node1"].keys() script["node"].keys())<line_sep>self.assertEqual(script["node1"]["out"].getValue() script["node"]["out"].getValue())<line_sep>assertExpectedMetadata(script["node1"])<block_end><def_stmt>testPlugTypes self<block_start>box=Gaffer.Box("PlugTypes")<line_sep>box["int"]=Gaffer.IntPlug(flags=Gaffer.Plug.Flags.Default|Gaffer.Plug.Flags.Dynamic)<line_sep>box["float"]=Gaffer.FloatPlug(flags=Gaffer.Plug.Flags.Default|Gaffer.Plug.Flags.Dynamic)<line_sep>box["string"]=Gaffer.StringPlug(flags=Gaffer.Plug.Flags.Default|Gaffer.Plug.Flags.Dynamic)<line_sep>box["v2i"]=Gaffer.V2iPlug(flags=Gaffer.Plug.Flags.Default|Gaffer.Plug.Flags.Dynamic)<line_sep>box["v3i"]=Gaffer.V3iPlug(flags=Gaffer.Plug.Flags.Default|Gaffer.Plug.Flags.Dynamic)<line_sep>box["color4f"]=Gaffer.Color4fPlug(flags=Gaffer.Plug.Flags.Default|Gaffer.Plug.Flags.Dynamic)<line_sep>box["spline"]=Gaffer.SplinefColor3fPlug(flags=Gaffer.Plug.Flags.Default|Gaffer.Plug.Flags.Dynamic)<line_sep>Gaffer.ExtensionAlgo.exportExtension("PlugTypesExtension" [box] self.temporaryDirectory())<line_sep>sys.path.append(os.path.join(self.temporaryDirectory() "python"))<import_stmt>PlugTypesExtension<line_sep>node=PlugTypesExtension.PlugTypes()<for_stmt>plug Gaffer.Plug.Range(node)<block_start>self.assertIsInstance(plug type(box[plug.getName()]))<if_stmt>hasattr(plug "getValue")<block_start>self.assertEqual(plug.getValue() box[plug.getName()].getValue())<block_end><block_end><for_stmt>plug Gaffer.Plug.RecursiveRange(node)<block_start>self.assertFalse(plug.getFlags(Gaffer.Plug.Flags.Dynamic))<block_end><block_end><def_stmt>testInternalExpression self<block_start>box=Gaffer.Box("AddOne")<line_sep>box["in"]=Gaffer.IntPlug(flags=Gaffer.Plug.Flags.Default|Gaffer.Plug.Flags.Dynamic)<line_sep>box["out"]=Gaffer.IntPlug(direction=Gaffer.Plug.Direction.Out flags=Gaffer.Plug.Flags.Default|Gaffer.Plug.Flags.Dynamic)<line_sep>box["__expression"]=Gaffer.Expression()<line_sep>box["__expression"].setExpression("""parent["out"] = parent["in"] + 1""")<line_sep>Gaffer.ExtensionAlgo.exportExtension("TestExtensionWithExpression" [box] self.temporaryDirectory())<line_sep>sys.path.append(os.path.join(self.temporaryDirectory() "python"))<import_stmt>TestExtensionWithExpression<line_sep>script=Gaffer.ScriptNode()<line_sep>script["node"]=TestExtensionWithExpression.AddOne()<line_sep>script["node"]["in"].setValue(2)<line_sep>self.assertEqual(script["node"]["out"].getValue() 3)<line_sep># Test copy/paste
script.execute(script.serialise(filter=Gaffer.StandardSet({script["node"]})))<line_sep>self.assertEqual(script["node1"].keys() script["node"].keys())<line_sep>self.assertEqual(script["node1"]["out"].getValue() 3)<block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>unittest.main()<block_end> |
<import_stmt>time<import_from_stmt>time sleep<def_stmt>print_elapsed_time exit_event<block_start>start_time=time.time()<while_stmt><true><block_start><if_stmt>exit_event.is_set()<block_start><break><block_end>print(f'Running for {round(time.time()-start_time)} s' end='\r')<line_sep>sleep(1)<block_end><block_end> |
# Copyright 2018 <NAME>
# 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_from_future_stmt> absolute_import<import_from_future_stmt> division<import_from_future_stmt> print_function<import_stmt>os<import_stmt>sys<import_stmt>tensorflow<as>tf<import_stmt>config<line_sep># scaffold related configuration
tf.app.flags.DEFINE_string('data_dir' '../Datasets/tfrecords' 'The directory where the dataset input data is stored.')<line_sep>tf.app.flags.DEFINE_string('dataset_name' '{}_????' 'The pattern of the dataset name to load.')<line_sep>tf.app.flags.DEFINE_string(#'blouse', 'dress', 'outwear', 'skirt', 'trousers', '*'
'dataset_split_name' 'blouse' 'The name of the train/test split.')<line_sep>tf.app.flags.DEFINE_string('model_dir' './logs/' 'The parent directory where the model will be stored.')<line_sep>tf.app.flags.DEFINE_integer('save_checkpoints_secs' 3600 'The frequency with which the model is saved, in seconds.')<line_sep># model related configuration
tf.app.flags.DEFINE_integer('train_image_size' 256 'The size of the input image for the model to use.')<line_sep>tf.app.flags.DEFINE_integer('heatmap_size' 64 'The size of the output heatmap of the model.')<line_sep>tf.app.flags.DEFINE_float('heatmap_sigma' 1. 'The sigma of Gaussian which generate the target heatmap.')<line_sep>tf.app.flags.DEFINE_integer('feats_channals' 256 'Number of features in the hourglass.')<line_sep>tf.app.flags.DEFINE_integer('num_stacks' 8 'Number of hourglasses to stack.')#8
tf.app.flags.DEFINE_integer('num_modules' 1 'Number of residual modules at each location in the hourglass.')<line_sep>tf.app.flags.DEFINE_float('bbox_border' 25. 'The nearest distance of the crop border to al keypoints.')<line_sep>tf.app.flags.DEFINE_integer('train_epochs' 5 'The number of epochs to use for training.')<line_sep>tf.app.flags.DEFINE_integer('epochs_per_eval' 1 'The number of training epochs to run between evaluations.')<line_sep>tf.app.flags.DEFINE_integer('batch_size' 6 'Batch size for training and evaluation.')<line_sep>tf.app.flags.DEFINE_string('data_format' 'channels_first' # 'channels_first' or 'channels_last'
'A flag to override the data format used in the model. channels_first '<concat>'provides a performance boost on GPU but is not always compatible '<concat>'with CPU. If left unspecified, the data format will be chosen '<concat>'automatically based on whether TensorFlow was built for CPU or GPU.')<line_sep># optimizer related configuration
tf.app.flags.DEFINE_integer('tf_random_seed' 20180406 'Random seed for TensorFlow initializers.')<line_sep>tf.app.flags.DEFINE_float('weight_decay' 0.00000 'The weight decay on the model weights.')<line_sep>tf.app.flags.DEFINE_float('mse_weight' 1.0 'The weight decay on the model weights.')<line_sep>tf.app.flags.DEFINE_float('momentum' 0.0 #0.9
'The momentum for the MomentumOptimizer and RMSPropOptimizer.')<line_sep>tf.app.flags.DEFINE_float('learning_rate' 2.5e-4 'Initial learning rate.')#2.5e-4
tf.app.flags.DEFINE_float('end_learning_rate' 0.000001 'The minimal end learning rate used by a polynomial decay learning rate.')<line_sep>tf.app.flags.DEFINE_float('warmup_learning_rate' 0.00001 'The start warm-up learning rate to avoid NAN.')<line_sep>tf.app.flags.DEFINE_integer('warmup_steps' 100 'The total steps to warm-up.')<line_sep># for learning rate piecewise_constant decay
tf.app.flags.DEFINE_string('decay_boundaries' '2, 3' 'Learning rate decay boundaries by global_step (comma-separated list).')<line_sep>tf.app.flags.DEFINE_string('lr_decay_factors' '1, 0.5, 0.1' 'The values of learning_rate decay factor for each segment between boundaries (comma-separated list).')<line_sep># checkpoint related configuration
tf.app.flags.DEFINE_string('checkpoint_path' <none> 'The path to a checkpoint from which to fine-tune.')<line_sep>tf.app.flags.DEFINE_string('checkpoint_model_scope' <none> 'Model scope in the checkpoint. None if the same as the trained model.')<line_sep>tf.app.flags.DEFINE_string(#'blouse', 'dress', 'outwear', 'skirt', 'trousers', 'all'
'model_scope' 'all' 'Model scope name used to replace the name_scope in checkpoint.')<line_sep>tf.app.flags.DEFINE_string('checkpoint_exclude_scopes' <none> #'all/hg_heatmap',#
'Comma-separated list of scopes of variables to exclude when restoring from a checkpoint.')<line_sep>tf.app.flags.DEFINE_boolean('run_on_cloud' <true> 'Wether we will train on cloud.')<line_sep>tf.app.flags.DEFINE_boolean('seq_train' <true> 'Wether we will train a sequence model.')<line_sep>tf.app.flags.DEFINE_string('model_to_train' 'all, blouse, dress, outwear, skirt, trousers' #'all, blouse, dress, outwear, skirt, trousers', 'skirt, dress, outwear, trousers',
'The sub-model to train (comma-separated list).')<line_sep>FLAGS=tf.app.flags.FLAGS<line_sep>total_params={'--data_dir':FLAGS.data_dir '--dataset_name':FLAGS.dataset_name #'blouse', 'dress', 'outwear', 'skirt', 'trousers', '*'
'--model_dir':FLAGS.model_dir '--save_checkpoints_secs':FLAGS.save_checkpoints_secs '--train_image_size':FLAGS.train_image_size '--heatmap_size':FLAGS.heatmap_size '--heatmap_sigma':FLAGS.heatmap_sigma '--feats_channals':FLAGS.feats_channals '--num_stacks':FLAGS.num_stacks '--num_modules':FLAGS.num_modules '--bbox_border':FLAGS.bbox_border '--train_epochs':FLAGS.train_epochs '--epochs_per_eval':FLAGS.epochs_per_eval '--batch_size':FLAGS.batch_size '--data_format':FLAGS.data_format '--tf_random_seed':FLAGS.tf_random_seed '--weight_decay':FLAGS.weight_decay '--mse_weight':FLAGS.mse_weight '--momentum':FLAGS.momentum '--learning_rate':FLAGS.learning_rate '--end_learning_rate':FLAGS.end_learning_rate '--warmup_learning_rate':FLAGS.warmup_learning_rate '--warmup_steps':FLAGS.warmup_steps '--decay_boundaries':FLAGS.decay_boundaries '--lr_decay_factors':FLAGS.lr_decay_factors '--checkpoint_path':FLAGS.checkpoint_path '--checkpoint_model_scope':FLAGS.checkpoint_model_scope '--model_scope':FLAGS.model_scope '--checkpoint_exclude_scopes':FLAGS.checkpoint_exclude_scopes '--run_on_cloud':FLAGS.run_on_cloud}<if_stmt>FLAGS.seq_train<block_start>detail_params={'all':{'model_dir':os.path.join(FLAGS.model_dir 'all') 'train_epochs':6 'epochs_per_eval':3 'decay_boundaries':'3, 4' 'model_scope':'all' } 'blouse':{'model_dir':os.path.join(FLAGS.model_dir 'blouse') 'train_epochs':50 'epochs_per_eval':20 'decay_boundaries':'15, 30' 'model_scope':'blouse' 'checkpoint_path':os.path.join(FLAGS.model_dir 'all') 'checkpoint_model_scope':'all' 'checkpoint_exclude_scopes':'blouse/hg_heatmap' } 'dress':{'model_dir':os.path.join(FLAGS.model_dir 'dress') 'train_epochs':50 'epochs_per_eval':20 'decay_boundaries':'15, 30' 'model_scope':'dress' 'checkpoint_path':os.path.join(FLAGS.model_dir 'all') 'checkpoint_model_scope':'all' 'checkpoint_exclude_scopes':'dress/hg_heatmap' } 'outwear':{'model_dir':os.path.join(FLAGS.model_dir 'outwear') 'train_epochs':50 'epochs_per_eval':20 'decay_boundaries':'15, 30' 'model_scope':'outwear' 'checkpoint_path':os.path.join(FLAGS.model_dir 'all') 'checkpoint_model_scope':'all' 'checkpoint_exclude_scopes':'outwear/hg_heatmap' } 'skirt':{'model_dir':os.path.join(FLAGS.model_dir 'skirt') 'train_epochs':50 'epochs_per_eval':20 'decay_boundaries':'15, 30' 'model_scope':'skirt' 'checkpoint_path':os.path.join(FLAGS.model_dir 'all') 'checkpoint_model_scope':'all' 'checkpoint_exclude_scopes':'skirt/hg_heatmap' } 'trousers':{'model_dir':os.path.join(FLAGS.model_dir 'trousers') 'train_epochs':50 'epochs_per_eval':20 'decay_boundaries':'15, 30' 'model_scope':'trousers' 'checkpoint_path':os.path.join(FLAGS.model_dir 'all') 'checkpoint_model_scope':'all' 'checkpoint_exclude_scopes':'trousers/hg_heatmap' } }<block_end><else_stmt><block_start>detail_params={'blouse':{'model_dir':os.path.join(FLAGS.model_dir 'blouse') 'train_epochs':60 'epochs_per_eval':20 'decay_boundaries':'20, 40' 'model_scope':'blouse' } 'dress':{'model_dir':os.path.join(FLAGS.model_dir 'dress') 'train_epochs':60 'epochs_per_eval':20 'decay_boundaries':'20, 40' 'model_scope':'dress' } 'outwear':{'model_dir':os.path.join(FLAGS.model_dir 'outwear') 'train_epochs':60 'epochs_per_eval':20 'decay_boundaries':'20, 40' 'model_scope':'outwear' } 'skirt':{'model_dir':os.path.join(FLAGS.model_dir 'skirt') 'train_epochs':60 'epochs_per_eval':20 'decay_boundaries':'20, 40' 'model_scope':'skirt' } 'trousers':{'model_dir':os.path.join(FLAGS.model_dir 'trousers') 'train_epochs':60 'epochs_per_eval':20 'decay_boundaries':'20, 40' 'model_scope':'trousers' } }<block_end><def_stmt>parse_comma_list args<block_start><return>[float(s.strip())<for>s args.split(',')]<block_end><def_stmt>parse_str_comma_list args<block_start><return>[s.strip()<for>s args.split(',')]<block_end><def_stmt>main _<block_start><import_stmt>subprocess<import_stmt>copy<line_sep>#['skirt', 'dress', 'outwear', 'trousers']#
all_category=parse_str_comma_list(FLAGS.model_to_train)<for_stmt>cat all_category<block_start>tf.gfile.MakeDirs(os.path.join(FLAGS.model_dir cat))<block_end><for_stmt>cat all_category<block_start>temp_params=copy.deepcopy(total_params)<for_stmt>k,v total_params.items()<block_start><if_stmt>k[2:]<in>detail_params[cat]<block_start>temp_params[k]=detail_params[cat][k[2:]]<block_end><block_end>params_str=[]<for_stmt>k,v temp_params.items()<block_start><if_stmt>v<is><not><none><block_start>params_str.append(k)<line_sep>params_str.append(str(v))<block_end><block_end>print('params send: ' params_str)<line_sep>train_process=subprocess.Popen(['python' './train_subnet.py']+params_str stdout=subprocess.PIPE cwd=os.getcwd())<line_sep>output,_=train_process.communicate()<line_sep>print(output)<block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>tf.logging.set_verbosity(tf.logging.INFO)<line_sep>tf.app.run()<block_end> |
<import_stmt>pytest<import_stmt>yaml<import_from_stmt>nequip.utils instantiate<line_sep>simple_default={"b":1 "d":31}<class_stmt>SimpleExample<block_start><def_stmt>__init__ self a b=simple_default["b"] d=simple_default["d"]<block_start>self.a=a<line_sep>self.b=b<line_sep>self.d=d<block_end><block_end>nested_default={"d":37}<class_stmt>NestedExample<block_start><def_stmt>__init__ self cls_c a cls_c_kwargs={} d=nested_default["d"]<block_start>self.c_obj=cls_c(**cls_c_kwargs)<line_sep>self.a=a<line_sep>self.d=d<block_end><block_end><def_stmt>assert_dict d<block_start><for_stmt>k,v d.items()<block_start><if_stmt>isinstance(v dict)<block_start>assert_dict(v)<block_end><elif_stmt>isinstance(v str)<block_start><assert_stmt>k<eq>v<block_end><block_end><block_end>@pytest.mark.parametrize("positional_args" [dict(a=3 b=4) dict(a=5) dict()])@pytest.mark.parametrize("optional_args" [dict(a=3 b=4) dict(a=5) dict()])@pytest.mark.parametrize("all_args" [dict(a=6 b=7) dict(a=8) dict()])@pytest.mark.parametrize("prefix" [<true> <false>])<def_stmt>test_simple_init positional_args optional_args all_args prefix<block_start>union={}<line_sep>union.update(all_args)<line_sep>union.update(optional_args)<line_sep>union.update(positional_args)<if_stmt>"a"<not><in>union<block_start><return><block_end># decorate test with prefix
_all_args=({"simple_example_"+k:v<for>k,v all_args.items()}<if>prefix<else>all_args)<line_sep># check key mapping is correct
km,params=instantiate(builder=SimpleExample prefix="simple_example" positional_args=positional_args optional_args=optional_args all_args=_all_args return_args_only=<true> )<for_stmt>t km<block_start><for_stmt>k,v km[t].items()<block_start><assert_stmt>k<in>locals()[t+"_args"]<if_stmt>prefix<and>t<eq>"all"<block_start><assert_stmt>v<eq>"simple_example_"+k<block_end><else_stmt><block_start><assert_stmt>v<eq>k<block_end><block_end><block_end>km,_=instantiate(builder=SimpleExample prefix="simple_example" positional_args=positional_args all_args=params return_args_only=<true> )<line_sep>assert_dict(km)<line_sep># check whether it gets the priority right
a1,params=instantiate(builder=SimpleExample prefix="simple_example" positional_args=positional_args optional_args=optional_args all_args=_all_args )<assert_stmt>a1.a<eq>union["a"]<if_stmt>"b"<in>union<block_start><assert_stmt>a1.b<eq>union["b"]<block_end><else_stmt><block_start><assert_stmt>a1.b<eq>simple_default["b"]<block_end><for_stmt>k params<block_start><if_stmt>k<in>simple_default<block_start><assert_stmt>params[k]<eq>union.get(k simple_default[k])<block_end><block_end># check whether the return value is right
a2=SimpleExample(**positional_args **params)<assert_stmt>a1.a<eq>a2.a<assert_stmt>a1.b<eq>a2.b<block_end><def_stmt>test_prefix_priority <block_start>args={"prefix_a":3 "a":4}<line_sep>a,params=instantiate(builder=SimpleExample prefix="prefix" all_args=args )<assert_stmt>a.a<eq>3<block_end>@pytest.mark.parametrize("optional_args" [dict(a=3 b=4) dict(a=5) dict()])@pytest.mark.parametrize("all_args" [dict(a=6 b=7) dict(a=8) dict()])@pytest.mark.parametrize("prefix" [<true> <false>])<def_stmt>test_nested_kwargs optional_args all_args prefix<block_start>union={}<line_sep>union.update(all_args)<line_sep>union.update(optional_args)<if_stmt>"a"<not><in>union<block_start><return><block_end>c,params=instantiate(builder=NestedExample prefix="prefix" positional_args={"cls_c":SimpleExample} optional_args=optional_args all_args=all_args )<block_end><def_stmt>test_default <block_start>"""
check the default value will not contaminate the other class
"""<line_sep>c,params=instantiate(builder=NestedExample prefix="prefix" positional_args={"cls_c":SimpleExample} optional_args={"a":11} )<line_sep>c.d=nested_default["d"]<line_sep>c.c_obj.d=simple_default["d"]<block_end><class_stmt>A<block_start><def_stmt>__init__ self cls_a cls_a_kwargs<block_start>self.a_obj=cls_a(**cls_a_kwargs)<block_end><block_end><class_stmt>B<block_start><def_stmt>__init__ self cls_b cls_b_kwargs<block_start>self.b_obj=cls_b(**cls_b_kwargs)<block_end><block_end><class_stmt>C<block_start><def_stmt>__init__ self cls_c cls_c_kwargs# noqa
<block_start>self.c_obj=c_cls(**c_cls_kwargs)<block_end><block_end># noqa
<def_stmt>test_deep_nests <block_start>all_args={"a":101 "b":103 "c":107}<line_sep>obj,params=instantiate(builder=NestedExample optional_args={"cls_c":A "cls_a":B "cls_b":SimpleExample} all_args=all_args )<line_sep>print(yaml.dump(params))<assert_stmt>obj.c_obj.a_obj.b_obj.a<eq>all_args["a"]<assert_stmt>obj.c_obj.a_obj.b_obj.b<eq>all_args["b"]<assert_stmt>obj.c_obj.a_obj.b_obj.d<eq>simple_default["d"]<assert_stmt>obj.d<eq>nested_default["d"]<line_sep>obj=NestedExample(**params)<assert_stmt>obj.c_obj.a_obj.b_obj.a<eq>all_args["a"]<assert_stmt>obj.c_obj.a_obj.b_obj.b<eq>all_args["b"]<assert_stmt>obj.c_obj.a_obj.b_obj.d<eq>simple_default["d"]<assert_stmt>obj.d<eq>nested_default["d"]<line_sep>km,params=instantiate(builder=NestedExample optional_args={"cls_c":A "cls_a":B "cls_b":SimpleExample} all_args=all_args return_args_only=<true> )<line_sep>print(yaml.dump(km))<line_sep># check the key mapping is unique for
km,_=instantiate(builder=NestedExample optional_args=params return_args_only=<true>)<line_sep>assert_dict(km)<block_end><def_stmt>test_recursion_nests <block_start><with_stmt>pytest.raises(RuntimeError)<as>excinfo<block_start>b,params=instantiate(builder=A positional_args={"cls_a":B} optional_args={"cls_b":A} )<block_end><assert_stmt>"cyclic"<in>str(excinfo.value)<line_sep>print(excinfo)<block_end><def_stmt>test_cyclic_nests <block_start><with_stmt>pytest.raises(RuntimeError)<as>excinfo<block_start>c,params=instantiate(builder=A positional_args={"cls_a":B} optional_args={"cls_b":C} all_args={"cls_c":A} )<block_end><assert_stmt>"cyclic"<in>str(excinfo.value)<line_sep>print(excinfo "hello")<block_end><class_stmt>BadKwargs1<block_start><def_stmt>__init__ self thing_kwargs={}<block_start><pass><block_end><block_end><class_stmt>BadKwargs2<block_start><def_stmt>__init__ self thing="a string" thing_kwargs={}<block_start><pass><block_end><block_end><def_stmt>test_bad_kwargs <block_start><with_stmt>pytest.raises(KeyError)<block_start>_=instantiate(BadKwargs1)<block_end><with_stmt>pytest.raises(ValueError)<block_start>_=instantiate(BadKwargs2)<block_end><block_end> |
<import_from_stmt>flask_login current_user<import_from_stmt>flask_socketio ConnectionRefusedError<import_from_stmt>app.flask_app socketio<import_from_stmt>const.data_doc DATA_DOC_NAMESPACE<import_from_stmt>const.query_execution QUERY_EXECUTION_NAMESPACE<def_stmt>connect <block_start><if_stmt><not>current_user.is_authenticated<block_start><raise>ConnectionRefusedError("User is not logged in, please refresh the page.")<block_end><block_end>socketio.on("connect" namespace=DATA_DOC_NAMESPACE)(connect)<line_sep>socketio.on("connect" namespace=QUERY_EXECUTION_NAMESPACE)(connect)<line_sep> |
"""
{
"swagger": "2.0",
"info": {
"title": "Python Cookbook\\nChapter 12, recipe 3.",
"version": "1.0"
},
"schemes": "http",
"host": "127.0.0.1:5000",
"basePath": "/dealer",
"consumes": "application/json",
"produces": "application/json",
"paths": {
"/hands": {
"get": {
"parameters": [
{"name": "cards",
"in": "query",
"description": "number of cards in each hand",
"type": "array", "items": {"type": "integer"},
"collectionFormat": "multi",
"default": [13, 13, 13, 13]
}
],
"responses": {
"200": {
"description": "one hand of cards for each `hand` value in the query string"
}
}
}
},
"/hand": {
"get": {
"parameters": [
{"name": "cards", "in": "query", "type": "integer", "default": 5}
],
"responses": {
"200": {
"description": "One hand of cards with a size given by the `hand` value in the query string"
}
}
}
}
}
}
"""<import_stmt>random<import_from_stmt>ch12_r01 Card Deck<import_from_stmt>flask Flask jsonify request abort<import_from_stmt>http HTTPStatus<line_sep>dealer=Flask('dealer')<line_sep>specification={'swagger':'2.0' 'info':{'title':'''Python Cookbook\nChapter 12, recipe 3.''' 'version':'1.0'} 'schemes':['http'] 'host':'127.0.0.1:5000' 'basePath':'/dealer' 'consumes':['application/json'] 'produces':['application/json'] 'paths':{'/hands':{'get':{'parameters':[{'name':'cards' 'in':'query' 'description':'number of cards in each hand' 'type':'array' 'items':{'type':'integer'} 'collectionFormat':'multi' 'default':[13 13 13 13]}] 'responses':{'200':{'description':'''One hand of cards for each `hand` value in the query string'''}}}} '/hand':{'get':{'parameters':[{'name':'cards' 'in':'query' 'type':'integer' 'default':5}] 'responses':{'200':{'description':'''One hand of cards with a size given by the `hand` value in the query string'''}}}}}}<import_stmt>os<line_sep>random.seed(os.environ.get('DEAL_APP_SEED'))<line_sep>deck=Deck()<line_sep>@dealer.before_request<def_stmt>check_json <block_start><if_stmt>request.path<eq>'/dealer/swagger.json'<block_start><return><block_end><if_stmt>'json'<in>request.headers.get('Accept' '*/*')<block_start><return><block_end><if_stmt>'json'<eq>request.args.get('$format' 'html')<block_start><return><block_end><return>abort(HTTPStatus.BAD_REQUEST)<block_end><import_from_stmt>flask send_file<line_sep># @dealer.route('/dealer/swagger.json')
<def_stmt>swagger1 <block_start>response=send_file('swagger.json' mimetype='application/json')<line_sep><return>response<block_end><import_from_stmt>flask make_response<line_sep># @dealer.route('/dealer/swagger.json')
<def_stmt>swagger2 <block_start>response=make_response(__doc__.encode('utf-8'))<line_sep>response.headers['Content-Type']='application/json'<line_sep><return>response<block_end><import_from_stmt>flask make_response<import_stmt>json<line_sep>@dealer.route('/dealer/swagger.json')<def_stmt>swagger3 <block_start>response=make_response(json.dumps(specification indent=2).encode('utf-8'))<line_sep>response.headers['Content-Type']='application/json'<line_sep><return>response<block_end>@dealer.route('/dealer/hand/')<def_stmt>deal <block_start><try_stmt><block_start>hand_size=int(request.args.get('cards' 5))<assert_stmt>1<le>hand_size<l>53<block_end><except_stmt>Exception<as>ex<block_start>abort(HTTPStatus.BAD_REQUEST)<block_end>cards=deck.deal(hand_size)<line_sep>response=jsonify([card.to_json()<for>card cards])<line_sep><return>response<block_end>@dealer.route('/dealer/hands/')<def_stmt>multi_hand <block_start><try_stmt><block_start>hand_sizes=request.args.getlist('cards' type=int)<if_stmt>len(hand_sizes)<eq>0<block_start>hand_sizes=[13 13 13 13]<block_end><assert_stmt>all(1<le>hand_size<l>53<for>hand_size hand_sizes)<assert_stmt>sum(hand_sizes)<l>53<block_end><except_stmt>Exception<as>ex<block_start>dealer.logger.exception(ex)<line_sep>abort(HTTPStatus.BAD_REQUEST)<block_end>hands=[deck.deal(hand_size)<for>hand_size hand_sizes]<line_sep>response=jsonify([{'hand':i 'cards':[card.to_json()<for>card hand]}<for>i,hand enumerate(hands)])<line_sep><return>response<block_end><if_stmt>__name__<eq>"__main__"<block_start>dealer.run(use_reloader=<true> threaded=<false>)<block_end> |
"""Defines various classes and definitions that provide assistance for
unit testing Actors in an ActorSystem."""<import_stmt>unittest<import_stmt>pytest<import_stmt>logging<import_stmt>time<import_from_stmt>thespian.actors ActorSystem<def_stmt>simpleActorTestLogging <block_start>"""This function returns a logging dictionary that can be passed as
the logDefs argument for ActorSystem() initialization to get
simple stdout logging configuration. This is not necessary for
typical unit testing that uses the simpleActorSystemBase, but
it can be useful for multiproc.. ActorSystems where the
separate processes created should have a very simple logging
configuration.
"""<import_stmt>sys<if_stmt>sys.platform<eq>'win32'# Windows will not allow sys.stdout to be passed to a child
# process, which breaks the startup/config for some of the
# tests.
<block_start>handler={'class':'logging.handlers.RotatingFileHandler' 'filename':'nosetests.log' 'maxBytes':256<times>1024 'backupCount':3 }<block_end><else_stmt><block_start>handler={'class':'logging.StreamHandler' 'stream':sys.stdout }<block_end><return>{'version':1 'handlers':{#'discarder': {'class': 'logging.NullHandler' },
'testStream':handler } 'root':{'handlers':['testStream']} 'disable_existing_loggers':<false> }<block_end><class_stmt>LocallyManagedActorSystem(object)<block_start><def_stmt>setSystemBase self newBase='simpleSystemBase' systemCapabilities=<none> logDefs='BestForBase'<block_start>newBaseStr=str(newBase)<if_stmt><not>hasattr(self 'currentBase')<or>self.currentBase<ne>newBaseStr<block_start>ldefs=logDefs<if>logDefs<ne>'BestForBase'<else>(simpleActorTestLogging()<if>newBase.startswith('multiproc')<else><false>)<line_sep># In case the ActorSystem was *already* setup, break the singleton aspect and re-init
ActorSystem(logDefs=ldefs).shutdown()<line_sep>ActorSystem(newBase systemCapabilities logDefs=ldefs)<line_sep>self.currentBase=newBaseStr<block_end><block_end><block_end><class_stmt>ActorSystemTestCase(unittest.TestCase LocallyManagedActorSystem)<block_start>"""The ActorSystemTestCase is a wrapper for the unittest TestCase
class that will startup a default ActorSystem in the provided
setUp() and tearDown() any active ActorSystem after testing.
If a non-default ActorSystem is to be used, the setSystemBase()
method should be called with that system base.
It also provides some additional methods for assistance in testing Actors.
"""<def_stmt>setUp self<block_start><if_stmt><not>hasattr(self 'currentBase')<block_start>self.setSystemBase()<block_end><block_end><def_stmt>tearDown self<block_start><if_stmt>hasattr(self 'currentBase')<block_start>ActorSystem().shutdown()<line_sep>delattr(self 'currentBase')<import_stmt>time<line_sep>time.sleep(0.02)<block_end><block_end>@staticmethod<def_stmt>actualActorObject actorClass<block_start>"""Normally an Actor is only instantiated in the context of an
ActorSystem, and then only responds to messages delivered
via that system. For testing purposes *only*, it may be
desireable to have the actual Actor instance to test
methods on that Actor directly. This method will return
that actual Actor instance after instantiating the actor in
an ActorSystem.
This method can ONLY be used with an ActorSystem that will
instantiate the Actor in the context of the current process
(e.g. simpleSystemBase) and the methods tested on the
resulting Actor CANNOT perform any Actor-related actions
(e.g. self.createActor(), self.send()).
This method is for TESTING only under very special
circumstances; if you're not sure you need this, then you
probably don't.
"""<line_sep># Create the Actor within the system.
aAddr=ActorSystem().createActor(actorClass)<line_sep># This depends on the internals of the systemBase
<return>ActorSystem()._systemBase.actorRegistry[aAddr.actorAddressString].instance<block_end><block_end>###
### pytest fixtures and helpers
###
testAdminPort=<none><def_stmt>get_free_admin_port_random <block_start><global>testAdminPort<if_stmt>testAdminPort<is><none><block_start><import_stmt>random<line_sep># Reserved system ports are typically below 1024. Ephemeral
# ports typically start at either 32768 (Linux) or 49152
# (IANA), or range from 1024-5000 (older Windows). Pick
# something unused outside those ranges for the admin.
testAdminPort=random.randint(10000 30000)<line_sep>#testAdminPort = random.randint(5,60) * 1000
<block_end><else_stmt><block_start>testAdminPort=testAdminPort+1<block_end><return>testAdminPort<block_end><def_stmt>get_free_admin_port <block_start><import_stmt>socket<import_stmt>random<for_stmt>tries range(100)<block_start>port=random.randint(5000 30000)<try_stmt><block_start><for_stmt>m,p [(socket.SOCK_STREAM socket.IPPROTO_TCP) (socket.SOCK_DGRAM socket.IPPROTO_UDP) ]<block_start>s=socket.socket(socket.AF_INET m p)<line_sep>s.setsockopt(socket.SOL_SOCKET socket.SO_REUSEADDR 1)<line_sep>s.bind(('' port))<line_sep>s.close()<block_end><return>port<block_end><except_stmt>Exception<block_start><pass><block_end><block_end><return>get_free_admin_port_random()<block_end>@pytest.fixture(params=['simpleSystemBase' 'multiprocQueueBase' 'multiprocUDPBase' 'multiprocTCPBase' 'multiprocTCPBase-AdminRouting' 'multiprocTCPBase-AdminRoutingTXOnly' ])<def_stmt>asys request<block_start>caps={'Foo Allowed':<true> 'Cows Allowed':<true> 'Dogs Allowed':<true> 'dog':'food'}<if_stmt>request.param.startswith('multiprocTCP')<or>request.param.startswith('multiprocUDP')<block_start>caps['Admin Port']=get_free_admin_port()<line_sep>caps['Convention Address.IPv4']='' caps['Admin Port']<block_end><if_stmt>request.param.endswith('-AdminRouting')<block_start>caps['Admin Routing']=<true><block_end><if_stmt>request.param.endswith('-AdminRoutingTXOnly')<block_start>caps['Admin Routing']=<true><line_sep>caps['Outbound Only']=<true><block_end>asys=ActorSystem(systemBase=request.param.partition('-')[0] capabilities=caps logDefs=(simpleActorTestLogging()<if>request.param.startswith('multiproc')<else><false>) transientUnique=<true>)<line_sep>asys.base_name=request.param<line_sep>asys.port_num=caps.get('Admin Port' <none>)<line_sep>asys.txonly=request.param.endswith('-AdminRoutingTXOnly')<line_sep>request.addfinalizer(<lambda>asys=asys:asys.shutdown())<line_sep><return>asys<block_end><def_stmt>similar_asys asys in_convention=<true> start_wait=<true> capabilities=<none><block_start>caps=capabilities<or>{}<if_stmt>asys.base_name.startswith('multiprocTCP')<or>asys.base_name.startswith('multiprocUDP')<block_start>caps['Admin Port']=get_free_admin_port()<if_stmt>in_convention<block_start>caps['Convention Address.IPv4']='' asys.port_num<block_end><block_end><if_stmt>asys.base_name.endswith('-AdminRouting')<block_start>caps['Admin Routing']=<true><block_end>asys2=ActorSystem(systemBase=asys.base_name.partition('-')[0] capabilities=caps logDefs=(simpleActorTestLogging()<if>asys.base_name.startswith('multiproc')<else><false>) transientUnique=<true>)<line_sep>asys2.base_name=asys.base_name<line_sep>asys2.port_num=caps.get('Admin Port' <none>)<if_stmt>in_convention<and>start_wait<block_start>time.sleep(0.25)# Wait for Actor Systems to start and connect together
<block_end><return>asys2<block_end>@pytest.fixture<def_stmt>asys2 request asys<block_start>asys2=similar_asys(asys in_convention=<false>)<line_sep># n.b. shutdown the second actor system first:
# 1. Some tests ask asys1 to create an actor
# 2. That actor is actually supported by asys2
# 3. There is an external port the tester uses for each asys
# 4. When asys2 is shutdown, it will attempt to notify the
# parent of the actor that the actor is dead
# 5. This parent is the external port for asys1.
# 6. If asys1 is shutdown first, then asys2 must time out
# on the transmit attempt (usually 5 minutes) before
# it can exit.
# 7. If the test is re-run within this 5 minute period, it will fail
# because the old asys2 is still existing but in shutdown state
# (and will therefore rightfully refuse new actions).
# By shutting down asys2 first, the parent notification can be
# performed and subsequent runs don't encounter the lingering
# asys2.
request.addfinalizer(<lambda>asys=asys2:asys2.shutdown())<line_sep><return>asys2<block_end>@pytest.fixture<def_stmt>asys_pair request asys<block_start>asys2=similar_asys(asys in_convention=<true>)<line_sep># n.b. shutdown the second actor system first:
# 1. Some tests ask asys1 to create an actor
# 2. That actor is actually supported by asys2
# 3. There is an external port the tester uses for each asys
# 4. When asys2 is shutdown, it will attempt to notify the
# parent of the actor that the actor is dead
# 5. This parent is the external port for asys1.
# 6. If asys1 is shutdown first, then asys2 must time out
# on the transmit attempt (usually 5 minutes) before
# it can exit.
# 7. If the test is re-run within this 5 minute period, it will fail
# because the old asys2 is still existing but in shutdown state
# (and will therefore rightfully refuse new actions).
# By shutting down asys2 first, the parent notification can be
# performed and subsequent runs don't encounter the lingering
# asys2.
request.addfinalizer(<lambda>asys=asys2:asys2.shutdown())<line_sep><return>(asys asys2)<block_end>@pytest.fixture<def_stmt>run_unstable_tests request<block_start><return>request.config.getoption('unstable' default=<false>)<block_end><def_stmt>unstable_test run_unstable_tests asys *unstable_bases<block_start><if_stmt>asys.base_name<in>unstable_bases<and><not>run_unstable_tests<block_start>pytest.skip("Test unstable for %s system base"%asys.base_name)<block_end><block_end><def_stmt>actor_system_unsupported asys *unsupported_bases<block_start><if_stmt>asys.base_name<in>unsupported_bases<block_start>pytest.skip("Functionality not supported for %s system base"%asys.base_name)<block_end><block_end><import_from_stmt>thespian.system.timing timePeriodSeconds<import_stmt>time<line_sep>inTestDelay=<lambda>period:time.sleep(timePeriodSeconds(period))<def_stmt>delay_for_next_of_kin_notification system<block_start><if_stmt>system.base_name<eq>'multiprocQueueBase'# The multiprocQueueBase signal processor cannot interrupt a
# sleeping Queue.get(), so for this base it is necessary to
# wait for the timeout on the Queue.get() to allow it time to
# notice and process the child exit.
<block_start>time.sleep(2.5)<block_end><elif_stmt>system.base_name<eq>'multiprocUDPBase'<block_start>time.sleep(0.6)<block_end><else_stmt><block_start>time.sleep(0.1)<block_end><block_end> |
<import_from_stmt>com.huawei.iotplatform.client.dto.DeviceCommandCancelTaskRespV4 DeviceCommandCancelTaskRespV4<import_from_stmt>com.huawei.iotplatform.client.dto.Pagination Pagination<class_stmt>QueryDeviceCmdCancelTaskOutDTO(object)<block_start>pagination=Pagination()<line_sep>data=DeviceCommandCancelTaskRespV4()<def_stmt>__init__ self<block_start><pass><block_end><def_stmt>getPagination self<block_start><return>self.pagination<block_end><def_stmt>setPagination self pagination<block_start>self.pagination=pagination<block_end><def_stmt>getData self<block_start><return>self.data<block_end><def_stmt>setData self data<block_start>self.data=data<block_end><block_end> |
# Copyright 2021 Spotify AB
#
# 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 KlioPubSubReadEvaluator
These were adapted from
apache_beam/io/gcp/pubsub_test.py::TestReadFromPubSub.
These validate that the original expected behavior from _PubSubReadEvaluator
was kept, as well checking that:
* Responses are not auto-acked
* MessageManager daemon threads started
* Messages added to MessageManager
* Messages handled one at a time, instead of 10 at a time
"""<import_stmt>pytest<import_from_stmt>apache_beam transforms<as>beam_transforms<import_from_stmt>apache_beam utils<as>beam_utils<import_from_stmt>apache_beam.io.gcp pubsub<as>b_pubsub<import_from_stmt>apache_beam.options pipeline_options<import_from_stmt>apache_beam.runners.direct direct_runner<import_from_stmt>apache_beam.runners.direct transform_evaluator<import_from_stmt>apache_beam.testing test_pipeline<as>beam_test_pipeline<import_from_stmt>apache_beam.testing test_utils<as>beam_test_utils<import_from_stmt>apache_beam.testing util<as>beam_testing_util<import_from_stmt>klio.message pubsub_message_manager<as>pmm<import_from_stmt>klio_core.proto klio_pb2<import_from_stmt>klio_exec.runners evaluators<line_sep>@pytest.fixture<def_stmt>patch_msg_manager mocker monkeypatch<block_start>p=mocker.Mock(name="patch_msg_manager")<line_sep>monkeypatch.setattr(pmm "MessageManager" p)<line_sep><return>p<block_end>@pytest.fixture<def_stmt>patch_sub_client mocker monkeypatch# patch out network calls in SubscriberClient instantiation
<block_start>c=mocker.Mock(name="patch_sub_client")<line_sep>monkeypatch.setattr(evaluators.g_pubsub "SubscriberClient" c)<line_sep><return>c.return_value<block_end><class_stmt>KlioTestPubSubReadEvaluator(object)<block_start>"""Wrapper of _PubSubReadEvaluator that makes it bounded."""<line_sep>_pubsub_read_evaluator=evaluators.KlioPubSubReadEvaluator<def_stmt>__init__ self *args **kwargs<block_start>self._evaluator=self._pubsub_read_evaluator(*args **kwargs)<block_end><def_stmt>start_bundle self<block_start><return>self._evaluator.start_bundle()<block_end><def_stmt>process_element self element<block_start><return>self._evaluator.process_element(element)<block_end><def_stmt>finish_bundle self<block_start>result=self._evaluator.finish_bundle()<line_sep>result.unprocessed_bundles=[]<line_sep>result.keyed_watermark_holds={<none>:<none>}<line_sep><return>result<block_end><block_end>transform_evaluator.TransformEvaluatorRegistry._test_evaluators_overrides={direct_runner._DirectReadFromPubSub:KlioTestPubSubReadEvaluator }<def_stmt>test_klio_pubsub_read_eval_read_messages_success mocker patch_sub_client patch_msg_manager <block_start>exp_entity_id="entity_id"<line_sep>kmsg=klio_pb2.KlioMessage()<line_sep>kmsg.data.element=bytes(exp_entity_id "utf-8")<line_sep>data=kmsg.SerializeToString()<line_sep>publish_time_secs=1520861821<line_sep>publish_time_nanos=234567000<line_sep>attributes={"key":"value"}<line_sep>ack_id="ack_id"<line_sep>pull_response=beam_test_utils.create_pull_response([beam_test_utils.PullResponseMessage(data attributes publish_time_secs publish_time_nanos ack_id)])<line_sep>pmsg=b_pubsub.PubsubMessage(data attributes)<line_sep>expected_elements=[beam_testing_util.TestWindowedValue(pmsg beam_utils.timestamp.Timestamp(1520861821.234567) [beam_transforms.window.GlobalWindow()] )]<line_sep>patch_sub_client.pull.return_value=pull_response<line_sep>options=pipeline_options.PipelineOptions([])<line_sep>options.view_as(pipeline_options.StandardOptions).streaming=<true><with_stmt>beam_test_pipeline.TestPipeline(options=options)<as>p<block_start>pcoll=p|b_pubsub.ReadFromPubSub("projects/fakeprj/topics/a_topic" <none> <none> with_attributes=<true>)<line_sep>beam_testing_util.assert_that(pcoll beam_testing_util.equal_to(expected_elements) reify_windows=<true> )<block_end># Check overridden functionality:
# 1. Check that auto-acking is skipped
patch_sub_client.acknowledge.assert_not_called()<line_sep># 2. Check that MessageManager daemon threads were started
patch_msg_manager.assert_called_once_with(patch_sub_client.subscription_path())<line_sep># 3. Check that messages were added to the MessageManager
patch_msg_manager.return_value.add.assert_called_once_with(ack_id pmsg)<line_sep># 4. Check that one message is handled at a time, instead of the
# original 10
patch_sub_client.pull.assert_called_once_with(mocker.ANY max_messages=1 return_immediately=<true>)<line_sep>patch_sub_client.api.transport.channel.close.assert_called_once_with()<block_end><def_stmt>test_read_messages_timestamp_attribute_milli_success mocker patch_sub_client patch_msg_manager <block_start>exp_entity_id="entity_id"<line_sep>kmsg=klio_pb2.KlioMessage()<line_sep>kmsg.data.element=bytes(exp_entity_id "utf-8")<line_sep>data=kmsg.SerializeToString()<line_sep>attributes={"time":"1337"}<line_sep>publish_time_secs=1520861821<line_sep>publish_time_nanos=234567000<line_sep>ack_id="ack_id"<line_sep>pull_response=beam_test_utils.create_pull_response([beam_test_utils.PullResponseMessage(data attributes publish_time_secs publish_time_nanos ack_id)])<line_sep>pmsg=b_pubsub.PubsubMessage(data attributes)<line_sep>expected_elements=[beam_testing_util.TestWindowedValue(pmsg beam_utils.timestamp.Timestamp(micros=int(attributes["time"])<times>1000) [beam_transforms.window.GlobalWindow()] ) ]<line_sep>patch_sub_client.pull.return_value=pull_response<line_sep>options=pipeline_options.PipelineOptions([])<line_sep>options.view_as(pipeline_options.StandardOptions).streaming=<true><with_stmt>beam_test_pipeline.TestPipeline(options=options)<as>p<block_start>pcoll=p|b_pubsub.ReadFromPubSub("projects/fakeprj/topics/a_topic" <none> <none> with_attributes=<true> timestamp_attribute="time" )<line_sep># Check original functionality that was kept the same
beam_testing_util.assert_that(pcoll beam_testing_util.equal_to(expected_elements) reify_windows=<true> )<block_end># Check overridden functionality:
# 1. Check that auto-acking is skipped
patch_sub_client.acknowledge.assert_not_called()<line_sep># 2. Check that MessageManager daemon threads were started
patch_msg_manager.assert_called_once_with(patch_sub_client.subscription_path())<line_sep># 3. Check that messages were added to the MessageManager
patch_msg_manager.return_value.add.assert_called_once_with(ack_id pmsg)<line_sep># 4. Check that one message is handled at a time, instead of the
# original 10
patch_sub_client.pull.assert_called_once_with(mocker.ANY max_messages=1 return_immediately=<true>)<line_sep>patch_sub_client.api.transport.channel.close.assert_called_once_with()<block_end><def_stmt>test_read_messages_timestamp_attribute_rfc3339_success mocker patch_sub_client patch_msg_manager <block_start>exp_entity_id="entity_id"<line_sep>kmsg=klio_pb2.KlioMessage()<line_sep>kmsg.data.element=bytes(exp_entity_id "utf-8")<line_sep>data=kmsg.SerializeToString()<line_sep>attributes={"time":"2018-03-12T13:37:01.234567Z"}<line_sep>publish_time_secs=1337000000<line_sep>publish_time_nanos=133700000<line_sep>ack_id="ack_id"<line_sep>pull_response=beam_test_utils.create_pull_response([beam_test_utils.PullResponseMessage(data attributes publish_time_secs publish_time_nanos ack_id)])<line_sep>pmsg=b_pubsub.PubsubMessage(data attributes)<line_sep>expected_elements=[beam_testing_util.TestWindowedValue(pmsg beam_utils.timestamp.Timestamp.from_rfc3339(attributes["time"]) [beam_transforms.window.GlobalWindow()] ) ]<line_sep>patch_sub_client.pull.return_value=pull_response<line_sep>options=pipeline_options.PipelineOptions([])<line_sep>options.view_as(pipeline_options.StandardOptions).streaming=<true><with_stmt>beam_test_pipeline.TestPipeline(options=options)<as>p<block_start>pcoll=p|b_pubsub.ReadFromPubSub("projects/fakeprj/topics/a_topic" <none> <none> with_attributes=<true> timestamp_attribute="time" )<line_sep># Check original functionality that was kept the same
beam_testing_util.assert_that(pcoll beam_testing_util.equal_to(expected_elements) reify_windows=<true> )<block_end># Check overridden functionality:
# 1. Check that auto-acking is skipped
patch_sub_client.acknowledge.assert_not_called()<line_sep># 2. Check that MessageManager daemon threads were started
patch_msg_manager.assert_called_once_with(patch_sub_client.subscription_path())<line_sep># 3. Check that messages were added to the MessageManager
patch_msg_manager.return_value.add.assert_called_once_with(ack_id pmsg)<line_sep># 4. Check that one message is handled at a time, instead of the
# original 10
patch_sub_client.pull.assert_called_once_with(mocker.ANY max_messages=1 return_immediately=<true>)<line_sep>patch_sub_client.api.transport.channel.close.assert_called_once_with()<block_end><def_stmt>test_read_messages_timestamp_attribute_missing mocker patch_sub_client patch_msg_manager <block_start>exp_entity_id="entity_id"<line_sep>kmsg=klio_pb2.KlioMessage()<line_sep>kmsg.data.element=bytes(exp_entity_id "utf-8")<line_sep>data=kmsg.SerializeToString()<line_sep>attributes={}<line_sep>publish_time_secs=1520861821<line_sep>publish_time_nanos=234567000<line_sep>publish_time="2018-03-12T13:37:01.234567Z"<line_sep>ack_id="ack_id"<line_sep>pull_response=beam_test_utils.create_pull_response([beam_test_utils.PullResponseMessage(data attributes publish_time_secs publish_time_nanos ack_id)])<line_sep>pmsg=b_pubsub.PubsubMessage(data attributes)<line_sep>expected_elements=[beam_testing_util.TestWindowedValue(pmsg beam_utils.timestamp.Timestamp.from_rfc3339(publish_time) [beam_transforms.window.GlobalWindow()] ) ]<line_sep>patch_sub_client.pull.return_value=pull_response<line_sep>options=pipeline_options.PipelineOptions([])<line_sep>options.view_as(pipeline_options.StandardOptions).streaming=<true><with_stmt>beam_test_pipeline.TestPipeline(options=options)<as>p<block_start>pcoll=p|b_pubsub.ReadFromPubSub("projects/fakeprj/topics/a_topic" <none> <none> with_attributes=<true> timestamp_attribute="nonexistent" )<line_sep># Check original functionality that was kept the same
beam_testing_util.assert_that(pcoll beam_testing_util.equal_to(expected_elements) reify_windows=<true> )<block_end># Check overridden functionality:
# 1. Check that auto-acking is skipped
patch_sub_client.acknowledge.assert_not_called()<line_sep># 2. Check that MessageManager daemon threads were started
patch_msg_manager.assert_called_once_with(patch_sub_client.subscription_path())<line_sep># 3. Check that messages were added to the MessageManager
patch_msg_manager.return_value.add.assert_called_once_with(ack_id pmsg)<line_sep># 4. Check that one message is handled at a time, instead of the
# original 10
patch_sub_client.pull.assert_called_once_with(mocker.ANY max_messages=1 return_immediately=<true>)<line_sep>patch_sub_client.api.transport.channel.close.assert_called_once_with()<block_end><def_stmt>test_read_messages_timestamp_attribute_fail_parse patch_sub_client<block_start>exp_entity_id="entity_id"<line_sep>kmsg=klio_pb2.KlioMessage()<line_sep>kmsg.data.element=bytes(exp_entity_id "utf-8")<line_sep>data=kmsg.SerializeToString()<line_sep>attributes={"time":"1337 unparseable"}<line_sep>publish_time_secs=1520861821<line_sep>publish_time_nanos=234567000<line_sep>ack_id="ack_id"<line_sep>pull_response=beam_test_utils.create_pull_response([beam_test_utils.PullResponseMessage(data attributes publish_time_secs publish_time_nanos ack_id)])<line_sep>patch_sub_client.pull.return_value=pull_response<line_sep>options=pipeline_options.PipelineOptions([])<line_sep>options.view_as(pipeline_options.StandardOptions).streaming=<true><line_sep>p=beam_test_pipeline.TestPipeline(options=options)<line_sep>_=p|b_pubsub.ReadFromPubSub("projects/fakeprj/topics/a_topic" <none> <none> with_attributes=<true> timestamp_attribute="time" )<with_stmt>pytest.raises(ValueError match=r"parse")<block_start>p.run()<block_end>patch_sub_client.acknowledge.assert_not_called()<line_sep>patch_sub_client.api.transport.channel.close.assert_called_with()<block_end> |
"""Tests for the Geofency component."""<line_sep> |
"""
Copyright (c) 2020 COTOBA DESIGN, Inc.
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_stmt>unittest<import_stmt>os<import_from_stmt>programy.mappings.properties PropertiesCollection<import_from_stmt>programy.storage.factory StorageFactory<import_from_stmt>programy.storage.stores.file.config FileStorageConfiguration<import_from_stmt>programy.storage.stores.file.engine FileStorageEngine<import_from_stmt>programy.storage.stores.file.config FileStoreConfiguration<class_stmt>PropertysTests(unittest.TestCase)<block_start><def_stmt>test_initialise_collection self<block_start>collection=PropertiesCollection()<line_sep>self.assertIsNotNone(collection)<block_end><def_stmt>test_properties_operations self<block_start>collection=PropertiesCollection()<line_sep>self.assertIsNotNone(collection)<line_sep>collection.add_property("name" "KeiffBot 1.0")<line_sep>collection.add_property("firstname" "Keiff")<line_sep>collection.add_property("middlename" "AIML")<line_sep>collection.add_property("lastname" "BoT")<line_sep>collection.add_property("fullname" "KeiffBot")<line_sep>self.assertTrue(collection.has_property("name"))<line_sep>self.assertFalse(collection.has_property("age"))<line_sep>self.assertEqual("KeiffBot 1.0" collection.property("name"))<line_sep>self.assertIsNone(collection.property("age"))<block_end><def_stmt>test_load_from_file self<block_start>storage_factory=StorageFactory()<line_sep>file_store_config=FileStorageConfiguration()<line_sep>file_store_config._properties_storage=FileStoreConfiguration(file=os.path.dirname(__file__)+os.sep+"test_files"+os.sep+"properties.txt" format="text" extension="txt" encoding="utf-8" delete_on_start=<false>)<line_sep>storage_engine=FileStorageEngine(file_store_config)<line_sep>storage_factory._storage_engines[StorageFactory.PROPERTIES]=storage_engine<line_sep>storage_factory._store_to_engine_map[StorageFactory.PROPERTIES]=storage_engine<line_sep>collection=PropertiesCollection()<line_sep>self.assertIsNotNone(collection)<line_sep>collection.load(storage_factory)<line_sep>self.assertTrue(collection.has_property("name"))<line_sep>self.assertFalse(collection.has_property("age"))<line_sep>self.assertEqual("KeiffBot 1.0" collection.property("name"))<line_sep>self.assertIsNone(collection.property("age"))<block_end><def_stmt>test_reload_from_file self<block_start>storage_factory=StorageFactory()<line_sep>file_store_config=FileStorageConfiguration()<line_sep>file_store_config._properties_storage=FileStoreConfiguration(file=os.path.dirname(__file__)+os.sep+"test_files"+os.sep+"properties.txt" format="text" extension="txt" encoding="utf-8" delete_on_start=<false>)<line_sep>storage_engine=FileStorageEngine(file_store_config)<line_sep>storage_factory._storage_engines[StorageFactory.PROPERTIES]=storage_engine<line_sep>storage_factory._store_to_engine_map[StorageFactory.PROPERTIES]=storage_engine<line_sep>collection=PropertiesCollection()<line_sep>self.assertIsNotNone(collection)<line_sep>collection.load(storage_factory)<line_sep>self.assertTrue(collection.has_property("name"))<line_sep>self.assertFalse(collection.has_property("age"))<line_sep>self.assertEqual("KeiffBot 1.0" collection.property("name"))<line_sep>self.assertIsNone(collection.property("age"))<line_sep>collection.remove()<line_sep>collection.reload_file(storage_factory)<line_sep>self.assertTrue(collection.has_property("name"))<line_sep>self.assertFalse(collection.has_property("age"))<line_sep>self.assertEqual("KeiffBot 1.0" collection.property("name"))<line_sep>self.assertIsNone(collection.property("age"))<block_end><block_end> |
<import_stmt>asyncio<import_stmt>sys<import_stmt>contextlib<line_sep>@asyncio.coroutine<def_stmt>show_remaining dots_task<block_start>remaining=5<while_stmt>remaining<block_start>print('Remaining: ' remaining)<line_sep>sys.stdout.flush()<line_sep><yield><from>asyncio.sleep(1)<line_sep>remaining<augsub>1<block_end>dots_task.cancel()<line_sep>print()<block_end>@asyncio.coroutine<def_stmt>dots <block_start><while_stmt><true><block_start>print('.' sep='' end='')<line_sep>sys.stdout.flush()<line_sep><yield><from>asyncio.sleep(.1)<block_end><block_end><def_stmt>main <block_start><with_stmt>contextlib.closing(asyncio.get_event_loop())<as>loop<block_start>dots_task=asyncio.Task(dots())<line_sep>coros=[show_remaining(dots_task) dots_task]<line_sep>loop.run_until_complete(asyncio.wait(coros))<block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>main()<block_end> |
<import_from_stmt>django.conf.urls url<import_from_stmt>django.conf.urls patterns<import_from_stmt>django.views.generic TemplateView<line_sep>view=TemplateView.as_view(template_name='dummy.html')<line_sep>urlpatterns=patterns('' url(r'^nl/foo/' view name='not-translated') )<line_sep> |
<import_from_stmt>rest_framework serializers<import_from_stmt>.models Subscriber<class_stmt>SubscriberSerializer(serializers.ModelSerializer)<block_start><class_stmt>Meta<block_start>model=Subscriber<line_sep>fields=('email' )<block_end><block_end> |
<import_stmt>os<import_stmt>shutil<import_stmt>argparse<import_stmt>torch<import_from_stmt>torch nn<import_from_stmt>torchvision.utils save_image make_grid<import_stmt>matplotlib.pyplot<as>plt<import_stmt>numpy<as>np<import_stmt>cv2<as>cv<import_stmt>utils.utils<as>utils<import_from_stmt>utils.constants *<class_stmt>GenerationMode(enum.Enum)<block_start>SINGLE_IMAGE=0 <line_sep>INTERPOLATION=1 <line_sep>VECTOR_ARITHMETIC=2<block_end><def_stmt>postprocess_generated_img generated_img_tensor<block_start><assert_stmt>isinstance(generated_img_tensor torch.Tensor) f'Expected PyTorch tensor but got {type(generated_img_tensor)}.'<line_sep># Move the tensor from GPU to CPU, convert to numpy array, extract 0th batch, move the image channel
# from 0th to 2nd position (CHW -> HWC)
generated_img=np.moveaxis(generated_img_tensor.to('cpu').numpy()[0] 0 2)<line_sep># If grayscale image repeat 3 times to get RGB image (for generators trained on MNIST)
<if_stmt>generated_img.shape[2]<eq>1<block_start>generated_img=np.repeat(generated_img 3 axis=2)<block_end># Imagery is in the range [-1, 1] (generator has tanh as the output activation) move it into [0, 1] range
generated_img<augsub>np.min(generated_img)<line_sep>generated_img<augdiv>np.max(generated_img)<line_sep><return>generated_img<block_end><def_stmt>generate_from_random_latent_vector generator cgan_digit=<none><block_start><with_stmt>torch.no_grad()<block_start>latent_vector=utils.get_gaussian_latent_batch(1 next(generator.parameters()).device)<if_stmt>cgan_digit<is><none><block_start>generated_img=postprocess_generated_img(generator(latent_vector))<block_end><else_stmt># condition and generate the digit specified by cgan_digit
<block_start>ref_label=torch.tensor([cgan_digit] dtype=torch.int64)<line_sep>ref_label_one_hot_encoding=torch.nn.functional.one_hot(ref_label MNIST_NUM_CLASSES).type(torch.FloatTensor).to(next(generator.parameters()).device)<line_sep>generated_img=postprocess_generated_img(generator(latent_vector ref_label_one_hot_encoding))<block_end><block_end><return>generated_img latent_vector.to('cpu').numpy()[0]<block_end><def_stmt>generate_from_specified_numpy_latent_vector generator latent_vector<block_start><assert_stmt>isinstance(latent_vector np.ndarray) f'Expected latent vector to be numpy array but got {type(latent_vector)}.'<with_stmt>torch.no_grad()<block_start>latent_vector_tensor=torch.unsqueeze(torch.tensor(latent_vector device=next(generator.parameters()).device) dim=0)<line_sep><return>postprocess_generated_img(generator(latent_vector_tensor))<block_end><block_end><def_stmt>linear_interpolation t p0 p1<block_start><return>p0+t<times>(p1-p0)<block_end><def_stmt>spherical_interpolation t p0 p1<block_start>""" Spherical interpolation (slerp) formula: https://en.wikipedia.org/wiki/Slerp
Found inspiration here: https://github.com/soumith/ganhacks
but I didn't get any improvement using it compared to linear interpolation.
Args:
t (float): has [0, 1] range
p0 (numpy array): First n-dimensional vector
p1 (numpy array): Second n-dimensional vector
Result:
Returns spherically interpolated vector.
"""<if_stmt>t<le>0<block_start><return>p0<block_end><elif_stmt>t<ge>1<block_start><return>p1<block_end><elif_stmt>np.allclose(p0 p1)<block_start><return>p0<block_end># Convert p0 and p1 to unit vectors and find the angle between them (omega)
omega=np.arccos(np.dot(p0/np.linalg.norm(p0) p1/np.linalg.norm(p1)))<line_sep>sin_omega=np.sin(omega)# syntactic sugar
<return>np.sin((1.0-t)<times>omega)/sin_omega<times>p0+np.sin(t<times>omega)/sin_omega<times>p1<block_end><def_stmt>display_vector_arithmetic_results imgs_to_display<block_start>fig=plt.figure(figsize=(6 6))<line_sep>title_fontsize='x-small'<line_sep>num_display_imgs=7<line_sep>titles=['happy women' 'happy woman (avg)' 'neutral women' 'neutral woman (avg)' 'neutral men' 'neutral man (avg)' 'result - happy man']<line_sep>ax=np.zeros(num_display_imgs dtype=object)<assert_stmt>len(imgs_to_display)<eq>num_display_imgs f'Expected {num_display_imgs} got {len(imgs_to_display)} images.'<line_sep>gs=fig.add_gridspec(5 4 left=0.02 right=0.98 wspace=0.05 hspace=0.3)<line_sep>ax[0]=fig.add_subplot(gs[0 :3])<line_sep>ax[1]=fig.add_subplot(gs[0 3])<line_sep>ax[2]=fig.add_subplot(gs[1 :3])<line_sep>ax[3]=fig.add_subplot(gs[1 3])<line_sep>ax[4]=fig.add_subplot(gs[2 :3])<line_sep>ax[5]=fig.add_subplot(gs[2 3])<line_sep>ax[6]=fig.add_subplot(gs[3: 1:3])<for_stmt>i range(num_display_imgs)<block_start>ax[i].imshow(cv.resize(imgs_to_display[i] (0 0) fx=3 fy=3 interpolation=cv.INTER_NEAREST))<line_sep>ax[i].set_title(titles[i] fontsize=title_fontsize)<line_sep>ax[i].tick_params(which='both' bottom=<false> left=<false> labelleft=<false> labelbottom=<false>)<block_end>plt.show()<block_end><def_stmt>generate_new_images model_name cgan_digit=<none> generation_mode=<true> slerp=<true> a=<none> b=<none> should_display=<true><block_start>""" Generate imagery using pre-trained generator (using vanilla_generator_000000.pth by default)
Args:
model_name (str): model name you want to use (default lookup location is BINARIES_PATH).
cgan_digit (int): if specified generate that exact digit.
generation_mode (enum): generate a single image from a random vector, interpolate between the 2 chosen latent
vectors, or perform arithmetic over latent vectors (note: not every mode is supported for every model type)
slerp (bool): if True use spherical interpolation otherwise use linear interpolation.
a, b (numpy arrays): latent vectors, if set to None you'll be prompted to choose images you like,
and use corresponding latent vectors instead.
should_display (bool): Display the generated images before saving them.
"""<line_sep>model_path=os.path.join(BINARIES_PATH model_name)<assert_stmt>os.path.exists(model_path) f'Could not find the model {model_path}. You first need to train your generator.'<line_sep>device=torch.device("cuda"<if>torch.cuda.is_available()<else>"cpu")<line_sep># Prepare the correct (vanilla, cGAN, DCGAN, ...) model, load the weights and put the model into evaluation mode
model_state=torch.load(model_path)<line_sep>gan_type=model_state["gan_type"]<line_sep>print(f'Found {gan_type} GAN!')<line_sep>_,generator=utils.get_gan(device gan_type)<line_sep>generator.load_state_dict(model_state["state_dict"] strict=<true>)<line_sep>generator.eval()<line_sep># Generate a single image, save it and potentially display it
<if_stmt>generation_mode<eq>GenerationMode.SINGLE_IMAGE<block_start>generated_imgs_path=os.path.join(DATA_DIR_PATH 'generated_imagery')<line_sep>os.makedirs(generated_imgs_path exist_ok=<true>)<line_sep>generated_img,_=generate_from_random_latent_vector(generator cgan_digit<if>gan_type<eq>GANType.CGAN.name<else><none>)<line_sep>utils.save_and_maybe_display_image(generated_imgs_path generated_img should_display=should_display)<block_end># Pick 2 images you like between which you'd like to interpolate (by typing 'y' into console)
<elif_stmt>generation_mode<eq>GenerationMode.INTERPOLATION<block_start><assert_stmt>gan_type<eq>GANType.VANILLA.name<or>gan_type<eq>GANType.DCGAN.name f'Got {gan_type} but only VANILLA/DCGAN are supported for the interpolation mode.'<line_sep>interpolation_name="spherical"<if>slerp<else>"linear"<line_sep>interpolation_fn=spherical_interpolation<if>slerp<else>linear_interpolation<line_sep>grid_interpolated_imgs_path=os.path.join(DATA_DIR_PATH 'interpolated_imagery')# combined results dir
decomposed_interpolated_imgs_path=os.path.join(grid_interpolated_imgs_path f'tmp_{gan_type}_{interpolation_name}_dump')# dump separate results
<if_stmt>os.path.exists(decomposed_interpolated_imgs_path)<block_start>shutil.rmtree(decomposed_interpolated_imgs_path)<block_end>os.makedirs(grid_interpolated_imgs_path exist_ok=<true>)<line_sep>os.makedirs(decomposed_interpolated_imgs_path exist_ok=<true>)<line_sep>latent_vector_a,latent_vector_b=[<none> <none>]<line_sep># If a and b were not specified loop until the user picked the 2 images he/she likes.
found_good_vectors_flag=<false><if_stmt>a<is><none><or>b<is><none><block_start><while_stmt><not>found_good_vectors_flag<block_start>generated_img,latent_vector=generate_from_random_latent_vector(generator)<line_sep>plt.imshow(generated_img)<line_sep>plt.title('Do you like this image?')<line_sep>plt.show()<line_sep>user_input=input("Do you like this generated image? [y for yes]:")<if_stmt>user_input<eq>'y'<block_start><if_stmt>latent_vector_a<is><none><block_start>latent_vector_a=latent_vector<line_sep>print('Saved the first latent vector.')<block_end><elif_stmt>latent_vector_b<is><none><block_start>latent_vector_b=latent_vector<line_sep>print('Saved the second latent vector.')<line_sep>found_good_vectors_flag=<true><block_end><block_end><else_stmt><block_start>print('Well lets generate a new one!')<line_sep><continue><block_end><block_end><block_end><else_stmt><block_start>print('Skipping latent vectors selection section and using cached ones.')<line_sep>latent_vector_a,latent_vector_b=[a b]<block_end># Cache latent vectors
<if_stmt>a<is><none><or>b<is><none><block_start>np.save(os.path.join(grid_interpolated_imgs_path 'a.npy') latent_vector_a)<line_sep>np.save(os.path.join(grid_interpolated_imgs_path 'b.npy') latent_vector_b)<block_end>print(f'Lets do some {interpolation_name} interpolation!')<line_sep>interpolation_resolution=47# number of images between the vectors a and b
num_interpolated_imgs=interpolation_resolution+2# + 2 so that we include a and b
generated_imgs=[]<for_stmt>i range(num_interpolated_imgs)<block_start>t=i/(num_interpolated_imgs-1)# goes from 0. to 1.
current_latent_vector=interpolation_fn(t latent_vector_a latent_vector_b)<line_sep>generated_img=generate_from_specified_numpy_latent_vector(generator current_latent_vector)<line_sep>print(f'Generated image [{i+1}/{num_interpolated_imgs}].')<line_sep>utils.save_and_maybe_display_image(decomposed_interpolated_imgs_path generated_img should_display=should_display)<line_sep># Move from channel last to channel first (CHW->HWC), PyTorch's save_image function expects BCHW format
generated_imgs.append(torch.tensor(np.moveaxis(generated_img 2 0)))<block_end>interpolated_block_img=torch.stack(generated_imgs)<line_sep>interpolated_block_img=nn.Upsample(scale_factor=2.5 mode='nearest')(interpolated_block_img)<line_sep>save_image(interpolated_block_img os.path.join(grid_interpolated_imgs_path utils.get_available_file_name(grid_interpolated_imgs_path)) nrow=int(np.sqrt(num_interpolated_imgs)))<block_end><elif_stmt>generation_mode<eq>GenerationMode.VECTOR_ARITHMETIC<block_start><assert_stmt>gan_type<eq>GANType.DCGAN.name f'Got {gan_type} but only DCGAN is supported for arithmetic mode.'<line_sep># Generate num_options face images and create a grid image from them
num_options=100<line_sep>generated_imgs=[]<line_sep>latent_vectors=[]<line_sep>padding=2<for_stmt>i range(num_options)<block_start>generated_img,latent_vector=generate_from_random_latent_vector(generator)<line_sep>generated_imgs.append(torch.tensor(np.moveaxis(generated_img 2 0)))# make_grid expects CHW format
latent_vectors.append(latent_vector)<block_end>stacked_tensor_imgs=torch.stack(generated_imgs)<line_sep>final_tensor_img=make_grid(stacked_tensor_imgs nrow=int(np.sqrt(num_options)) padding=padding)<line_sep>display_img=np.moveaxis(final_tensor_img.numpy() 0 2)<line_sep># For storing latent vectors
num_of_vectors_per_category=3<line_sep>happy_woman_latent_vectors=[]<line_sep>neutral_woman_latent_vectors=[]<line_sep>neutral_man_latent_vectors=[]<line_sep># Make it easy - by clicking on the plot you pick the image.
<def_stmt>onclick event<block_start><if_stmt>event.dblclick<block_start><pass><block_end><else_stmt># single click
<block_start><if_stmt>event.button<eq>1# left click
<block_start>x_coord=event.xdata<line_sep>y_coord=event.ydata<line_sep>column=int(x_coord/(64+padding))<line_sep>row=int(y_coord/(64+padding))<line_sep># Store latent vector corresponding to the image that the user clicked on.
<if_stmt>len(happy_woman_latent_vectors)<l>num_of_vectors_per_category<block_start>happy_woman_latent_vectors.append(latent_vectors[10<times>row+column])<line_sep>print(f'Picked image row={row}, column={column} as {len(happy_woman_latent_vectors)}. happy woman.')<block_end><elif_stmt>len(neutral_woman_latent_vectors)<l>num_of_vectors_per_category<block_start>neutral_woman_latent_vectors.append(latent_vectors[10<times>row+column])<line_sep>print(f'Picked image row={row}, column={column} as {len(neutral_woman_latent_vectors)}. neutral woman.')<block_end><elif_stmt>len(neutral_man_latent_vectors)<l>num_of_vectors_per_category<block_start>neutral_man_latent_vectors.append(latent_vectors[10<times>row+column])<line_sep>print(f'Picked image row={row}, column={column} as {len(neutral_man_latent_vectors)}. neutral man.')<block_end><else_stmt><block_start>plt.close()<block_end><block_end><block_end><block_end>plt.figure(figsize=(10 10))<line_sep>plt.imshow(display_img)<line_sep># This is just an example you could also pick 3 neutral woman images with sunglasses, etc.
plt.title('Click on 3 happy women, 3 neutral women and \n 3 neutral men images (order matters!)')<line_sep>cid=plt.gcf().canvas.mpl_connect('button_press_event' onclick)<line_sep>plt.show()<line_sep>plt.gcf().canvas.mpl_disconnect(cid)<line_sep>print('Done choosing images.')<line_sep># Calculate the average latent vector for every category (happy woman, neutral woman, neutral man)
happy_woman_avg_latent_vector=np.mean(np.array(happy_woman_latent_vectors) axis=0)<line_sep>neutral_woman_avg_latent_vector=np.mean(np.array(neutral_woman_latent_vectors) axis=0)<line_sep>neutral_man_avg_latent_vector=np.mean(np.array(neutral_man_latent_vectors) axis=0)<line_sep># By subtracting neutral woman from the happy woman we capture the "vector of smiling". Adding that vector
# to a neutral man we get a happy man's latent vector! Our latent space has amazingly beautiful structure!
happy_man_latent_vector=neutral_man_avg_latent_vector+(happy_woman_avg_latent_vector-neutral_woman_avg_latent_vector)<line_sep># Generate images from these latent vectors
happy_women_imgs=np.hstack([generate_from_specified_numpy_latent_vector(generator v)<for>v happy_woman_latent_vectors])<line_sep>neutral_women_imgs=np.hstack([generate_from_specified_numpy_latent_vector(generator v)<for>v neutral_woman_latent_vectors])<line_sep>neutral_men_imgs=np.hstack([generate_from_specified_numpy_latent_vector(generator v)<for>v neutral_man_latent_vectors])<line_sep>happy_woman_avg_img=generate_from_specified_numpy_latent_vector(generator happy_woman_avg_latent_vector)<line_sep>neutral_woman_avg_img=generate_from_specified_numpy_latent_vector(generator neutral_woman_avg_latent_vector)<line_sep>neutral_man_avg_img=generate_from_specified_numpy_latent_vector(generator neutral_man_avg_latent_vector)<line_sep>happy_man_img=generate_from_specified_numpy_latent_vector(generator happy_man_latent_vector)<line_sep>display_vector_arithmetic_results([happy_women_imgs happy_woman_avg_img neutral_women_imgs neutral_woman_avg_img neutral_men_imgs neutral_man_avg_img happy_man_img])<block_end><else_stmt><block_start><raise>Exception(f'Generation mode not yet supported.')<block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>parser=argparse.ArgumentParser()<line_sep>parser.add_argument("--model_name" type=str help="Pre-trained generator model name" default=r'VANILLA_000000.pth')<line_sep>parser.add_argument("--cgan_digit" type=int help="Used only for cGAN - generate specified digit" default=3)<line_sep>parser.add_argument("--generation_mode" type=bool help="Pick between 3 generation modes" default=GenerationMode.SINGLE_IMAGE)<line_sep>parser.add_argument("--slerp" type=bool help="Should use spherical interpolation (default No)" default=<false>)<line_sep>parser.add_argument("--should_display" type=bool help="Display intermediate results" default=<true>)<line_sep>args=parser.parse_args()<line_sep># The first time you start generation in the interpolation mode it will cache a and b
# which you'll choose the first time you run the it.
a_path=os.path.join(DATA_DIR_PATH 'interpolated_imagery' 'a.npy')<line_sep>b_path=os.path.join(DATA_DIR_PATH 'interpolated_imagery' 'b.npy')<line_sep>latent_vector_a=np.load(a_path)<if>os.path.exists(a_path)<else><none><line_sep>latent_vector_b=np.load(b_path)<if>os.path.exists(b_path)<else><none><line_sep>generate_new_images(args.model_name args.cgan_digit generation_mode=args.generation_mode slerp=args.slerp a=latent_vector_a b=latent_vector_b should_display=args.should_display)<block_end> |
# First make the vocabulary, etc.
<import_stmt>os<import_stmt>pickle<as>pkl<import_stmt>random<import_stmt>simplejson<as>json<import_from_stmt>allennlp.common.util get_spacy_model<import_from_stmt>allennlp.data Instance<import_from_stmt>allennlp.data Token<import_from_stmt>allennlp.data Vocabulary<import_from_stmt>allennlp.data.dataset Batch<import_from_stmt>allennlp.data.fields TextField<import_from_stmt>allennlp.data.token_indexers SingleIdTokenIndexer<import_from_stmt>allennlp.data.token_indexers.elmo_indexer ELMoTokenCharactersIndexer<import_from_stmt>torch.utils.data Dataset<import_from_stmt>torch.utils.data.dataloader DataLoader<import_from_stmt>tqdm tqdm<import_from_stmt>raw_data.events DATA_PATH<import_from_stmt>pytorch_misc pairwise<import_from_stmt>create_swag.lm.config NUM_FOLDS<def_stmt>load_lm_data fold=<none> mode='train'<block_start>"""
Turns the sequential data into instances.
:param split:
:return:
"""<line_sep># Get or make vocab
spacy_model=get_spacy_model("en_core_web_sm" pos_tags=<false> parse=<false> ner=<false>)<if_stmt>os.path.exists('vocabulary')<block_start>print("Loading cached vocab. caution if you're building the dataset again!!!!" flush=<true>)<line_sep>vocab=Vocabulary.from_files('vocabulary')<with_stmt>open(os.path.join(DATA_PATH 'events-3.json') 'r')<as>f<block_start>lm_data=json.load(f)<block_end>lm_data=[data_item<for>s ('train' 'val' 'test')<for>data_item lm_data[s]]<block_end><else_stmt><block_start><assert_stmt>fold<is><none><with_stmt>open(os.path.join(DATA_PATH 'events-3.json') 'r')<as>f<block_start>lm_data=json.load(f)<block_end>lm_data=[data_item<for>s ('train' 'val' 'test')<for>data_item lm_data[s]]<line_sep># Manually doing this because I don't want to double count things
vocab=Vocabulary.from_instances([Instance({'story':TextField([Token(x)<for>x ['@@bos@@']+[x.orth_<for>x spacy_model(sent)]+['@@eos@@']] token_indexers={'tokens':SingleIdTokenIndexer(namespace='tokens' lowercase_tokens=<true>)})})<for>data_item lm_data<for>sent data_item['sentences']] min_count={'tokens':3})<line_sep>vocab.get_index_to_token_vocabulary('tokens')<line_sep>vocab.save_to_files('vocabulary')<line_sep>print("VOCABULARY HAS {} ITEMS".format(vocab.get_vocab_size(namespace='tokens')))<block_end><if_stmt>all([os.path.exists('lm-{}-of-{}.pkl'.format(i NUM_FOLDS))<for>i range(NUM_FOLDS)])<block_start>print("LOADING CACHED DATASET" flush=<true>)<if_stmt>mode<eq>'val'<block_start><with_stmt>open('lm-{}-of-{}.pkl'.format(fold NUM_FOLDS) 'rb')<as>f<block_start>print("Loading split{} for {}".format(fold mode))<line_sep>instances=pkl.load(f)<block_end><block_end><else_stmt><block_start>instances=[]<for_stmt>other_fold range(NUM_FOLDS)<block_start><if_stmt>other_fold<ne>fold<block_start><with_stmt>open('lm-{}-of-{}.pkl'.format(other_fold NUM_FOLDS) 'rb')<as>f<block_start>print("Loading split{} for {}".format(other_fold mode))<line_sep>instances<augadd>pkl.load(f)<block_end><block_end><block_end><block_end><return>instances vocab<block_end>print("MAKING THE DATASET" flush=<true>)<assert_stmt>fold<is><none><for_stmt>item tqdm(lm_data)<block_start>item['sentences_tokenized']=[[st.orth_<for>st spacy_model(sent)]<for>sent item['sentences']]<block_end><def_stmt>_to_instances data# flatten this
<block_start>instances=[]<for_stmt>item data<block_start><for_stmt>s1,s2 pairwise(item['sentences_tokenized'])<block_start>instances.append((Instance({'story':TextField([Token(x)<for>x ['@@bos@@']+s1+s2+['@@eos@@']] token_indexers={'tokens':SingleIdTokenIndexer(namespace='tokens' lowercase_tokens=<true>)})}) s1 s2 item ))<block_end><block_end><return>instances<block_end>random.seed(123456)<line_sep>random.shuffle(lm_data)<line_sep>all_sets=[]<for_stmt>fold_ range(NUM_FOLDS)<block_start>val_set=_to_instances(lm_data[len(lm_data)<times>fold_<floordiv>NUM_FOLDS:len(lm_data)<times>(fold_+1)<floordiv>NUM_FOLDS])<with_stmt>open('lm-{}-of-{}.pkl'.format(fold_ NUM_FOLDS) 'wb')<as>f<block_start>pkl.dump(val_set f)<block_end>all_sets.extend(val_set)<block_end><return>all_sets vocab<block_end><class_stmt>RawPassages(Dataset)<block_start><def_stmt>__init__ self fold mode<block_start>self.mode=mode<line_sep>self.fold=fold<line_sep>self.instances,self.vocab=load_lm_data(fold=self.fold mode=self.mode)<line_sep>self.dataloader=DataLoader(dataset=self batch_size=32 shuffle=self.mode<eq>'train' num_workers=0 collate_fn=self.collate drop_last=self.mode<eq>'train')<line_sep>self.indexer=ELMoTokenCharactersIndexer()<block_end><def_stmt>collate self instances_l<block_start>batch=Batch([x[0]<for>x instances_l])<line_sep>batch.index_instances(self.vocab)<line_sep>batch_dict={k:v['tokens']<for>k,v batch.as_tensor_dict().items()}<line_sep>batch_dict['story_tokens']=[instance[0].fields['story'].tokens<for>instance instances_l]<line_sep>batch_dict['story_full']=[x[1]+x[2]<for>x instances_l]<line_sep>batch_dict['items']=[x[3]<for>x instances_l]<line_sep><return>batch_dict<block_end><def_stmt>__len__ self<block_start><return>len(self.instances)<block_end><def_stmt>__getitem__ self index<block_start>"""
:param index:
:return: * raw rocstories
* entities
* entity IDs + sentences
* Instance. to print use r3.fields['verb_phrase'].field_list[5].tokens
"""<line_sep><return>self.instances[index]<block_end>@classmethod<def_stmt>splits cls fold<block_start><return>cls(fold mode='train') cls(fold mode='val')<block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>instances,vocab=load_lm_data()<line_sep># train, val = RawPassages.splits()
# for item in train.dataloader:
# for story in item['story_tokens']:
# tok_text = [x.text.lower() for x in story]
# remapped_text = [vocab.get_token_from_index(vocab.get_token_index(x)) for x in tok_text]
# print('({}) {} -> {}'.format('D' if tok_text != remapped_text else ' ',
# ' '.join(tok_text), ' '.join(remapped_text)), flush=True)
<block_end> |
# $Id$
#
# Copyright (C) 2003-2006 <NAME> and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
""" unit testing code for BitEnsembles
"""<import_stmt>os<import_stmt>shutil<import_stmt>tempfile<import_stmt>unittest<import_from_stmt>rdkit RDConfig<import_from_stmt>rdkit.DataStructs SparseBitVect<line_sep># This import is important to initialize the BitEnsemble module
<import_from_stmt>rdkit.DataStructs BitEnsembleDb<import_from_stmt>rdkit.DataStructs.BitEnsemble BitEnsemble<class_stmt>TestCase(unittest.TestCase)<block_start><def_stmt>test1 self<block_start>ensemble=BitEnsemble()<line_sep>ensemble.SetBits([1 11 21 31])<line_sep>self.assertEqual(ensemble.GetNumBits() 4)<line_sep>bv=SparseBitVect(100)<line_sep>bv.SetBit(1)<line_sep>bv.SetBit(11)<line_sep>bv.SetBit(13)<line_sep>score=ensemble.ScoreWithOnBits(bv)<assert_stmt>score<eq>2 'bad score: %d'%(score)<line_sep>score=ensemble.ScoreWithIndex(bv)<assert_stmt>score<eq>2 'bad score: %d'%(score)<block_end><def_stmt>test2 self<block_start>ensemble=BitEnsemble([1 11 21 31])<line_sep>bv=SparseBitVect(100)<line_sep>bv.SetBit(1)<line_sep>bv.SetBit(11)<line_sep>bv.SetBit(13)<line_sep>score=ensemble.ScoreWithOnBits(bv)<assert_stmt>score<eq>2 'bad score: %d'%(score)<line_sep>score=ensemble.ScoreWithIndex(bv)<assert_stmt>score<eq>2 'bad score: %d'%(score)<block_end><def_stmt>test3 self<block_start>ensemble=BitEnsemble()<for_stmt>bit [1 11 21 31]<block_start>ensemble.AddBit(bit)<block_end>bv=SparseBitVect(100)<line_sep>bv.SetBit(1)<line_sep>bv.SetBit(11)<line_sep>bv.SetBit(13)<line_sep>score=ensemble.ScoreWithOnBits(bv)<assert_stmt>score<eq>2 'bad score: %d'%(score)<line_sep>score=ensemble.ScoreWithIndex(bv)<assert_stmt>score<eq>2 'bad score: %d'%(score)<block_end><def_stmt>_setupDb self<block_start><import_from_stmt>rdkit.Dbase.DbConnection DbConnect<line_sep>fName=RDConfig.RDTestDatabase<if_stmt>RDConfig.useSqlLite<block_start>_,tempName=tempfile.mkstemp(suffix='sqlt')<line_sep>self.tempDbName=tempName<line_sep>shutil.copyfile(fName tempName)<block_end><else_stmt># pragma: nocover
<block_start>tempName='::RDTests'<block_end>self.conn=DbConnect(tempName)<line_sep>self.dbTblName='bit_ensemble_test'<line_sep><return>self.conn<block_end><def_stmt>tearDown self<block_start><if_stmt>hasattr(self 'tempDbName')<and>RDConfig.useSqlLite<and>os.path.exists(self.tempDbName)<block_start><try_stmt><block_start>os.unlink(self.tempDbName)<block_end><except_stmt># pragma: nocover
<block_start><import_stmt>traceback<line_sep>traceback.print_exc()<block_end><block_end><block_end><def_stmt>testdb1 self<block_start>""" test the sig - db functionality """<line_sep>conn=self._setupDb()<line_sep>ensemble=BitEnsemble()<for_stmt>bit [1 3 4]<block_start>ensemble.AddBit(bit)<block_end>sigBs=[([0 0 0 0 0 0] (0 0 0)) ([0 1 0 1 0 0] (1 1 0)) ([0 1 0 0 1 0] (1 0 1)) ([0 1 0 0 1 1] (1 0 1)) ]<line_sep>ensemble.InitScoreTable(conn self.dbTblName)<for_stmt>bs,tgt sigBs<block_start>ensemble.ScoreToDb(bs conn)<block_end>conn.Commit()<line_sep>d=conn.GetData(table=self.dbTblName)<assert_stmt>len(d)<eq>len(sigBs) 'bad number of results returned'<for_stmt>i range(len(sigBs))<block_start>bs,tgt=tuple(sigBs[i])<line_sep>dbRes=tuple(d[i])<assert_stmt>dbRes<eq>tgt 'bad bits returned: %s != %s'%(str(dbRes) str(tgt))<block_end>d=<none><line_sep>self.conn=<none><block_end><def_stmt>testdb2 self<block_start>""" test the sig - db functionality """<line_sep>conn=self._setupDb()<line_sep>ensemble=BitEnsemble()<for_stmt>bit [1 3 4]<block_start>ensemble.AddBit(bit)<block_end>sigBs=[([0 0 0 0 0 0] (0 0 0)) ([0 1 0 1 0 0] (1 1 0)) ([0 1 0 0 1 0] (1 0 1)) ([0 1 0 0 1 1] (1 0 1)) ]<line_sep>ensemble.InitScoreTable(conn self.dbTblName idInfo='id varchar(10)' actInfo='act int')<for_stmt>bs,tgt sigBs<block_start>ensemble.ScoreToDb(bs conn id='foo' act=1)<block_end>conn.Commit()<line_sep>d=conn.GetData(table=self.dbTblName)<assert_stmt>len(d)<eq>len(sigBs) 'bad number of results returned'<for_stmt>i range(len(sigBs))<block_start>bs,tgt=tuple(sigBs[i])<line_sep>dbRes=tuple(d[i])<assert_stmt>dbRes[1:-1]<eq>tgt 'bad bits returned: %s != %s'%(str(dbRes[1:-1]) str(tgt))<block_end>d=<none><line_sep>self.conn=<none><block_end><block_end><if_stmt>__name__<eq>'__main__'# pragma: nocover
<block_start>unittest.main()<block_end> |
<import_stmt>numpy<as>np<import_stmt>torch<import_stmt>torch.nn<as>nn<import_stmt>torchtestcase<import_stmt>unittest<import_from_stmt>survae.transforms.bijections.conditional.coupling *<import_from_stmt>survae.nn.layers ElementwiseParams ElementwiseParams2d scale_fn<import_from_stmt>survae.tests.transforms.bijections.conditional ConditionalBijectionTest<class_stmt>ConditionalGaussianMixtureCouplingBijectionTest(ConditionalBijectionTest)<block_start><def_stmt>test_bijection_is_well_behaved self<block_start>num_mix=8<line_sep>batch_size=10<line_sep>elementwise_params=3<times>num_mix<line_sep>self.eps=5e-5<for_stmt>shape [(6 ) (6 4 4)]<block_start><for_stmt>num_condition [<none> 1]<block_start><with_stmt>self.subTest(shape=shape num_condition=num_condition)<block_start>x=torch.randn(batch_size *shape)<line_sep>context=torch.randn(batch_size *shape)<if_stmt>num_condition<is><none><block_start><if_stmt>len(shape)<eq>1<block_start>net=nn.Sequential(nn.Linear(3+6 3<times>elementwise_params) ElementwiseParams(elementwise_params))<block_end><if_stmt>len(shape)<eq>3<block_start>net=nn.Sequential(nn.Conv2d(3+6 3<times>elementwise_params kernel_size=3 padding=1) ElementwiseParams2d(elementwise_params))<block_end><block_end><else_stmt><block_start><if_stmt>len(shape)<eq>1<block_start>net=nn.Sequential(nn.Linear(1+6 5<times>elementwise_params) ElementwiseParams(elementwise_params))<block_end><if_stmt>len(shape)<eq>3<block_start>net=nn.Sequential(nn.Conv2d(1+6 5<times>elementwise_params kernel_size=3 padding=1) ElementwiseParams2d(elementwise_params))<block_end><block_end>bijection=ConditionalGaussianMixtureCouplingBijection(net num_mixtures=num_mix num_condition=num_condition)<line_sep>self.assert_bijection_is_well_behaved(bijection x context z_shape=(batch_size *shape))<line_sep>z,_=bijection.forward(x context=context)<if_stmt>num_condition<is><none><block_start>self.assertEqual(x[: :3] z[: :3])<block_end><else_stmt><block_start>self.assertEqual(x[: :1] z[: :1])<block_end><block_end><block_end><block_end><block_end><block_end><class_stmt>ConditionalLogisticMixtureCouplingBijectionTest(ConditionalBijectionTest)<block_start><def_stmt>test_bijection_is_well_behaved self<block_start>num_mix=8<line_sep>batch_size=10<line_sep>elementwise_params=3<times>num_mix<line_sep>self.eps=5e-5<for_stmt>shape [(6 ) (6 4 4)]<block_start><for_stmt>num_condition [<none> 1]<block_start><with_stmt>self.subTest(shape=shape num_condition=num_condition)<block_start>x=torch.randn(batch_size *shape)<line_sep>context=torch.randn(batch_size *shape)<if_stmt>num_condition<is><none><block_start><if_stmt>len(shape)<eq>1<block_start>net=nn.Sequential(nn.Linear(3+6 3<times>elementwise_params) ElementwiseParams(elementwise_params))<block_end><if_stmt>len(shape)<eq>3<block_start>net=nn.Sequential(nn.Conv2d(3+6 3<times>elementwise_params kernel_size=3 padding=1) ElementwiseParams2d(elementwise_params))<block_end><block_end><else_stmt><block_start><if_stmt>len(shape)<eq>1<block_start>net=nn.Sequential(nn.Linear(1+6 5<times>elementwise_params) ElementwiseParams(elementwise_params))<block_end><if_stmt>len(shape)<eq>3<block_start>net=nn.Sequential(nn.Conv2d(1+6 5<times>elementwise_params kernel_size=3 padding=1) ElementwiseParams2d(elementwise_params))<block_end><block_end>bijection=ConditionalLogisticMixtureCouplingBijection(net num_mixtures=num_mix num_condition=num_condition)<line_sep>self.assert_bijection_is_well_behaved(bijection x context z_shape=(batch_size *shape))<line_sep>z,_=bijection.forward(x context=context)<if_stmt>num_condition<is><none><block_start>self.assertEqual(x[: :3] z[: :3])<block_end><else_stmt><block_start>self.assertEqual(x[: :1] z[: :1])<block_end><block_end><block_end><block_end><block_end><block_end><class_stmt>ConditionalCensoredLogisticMixtureCouplingBijectionTest(ConditionalBijectionTest)<block_start><def_stmt>test_bijection_is_well_behaved self<block_start>num_bins=16<line_sep>num_mix=8<line_sep>batch_size=10<line_sep>elementwise_params=3<times>num_mix<line_sep>self.eps=1e-6<for_stmt>shape [(6 ) (6 4 4)]<block_start><for_stmt>num_condition [<none> 1]<block_start><with_stmt>self.subTest(shape=shape num_condition=num_condition)<block_start>x=torch.rand(batch_size *shape)<line_sep>context=torch.randn(batch_size *shape)<if_stmt>num_condition<is><none><block_start><if_stmt>len(shape)<eq>1<block_start>net=nn.Sequential(nn.Linear(3+6 3<times>elementwise_params) ElementwiseParams(elementwise_params))<block_end><if_stmt>len(shape)<eq>3<block_start>net=nn.Sequential(nn.Conv2d(3+6 3<times>elementwise_params kernel_size=3 padding=1) ElementwiseParams2d(elementwise_params))<block_end><block_end><else_stmt><block_start><if_stmt>len(shape)<eq>1<block_start>net=nn.Sequential(nn.Linear(1+6 5<times>elementwise_params) ElementwiseParams(elementwise_params))<block_end><if_stmt>len(shape)<eq>3<block_start>net=nn.Sequential(nn.Conv2d(1+6 5<times>elementwise_params kernel_size=3 padding=1) ElementwiseParams2d(elementwise_params))<block_end><block_end>bijection=ConditionalCensoredLogisticMixtureCouplingBijection(net num_mixtures=num_mix num_bins=num_bins num_condition=num_condition)<line_sep>self.assert_bijection_is_well_behaved(bijection x context z_shape=(batch_size *shape))<line_sep>z,_=bijection.forward(x context=context)<if_stmt>num_condition<is><none><block_start>self.assertEqual(x[: :3] z[: :3])<block_end><else_stmt><block_start>self.assertEqual(x[: :1] z[: :1])<block_end><block_end><block_end><block_end><block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>unittest.main()<block_end> |
##############################################################################
# Copyright (c) 2017 <NAME> <<EMAIL>>, Red Hat
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
##############################################################################
# python generate-sha256.py --project /home/user/opnfv/infra
# output made to working directory, file `output.yaml`
<import_stmt>os<import_stmt>sys<import_stmt>hashlib<import_stmt>argparse<import_from_stmt>binaryornot.check is_binary<line_sep>hasher=hashlib.sha256()<line_sep>parser=argparse.ArgumentParser()<line_sep>parser.add_argument('--project' help="Full path to project folder" required=<true>)<line_sep>args=parser.parse_args()<line_sep>ignore_dirs=['.git']<line_sep>sys.stdout=open('output.yaml' 'w')<line_sep>print("binaries:")<for_stmt>root,dirs,files os.walk(args.project)<block_start>dirs[:]=[d<for>d dirs<if>d<not><in>ignore_dirs]<for_stmt>file files<block_start>full_path=os.path.join(root file)<if_stmt>is_binary(full_path)<block_start><with_stmt>open(full_path 'rb')<as>afile<block_start>buf=afile.read()<line_sep>hasher.update(buf)<line_sep>split_path=full_path.split(args.project+'/' 1)[-1]<line_sep>print(" {}:".format(split_path))<line_sep>sum=hasher.hexdigest()<line_sep>print(" - {}".format(sum))<block_end><block_end><block_end><block_end> |
<import_stmt>inspect<import_from_stmt>collections namedtuple<import_stmt>numpy<as>np<import_from_stmt>sklearn.ensemble GradientBoostingRegressor<import_from_stmt>sklearn.model_selection train_test_split<import_from_stmt>sklearn.exceptions NotFittedError<import_from_stmt>uq360.algorithms.posthocuq PostHocUQ<class_stmt>MetamodelRegression(PostHocUQ)<block_start>""" Extracts confidence scores from black-box regression models using a meta-model [2]_ .
References:
.. [2] Chen, Tongfei, et al. Confidence scoring using whitebox meta-models with linear classifier probes.
The 22nd International Conference on Artificial Intelligence and Statistics. PMLR, 2019.
"""<def_stmt>_create_named_model self mdltype config<block_start>"""
Instantiates a model by name passed in 'mdltype'
:param mdltype: string with name (must be supprted)
:param config: dict with args passed in the instantiation call
:return: mdl instance
"""<assert_stmt>(isinstance(mdltype str))<if_stmt>mdltype<eq>'gbr'<block_start>mdl=GradientBoostingRegressor(**config)<block_end><else_stmt><block_start><raise>NotImplementedError("ERROR: Requested model type unknown: \"%s\""%mdltype)<block_end><return>mdl<block_end><def_stmt>_get_model_instance self model config<block_start>"""
Returns an instance of a model based on (a) a desired name or (b) passed in class, or
(c) passed in instance
:param model: string, class, or instance. Class and instance must have certain methods callable.
:param config: dict with args passed in during the instantiation
:return: model instance
"""<assert_stmt>(model<is><not><none><and>config<is><not><none>)<if_stmt>isinstance(model str)# 'model' is a name, create it
<block_start>mdl=self._create_named_model(model config)<block_end><elif_stmt>inspect.isclass(model)# 'model' is a class, instantiate it
<block_start>mdl=model(**config)<block_end><else_stmt># 'model' is an instance, register it
<block_start>mdl=model<block_end><if_stmt><not>all([hasattr(mdl key)<and>callable(getattr(mdl key))<for>key self.callable_keys])<block_start><raise>ValueError("ERROR: Passed model/method failed the interface test. Methods required: %s"%','.join(self.callable_keys))<block_end><return>mdl<block_end><def_stmt>__init__ self base_model=<none> meta_model=<none> base_config=<none> meta_config=<none> random_seed=42<block_start>"""
:param base_model: Base model. Can be:
(1) None (default mdl will be set up),
(2) Named model (e.g., 'gbr'),
(3) Base model class declaration (e.g., sklearn.linear_model.LinearRegressor). Will instantiate.
(4) Model instance (instantiated outside). Will be re-used. Must have required callable methods.
Note: user-supplied classes and models must have certain callable methods ('predict', 'fit')
and be capable of raising NotFittedError.
:param meta_model: Meta model. Same values possible as with 'base_model'
:param base_config: None or a params dict to be passed to 'base_model' at instantiation
:param meta_config: None or a params dict to be passed to 'meta_model' at instantiation
:param random_seed: seed used in the various pipeline steps
"""<line_sep>super(MetamodelRegression).__init__()<line_sep>self.random_seed=random_seed<line_sep>self.callable_keys=['predict' 'fit']# required methods - must be present in models passed in
self.base_model_default='gbr'<line_sep>self.meta_model_default='gbr'<line_sep>self.base_config_default={'loss':'ls' 'n_estimators':300 'max_depth':10 'learning_rate':0.001 'min_samples_leaf':10 'min_samples_split':10 'random_state':self.random_seed}<line_sep>self.meta_config_default={'loss':'quantile' 'alpha':0.95 'n_estimators':300 'max_depth':10 'learning_rate':0.001 'min_samples_leaf':10 'min_samples_split':10 'random_state':self.random_seed}<line_sep>self.base_config=base_config<if>base_config<is><not><none><else>self.base_config_default<line_sep>self.meta_config=meta_config<if>meta_config<is><not><none><else>self.meta_config_default<line_sep>self.base_model=<none><line_sep>self.meta_model=<none><line_sep>self.base_model=self._get_model_instance(base_model<if>base_model<is><not><none><else>self.base_model_default self.base_config)<line_sep>self.meta_model=self._get_model_instance(meta_model<if>meta_model<is><not><none><else>self.meta_model_default self.meta_config)<block_end><def_stmt>get_params self deep=<true><block_start><return>{"base_model":self.base_model "meta_model":self.meta_model "base_config":self.base_config "meta_config":self.meta_config "random_seed":self.random_seed}<block_end><def_stmt>fit self X y meta_fraction=0.2 randomize_samples=<true> base_is_prefitted=<false> meta_train_data=(<none> <none>)<block_start>"""
Fit base and meta models.
:param X: input to the base model
:param y: ground truth for the base model
:param meta_fraction: float in [0,1] - a fractional size of the partition carved out to train the meta model
(complement will be used to train the base model)
:param randomize_samples: use shuffling when creating partitions
:param base_is_prefitted: Setting True will skip fitting the base model (useful for base models that have been
instantiated outside/by the user and are already fitted.
:param meta_train_data: User supplied data to train the meta model. Note that this option should only be used
with 'base_is_prefitted'==True. Pass a tuple meta_train_data=(X_meta, y_meta) to activate.
Note that (X,y,meta_fraction, randomize_samples) will be ignored in this mode.
:return: self
"""<line_sep>X=np.asarray(X)<line_sep>y=np.asarray(y)<assert_stmt>(len(meta_train_data)<eq>2)<if_stmt>meta_train_data[0]<is><none><block_start>X_base,X_meta,y_base,y_meta=train_test_split(X y shuffle=randomize_samples test_size=meta_fraction random_state=self.random_seed)<block_end><else_stmt><block_start><if_stmt><not>base_is_prefitted<block_start><raise>ValueError("ERROR: fit(): base model must be pre-fitted to use the 'meta_train_data' option")<block_end>X_base=y_base=<none><line_sep>X_meta=meta_train_data[0]<line_sep>y_meta=meta_train_data[1]<block_end># fit the base model
<if_stmt><not>base_is_prefitted<block_start>self.base_model.fit(X_base y_base)<block_end># get input for the meta model from the base
<try_stmt><block_start>y_hat_meta=self.base_model.predict(X_meta)<block_end><except_stmt>NotFittedError<as>e<block_start><raise>RuntimeError("ERROR: fit(): The base model appears not pre-fitted (%s)"%repr(e))<block_end># used base input and output as meta input
X_meta_in=self._process_pretrained_model(X_meta y_hat_meta)<line_sep># train meta model to predict abs diff
self.meta_model.fit(X_meta_in np.abs(y_hat_meta-y_meta))<line_sep><return>self<block_end><def_stmt>_process_pretrained_model self X y_hat<block_start>"""
Given the original input features and the base output probabilities, generate input features
to train a meta model. Current implementation copies all input features and appends.
:param X: numpy [nsamples, dim]
:param y_hat: [nsamples,]
:return: array with new features [nsamples, newdim]
"""<line_sep>y_hat_meta_prime=np.expand_dims(y_hat -1)<if>len(y_hat.shape)<l>2<else>y_hat<line_sep>X_meta_in=np.hstack([X y_hat_meta_prime])<line_sep><return>X_meta_in<block_end><def_stmt>predict self X<block_start>"""
Generate prediction and uncertainty bounds for data X.
:param X: input features
:return: namedtuple: A namedtuple that holds
y_mean: ndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution of the test points.
y_lower: ndarray of shape (n_samples, [n_output_dims])
Lower quantile of predictive distribution of the test points.
y_upper: ndarray of shape (n_samples, [n_output_dims])
Upper quantile of predictive distribution of the test points.
"""<line_sep>y_hat=self.base_model.predict(X)<line_sep>y_hat_prime=np.expand_dims(y_hat -1)<if>len(y_hat.shape)<l>2<else>y_hat<line_sep>X_meta_in=np.hstack([X y_hat_prime])<line_sep>z_hat=self.meta_model.predict(X_meta_in)<line_sep>Result=namedtuple('res' ['y_mean' 'y_lower' 'y_upper'])<line_sep>res=Result(y_hat y_hat-z_hat y_hat+z_hat)<line_sep><return>res<block_end><block_end> |
'''
Copyright 2020, Amazon Web Services Inc.
This code is licensed under MIT license (see LICENSE.txt for details)
Python 3
Provides a buffer object that holds log lines in Elasticsearch _bulk
format. As each line is added, the buffer stores the control line
as well as the log line.
Employs an line_buffer to hold log lines as they are added. Optionally
sends monitor information to an ES cluster. Set the flush_trigger to
control how many lines are buffered before each flush.
'''<import_stmt>time<import_from_stmt>es_sink.descriptor ESDescriptor SQSDescriptor<import_from_stmt>es_sink.line_buffer ESLineBuffer SQSLineBuffer<import_from_stmt>es_sink.es_transport ESTransport<import_from_stmt>es_sink.sqs_transport SQSTransport<import_from_stmt>es_sink.transport_exceptions BadSink<class_stmt>FlushingESBuffer()<block_start>'''Wraps an ESLineBuffer object to provide _bulk flushing when the
flush_trigger is hit.'''<def_stmt>__init__ self descriptor flush_trigger=1<block_start>''' target_descriptor must be an ESDescriptor'''<line_sep>self.transport=ESTransport(descriptor)<line_sep>self.target_descriptor=descriptor<line_sep>self.flush_trigger=flush_trigger<line_sep>self.buffer=ESLineBuffer(descriptor)<block_end><def_stmt>add_log_line self log_line<block_start>'''Add a single log line to the internal buffer. If the flush trigger
is hit, send the bulk request.'''<line_sep>self.buffer.add_log_line(log_line)<if_stmt>self.buffer.es_doc_count()<ge>self.flush_trigger<block_start>self.flush()<block_end><block_end># swallows the result. Do something with it?
<def_stmt>flush self<block_start>'''Flushes the line_buffer, sending all to the _bulk API'''<if_stmt>self.buffer.es_doc_count()<g>0<block_start><try_stmt><block_start>url=self.target_descriptor.bulk_url()<line_sep>print("Flushing {} documents {} to {}".format(self.buffer.es_doc_count() time.time() url))<line_sep>result=self.transport.send('post' url body=str(self.buffer))<line_sep>result=result._asdict()<line_sep>result['docs']=self.buffer.es_doc_count()<line_sep>self.buffer.clear()<line_sep><return>result<block_end><except_stmt>Exception<as>exc<block_start>message="Exception sending request '{}'"<line_sep>print(message.format(str(exc)))<line_sep><raise>exc<block_end><block_end><return><none><block_end><block_end><class_stmt>FlushingSQSBuffer()<block_start>'''Use to send ES _bulk data to SQS in batches.'''<def_stmt>__init__ self descriptor flush_trigger=1<block_start>self.target_descriptor=descriptor<line_sep>self.flush_trigger=flush_trigger<line_sep>self.transport=SQSTransport(descriptor)<line_sep>self.buffer=SQSLineBuffer()<block_end><def_stmt>add_log_line self line<block_start>'''Add a single log line to the internal buffer. If the flush trigger
is hit, send the bulk request.'''<line_sep>self.buffer.add_log_line(line)<if_stmt>self.buffer.es_doc_count()<ge>self.flush_trigger<block_start>self.flush()<block_end><block_end># swallows the result. Do something with it?
<def_stmt>flush self<block_start>'''Flushes the line_buffer, sending all to the _bulk API'''<line_sep>print("Flushing {} documents {}".format(self.buffer.es_doc_count() time.time()))<if_stmt>self.buffer.es_doc_count()<g>0<block_start>result=self.transport.send(str(self.buffer))<line_sep>result=result._asdict()<line_sep>result['docs']=self.buffer.es_doc_count()<line_sep>self.buffer.clear()<line_sep>print(result)<line_sep><return>result<block_end><return><none><block_end><block_end><def_stmt>flushing_buffer_factory descriptor flush_trigger=1<block_start>'''Call with a descriptor to receive a buffer object.'''<if_stmt>isinstance(descriptor ESDescriptor)<block_start><return>FlushingESBuffer(descriptor flush_trigger)<block_end><if_stmt>isinstance(descriptor SQSDescriptor)<block_start><return>FlushingSQSBuffer(descriptor flush_trigger)<block_end><raise>BadSink()<block_end> |
"""Early stopping."""<import_stmt>typing<import_stmt>torch<import_stmt>numpy<as>np<class_stmt>EarlyStopping<block_start>"""
EarlyStopping stops training if no improvement after a given patience.
:param patience: Number fo events to wait if no improvement and then
stop the training.
:param should_decrease: The way to judge the best so far.
:param key: Key of metric to be compared.
"""<def_stmt>__init__ self patience:typing.Optional[int]=<none> should_decrease:bool=<none> key:typing.Any=<none><block_start>"""Early stopping Constructor."""<line_sep>self._patience=patience<line_sep>self._key=key<line_sep>self._best_so_far=0<line_sep>self._epochs_with_no_improvement=0<line_sep>self._is_best_so_far=<false><line_sep>self._early_stop=<false><block_end><def_stmt>state_dict self<arrow>typing.Dict[str typing.Any]<block_start>"""A `Trainer` can use this to serialize the state."""<line_sep><return>{'patience':self._patience 'best_so_far':self._best_so_far 'is_best_so_far':self._is_best_so_far 'epochs_with_no_improvement':self._epochs_with_no_improvement }<block_end><def_stmt>load_state_dict self state_dict:typing.Dict[str typing.Any]<arrow><none><block_start>"""Hydrate a early stopping from a serialized state."""<line_sep>self._patience=state_dict["patience"]<line_sep>self._is_best_so_far=state_dict["is_best_so_far"]<line_sep>self._best_so_far=state_dict["best_so_far"]<line_sep>self._epochs_with_no_improvement=state_dict["epochs_with_no_improvement"]<block_end><def_stmt>update self result:list<block_start>"""Call function."""<line_sep>score=result[self._key]<if_stmt>score<g>self._best_so_far<block_start>self._best_so_far=score<line_sep>self._is_best_so_far=<true><line_sep>self._epochs_with_no_improvement=0<block_end><else_stmt><block_start>self._is_best_so_far=<false><line_sep>self._epochs_with_no_improvement<augadd>1<block_end><block_end>@property<def_stmt>best_so_far self<arrow>bool<block_start>"""Returns best so far."""<line_sep><return>self._best_so_far<block_end>@property<def_stmt>is_best_so_far self<arrow>bool<block_start>"""Returns true if it is the best so far."""<line_sep><return>self._is_best_so_far<block_end>@property<def_stmt>should_stop_early self<arrow>bool<block_start>"""Returns true if improvement has stopped for long enough."""<if_stmt><not>self._patience<block_start><return><false><block_end><else_stmt><block_start><return>self._epochs_with_no_improvement<ge>self._patience<block_end><block_end><block_end> |
<import_from_stmt>typing Tuple<class_stmt>BaseTimer<block_start>"""
A timer controls the time passed into the the render function.
This can be used in creative ways to control the current time
such as basing it on current location in an audio file.
All methods must be implemented.
"""<line_sep>@property<def_stmt>is_paused self<arrow>bool<block_start>"""bool: The pause state of the timer"""<line_sep><raise>NotImplementedError()<block_end>@property<def_stmt>is_running self<arrow>bool<block_start>"""bool: Is the timer currently running?"""<line_sep><raise>NotImplementedError()<block_end>@property<def_stmt>time self<arrow>float<block_start>"""Get or set the current time.
This can be used to jump around in the timeline.
Returns:
float: The current time in seconds
"""<line_sep><raise>NotImplementedError()<block_end>@time.setter<def_stmt>time self value:float<block_start><raise>NotImplementedError()<block_end><def_stmt>next_frame self<arrow>Tuple[float float]<block_start>"""Get timer information for the next frame.
Returns:
Tuple[float, float]: The frametime and current time
"""<line_sep><raise>NotImplementedError()<block_end><def_stmt>start self<block_start>"""Start the timer initially or resume after pause"""<line_sep><raise>NotImplementedError()<block_end><def_stmt>pause self<block_start>"""Pause the timer"""<line_sep><raise>NotImplementedError()<block_end><def_stmt>toggle_pause self<block_start>"""Toggle pause state"""<line_sep><raise>NotImplementedError()<block_end><def_stmt>stop self<arrow>Tuple[float float]<block_start>"""
Stop the timer. Should only be called once when stopping the timer.
Returns:
Tuple[float, float]> Current position in the timer, actual running duration
"""<line_sep><raise>NotImplementedError()<block_end><block_end> |
<def_stmt>coding_problem_41 flights_db starting_airport<block_start>"""
Given an unordered list of flights taken by someone, each represented as (origin, destination) pairs, and a
starting airport, compute the person's itinerary. If no such itinerary exists, return null. If there are multiple
possible itineraries, return the lexicographically smallest one. All flights must be used in the itinerary.
Examples:
>>> coding_problem_41([('SFO', 'HKO'), ('YYZ', 'SFO'), ('YUL', 'YYZ'), ('HKO', 'ORD')], 'YUL')
['YUL', 'YYZ', 'SFO', 'HKO', 'ORD']
>>> coding_problem_41([('SFO', 'COM'), ('COM', 'YYZ')], 'COM') # returns None
>>> coding_problem_41([('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'A')], 'A')
['A', 'B', 'C', 'A', 'C']
The itinerary ['A', 'C', 'A', 'B', 'C'] is also a valid however the first one is lexicographically smaller.
"""<line_sep><pass><block_end><if_stmt>__name__<eq>'__main__'<block_start><import_stmt>doctest<line_sep>doctest.testmod(verbose=<true>)<block_end> |
# -*- coding: UTF-8 -*-
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
<import_from_stmt>paddlepalm.reader.base_reader Reader<import_from_stmt>paddlepalm.reader.utils.reader4ernie ClassifyReader<as>CLSReader<class_stmt>MatchReader(Reader)<block_start>"""
The reader completes the loading and processing of matching-like task (e.g, query-query, question-answer, text similarity, natural language inference) dataset. Supported file format: tsv.
For pointwise learning strategy, there should be two fields in training dataset file, i.e., `text_a`, `text_b` and `label`. For pairwise learning, there should exist three fields, i.e., `text_a`, `text_b` and `text_b_neg`. For predicting, only `text_a` and `text_b` are required.
A pointwise learning case shows as follows:
```
label [TAB] text_a [TAB] text_b
1 [TAB] Today is a good day. [TAB] what a nice day!
0 [TAB] Such a terriable day! [TAB] There is a dog.
1 [TAB] I feel lucky to meet you, dear. [TAB] You are my lucky, darling.
1 [TAB] He likes sunshine and I like him :). [TAB] I like him. He like sunshine.
0 [TAB] JUST! GO! OUT! [TAB] Come in please.
```
A pairwise learning case shows as follows:
text_a [TAB] text_b [TAB] text_b_neg
Today is a good day. [TAB] what a nice day! [TAB] terriable day!
Such a terriable day! [TAB] So terriable today! [TAB] There is a dog.
I feel lucky to meet you, dear. [TAB] You are my lucky, darling. [TAB] Buy some bananas, okey?
He likes sunshine and I like him :). [TAB] I like him. He like sunshine. [TAB] He has a dog.
JUST! GO! OUT! [TAB] go out now! [TAB] Come in please.
CAUTIOUS: the HEADER is required for each dataset file! And fields (columns) should be splited by Tab (\\t).
"""<def_stmt>__init__ self vocab_path max_len tokenizer='wordpiece' lang='en' seed=<none> do_lower_case=<false> learning_strategy='pointwise' phase='train' dev_count=1 print_prefix=''<block_start>"""Create a new Reader for classification task data.
Args:
vocab_path: the vocab file path to do tokenization and token_ids generation.
max_len: The maximum length of the sequence (after word segmentation). The part exceeding max_len will be removed from right.
tokenizer: string type. The name of the used tokenizer. A tokenizer is to convert raw text into tokens. Avaliable tokenizers: wordpiece.
lang: the language of dataset. Supported language: en (English), cn (Chinese). Default is en (English).
seed: int type. The random seed to shuffle dataset. Default is None, means no use of random seed.
do_lower_case: bool type. Whether to do lowercase on English text. Default is False. This argument only works on English text.
learning_strategy: string type. This only works for training phase. Available strategies: pointwise, pairwise.
phase: the running phase of this reader. Supported phase: train, predict. Default is train.
Return:
a Reader object for matching-like task.
"""<line_sep>Reader.__init__(self phase)<assert_stmt>lang.lower()<in>['en' 'cn' 'english' 'chinese'] "supported language: en (English), cn (Chinese)."<assert_stmt>phase<in>['train' 'predict'] "supported phase: train, predict."<line_sep>for_cn=lang.lower()<eq>'cn'<or>lang.lower()<eq>'chinese'<line_sep>self._register.add('token_ids')<if_stmt>phase<eq>'train'<block_start><if_stmt>learning_strategy<eq>'pointwise'<block_start>self._register.add('label_ids')<block_end><if_stmt>learning_strategy<eq>'pairwise'<block_start>self._register.add('token_ids_neg')<line_sep>self._register.add('position_ids_neg')<line_sep>self._register.add('segment_ids_neg')<line_sep>self._register.add('input_mask_neg')<line_sep>self._register.add('task_ids_neg')<block_end><block_end>self._is_training=phase<eq>'train'<line_sep>self._learning_strategy=learning_strategy<line_sep>match_reader=CLSReader(vocab_path max_seq_len=max_len do_lower_case=do_lower_case for_cn=for_cn random_seed=seed learning_strategy=learning_strategy)<line_sep>self._reader=match_reader<line_sep>self._dev_count=dev_count<line_sep>self._phase=phase<block_end>@property<def_stmt>outputs_attr self<block_start>attrs={"token_ids":[[-1 -1] 'int64'] "position_ids":[[-1 -1] 'int64'] "segment_ids":[[-1 -1] 'int64'] "input_mask":[[-1 -1 1] 'float32'] "task_ids":[[-1 -1] 'int64'] "label_ids":[[-1] 'int64'] "token_ids_neg":[[-1 -1] 'int64'] "position_ids_neg":[[-1 -1] 'int64'] "segment_ids_neg":[[-1 -1] 'int64'] "input_mask_neg":[[-1 -1 1] 'float32'] "task_ids_neg":[[-1 -1] 'int64']}<line_sep><return>self._get_registed_attrs(attrs)<block_end><def_stmt>load_data self input_file batch_size num_epochs=<none> file_format='tsv' shuffle_train=<true><block_start>"""Load matching data into reader.
Args:
input_file: the dataset file path. File format should keep consistent with `file_format` argument.
batch_size: number of examples for once yield. CAUSIOUS! If your environment exists multiple GPU devices (marked as dev_count), the batch_size should be divided by dev_count with no remainder!
num_epochs: the travelsal times of input examples. Default is None, means once for single-task learning and automatically calculated for multi-task learning. This argument only works on train phase.
file_format: the file format of input file. Supported format: tsv. Default is tsv.
shuffle_train: whether to shuffle training dataset. Default is True. This argument only works on training phase.
"""<line_sep>self._batch_size=batch_size<line_sep>self._num_epochs=num_epochs<line_sep>self._data_generator=self._reader.data_generator(input_file batch_size num_epochs<if>self._phase<eq>'train'<else>1 shuffle=shuffle_train<if>self._phase<eq>'train'<else><false> phase=self._phase)<block_end><def_stmt>_iterator self<block_start>names=['token_ids' 'segment_ids' 'position_ids' 'task_ids' 'input_mask' 'label_ids' 'token_ids_neg' 'segment_ids_neg' 'position_ids_neg' 'task_ids_neg' 'input_mask_neg']<if_stmt>self._learning_strategy<eq>'pairwise'<block_start>names.remove('label_ids')<block_end><for_stmt>batch self._data_generator()<block_start>outputs={n:i<for>n,i zip(names batch)}<line_sep>ret={}<line_sep># TODO: move runtime shape check here
<for_stmt>attr self.outputs_attr.keys()<block_start>ret[attr]=outputs[attr]<block_end><yield>ret<block_end><block_end>@property<def_stmt>num_examples self<block_start><return>self._reader.get_num_examples(phase=self._phase)<block_end>@property<def_stmt>num_epochs self<block_start><return>self._num_epochs<block_end><block_end> |
# Copyright 2019 Google LLC. 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.
"""Commands for pipeline group."""<import_stmt>sys<import_from_stmt>typing Optional<import_stmt>click<import_from_stmt>tfx.tools.cli labels<import_from_stmt>tfx.tools.cli.cli_context Context<import_from_stmt>tfx.tools.cli.cli_context pass_context<import_from_stmt>tfx.tools.cli.handler handler_factory<def_stmt>_check_deprecated_image_build_flags build_target_image=<none> skaffold_cmd=<none> pipeline_package_path=<none><block_start>"""Checks and exits if deprecated flags were used."""<if_stmt>build_target_image<is><not><none><block_start>sys.exit('[Error] --build-target-image flag was DELETED. You should specify '<concat>'the build target image at the `KubeflowDagRunnerConfig` class '<concat>'instead, and use --build-image flag without argument to build a '<concat>'container image when creating or updating a pipeline.')<block_end><if_stmt>skaffold_cmd<is><not><none><block_start>sys.exit('[Error] --skaffold-cmd flag was DELETED. TFX doesn\'t use skaffold '<concat>'any more. You can delete --skaffold-cmd flag and the auto-genrated '<concat>'build.yaml file. You must specify --build-image to trigger an '<concat>'image build when creating or updating a pipeline.')<block_end><if_stmt>pipeline_package_path<is><not><none><block_start>sys.exit('[Error] --pipeline-package-path flag was DELETED. You can specify '<concat>'the package location as `output_filename` and `output_dir` when '<concat>'creating a `KubeflowDagRunner` instance. CLI will read the pacakge '<concat>'path specified there.')<block_end><block_end>@click.group('pipeline')<def_stmt>pipeline_group <arrow><none><block_start><pass><block_end># TODO(b/132286477): Add support for requirements file.
@pipeline_group.command('create' help='Create a pipeline')@pass_context@click.option('--engine' default='auto' type=str help='Orchestrator for pipelines')@click.option('--pipeline_path' '--pipeline-path' required=<true> type=str help='Path to Python DSL.')@click.option('--package_path' '--package-path' default=<none> type=str help='[DEPRECATED] Package path specified in a KubeflowDagRunner instace '<concat>'will be used.')@click.option('--build_target_image' '--build-target-image' default=<none> type=str help='[DEPRECATED] Please specify target image to the '<concat>'KubeflowDagRunnerConfig class directly. `KUBEFLOW_TFX_IMAGE` environment '<concat>'variable is not used any more.')@click.option('--build_base_image' '--build-base-image' default=<none> type=str help='Container image path to be used as the base image. If not specified, '<concat>'official TFX image with the same version will be used. You need to '<concat>'specify --build-image flag to trigger an image build.')@click.option('--skaffold_cmd' '--skaffold-cmd' default=<none> type=str help='[DEPRECATED] Skaffold is not used any more. Do not use this flag.')@click.option('--endpoint' default=<none> type=str help='Endpoint of the KFP API service to connect.')@click.option('--iap_client_id' '--iap-client-id' default=<none> type=str help='Client ID for IAP protected endpoint.')@click.option('-n' '--namespace' default='kubeflow' type=str help='Kubernetes namespace to connect to the KFP API.')@click.option('--build_image' '--build-image' is_flag=<true> default=<false> help='Build a container image for the pipeline using Dockerfile in the '<concat>'current directory. If Dockerfile does not exist, a default Dockerfile '<concat>'will be generated using --build-base-image.')<def_stmt>create_pipeline ctx:Context engine:str pipeline_path:str package_path:Optional[str] build_target_image:Optional[str] build_base_image:Optional[str] skaffold_cmd:Optional[str] endpoint:Optional[str] iap_client_id:Optional[str] namespace:str build_image:bool<arrow><none><block_start>"""Command definition to create a pipeline."""<line_sep># TODO(b/179847638): Delete checks for deprecated flags.
_check_deprecated_image_build_flags(build_target_image skaffold_cmd package_path)<if_stmt>build_base_image<is><not><none><and><not>build_image<block_start>sys.exit('--build-base-image used without --build-image. You have to use '<concat>'--build-image flag to build a container image for the pipeline.')<block_end># TODO(b/142358865): Add support for container building for Airflow and Beam
# runners when they support container executors.
click.echo('Creating pipeline')<line_sep>ctx.flags_dict[labels.ENGINE_FLAG]=engine<line_sep>ctx.flags_dict[labels.PIPELINE_DSL_PATH]=pipeline_path<line_sep>ctx.flags_dict[labels.BASE_IMAGE]=build_base_image<line_sep>ctx.flags_dict[labels.ENDPOINT]=endpoint<line_sep>ctx.flags_dict[labels.IAP_CLIENT_ID]=iap_client_id<line_sep>ctx.flags_dict[labels.NAMESPACE]=namespace<line_sep>ctx.flags_dict[labels.BUILD_IMAGE]=build_image<line_sep>handler_factory.create_handler(ctx.flags_dict).create_pipeline()<block_end>@pipeline_group.command('update' help='Update an existing pipeline.')@pass_context@click.option('--engine' default='auto' type=str help='Orchestrator for pipelines')@click.option('--pipeline_path' '--pipeline-path' required=<true> type=str help='Path to Python DSL file')@click.option('--package_path' '--package-path' type=str default=<none> help='[DEPRECATED] Package path specified in a KubeflowDagRunner instace '<concat>'will be used.')@click.option('--skaffold_cmd' '--skaffold-cmd' default=<none> type=str help='[DEPRECATED] Skaffold is not used any more. Do not use this flag.')@click.option('--endpoint' default=<none> type=str help='Endpoint of the KFP API service to connect.')@click.option('--iap_client_id' '--iap-client-id' default=<none> type=str help='Client ID for IAP protected endpoint.')@click.option('-n' '--namespace' default='kubeflow' type=str help='Kubernetes namespace to connect to the KFP API.')@click.option('--build_image' '--build-image' is_flag=<true> default=<false> help='Build a container image for the pipeline using Dockerfile in the '<concat>'current directory.')<def_stmt>update_pipeline ctx:Context engine:str pipeline_path:str package_path:Optional[str] skaffold_cmd:Optional[str] endpoint:Optional[str] iap_client_id:Optional[str] namespace:str build_image:bool<arrow><none><block_start>"""Command definition to update a pipeline."""<line_sep># TODO(b/179847638): Delete checks for deprecated flags.
_check_deprecated_image_build_flags(<none> skaffold_cmd package_path)<line_sep>click.echo('Updating pipeline')<line_sep>ctx.flags_dict[labels.ENGINE_FLAG]=engine<line_sep>ctx.flags_dict[labels.PIPELINE_DSL_PATH]=pipeline_path<line_sep>ctx.flags_dict[labels.ENDPOINT]=endpoint<line_sep>ctx.flags_dict[labels.IAP_CLIENT_ID]=iap_client_id<line_sep>ctx.flags_dict[labels.NAMESPACE]=namespace<line_sep>ctx.flags_dict[labels.BUILD_IMAGE]=build_image<line_sep>handler_factory.create_handler(ctx.flags_dict).update_pipeline()<block_end>@pipeline_group.command('delete' help='Delete a pipeline')@pass_context@click.option('--engine' default='auto' type=str help='Orchestrator for pipelines')@click.option('--pipeline_name' '--pipeline-name' required=<true> type=str help='Name of the pipeline')@click.option('--endpoint' default=<none> type=str help='Endpoint of the KFP API service to connect.')@click.option('--iap_client_id' '--iap-client-id' default=<none> type=str help='Client ID for IAP protected endpoint.')@click.option('-n' '--namespace' default='kubeflow' type=str help='Kubernetes namespace to connect to the KFP API.')<def_stmt>delete_pipeline ctx:Context engine:str pipeline_name:str endpoint:str iap_client_id:str namespace:str<arrow><none><block_start>"""Command definition to delete a pipeline."""<line_sep>click.echo('Deleting pipeline')<line_sep>ctx.flags_dict[labels.ENGINE_FLAG]=engine<line_sep>ctx.flags_dict[labels.PIPELINE_NAME]=pipeline_name<line_sep>ctx.flags_dict[labels.ENDPOINT]=endpoint<line_sep>ctx.flags_dict[labels.IAP_CLIENT_ID]=iap_client_id<line_sep>ctx.flags_dict[labels.NAMESPACE]=namespace<line_sep>handler_factory.create_handler(ctx.flags_dict).delete_pipeline()<block_end>@pipeline_group.command('list' help='List all the pipelines')@pass_context@click.option('--engine' default='auto' type=str help='orchestrator for pipelines')@click.option('--endpoint' default=<none> type=str help='Endpoint of the KFP API service to connect.')@click.option('--iap_client_id' '--iap-client-id' default=<none> type=str help='Client ID for IAP protected endpoint.')@click.option('-n' '--namespace' default='kubeflow' type=str help='Kubernetes namespace to connect to the KFP API.')<def_stmt>list_pipelines ctx:Context engine:str endpoint:str iap_client_id:str namespace:str<arrow><none><block_start>"""Command definition to list pipelines."""<line_sep>click.echo('Listing all pipelines')<line_sep>ctx.flags_dict[labels.ENGINE_FLAG]=engine<line_sep>ctx.flags_dict[labels.ENDPOINT]=endpoint<line_sep>ctx.flags_dict[labels.IAP_CLIENT_ID]=iap_client_id<line_sep>ctx.flags_dict[labels.NAMESPACE]=namespace<line_sep>handler_factory.create_handler(ctx.flags_dict).list_pipelines()<block_end>@pipeline_group.command('compile' help='Compile a pipeline')@pass_context@click.option('--engine' default='auto' type=str help='Orchestrator for pipelines')@click.option('--pipeline_path' '--pipeline-path' required=<true> type=str help='Path to Python DSL.')@click.option('--package_path' '--package-path' default=<none> type=str help='[DEPRECATED] Package path specified in a KubeflowDagRunner instace '<concat>'will be used.')<def_stmt>compile_pipeline ctx:Context engine:str pipeline_path:str package_path:str<arrow><none><block_start>"""Command definition to compile a pipeline."""<line_sep># TODO(b/179847638): Delete checks for deprecated flags.
_check_deprecated_image_build_flags(pipeline_package_path=package_path)<line_sep>click.echo('Compiling pipeline')<line_sep>ctx.flags_dict[labels.ENGINE_FLAG]=engine<line_sep>ctx.flags_dict[labels.PIPELINE_DSL_PATH]=pipeline_path<line_sep>handler_factory.create_handler(ctx.flags_dict).compile_pipeline()<block_end>@pipeline_group.command('schema' help='Obtain latest database schema.')@pass_context@click.option('--engine' default='auto' type=str help='Orchestrator for pipelines')@click.option('--pipeline_name' '--pipeline-name' required=<true> type=str help='Name of the pipeline')<def_stmt>get_schema ctx:Context engine:str pipeline_name:str<arrow><none><block_start>"""Command definition to infer latest schema."""<line_sep>click.echo('Getting latest schema.')<line_sep>ctx.flags_dict[labels.ENGINE_FLAG]=engine<line_sep>ctx.flags_dict[labels.PIPELINE_NAME]=pipeline_name<line_sep>handler_factory.create_handler(ctx.flags_dict).get_schema()<block_end> |
<import_stmt>time<def_stmt>f <block_start>[# Must be split over multiple lines to see the error.
# https://github.com/benfred/py-spy/pull/208
time.sleep(1)<for>_ range(1000)]<block_end>f()<line_sep> |
<import_from_stmt>collections OrderedDict<import_from_stmt>typing Collection List Mapping MutableSequence Optional Set Tuple Union<import_stmt>numpy<as>np<import_from_stmt>slicedimage Tile TileSet<import_from_stmt>starfish.core.imagestack.parser TileCollectionData TileData TileKey<import_from_stmt>starfish.core.types ArrayLike Axes Coordinates Number<class_stmt>CropParameters<block_start>"""Parameters for cropping an ImageStack at load time."""<def_stmt>__init__ self * permitted_rounds:Optional[Collection[int]]=<none> permitted_chs:Optional[Collection[int]]=<none> permitted_zplanes:Optional[Collection[int]]=<none> x_slice:Optional[Union[int slice]]=<none> y_slice:Optional[Union[int slice]]=<none> <block_start>"""
Parameters
----------
permitted_rounds : Optional[Collection[int]]
The rounds in the original dataset to load into the ImageStack. If this is not set,
then all rounds are loaded into the ImageStack.
permitted_chs : Optional[Collection[int]]
The channels in the original dataset to load into the ImageStack. If this is not set,
then all channels are loaded into the ImageStack.
permitted_zplanes : Optional[Collection[int]]
The z-layers in the original dataset to load into the ImageStack. If this is not set,
then all z-layers are loaded into the ImageStack.
x_slice : Optional[Union[int, slice]]
The x-range in the x-y tile that is loaded into the ImageStack. If this is not set,
then the entire x-y tile is loaded into the ImageStack.
y_slice : Optional[Union[int, slice]]
The y-range in the x-y tile that is loaded into the ImageStack. If this is not set,
then the entire x-y tile is loaded into the ImageStack.
"""<line_sep>self._permitted_rounds=set(permitted_rounds)<if>permitted_rounds<else><none><line_sep>self._permitted_chs=set(permitted_chs)<if>permitted_chs<else><none><line_sep>self._permitted_zplanes=set(permitted_zplanes)<if>permitted_zplanes<else><none><line_sep>self._x_slice=x_slice<line_sep>self._y_slice=y_slice<block_end><def_stmt>_add_permitted_axes self axis_type:Axes permitted_axis:int<arrow><none><block_start>"""
Add a value to one of the permitted axes sets.
"""<if_stmt>axis_type<eq>Axes.ROUND<and>self._permitted_rounds<block_start>self._permitted_rounds.add(permitted_axis)<block_end><if_stmt>axis_type<eq>Axes.CH<and>self._permitted_chs<block_start>self._permitted_chs.add(permitted_axis)<block_end><if_stmt>axis_type<eq>Axes.ZPLANE<and>self._permitted_zplanes<block_start>self._permitted_zplanes.add(permitted_axis)<block_end><block_end><def_stmt>filter_tilekeys self tilekeys:Collection[TileKey]<arrow>Collection[TileKey]<block_start>"""
Filters tilekeys for those that should be included in the resulting ImageStack.
"""<line_sep>results:MutableSequence[TileKey]=list()<for_stmt>tilekey tilekeys<block_start><if_stmt>self._permitted_rounds<is><not><none><and>tilekey.round<not><in>self._permitted_rounds<block_start><continue><block_end><if_stmt>self._permitted_chs<is><not><none><and>tilekey.ch<not><in>self._permitted_chs<block_start><continue><block_end><if_stmt>self._permitted_zplanes<is><not><none><and>tilekey.z<not><in>self._permitted_zplanes<block_start><continue><block_end>results.append(tilekey)<block_end><return>results<block_end>@staticmethod<def_stmt>_crop_axis size:int crop:Optional[Union[int slice]]<arrow>Tuple[int int]<block_start>"""
Given the size of along an axis, and an optional cropping, return the start index
(inclusive) and end index (exclusive) of the crop. If no crop is specified, then the
original size (0, size) is returned.
"""<line_sep># convert int crops to a slice operation.
<if_stmt>isinstance(crop int)<block_start><if_stmt>crop<l>0<or>crop<ge>size<block_start><raise>IndexError("crop index out of range")<block_end><return>crop crop+1<block_end># convert start and stop to absolute values.
start:int<if_stmt>crop<is><none><or>crop.start<is><none><block_start>start=0<block_end><elif_stmt>crop.start<is><not><none><and>crop.start<l>0<block_start>start=max(0 size+crop.start)<block_end><else_stmt><block_start>start=min(size crop.start)<block_end>stop:int<if_stmt>crop<is><none><or>crop.stop<is><none><block_start>stop=size<block_end><elif_stmt>crop.stop<is><not><none><and>crop.stop<l>0<block_start>stop=max(0 size+crop.stop)<block_end><else_stmt><block_start>stop=min(size crop.stop)<block_end><return>start stop<block_end>@staticmethod<def_stmt>parse_aligned_groups tileset:TileSet rounds:Optional[Collection[int]]=<none> chs:Optional[Collection[int]]=<none> zplanes:Optional[Collection[int]]=<none> x:Optional[Union[int slice]]=<none> y:Optional[Union[int slice]]=<none><arrow>List["CropParameters"]<block_start>"""Takes a tileset and any optional selected axes lists compares the physical coordinates on each
tile to create aligned coordinate groups (groups of tiles that have the same physical
coordinates)
Parameters
----------
tileset: TileSet
The TileSet to parse
rounds: Optional[Collection[int]]
The rounds in the tileset to include in the final aligned groups. If this is not set,
then all rounds are included.
chs: Optional[Collection[int]]
The chs in the tileset to include in the final aligned groups. If this is not set,
then all chs are included.
zplanes: Optional[Collection[int]]
The zplanes in the tileset to include in the final aligned groups. If this is not set,
then all zplanes are included.
x: Optional[Union[int, slice]]
The x-range in the x-y tile to include in the final aligned groups. If this is not set,
then the entire x-y tile is included.
y: Optional[Union[int, slice]]
The y-range in the x-y tile to include in the final aligned groups. If this is not set,
then the entire x-y tile is included.
Returns
-------
List["CropParameters"]
A list of CropParameters. Each entry describes the r/ch/z values of tiles that are
aligned (have matching coordinates) and are within the selected_axes if provided.
"""<line_sep>coord_groups:OrderedDict[tuple CropParameters]=OrderedDict()<for_stmt>tile tileset.tiles()<block_start><if_stmt>CropParameters.tile_in_selected_axes(tile rounds chs zplanes)<block_start>x_y_coords=(tile.coordinates[Coordinates.X][0] tile.coordinates[Coordinates.X][1] tile.coordinates[Coordinates.Y][0] tile.coordinates[Coordinates.Y][1])<line_sep># A tile with this (x, y) has already been seen, add tile's indices to
# CropParameters
<if_stmt>x_y_coords<in>coord_groups<block_start>crop_params=coord_groups[x_y_coords]<line_sep>crop_params._add_permitted_axes(Axes.CH tile.indices[Axes.CH])<line_sep>crop_params._add_permitted_axes(Axes.ROUND tile.indices[Axes.ROUND])<if_stmt>Axes.ZPLANE<in>tile.indices<block_start>crop_params._add_permitted_axes(Axes.ZPLANE tile.indices[Axes.ZPLANE])<block_end><block_end><else_stmt><block_start>coord_groups[x_y_coords]=CropParameters(permitted_chs=[tile.indices[Axes.CH]] permitted_rounds=[tile.indices[Axes.ROUND]] permitted_zplanes=[tile.indices[Axes.ZPLANE]]<if>Axes.ZPLANE<in>tile.indices<else><none> x_slice=x y_slice=y)<block_end><block_end><block_end><return>list(coord_groups.values())<block_end>@staticmethod<def_stmt>tile_in_selected_axes tile:Tile rounds:Optional[Collection[int]]=<none> chs:Optional[Collection[int]]=<none> zplanes:Optional[Collection[int]]=<none><arrow>bool<block_start>"""
Return True if a tile belongs in a list of selected axes.
Parameters
----------
tile:
The tile in question
rounds: Optional[Collection[int]]
The allowed rounds.
chs: Optional[Collection[int]]
The allowed chs.
zplanes: Optional[Collection[int]]
The allowed zplanes.
Returns
-------
Boolean
True if tile belongs with selected axes, False if not.
"""<if_stmt>rounds<and>tile.indices[Axes.ROUND]<not><in>rounds<block_start><return><false><block_end><if_stmt>chs<and>tile.indices[Axes.CH]<not><in>chs<block_start><return><false><block_end><if_stmt>zplanes<and>tile.indices[Axes.ZPLANE]<not><in>zplanes<block_start><return><false><block_end><return><true><block_end><def_stmt>crop_shape self shape:Mapping[Axes int]<arrow>Mapping[Axes int]<block_start>"""
Given the shape of the original tile, return the shape of the cropped tile.
"""<line_sep>output_x_shape=CropParameters._crop_axis(shape[Axes.X] self._x_slice)<line_sep>output_y_shape=CropParameters._crop_axis(shape[Axes.Y] self._y_slice)<line_sep>width=output_x_shape[1]-output_x_shape[0]<line_sep>height=output_y_shape[1]-output_y_shape[0]<line_sep><return>{Axes.Y:height Axes.X:width}<block_end><def_stmt>crop_image self image:np.ndarray<arrow>np.ndarray<block_start>"""
Given the original image, return the cropped image.
"""<line_sep>output_x_shape=CropParameters._crop_axis(image.shape[1] self._x_slice)<line_sep>output_y_shape=CropParameters._crop_axis(image.shape[0] self._y_slice)<line_sep><return>image[output_y_shape[0]:output_y_shape[1] output_x_shape[0]:output_x_shape[1]]<block_end><def_stmt>crop_coordinates self coordinates:Mapping[Coordinates ArrayLike[Number]] <arrow>Mapping[Coordinates ArrayLike[Number]]<block_start>"""
Given a mapping of coordinate to coordinate values, return a mapping of the coordinate to
cropped coordinate values.
"""<line_sep>output_x_shape=CropParameters._crop_axis(len(coordinates[Coordinates.X]) self._x_slice)<line_sep>output_y_shape=CropParameters._crop_axis(len(coordinates[Coordinates.Y]) self._y_slice)<line_sep>return_coords={Coordinates.X:coordinates[Coordinates.X][output_x_shape[0]:output_x_shape[1]] Coordinates.Y:coordinates[Coordinates.Y][output_y_shape[0]:output_y_shape[1]] }<if_stmt>Coordinates.Z<in>coordinates<block_start>return_coords[Coordinates.Z]=coordinates[Coordinates.Z]<block_end><return>return_coords<block_end><block_end><class_stmt>CroppedTileData(TileData)<block_start>"""Represent a cropped view of a TileData object."""<def_stmt>__init__ self tile_data:TileData cropping_parameters:CropParameters<block_start>self.backing_tile_data=tile_data<line_sep>self.cropping_parameters=cropping_parameters<block_end>@property<def_stmt>tile_shape self<arrow>Mapping[Axes int]<block_start><return>self.cropping_parameters.crop_shape(self.backing_tile_data.tile_shape)<block_end>@property<def_stmt>numpy_array self<arrow>np.ndarray<block_start><return>self.cropping_parameters.crop_image(self.backing_tile_data.numpy_array)<block_end>@property<def_stmt>coordinates self<arrow>Mapping[Coordinates ArrayLike[Number]]<block_start><return>self.cropping_parameters.crop_coordinates(self.backing_tile_data.coordinates)<block_end>@property<def_stmt>selector self<arrow>Mapping[Axes int]<block_start><return>self.backing_tile_data.selector<block_end><block_end><class_stmt>CroppedTileCollectionData(TileCollectionData)<block_start>"""Represent a cropped view of a TileCollectionData object."""<def_stmt>__init__ self backing_tile_collection_data:TileCollectionData crop_parameters:CropParameters <arrow><none><block_start>self.backing_tile_collection_data=backing_tile_collection_data<line_sep>self.crop_parameters=crop_parameters<block_end><def_stmt>__getitem__ self tilekey:TileKey<arrow>dict<block_start><return>self.backing_tile_collection_data[tilekey]<block_end><def_stmt>keys self<arrow>Collection[TileKey]<block_start><return>self.crop_parameters.filter_tilekeys(self.backing_tile_collection_data.keys())<block_end>@property<def_stmt>group_by self<arrow>Set[Axes]<block_start>"""Returns the axes to group by when we load the data."""<line_sep><return>self.backing_tile_collection_data.group_by<block_end>@property<def_stmt>tile_shape self<arrow>Mapping[Axes int]<block_start><return>self.crop_parameters.crop_shape(self.backing_tile_collection_data.tile_shape)<block_end>@property<def_stmt>extras self<arrow>dict<block_start><return>self.backing_tile_collection_data.extras<block_end><def_stmt>get_tile_by_key self tilekey:TileKey<arrow>TileData<block_start><return>CroppedTileData(self.backing_tile_collection_data.get_tile_by_key(tilekey) self.crop_parameters )<block_end><def_stmt>get_tile self r:int ch:int z:int<arrow>TileData<block_start><return>CroppedTileData(self.backing_tile_collection_data.get_tile(r ch z) self.crop_parameters )<block_end><block_end> |
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-UAC-FileVirtualization
GUID : c02afc2b-e24e-4449-ad76-bcc2c2575ead
"""<import_from_stmt>construct Int8sl Int8ul Int16ul Int16sl Int32sl Int32ul Int64sl Int64ul Bytes Double Float32l Struct<import_from_stmt>etl.utils WString CString SystemTime Guid<import_from_stmt>etl.dtyp Sid<import_from_stmt>etl.parsers.etw.core Etw declare guid<line_sep>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2000 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2000_0(Etw)<block_start>pattern=Struct("Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2001 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2001_0(Etw)<block_start>pattern=Struct("Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2002 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2002_0(Etw)<block_start>pattern=Struct("Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2003 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2003_0(Etw)<block_start>pattern=Struct("Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2004 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2004_0(Etw)<block_start>pattern=Struct("Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2005 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2005_0(Etw)<block_start>pattern=Struct("Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2006 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2006_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2007 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2007_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2008 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2008_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2009 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2009_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2010 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2010_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2011 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2011_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2012 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2012_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2013 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2013_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2014 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2014_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2015 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2015_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2016 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2016_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2017 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2017_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2018 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2018_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=2019 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_2019_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "Error"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=4000 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_4000_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "CreateOptions"/Int32ul "DesiredAccess"/Int32ul "IrpMajorFunction"/Int8ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=4001 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_4001_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "TargetFileNameLength"/Int16ul "TargetFileNameBuffer"/Bytes(<lambda>this:this.TargetFileNameLength))<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=4002 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_4002_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength))<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=5000 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_5000_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "CreateOptions"/Int32ul "DesiredAccess"/Int32ul "IrpMajorFunction"/Int8ul "Exclusions"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=5002 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_5002_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength) "CreateOptions"/Int32ul "DesiredAccess"/Int32ul)<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=5003 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_5003_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength))<block_end>@declare(guid=guid("c02afc2b-e24e-4449-ad76-bcc2c2575ead") event_id=5004 version=0)<class_stmt>Microsoft_Windows_UAC_FileVirtualization_5004_0(Etw)<block_start>pattern=Struct("Flags"/Int32ul "SidLength"/Int32ul "Sid"/Bytes(<lambda>this:this.SidLength) "FileNameLength"/Int16ul "FileNameBuffer"/Bytes(<lambda>this:this.FileNameLength) "ProcessImageNameLength"/Int16ul "ProcessImageNameBuffer"/Bytes(<lambda>this:this.ProcessImageNameLength))<block_end> |
<import_stmt>asyncio<import_from_stmt>aiohttp web<import_from_stmt>concurrent.futures ThreadPoolExecutor ProcessPoolExecutor<import_from_stmt>multiprocessing Queue Process<import_stmt>os<import_from_stmt>time sleep<async_keyword><def_stmt>handle request<block_start>index=open("index.html" 'rb')<line_sep>content=index.read()<line_sep><return>web.Response(body=content content_type='text/html')<block_end>tick=asyncio.Condition()<async_keyword><def_stmt>wshandler request<block_start>ws=web.WebSocketResponse()<line_sep><await>ws.prepare(request)<line_sep>recv_task=<none><line_sep>tick_task=<none><while_stmt>1<block_start><if_stmt><not>recv_task<block_start>recv_task=asyncio.ensure_future(ws.receive())<block_end><if_stmt><not>tick_task<block_start><await>tick.acquire()<line_sep>tick_task=asyncio.ensure_future(tick.wait())<block_end>done,pending=<await>asyncio.wait([recv_task tick_task] return_when=asyncio.FIRST_COMPLETED)<if_stmt>recv_task<in>done<block_start>msg=recv_task.result()<if_stmt>msg.tp<eq>web.MsgType.text<block_start>print("Got message %s"%msg.data)<line_sep>ws.send_str("Pressed key code: {}".format(msg.data))<block_end><elif_stmt>msg.tp<eq>web.MsgType.close<or>msg.tp<eq>web.MsgType.error<block_start><break><block_end>recv_task=<none><block_end><if_stmt>tick_task<in>done<block_start>ws.send_str("game loop ticks")<line_sep>tick.release()<line_sep>tick_task=<none><block_end><block_end><return>ws<block_end><def_stmt>game_loop asyncio_loop# coroutine to run in main thread
<block_start><async_keyword><def_stmt>notify <block_start><await>tick.acquire()<line_sep>tick.notify_all()<line_sep>tick.release()<block_end>queue=Queue()<line_sep># function to run in a different process
<def_stmt>worker <block_start><while_stmt>1<block_start>print("doing heavy calculation in process {}".format(os.getpid()))<line_sep>sleep(1)<line_sep>queue.put("calculation result")<block_end><block_end>Process(target=worker).start()<while_stmt>1# blocks this thread but not main thread with event loop
<block_start>result=queue.get()<line_sep>print("getting {} in process {}".format(result os.getpid()))<line_sep>task=asyncio.run_coroutine_threadsafe(notify() asyncio_loop)<line_sep>task.result()<block_end><block_end>asyncio_loop=asyncio.get_event_loop()<line_sep>executor=ThreadPoolExecutor(max_workers=1)<line_sep>asyncio_loop.run_in_executor(executor game_loop asyncio_loop)<line_sep>app=web.Application()<line_sep>app.router.add_route('GET' '/connect' wshandler)<line_sep>app.router.add_route('GET' '/' handle)<line_sep>web.run_app(app)<line_sep> |
# Copyright (c) 2019 - now, Eggroll 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_from_stmt>importlib import_module<import_from_stmt>concurrent.futures _base ThreadPoolExecutor<import_from_stmt>eggroll.core.datastructure.threadpool ErThreadUnpooledExecutor<import_from_stmt>eggroll.core.datastructure.queue _PySimpleQueue<import_from_stmt>eggroll.utils.log_utils get_logger<line_sep>L=get_logger()<try_stmt><block_start><import_from_stmt>queue SimpleQueue<block_end><except_stmt>ImportError<block_start>SimpleQueue=_PySimpleQueue<block_end><def_stmt>create_executor_pool canonical_name:str=<none> max_workers=<none> thread_name_prefix=<none> *args **kwargs<arrow>_base.Executor<block_start><if_stmt><not>canonical_name<block_start>canonical_name="concurrent.futures.ThreadPoolExecutor"<block_end>module_name,class_name=canonical_name.rsplit("." 1)<line_sep>_module=import_module(module_name)<line_sep>_class=getattr(_module class_name)<line_sep><return>_class(max_workers=max_workers thread_name_prefix=thread_name_prefix *args **kwargs)<block_end><def_stmt>create_simple_queue *args **kwargs<block_start><return>SimpleQueue()<block_end> |
<import_stmt>math<import_stmt>numpy<as>np<import_from_stmt>sklearn.linear_model LinearRegression<def_stmt>get_heading_angle traj:np.ndarray<block_start>"""
get the heading angle
traj: [N,2] N>=6
"""<line_sep># length == 6
# sort position
_traj=traj.copy()<line_sep>traj=traj.copy()<line_sep>traj=traj[traj[: 0].argsort()]<line_sep>traj=traj[traj[: 1].argsort()]<if_stmt>traj.T[0].max()-traj.T[0].min()<g>traj.T[1].max()-traj.T[1].min()# * dominated by x
<block_start>reg=LinearRegression().fit(traj[: 0].reshape(-1 1) traj[: 1])<line_sep>traj_dir=_traj[-2:].mean(0)-_traj[:2].mean(0)<line_sep>reg_dir=np.array([1 reg.coef_[0]])<line_sep>angle=np.arctan(reg.coef_[0])<block_end><else_stmt># using y as sample and x as the target to fit a line
<block_start>reg=LinearRegression().fit(traj[: 1].reshape(-1 1) traj[: 0])<line_sep>traj_dir=_traj[-2:].mean(0)-_traj[:2].mean(0)<line_sep>reg_dir=np.array([reg.coef_[0] 1])<times>np.sign(reg.coef_[0])<if_stmt>reg.coef_[0]<eq>0<block_start><import_stmt>pdb<line_sep>pdb.set_trace()<block_end>angle=np.arctan(1/reg.coef_[0])<block_end><if_stmt>angle<l>0<block_start>angle=2<times>np.pi+angle<block_end><if_stmt>(reg_dir<times>traj_dir).sum()<l>0# not same direction
<block_start>angle=(angle+np.pi)%(2<times>np.pi)<block_end># angle from y
angle_to_y=angle-np.pi/2<line_sep>angle_to_y=-angle_to_y<line_sep><return>angle_to_y<block_end><def_stmt>transform_coord coords angle<block_start>x=coords[<ellipsis> 0]<line_sep>y=coords[<ellipsis> 1]<line_sep>x_transform=np.cos(angle)<times>x-np.sin(angle)<times>y<line_sep>y_transform=np.cos(angle)<times>y+np.sin(angle)<times>x<line_sep>output_coords=np.stack((x_transform y_transform) axis=-1)<line_sep><return>output_coords<block_end><def_stmt>transform_coord_flip coords angle<block_start>x=coords[: 0]<line_sep>y=coords[: 1]<line_sep>x_transform=math.cos(angle)<times>x-math.sin(angle)<times>y<line_sep>y_transform=math.cos(angle)<times>y+math.sin(angle)<times>x<line_sep>x_transform=-1<times>x_transform# flip
# y_transform = -1*y_transform # flip
output_coords=np.stack((x_transform y_transform) axis=-1)<line_sep><return>output_coords<block_end> |
<import_stmt>copy<import_stmt>datetime<import_stmt>tempfile<import_from_stmt>collections OrderedDict<import_from_stmt>django.utils.functional cached_property<import_from_stmt>django.utils.translation ugettext<as>_<import_stmt>polib<import_from_stmt>memoized memoized<import_from_stmt>corehq.apps.app_manager.dbaccessors get_app<import_from_stmt>corehq.apps.translations.integrations.transifex.client TransifexApiClient <import_from_stmt>corehq.apps.translations.integrations.transifex.const SOURCE_LANGUAGE_MAPPING TRANSIFEX_SLUG_PREFIX_MAPPING <import_from_stmt>corehq.apps.translations.integrations.transifex.exceptions InvalidProjectMigration ResourceMissing <import_from_stmt>corehq.apps.translations.models TransifexProject<class_stmt>ProjectMigrator(object)<block_start><def_stmt>__init__ self domain project_slug source_app_id target_app_id resource_ids_mapping<block_start>"""
Migrate a transifex project from one app to another by
1. updating slugs of resources to use new module/form ids
2. updating context of translations in "Menus_and_forms" sheet to use new module/form ids
:param resource_ids_mapping: tuple of type, old_id, new_id
"""<line_sep>self.domain=domain<line_sep>self.project_slug=project_slug<line_sep>self.project=TransifexProject.objects.get(slug=project_slug)<line_sep>self.client=TransifexApiClient(self.project.organization.get_api_token self.project.organization project_slug)<line_sep>self.source_app_id=source_app_id<line_sep>self.target_app_id=target_app_id<line_sep>self.resource_ids_mapping=resource_ids_mapping<line_sep>self.id_mapping={old_id:new_id<for>_,old_id,new_id self.resource_ids_mapping}<block_end><def_stmt>validate self<block_start>ProjectMigrationValidator(self).validate()<block_end><def_stmt>migrate self<block_start>slug_update_responses=self._update_slugs()<line_sep>menus_and_forms_sheet_update_responses=self._update_menus_and_forms_sheet()<line_sep><return>slug_update_responses menus_and_forms_sheet_update_responses<block_end><def_stmt>_update_slugs self<block_start>responses={}<for_stmt>resource_type,old_id,new_id self.resource_ids_mapping<block_start>slug_prefix=self._get_slug_prefix(resource_type)<if_stmt><not>slug_prefix<block_start><continue><block_end>resource_slug="%s_%s"%(slug_prefix old_id)<line_sep>new_resource_slug="%s_%s"%(slug_prefix new_id)<line_sep>responses[old_id]=self.client.update_resource_slug(resource_slug new_resource_slug)<block_end><return>responses<block_end>@memoized<def_stmt>_get_slug_prefix self resource_type<block_start><return>TRANSIFEX_SLUG_PREFIX_MAPPING.get(resource_type)<block_end><def_stmt>_update_menus_and_forms_sheet self<block_start>langs=copy.copy(self.source_app_langs)<line_sep>translations=OrderedDict()<for_stmt>lang langs<block_start><try_stmt><block_start>translations[lang]=self.client.get_translation("Menus_and_forms" lang lock_resource=<false>)<block_end><except_stmt>ResourceMissing# Probably a lang in app not present on Transifex, so skip
<block_start><pass><block_end><block_end>self._update_context(translations)<line_sep><return>self._upload_new_translations(translations)<block_end>@cached_property<def_stmt>source_app_langs self<block_start><return>self._source_app.langs<block_end>@cached_property<def_stmt>_source_app self<block_start><return>get_app(self.domain self.source_app_id)<block_end><def_stmt>_update_context self translations<block_start>"""
update msgctxt for all POEntry objects replacing ids
:param translations: dict of lang code mapped to it list of POEntries
"""<for_stmt>po_entries translations.values()<block_start><for_stmt>po_entry po_entries# make sure the format is as expected, if not skip
<block_start>context_entries=po_entry.msgctxt.split(":")<if_stmt>len(context_entries)<eq>3<block_start>resource_id=context_entries[-1]<line_sep># replace if we have been asked to replace it
<if_stmt>resource_id<in>self.id_mapping<block_start>po_entry.msgctxt=po_entry.msgctxt.replace(resource_id self.id_mapping[resource_id])<block_end><block_end><block_end><block_end><block_end><def_stmt>_upload_new_translations self translations<block_start>responses={}<line_sep># the project source lang, which is the app default language should be the first to update.
# HQ keeps the default lang on top and hence it should be the first one here
<assert_stmt>list(translations.keys())[0]<eq>self.target_app_default_lang<for_stmt>lang_code translations<block_start>responses[lang_code]=self._upload_translation(translations[lang_code] lang_code)<block_end><return>responses<block_end><def_stmt>_upload_translation self translations lang_code<block_start>po=polib.POFile()<line_sep>po.check_for_duplicates=<false><line_sep>po.metadata=self.get_metadata()<line_sep>po.extend(translations)<with_stmt>tempfile.NamedTemporaryFile()<as>temp_file<block_start>po.save(temp_file.name)<line_sep>temp_file.seek(0)<if_stmt>lang_code<eq>self.target_app_default_lang<block_start><return>self.client.upload_resource(temp_file.name "Menus_and_forms" "Menus_and_forms" update_resource=<true>)<block_end><else_stmt><block_start><return>self.client.upload_translation(temp_file.name "Menus_and_forms" "Menus_and_forms" lang_code)<block_end><block_end><block_end><def_stmt>get_metadata self<block_start>now=str(datetime.datetime.now())<line_sep><return>{'App-Id':self.target_app_id 'PO-Creation-Date':now 'MIME-Version':'1.0' 'Content-Type':'text/plain; charset=utf-8' 'Language':self.target_app_default_lang}<block_end>@cached_property<def_stmt>target_app_default_lang self<block_start><return>self._target_app.default_language<block_end>@cached_property<def_stmt>_target_app self<block_start><return>get_app(self.domain self.target_app_id)<block_end>@cached_property<def_stmt>get_project_source_lang self<block_start><return>self.client.project_details().json()['source_language_code']<block_end>@cached_property<def_stmt>source_app_default_lang self<block_start><return>self._source_app.default_language<block_end><block_end><class_stmt>ProjectMigrationValidator(object)<block_start><def_stmt>__init__ self migrator<block_start>self.migrator=migrator<line_sep>self.source_app_default_lang=migrator.source_app_default_lang<line_sep>self.target_app_default_lang=migrator.target_app_default_lang<block_end><def_stmt>validate self<block_start>self._ensure_same_source_lang()<block_end><def_stmt>_ensure_same_source_lang self<block_start>"""
ensure same source lang for source app, target app and on transifex project
"""<if_stmt><not>self.source_app_default_lang<or>(self.source_app_default_lang<ne>self.target_app_default_lang)<block_start><raise>InvalidProjectMigration(_("Target app default language and the source app default language don't match"))<block_end>project_source_lang=self.migrator.get_project_source_lang<line_sep>source_app_lang_code=SOURCE_LANGUAGE_MAPPING.get(self.source_app_default_lang self.source_app_default_lang)<if_stmt>source_app_lang_code<ne>project_source_lang<block_start><raise>InvalidProjectMigration(_("Transifex project source lang and the source app default language don't match"))<block_end>target_app_lang_code=SOURCE_LANGUAGE_MAPPING.get(self.target_app_default_lang self.target_app_default_lang)<if_stmt>target_app_lang_code<ne>project_source_lang<block_start><raise>InvalidProjectMigration(_("Transifex project source lang and the target app default language don't match"))<block_end><block_end><block_end> |
<import_stmt>re<line_sep>s='aaa-AAA-123'<line_sep>print(re.search('aaa' s))<line_sep># <re.Match object; span=(0, 3), match='aaa'>
print(re.search('xxx' s))<line_sep># None
print(re.search('^aaa' s))<line_sep># <re.Match object; span=(0, 3), match='aaa'>
print(re.search('^123' s))<line_sep># None
print(re.search('aaa$' s))<line_sep># None
print(re.search('123$' s))<line_sep># <re.Match object; span=(8, 11), match='123'>
print(re.search('[A-Z]+' s))<line_sep># <re.Match object; span=(4, 7), match='AAA'>
s='012-3456-7890'<line_sep>print(re.fullmatch(r'\d{3}-\d{4}-\d{4}' s))<line_sep># <re.Match object; span=(0, 13), match='012-3456-7890'>
s='tel: 012-3456-7890'<line_sep>print(re.fullmatch(r'\d{3}-\d{4}-\d{4}' s))<line_sep># None
s='012-3456-7890'<line_sep>print(re.search(r'^\d{3}-\d{4}-\d{4}$' s))<line_sep># <re.Match object; span=(0, 13), match='012-3456-7890'>
s='tel: 012-3456-7890'<line_sep>print(re.search('^\d{3}-\d{4}-\d{4}$' s))<line_sep># None
s='ABC'<line_sep>print(re.search('abc' s))<line_sep># None
print(re.search('abc' s re.IGNORECASE))<line_sep># <re.Match object; span=(0, 3), match='ABC'>
|
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
<import_stmt>unittest<import_stmt>numpy<as>np<import_from_stmt>extensions.ops.sparse_reshape SparseReshape<import_from_stmt>mo.front.common.partial_infer.utils int64_array<import_from_stmt>mo.graph.graph Node<import_from_stmt>unit_tests.utils.graph build_graph<line_sep>nodes_attributes={'input_indices':{'shape':<none> 'value':<none> 'kind':'data'} 'input_shape':{'shape':<none> 'value':<none> 'kind':'data'} 'new_shape':{'shape':<none> 'value':<none> 'kind':'data'} 'sparse_reshape_node':{'op':'SparseReshape' 'kind':'op'} 'output_indices':{'shape':<none> 'value':<none> 'kind':'data'} 'output_shape':{'shape':<none> 'value':<none> 'kind':'data'}}<line_sep># graph 1
edges1=[('input_indices' 'sparse_reshape_node' {'in':0}) ('input_shape' 'sparse_reshape_node' {'in':1}) ('new_shape' 'sparse_reshape_node' {'in':2}) ('sparse_reshape_node' 'output_indices' {'out':0}) ('sparse_reshape_node' 'output_shape' {'out':1})]<line_sep>inputs1={'input_indices':{'shape':int64_array([5 2]) 'value':<none>} 'input_shape':{'shape':int64_array([2]) 'value':int64_array([4 5])} 'new_shape':{'shape':int64_array([3]) 'value':int64_array([5 -1 2])}}<class_stmt>TestSparseReshape(unittest.TestCase)<block_start><def_stmt>test_partial_infer1 self<block_start>graph=build_graph(nodes_attributes edges1 inputs1)<line_sep>sparse_reshape_node=Node(graph 'sparse_reshape_node')<line_sep>SparseReshape.infer(sparse_reshape_node)<line_sep># prepare reference results
ref_output_indices_shape=np.array([5 3] dtype=np.int32)<line_sep>ref_output_shape_value=np.array([5 2 2] dtype=np.int32)<line_sep># get the result
res_output_indices_shape=graph.node['output_indices']['shape']<line_sep>res_output_shape_value=graph.node['output_shape']['value']<line_sep>self.assertTrue(np.array_equal(ref_output_indices_shape res_output_indices_shape) 'shapes do not match expected: {} and given: {}'.format(ref_output_indices_shape res_output_indices_shape))<line_sep>self.assertTrue(np.array_equal(ref_output_shape_value res_output_shape_value) 'values do not match expected: {} and given: {}'.format(ref_output_shape_value res_output_shape_value))<block_end><block_end> |
<import_stmt>os<import_from_stmt>newspaper Article<line_sep>url='http://fox13now.com/2013/12/30/new-year-new-laws-obamacare-pot-guns-and-drones/'<line_sep>article=Article(url)<line_sep>article.download()<line_sep>article.parse()<with_stmt>open(os.path.join('testdata' 'article.txt') 'w')<as>f<block_start>f.write(article.text)<block_end> |
<import_from_stmt>typing cast List Optional Tuple<import_stmt>h11<import_stmt>pytest<import_from_stmt>wsproto WSConnection<import_from_stmt>wsproto.connection SERVER<import_from_stmt>wsproto.events AcceptConnection Event RejectConnection RejectData Request <import_from_stmt>wsproto.extensions Extension<import_from_stmt>wsproto.typing Headers<import_from_stmt>wsproto.utilities generate_accept_token generate_nonce normed_header_dict RemoteProtocolError <import_from_stmt>.helpers FakeExtension<def_stmt>_make_connection_request request_headers:Headers method:str="GET"<arrow>Request<block_start>client=h11.Connection(h11.CLIENT)<line_sep>server=WSConnection(SERVER)<line_sep>server.receive_data(client.send(h11.Request(method=method target="/" headers=request_headers)))<line_sep>event=next(server.events())<assert_stmt>isinstance(event Request)<line_sep><return>event<block_end><def_stmt>test_connection_request <arrow><none><block_start>event=_make_connection_request([(b"Host" b"localhost") (b"Connection" b"Keep-Alive, Upgrade") (b"Upgrade" b"WebSocket") (b"Sec-WebSocket-Version" b"13") (b"Sec-WebSocket-Key" generate_nonce()) (b"X-Foo" b"bar") ])<assert_stmt>event.extensions<eq>[]<assert_stmt>event.host<eq>"localhost"<assert_stmt>event.subprotocols<eq>[]<assert_stmt>event.target<eq>"/"<line_sep>headers=normed_header_dict(event.extra_headers)<assert_stmt>b"host"<not><in>headers<assert_stmt>b"sec-websocket-extensions"<not><in>headers<assert_stmt>b"sec-websocket-protocol"<not><in>headers<assert_stmt>headers[b"connection"]<eq>b"Keep-Alive, Upgrade"<assert_stmt>headers[b"sec-websocket-version"]<eq>b"13"<assert_stmt>headers[b"upgrade"]<eq>b"WebSocket"<assert_stmt>headers[b"x-foo"]<eq>b"bar"<block_end><def_stmt>test_connection_request_bad_method <arrow><none><block_start><with_stmt>pytest.raises(RemoteProtocolError)<as>excinfo<block_start>_make_connection_request([(b"Host" b"localhost") (b"Connection" b"Keep-Alive, Upgrade") (b"Upgrade" b"WebSocket") (b"Sec-WebSocket-Version" b"13") (b"Sec-WebSocket-Key" generate_nonce()) ] method="POST" )<block_end><assert_stmt>str(excinfo.value)<eq>"Request method must be GET"<block_end><def_stmt>test_connection_request_bad_connection_header <arrow><none><block_start><with_stmt>pytest.raises(RemoteProtocolError)<as>excinfo<block_start>_make_connection_request([(b"Host" b"localhost") (b"Connection" b"Keep-Alive, No-Upgrade") (b"Upgrade" b"WebSocket") (b"Sec-WebSocket-Version" b"13") (b"Sec-WebSocket-Key" generate_nonce()) ])<block_end><assert_stmt>str(excinfo.value)<eq>"Missing header, 'Connection: Upgrade'"<block_end><def_stmt>test_connection_request_bad_upgrade_header <arrow><none><block_start><with_stmt>pytest.raises(RemoteProtocolError)<as>excinfo<block_start>_make_connection_request([(b"Host" b"localhost") (b"Connection" b"Keep-Alive, Upgrade") (b"Upgrade" b"h2c") (b"Sec-WebSocket-Version" b"13") (b"Sec-WebSocket-Key" generate_nonce()) ])<block_end><assert_stmt>str(excinfo.value)<eq>"Missing header, 'Upgrade: WebSocket'"<block_end>@pytest.mark.parametrize("version" [b"12" b"not-a-digit"])<def_stmt>test_connection_request_bad_version_header version:bytes<arrow><none><block_start><with_stmt>pytest.raises(RemoteProtocolError)<as>excinfo<block_start>_make_connection_request([(b"Host" b"localhost") (b"Connection" b"Keep-Alive, Upgrade") (b"Upgrade" b"WebSocket") (b"Sec-WebSocket-Version" version) (b"Sec-WebSocket-Key" generate_nonce()) ])<block_end><assert_stmt>str(excinfo.value)<eq>"Missing header, 'Sec-WebSocket-Version'"<assert_stmt>excinfo.value.event_hint<eq>RejectConnection(headers=[(b"Sec-WebSocket-Version" b"13")] status_code=426)<block_end><def_stmt>test_connection_request_key_header <arrow><none><block_start><with_stmt>pytest.raises(RemoteProtocolError)<as>excinfo<block_start>_make_connection_request([(b"Host" b"localhost") (b"Connection" b"Keep-Alive, Upgrade") (b"Upgrade" b"WebSocket") (b"Sec-WebSocket-Version" b"13") ])<block_end><assert_stmt>str(excinfo.value)<eq>"Missing header, 'Sec-WebSocket-Key'"<block_end><def_stmt>test_upgrade_request <arrow><none><block_start>server=WSConnection(SERVER)<line_sep>server.initiate_upgrade_connection([(b"Host" b"localhost") (b"Connection" b"Keep-Alive, Upgrade") (b"Upgrade" b"WebSocket") (b"Sec-WebSocket-Version" b"13") (b"Sec-WebSocket-Key" generate_nonce()) (b"X-Foo" b"bar") ] "/" )<line_sep>event=next(server.events())<line_sep>event=cast(Request event)<assert_stmt>event.extensions<eq>[]<assert_stmt>event.host<eq>"localhost"<assert_stmt>event.subprotocols<eq>[]<assert_stmt>event.target<eq>"/"<line_sep>headers=normed_header_dict(event.extra_headers)<assert_stmt>b"host"<not><in>headers<assert_stmt>b"sec-websocket-extensions"<not><in>headers<assert_stmt>b"sec-websocket-protocol"<not><in>headers<assert_stmt>headers[b"connection"]<eq>b"Keep-Alive, Upgrade"<assert_stmt>headers[b"sec-websocket-version"]<eq>b"13"<assert_stmt>headers[b"upgrade"]<eq>b"WebSocket"<assert_stmt>headers[b"x-foo"]<eq>b"bar"<block_end><def_stmt>_make_handshake request_headers:Headers accept_headers:Optional[Headers]=<none> subprotocol:Optional[str]=<none> extensions:Optional[List[Extension]]=<none> <arrow>Tuple[h11.InformationalResponse bytes]<block_start>client=h11.Connection(h11.CLIENT)<line_sep>server=WSConnection(SERVER)<line_sep>nonce=generate_nonce()<line_sep>server.receive_data(client.send(h11.Request(method="GET" target="/" headers=[(b"Host" b"localhost") (b"Connection" b"Keep-Alive, Upgrade") (b"Upgrade" b"WebSocket") (b"Sec-WebSocket-Version" b"13") (b"Sec-WebSocket-Key" nonce) ]+request_headers )))<line_sep>client.receive_data(server.send(AcceptConnection(extra_headers=accept_headers<or>[] subprotocol=subprotocol extensions=extensions<or>[] )))<line_sep>event=client.next_event()<line_sep><return>event nonce<block_end><def_stmt>test_handshake <arrow><none><block_start>response,nonce=_make_handshake([])<line_sep>response.headers=sorted(response.headers)# For test determinism
<assert_stmt>response<eq>h11.InformationalResponse(status_code=101 headers=[(b"connection" b"Upgrade") (b"sec-websocket-accept" generate_accept_token(nonce)) (b"upgrade" b"WebSocket") ] )<block_end><def_stmt>test_handshake_extra_headers <arrow><none><block_start>response,nonce=_make_handshake([] accept_headers=[(b"X-Foo" b"bar")])<line_sep>response.headers=sorted(response.headers)# For test determinism
<assert_stmt>response<eq>h11.InformationalResponse(status_code=101 headers=[(b"connection" b"Upgrade") (b"sec-websocket-accept" generate_accept_token(nonce)) (b"upgrade" b"WebSocket") (b"x-foo" b"bar") ] )<block_end>@pytest.mark.parametrize("accept_subprotocol" ["one" "two"])<def_stmt>test_handshake_with_subprotocol accept_subprotocol:str<arrow><none><block_start>response,_=_make_handshake([(b"Sec-Websocket-Protocol" b"one, two")] subprotocol=accept_subprotocol)<line_sep>headers=normed_header_dict(response.headers)<assert_stmt>headers[b"sec-websocket-protocol"]<eq>accept_subprotocol.encode("ascii")<block_end><def_stmt>test_handshake_with_extension <arrow><none><block_start>extension=FakeExtension(accept_response=<true>)<line_sep>response,_=_make_handshake([(b"Sec-Websocket-Extensions" extension.name.encode("ascii"))] extensions=[extension] )<line_sep>headers=normed_header_dict(response.headers)<assert_stmt>headers[b"sec-websocket-extensions"]<eq>extension.name.encode("ascii")<block_end><def_stmt>test_handshake_with_extension_params <arrow><none><block_start>offered_params="parameter1=value3; parameter2=value4"<line_sep>accepted_params="parameter1=value1; parameter2=value2"<line_sep>extension=FakeExtension(accept_response=accepted_params)<line_sep>response,_=_make_handshake([(b"Sec-Websocket-Extensions" (f"{extension.name}; {offered_params}").encode("ascii") )] extensions=[extension] )<line_sep>headers=normed_header_dict(response.headers)<assert_stmt>extension.offered<eq>f"{extension.name}; {offered_params}"<assert_stmt>headers[b"sec-websocket-extensions"]<eq>(f"{extension.name}; {accepted_params}").encode("ascii")<block_end><def_stmt>test_handshake_with_extra_unaccepted_extension <arrow><none><block_start>extension=FakeExtension(accept_response=<true>)<line_sep>response,_=_make_handshake([(b"Sec-Websocket-Extensions" b"pretend, %s"%extension.name.encode("ascii") )] extensions=[extension] )<line_sep>headers=normed_header_dict(response.headers)<assert_stmt>headers[b"sec-websocket-extensions"]<eq>extension.name.encode("ascii")<block_end><def_stmt>test_protocol_error <arrow><none><block_start>server=WSConnection(SERVER)<with_stmt>pytest.raises(RemoteProtocolError)<as>excinfo<block_start>server.receive_data(b"broken nonsense\r\n\r\n")<block_end><assert_stmt>str(excinfo.value)<eq>"Bad HTTP message"<block_end><def_stmt>_make_handshake_rejection status_code:int body:Optional[bytes]=<none><arrow>List[Event]<block_start>client=h11.Connection(h11.CLIENT)<line_sep>server=WSConnection(SERVER)<line_sep>nonce=generate_nonce()<line_sep>server.receive_data(client.send(h11.Request(method="GET" target="/" headers=[(b"Host" b"localhost") (b"Connection" b"Keep-Alive, Upgrade") (b"Upgrade" b"WebSocket") (b"Sec-WebSocket-Version" b"13") (b"Sec-WebSocket-Key" nonce) ] )))<if_stmt>body<is><not><none><block_start>client.receive_data(server.send(RejectConnection(headers=[(b"content-length" b"%d"%len(body))] status_code=status_code has_body=<true> )))<line_sep>client.receive_data(server.send(RejectData(data=body)))<block_end><else_stmt><block_start>client.receive_data(server.send(RejectConnection(status_code=status_code)))<block_end>events=[]<while_stmt><true><block_start>event=client.next_event()<line_sep>events.append(event)<if_stmt>isinstance(event h11.EndOfMessage)<block_start><return>events<block_end><block_end><block_end><def_stmt>test_handshake_rejection <arrow><none><block_start>events=_make_handshake_rejection(400)<assert_stmt>events<eq>[h11.Response(headers=[(b"content-length" b"0")] status_code=400) h11.EndOfMessage() ]<block_end><def_stmt>test_handshake_rejection_with_body <arrow><none><block_start>events=_make_handshake_rejection(400 body=b"Hello")<assert_stmt>events<eq>[h11.Response(headers=[(b"content-length" b"5")] status_code=400) h11.Data(data=b"Hello") h11.EndOfMessage() ]<block_end> |
# -*- encoding: utf-8 -*-
# This is a package that contains a number of modules that are used to
# test import from the source files that have different encodings.
# This file (the __init__ module of the package), is encoded in utf-8
# and contains a list of strings from various unicode planes that are
# encoded differently to compare them to the same strings encoded
# differently in submodules. The following list, test_strings,
# contains a list of tuples. The first element of each tuple is the
# suffix that should be prepended with 'module_' to arrive at the
# encoded submodule name, the second item is the encoding and the last
# is the test string. The same string is assigned to the variable
# named 'test' inside the submodule. If the decoding of modules works
# correctly, from module_xyz import test should result in the same
# string as listed below in the 'xyz' entry.
# module, encoding, test string
test_strings=(('iso_8859_1' 'iso-8859-1' "Les hommes ont oublié cette vérité, "<concat>"dit le renard. Mais tu ne dois pas l'oublier. Tu deviens "<concat>"responsable pour toujours de ce que tu as apprivoisé.") ('koi8_r' 'koi8-r' "Познание бесконечности требует бесконечного времени."))<line_sep> |
# Copyright 2020 Datawire. 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_from_stmt>typing Any Dict Optional Union<import_stmt>logging<import_from_stmt>.cache Cache<import_from_stmt>.config Config<import_from_stmt>.ir IR<import_from_stmt>.ir.ir IRFileChecker<import_from_stmt>.envoy EnvoyConfig<import_from_stmt>.fetch ResourceFetcher<import_from_stmt>.utils SecretHandler NullSecretHandler Timer<def_stmt>Compile logger:logging.Logger input_text:str cache:Optional[Cache]=<none> file_checker:Optional[IRFileChecker]=<none> secret_handler:Optional[SecretHandler]=<none> k8s=<false> envoy_version="V2"<arrow>Dict[str Union[IR EnvoyConfig]]<block_start>"""
Compile is a helper function to take a bunch of YAML and compile it into an
IR and, optionally, an Envoy config.
The output is a dictionary:
{
"ir": the IR data structure
}
IFF v2 is True, there will be a toplevel "v2" key whose value is the Envoy
V2 config.
:param input_text: The input text (WATT snapshot JSON or K8s YAML per 'k8s')
:param k8s: If true, input_text is K8s YAML, otherwise it's WATT snapshot JSON
:param ir: Generate the IR IFF True
:param v2: Generate the V2 Envoy config IFF True
"""<if_stmt><not>file_checker<block_start>file_checker=<lambda>path:<true><block_end><if_stmt><not>secret_handler<block_start>secret_handler=NullSecretHandler(logger <none> <none> "fake")<block_end>aconf=Config()<line_sep>fetcher=ResourceFetcher(logger aconf)<if_stmt>k8s<block_start>fetcher.parse_yaml(input_text k8s=<true>)<block_end><else_stmt><block_start>fetcher.parse_watt(input_text)<block_end>aconf.load_all(fetcher.sorted())<line_sep>ir=IR(aconf cache=cache file_checker=file_checker secret_handler=secret_handler)<line_sep>out:Dict[str Union[IR EnvoyConfig]]={"ir":ir}<if_stmt>ir<block_start>out[envoy_version.lower()]=EnvoyConfig.generate(ir envoy_version.upper() cache=cache)<block_end><return>out<block_end> |
#
# File:
# color4.py
#
# Synopsis:
# Draws sixteen sample color boxs with RGB labels.
#
# Category:
# Colors
#
# Author:
# <NAME>
#
# Date of initial publication:
# January, 2006
#
# Description:
# This example draws sixteen color boxes using the RGB
# values for named colors. The boxes are labeled with
# the color name and the associated RGB values.
#
# Effects illustrated:
# o Drawing lines and polygons in NDC space.
# o RGB equivalents for some named colors.
# o Converting integer RGB color specifications to floating point.
#
# Output:
# o One plot is produced with sixteen sample color boxes.
#
<import_from_future_stmt> print_function<import_stmt>Ngl<import_stmt>numpy<line_sep>#
# Define the colors and labels to be used.
#
colors_and_labels=[[233 150 122] "DarkSalmon" [164 42 42] "Brown" [255 127 0] "DarkOrange1" [255 0 0] "Red" [255 255 0] "Yellow" [0 255 0] "Green" [34 139 34] "ForestGreen" [0 255 255] "Cyan" [79 148 205] "SteelBlue3" [0 0 255] "Blue" [148 0 211] "DarkViolet" [255 0 255] "Magneta" [255 255 255] "White" [153 153 153] "Gray60" [102 102 102] "Gray40" [0 0 0] "Black"]<line_sep>#
# Open a workstation with a default color table having
# background color "black" and foreground color "white".
#
rlist=Ngl.Resources()<line_sep>rlist.wkColorMap="default"<line_sep>rlist.wkForegroundColor="White"<line_sep>rlist.wkBackgroundColor="Black"<line_sep>wks_type="png"<line_sep>wks=Ngl.open_wks(wks_type "color4" rlist)<line_sep>#
# Extract the colors and labels.
#
colors=colors_and_labels[0:len(colors_and_labels):2]<line_sep>labels=colors_and_labels[1:len(colors_and_labels):2]<line_sep>#
# Set up arrays and resource lists for drawing the boxes.
# Select "Helvetica-Bold" for all text.
#
x=numpy.zeros(5 'f')<line_sep>y=numpy.zeros(5 'f')<line_sep>poly_res=Ngl.Resources()<line_sep>text_res=Ngl.Resources()<line_sep>text_res.txFont="Helvetica-Bold"<line_sep>#
# Draw the color boxes and titles.
#
<for_stmt>i range(0 len(colors))#
# delx_0 - horizontal spacing between boxes.
# delx_1 - width of a box.
# dely_0 - vertical spacing between boxes.
# dely_1 - height of a box.
#
<block_start>delx_0,delx_1,dely_0,dely_1=0.245 0.235 0.22 0.15<line_sep>x[0],y[0]=0.015+delx_0<times>(i%4) 0.90-(i<floordiv>4)<times>dely_0<line_sep>x[1],y[1]=x[0]+delx_1 y[0]<line_sep>x[2],y[2]=x[1] y[1]-dely_1<line_sep>x[3],y[3]=x[0] y[2]<line_sep>x[4],y[4]=x[0] y[0]<line_sep>#
# Convert the integer color values obtained from the
# named color chart (as entered above) to floating
# point numbers in the range 0. to 1.
#
r,g,b=colors[i][0]/255. colors[i][1]/255. colors[i][2]/255.<line_sep>poly_res.gsFillColor=[r g b]# Ngl.new_color(wks, r, g, b)
#
# Draw a white outline if the color is black, otherwise draw a colored box.
#
<if_stmt>(labels[i]<eq>"Black")<block_start>Ngl.polyline_ndc(wks x y poly_res)<block_end><else_stmt><block_start>Ngl.polygon_ndc(wks x y poly_res)<block_end>#
# Label the boxes.
#
text_res.txFontHeightF=0.017<line_sep>Ngl.text_ndc(wks labels[i] 0.5<times>(x[0]+x[1]) y[0]+0.0125 text_res)<line_sep>rgb_label="R={:4.2f} G={:4.2f} B={:4.2f}".format(r g b)<line_sep>text_res.txFontHeightF=0.015<line_sep>Ngl.text_ndc(wks rgb_label 0.5<times>(x[0]+x[1]) y[3]-0.0125 text_res)<block_end>#
# Plot top and bottom labels.
#
text_res.txFontHeightF=0.025<line_sep>Ngl.text_ndc(wks "Sixteen Sample Colors" 0.5 0.96 text_res)<line_sep>text_res.txFontHeightF=0.018<line_sep>Ngl.text_ndc(wks "The titles below each box indicate Red, Green, and Blue intensity values." 0.5 0.035 text_res)<line_sep>Ngl.frame(wks)<line_sep>Ngl.end()<line_sep> |
<import_from_stmt>..tool clang_coverage<import_from_stmt>..util.setting CompilerType Option TestList TestPlatform<import_from_stmt>..util.utils check_compiler_type<import_from_stmt>.init detect_compiler_type<import_from_stmt>.run clang_run gcc_run<def_stmt>get_json_report test_list:TestList options:Option<block_start>cov_type=detect_compiler_type()<line_sep>check_compiler_type(cov_type)<if_stmt>cov_type<eq>CompilerType.CLANG# run
<block_start><if_stmt>options.need_run<block_start>clang_run(test_list)<block_end># merge && export
<if_stmt>options.need_merge<block_start>clang_coverage.merge(test_list TestPlatform.OSS)<block_end><if_stmt>options.need_export<block_start>clang_coverage.export(test_list TestPlatform.OSS)<block_end><block_end><elif_stmt>cov_type<eq>CompilerType.GCC# run
<block_start><if_stmt>options.need_run<block_start>gcc_run(test_list)<block_end><block_end><block_end> |
<import_stmt>os<import_stmt>matplotlib.pyplot<as>plt<import_stmt>torch<import_from_stmt>src.utils.get_model_and_data get_model_and_data<import_from_stmt>src.parser.visualize parser<import_from_stmt>.visualize viz_epoch<import_stmt>src.utils.fixseed# noqa
plt.switch_backend('agg')<def_stmt>main # parse options
<block_start>parameters,folder,checkpointname,epoch=parser()<line_sep>model,datasets=get_model_and_data(parameters)<line_sep>dataset=datasets["train"]<line_sep>print("Restore weights..")<line_sep>checkpointpath=os.path.join(folder checkpointname)<line_sep>state_dict=torch.load(checkpointpath map_location=parameters["device"])<line_sep>model.load_state_dict(state_dict)<line_sep># visualize_params
viz_epoch(model dataset epoch parameters folder=folder writer=<none>)<block_end><if_stmt>__name__<eq>'__main__'<block_start>main()<block_end> |
<import_stmt>relstorage.storage<import_stmt>ZODB.Connection<line_sep># Monkey patches, ook
<def_stmt>_ex_cursor self name=<none><block_start><if_stmt>self._stale_error<is><not><none><block_start><raise>self._stale_error<block_end><with_stmt>self._lock<block_start>self._before_load()<line_sep><return>self._load_conn.cursor(name)<block_end><block_end>relstorage.storage.RelStorage.ex_cursor=_ex_cursor<def_stmt>_ex_connect self<block_start><return>self._adapter.connmanager.open()<block_end>relstorage.storage.RelStorage.ex_connect=_ex_connect<def_stmt>_ex_get self oid ghost_pickle<block_start>"""Return the persistent object with oid 'oid'."""<if_stmt>self.opened<is><none><block_start><raise>ConnectionStateError("The database connection is closed")<block_end>obj=self._cache.get(oid <none>)<if_stmt>obj<is><not><none><block_start><return>obj<block_end>obj=self._added.get(oid <none>)<if_stmt>obj<is><not><none><block_start><return>obj<block_end>obj=self._pre_cache.get(oid <none>)<if_stmt>obj<is><not><none><block_start><return>obj<block_end>obj=self._reader.getGhost(ghost_pickle)# New code
# Avoid infiniate loop if obj tries to load its state before
# it is added to the cache and it's state refers to it.
# (This will typically be the case for non-ghostifyable objects,
# like persistent caches.)
self._pre_cache[oid]=obj<line_sep>self._cache.new_ghost(oid obj)<line_sep>self._pre_cache.pop(oid)<line_sep><return>obj<block_end>ZODB.Connection.Connection.ex_get=_ex_get<line_sep> |
# Generated by Django 3.1.5 on 2021-03-17 21:30
<import_from_stmt>django.conf settings<import_from_stmt>django.db migrations models<import_stmt>django.db.models.deletion<class_stmt>Migration(migrations.Migration)<block_start>initial=<true><line_sep>dependencies=[migrations.swappable_dependency(settings.AUTH_USER_MODEL) ]<line_sep>operations=[migrations.CreateModel(name="Movie" fields=[("id" models.AutoField(auto_created=<true> primary_key=<true> serialize=<false> verbose_name="ID" ) ) ("imdb_id" models.CharField(max_length=10)) ("title" models.CharField(blank=<true> max_length=120)) ("description" models.TextField(blank=<true> null=<true>)) ("moviedb_popularity" models.FloatField(blank=<true> null=<true>)) ("poster_path_big" models.CharField(blank=<true> max_length=255 null=<true>) ) ("poster_path_small" models.CharField(blank=<true> max_length=255 null=<true>) ) ("backdrop_path_big" models.CharField(blank=<true> max_length=255 null=<true>) ) ("backdrop_path_small" models.CharField(blank=<true> max_length=255 null=<true>) ) ("duration" models.IntegerField(default=0)) ("media_info_raw" models.JSONField(blank=<true> default=dict)) ("imdb_score" models.FloatField(default=0.0)) ("original_language" models.CharField(blank=<true> max_length=2 null=<true>) ) ("release_date" models.DateField(blank=<true> null=<true>)) ("is_adult" models.BooleanField(default=<false>)) ("is_ready" models.BooleanField(default=<false>)) ("updated_at" models.DateTimeField(auto_now=<true>)) ("created_at" models.DateTimeField(auto_now_add=<true>)) ] ) migrations.CreateModel(name="MovieDBCategory" fields=[("moviedb_id" models.IntegerField(primary_key=<true> serialize=<false>)) ("name" models.CharField(max_length=20)) ("updated_at" models.DateTimeField(auto_now=<true>)) ("created_at" models.DateTimeField(auto_now_add=<true>)) ] ) migrations.CreateModel(name="MovieSubtitle" fields=[("id" models.AutoField(auto_created=<true> primary_key=<true> serialize=<false> verbose_name="ID" ) ) ("full_path" models.CharField(max_length=255)) ("relative_path" models.CharField(max_length=255)) ("file_name" models.CharField(max_length=255)) ("suffix" models.CharField(max_length=7)) ("updated_at" models.DateTimeField(auto_now=<true>)) ("created_at" models.DateTimeField(auto_now_add=<true>)) ] ) migrations.CreateModel(name="UserMovieHistory" fields=[("id" models.AutoField(auto_created=<true> primary_key=<true> serialize=<false> verbose_name="ID" ) ) ("current_second" models.IntegerField(default=0)) ("remaining_seconds" models.IntegerField(default=0)) ("is_watched" models.BooleanField(default=<false>)) ("created_at" models.DateTimeField(auto_now_add=<true>)) ("updated_at" models.DateTimeField(auto_now=<true>)) ("movie" models.ForeignKey(on_delete=django.db.models.deletion.CASCADE related_name="history" to="stream.movie" ) ) ("user" models.ForeignKey(on_delete=django.db.models.deletion.CASCADE to=settings.AUTH_USER_MODEL ) ) ] ) migrations.CreateModel(name="MyList" fields=[("id" models.AutoField(auto_created=<true> primary_key=<true> serialize=<false> verbose_name="ID" ) ) ("created_at" models.DateTimeField(auto_now_add=<true>)) ("movie" models.OneToOneField(on_delete=django.db.models.deletion.CASCADE related_name="my_list" to="stream.movie" ) ) ("user" models.ForeignKey(on_delete=django.db.models.deletion.CASCADE to=settings.AUTH_USER_MODEL ) ) ] ) migrations.CreateModel(name="MovieContent" fields=[("id" models.AutoField(auto_created=<true> primary_key=<true> serialize=<false> verbose_name="ID" ) ) ("torrent_source" models.TextField(null=<true>)) ("full_path" models.CharField(blank=<true> max_length=255 null=<true>)) ("relative_path" models.CharField(blank=<true> max_length=255 null=<true>) ) ("main_folder" models.CharField(blank=<true> max_length=255 null=<true>) ) ("file_name" models.CharField(blank=<true> max_length=255 null=<true>)) ("file_extension" models.CharField(blank=<true> max_length=255 null=<true>) ) ("source_file_name" models.CharField(blank=<true> max_length=255 null=<true>) ) ("source_file_extension" models.CharField(blank=<true> max_length=255 null=<true>) ) ("resolution_width" models.IntegerField(default=0)) ("resolution_height" models.IntegerField(default=0)) ("raw_info" models.TextField(blank=<true> null=<true>)) ("is_ready" models.BooleanField(default=<false>)) ("updated_at" models.DateTimeField(auto_now=<true>)) ("created_at" models.DateTimeField(auto_now_add=<true>)) ("movie_subtitle" models.ManyToManyField(blank=<true> to="stream.MovieSubtitle") ) ] ) migrations.AddField(model_name="movie" name="movie_content" field=models.ManyToManyField(to="stream.MovieContent") ) migrations.AddField(model_name="movie" name="moviedb_category" field=models.ManyToManyField(blank=<true> to="stream.MovieDBCategory") ) ]<block_end> |
<import_from_stmt>.commands *<import_from_stmt>.core.event_handler *<import_from_stmt>.utils Constant <def_stmt>plugin_loaded <block_start>Constant.startup()<block_end> |
#Longest Common Prefix in python
#Implementation of python program to find the longest common prefix amongst the given list of strings.
#If there is no common prefix then returning 0.
#define the function to evaluate the longest common prefix
<def_stmt>longestCommonPrefix s<block_start>p=''#declare an empty string
<for_stmt>i range(len(min(s key=len)))<block_start>f=s[0][i]<for_stmt>j s[1:]<block_start><if_stmt>j[i]<ne>f<block_start><return>p<block_end><block_end>p<augadd>f<block_end><return>p<block_end>#return the longest common prefix
n=int(input("Enter the number of names in list for input:"))<line_sep>print("Enter the Strings:")<line_sep>s=[input()<for>i range(n)]<if_stmt>(longestCommonPrefix(s))<block_start>print("The Common Prefix is:" longestCommonPrefix(s))<block_end><else_stmt><block_start>print("There is no common prefix for the given list of strings, hence the answer is:" 0)<block_end> |
<import_from_stmt>django.db migrations models<class_stmt>Migration(migrations.Migration)<block_start>dependencies=[('extras' '0060_customlink_button_class') ]<line_sep>operations=[migrations.AddField(model_name='customfield' name='created' field=models.DateField(auto_now_add=<true> null=<true>) ) migrations.AddField(model_name='customfield' name='last_updated' field=models.DateTimeField(auto_now=<true> null=<true>) ) migrations.AddField(model_name='customlink' name='created' field=models.DateField(auto_now_add=<true> null=<true>) ) migrations.AddField(model_name='customlink' name='last_updated' field=models.DateTimeField(auto_now=<true> null=<true>) ) migrations.AddField(model_name='exporttemplate' name='created' field=models.DateField(auto_now_add=<true> null=<true>) ) migrations.AddField(model_name='exporttemplate' name='last_updated' field=models.DateTimeField(auto_now=<true> null=<true>) ) migrations.AddField(model_name='webhook' name='created' field=models.DateField(auto_now_add=<true> null=<true>) ) migrations.AddField(model_name='webhook' name='last_updated' field=models.DateTimeField(auto_now=<true> null=<true>) ) ]<block_end> |
<import_from_stmt>astral Vision# noqa: F401
|
"""
nydus.db.base
~~~~~~~~~~~~~
:copyright: (c) 2011-2012 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""<line_sep>__all__=('LazyConnectionHandler' 'BaseCluster')<import_stmt>collections<import_from_stmt>nydus.db.map DistributedContextManager<import_from_stmt>nydus.db.routers BaseRouter routing_params<import_from_stmt>nydus.utils apply_defaults<def_stmt>iter_hosts hosts# this can either be a dictionary (with the key acting as the numeric
# index) or it can be a sorted list.
<block_start><if_stmt>isinstance(hosts collections.Mapping)<block_start><return>hosts.iteritems()<block_end><return>enumerate(hosts)<block_end><def_stmt>create_connection Connection num host_settings defaults# host_settings can be an iterable or a dictionary depending on the style
# of connection (some connections share options and simply just need to
# pass a single host, or a list of hosts)
<block_start><if_stmt>isinstance(host_settings collections.Mapping)<block_start><return>Connection(num **apply_defaults(host_settings defaults<or>{}))<block_end><elif_stmt>isinstance(host_settings collections.Iterable)<block_start><return>Connection(num *host_settings **defaults<or>{})<block_end><return>Connection(num host_settings **defaults<or>{})<block_end><class_stmt>BaseCluster(object)<block_start>"""
Holds a cluster of connections.
"""<class_stmt>MaxRetriesExceededError(Exception)<block_start><pass><block_end><def_stmt>__init__ self hosts backend router=BaseRouter max_connection_retries=20 defaults=<none><block_start>self.hosts=dict((conn_number create_connection(backend conn_number host_settings defaults))<for>conn_number,host_settings iter_hosts(hosts))<line_sep>self.max_connection_retries=max_connection_retries<line_sep>self.install_router(router)<block_end><def_stmt>__len__ self<block_start><return>len(self.hosts)<block_end><def_stmt>__getitem__ self name<block_start><return>self.hosts[name]<block_end><def_stmt>__getattr__ self name<block_start><return>CallProxy(self name)<block_end><def_stmt>__iter__ self<block_start><for_stmt>name self.hosts.iterkeys()<block_start><yield>name<block_end><block_end><def_stmt>install_router self router<block_start>self.router=router(self)<block_end><def_stmt>execute self path args kwargs<block_start>connections=self.__connections_for(path args=args kwargs=kwargs)<line_sep>results=[]<for_stmt>conn connections<block_start><for_stmt>retry xrange(self.max_connection_retries)<block_start>func=conn<for_stmt>piece path.split('.')<block_start>func=getattr(func piece)<block_end><try_stmt><block_start>results.append(func(*args **kwargs))<block_end><except_stmt>tuple(conn.retryable_exceptions) e<block_start><if_stmt><not>self.router.retryable<block_start><raise>e<block_end><elif_stmt>retry<eq>self.max_connection_retries-1<block_start><raise>self.MaxRetriesExceededError(e)<block_end><else_stmt><block_start>conn=self.__connections_for(path retry_for=conn.num args=args kwargs=kwargs)[0]<block_end><block_end><else_stmt><block_start><break><block_end><block_end><block_end># If we only had one db to query, we simply return that res
<if_stmt>len(results)<eq>1<block_start><return>results[0]<block_end><else_stmt><block_start><return>results<block_end><block_end><def_stmt>disconnect self<block_start>"""Disconnects all connections in cluster"""<for_stmt>connection self.hosts.itervalues()<block_start>connection.disconnect()<block_end><block_end><def_stmt>get_conn self *args **kwargs<block_start>"""
Returns a connection object from the router given ``args``.
Useful in cases where a connection cannot be automatically determined
during all steps of the process. An example of this would be
Redis pipelines.
"""<line_sep>connections=self.__connections_for('get_conn' args=args kwargs=kwargs)<if_stmt>len(connections)<is>1<block_start><return>connections[0]<block_end><else_stmt><block_start><return>connections<block_end><block_end><def_stmt>map self workers=<none> **kwargs<block_start><return>DistributedContextManager(self workers **kwargs)<block_end>@routing_params<def_stmt>__connections_for self attr args kwargs **fkwargs<block_start><return>[self[n]<for>n self.router.get_dbs(attr=attr args=args kwargs=kwargs **fkwargs)]<block_end><block_end><class_stmt>CallProxy(object)<block_start>"""
Handles routing function calls to the proper connection.
"""<def_stmt>__init__ self cluster path<block_start>self.__cluster=cluster<line_sep>self.__path=path<block_end><def_stmt>__call__ self *args **kwargs<block_start><return>self.__cluster.execute(self.__path args kwargs)<block_end><def_stmt>__getattr__ self name<block_start><return>CallProxy(self.__cluster self.__path+'.'+name)<block_end><block_end><class_stmt>LazyConnectionHandler(dict)<block_start>"""
Maps clusters of connections within a dictionary.
"""<def_stmt>__init__ self conf_callback<block_start>self.conf_callback=conf_callback<line_sep>self.conf_settings={}<line_sep>self.__is_ready=<false><block_end><def_stmt>__getitem__ self key<block_start><if_stmt><not>self.is_ready()<block_start>self.reload()<block_end><return>super(LazyConnectionHandler self).__getitem__(key)<block_end><def_stmt>is_ready self<block_start><return>self.__is_ready<block_end><def_stmt>reload self<block_start><import_from_stmt>nydus.db create_cluster<for_stmt>conn_alias,conn_settings self.conf_callback().iteritems()<block_start>self[conn_alias]=create_cluster(conn_settings)<block_end>self._is_ready=<true><block_end><def_stmt>disconnect self<block_start>"""Disconnects all connections in cluster"""<for_stmt>connection self.itervalues()<block_start>connection.disconnect()<block_end><block_end><block_end> |
# -*- coding: utf-8 -*-
<import_from_future_stmt> division print_function absolute_import<import_stmt>numpy<as>np<def_stmt>extfrm data npow power_threshold=-20<block_start>"""Extract frame over the power threshold
Parameters
----------
data: array, shape (`T`, `dim`)
Array of input data
npow : array, shape (`T`)
Vector of normalized power sequence.
power_threshold : float, optional
Value of power threshold [dB]
Default set to -20
Returns
-------
data: array, shape (`T_ext`, `dim`)
Remaining data after extracting frame
`T_ext` <= `T`
"""<line_sep>T=data.shape[0]<if_stmt>T<ne>len(npow)<block_start><raise>("Length of two vectors is different.")<block_end>valid_index=np.where(npow<g>power_threshold)<line_sep>extdata=data[valid_index]<assert_stmt>extdata.shape[0]<le>T<line_sep><return>extdata<block_end> |
"""This module contains the implementation of the coordinator."""<import_from_stmt>typing Any Dict Optional Type List Callable<import_stmt>stp.play<import_stmt>stp.rc<as>rc<import_stmt>stp.role.assignment<as>assignment<import_stmt>stp.situation<import_stmt>stp.skill<import_from_stmt>rj_msgs msg<line_sep>NUM_ROBOTS=16<class_stmt>Coordinator<block_start>"""The coordinator is responsible for using SituationAnalyzer to select the best
play to run, calling tick() on the play to get the list of skills, then ticking
all of the resulting skills."""<line_sep>__slots__=["_play_selector" "_prev_situation" "_prev_play" "_prev_role_results" "_props" "_debug_callback" ]<line_sep>_play_selector:stp.situation.IPlaySelector<line_sep>_prev_situation:Optional[stp.situation.ISituation]<line_sep>_prev_play:Optional[stp.play.IPlay]<line_sep>_prev_role_results:assignment.FlatRoleResults<line_sep>_props:Dict[Type[stp.play.IPlay] Any]<line_sep># TODO(1585): Properly handle type annotations for props instead of using Any.
<def_stmt>__init__ self play_selector:stp.situation.IPlaySelector debug_callback:Callable[[stp.play.IPlay List[stp.skill.ISkill]] <none>]=<none><block_start>self._play_selector=play_selector<line_sep>self._props={}<line_sep>self._prev_situation=<none><line_sep>self._prev_play=<none><line_sep>self._prev_role_results={}<line_sep>self._debug_callback=debug_callback<block_end><def_stmt>tick self world_state:rc.WorldState<arrow>List[msg.RobotIntent]<block_start>"""Performs 1 ticks of the STP system:
1. Selects the best play to run given the passed in world state.
2. Ticks the best play, collecting the list of skills to run.
3. Ticks the list of skills.
:param world_state: The current state of the world.
"""<line_sep># Call situational analysis to see which play should be running.
cur_situation,cur_play=self._play_selector.select(world_state)<line_sep>cur_play_type:Type[stp.play.IPlay]=type(cur_play)<line_sep># Update the props.
cur_play_props=cur_play.compute_props(self._props.get(cur_play_type <none>))<if_stmt>isinstance(cur_play type(self._prev_play))<and><not>self._prev_play.is_done(world_state)<block_start>cur_play=self._prev_play<line_sep># This should be checked here or in the play selector, so we can restart a play easily
<block_end># Collect the list of skills from the play.
new_role_results,skills=cur_play.tick(world_state self._prev_role_results cur_play_props)<line_sep>self._debug_callback(cur_play [entry.skill<for>entry skills])<line_sep># Get the list of actions from the skills
intents=[msg.RobotIntent()<for>i range(NUM_ROBOTS)]<line_sep>intents_dict={}<for_stmt>skill skills<block_start>robot=new_role_results[skill][0].role.robot<line_sep>intents_dict.update(skill.skill.tick(robot world_state intents[robot.id]))<block_end># Get the list of robot intents from the actions
<for_stmt>i range(NUM_ROBOTS)<block_start><if_stmt>i<in>intents_dict.keys()<block_start>intents[i]=intents_dict[i]<block_end><else_stmt><block_start>intents[i].motion_command.empty_command=[msg.EmptyMotionCommand()]<block_end><block_end># Update _prev_*.
self._prev_situation=cur_situation<line_sep>self._prev_play=cur_play<line_sep>self._prev_role_results=new_role_results<line_sep>self._props[cur_play_type]=cur_play_props<line_sep><return>intents<block_end><block_end> |
"""Implement the Unit class."""<import_stmt>numpy<as>np<import_from_stmt>.. config constants<line_sep>__all__=["Pixels" "Degrees" "Munits" "Percent"]<class_stmt>_PixelUnits<block_start><def_stmt>__mul__ self val<block_start><return>val<times>config.frame_width/config.pixel_width<block_end><def_stmt>__rmul__ self val<block_start><return>val<times>config.frame_width/config.pixel_width<block_end><block_end><class_stmt>Percent<block_start><def_stmt>__init__ self axis<block_start><if_stmt>np.array_equal(axis constants.X_AXIS)<block_start>self.length=config.frame_width<block_end><if_stmt>np.array_equal(axis constants.Y_AXIS)<block_start>self.length=config.frame_height<block_end><if_stmt>np.array_equal(axis constants.Z_AXIS)<block_start><raise>NotImplementedError("length of Z axis is undefined")<block_end><block_end><def_stmt>__mul__ self val<block_start><return>val/100<times>self.length<block_end><def_stmt>__rmul__ self val<block_start><return>val/100<times>self.length<block_end><block_end>Pixels=_PixelUnits()<line_sep>Degrees=constants.PI/180<line_sep>Munits=1<line_sep> |
"""In this module we provide the functionality of a Modal.
The Modal can be used to focus some kind of information like text, images, chart or an interactive
dashboard.
The implementation is inspired by
- https://css-tricks.com/considerations-styling-modal/
- https://codepen.io/henchmen/embed/preview/PzQpvk
- https://getbootstrap.com/docs/4.3/components/modal/
"""<import_stmt>panel<as>pn<import_stmt>param<line_sep>_CSS="""
.bk.modal {
/* This way it could be display flex or grid or whatever also. */
display: block;
max-width: 100%;
max-height: 100%;
position: fixed!important;
z-index: 100;
left: 0!important;
top: 0!important;
bottom: 0!important;
right: 0!important;
margin: auto!important;
box-shadow: 5px 5px 20px grey;
box-shadow: 0 0 60px 10px rgba(0, 0, 0, 0.9);
border: 1px solid rgba(0,0,0,.125);
border-radius: 0.25rem;
}
.closed {
display: none!important;
}
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 50;
background: rgba(0, 0, 0, 0.6);
}
.modal-body {
overflow: auto;
}
"""<class_stmt>Modal(param.Parameterized)<block_start>"""The Modal can be used to focus some kind of information like text, images, chart or an
interactive dashboard.
In order to use this modal you need to
- Instantiate the Modal
- Add the CSS from the get_css function to the app
- using `pn.config.raw_css.append` or
- directly in your template
The implementation is inspired by
- https://css-tricks.com/considerations-styling-modal/
- https://codepen.io/henchmen/embed/preview/PzQpvk
- https://getbootstrap.com/docs/4.3/components/modal/
"""<line_sep>title=param.String(default="Modal")<line_sep>body=param.List()<def_stmt>__init__ self **params<block_start>super().__init__(**params)<line_sep>self.modal_overlay=pn.pane.HTML('<div class="modal-overlay" id="modal-overlay"></div>')<line_sep>self.close_button=pn.widgets.Button(name="X" css_classes=["close-modal-button"] width=50 )<line_sep>self.close_button.js_on_click(code="""
var modal = document.querySelector(".bk.modal");
var modalOverlay = document.querySelector("#modal-overlay");
modal.classList.toggle("closed");
modalOverlay.classList.toggle("closed");
""")<line_sep>self._modal_title=pn.pane.Markdown("# "+self.title)<line_sep>self._modal_body=pn.Column(*self.body)# pylint: disable=not-an-iterable
self.modal=pn.Column(pn.Column(pn.Row(self._modal_title pn.layout.HSpacer() self.close_button ) pn.layout.Divider() self._modal_body sizing_mode="stretch_width" margin=10 ) background="white" width=400 height=400 css_classes=["modal"] )<block_end>@staticmethod<def_stmt>get_open_modal_button name:str="Open Modal" **kwargs<arrow>pn.widgets.Button<block_start>"""A Button to open the modal with"""<line_sep>open_modal_button=pn.widgets.Button(name=name css_classes=["open-modal-button"] **kwargs)<line_sep>open_modal_button.js_on_click(code="""
var modal = document.querySelector(".modal");
var modalOverlay = document.querySelector("#modal-overlay");
modal.classList.toggle("closed");
modalOverlay.classList.toggle("closed");
""")<line_sep><return>open_modal_button<block_end>@staticmethod<def_stmt>get_css <arrow>str<block_start>"""Add the CSS from this function to the app
- using `pn.config.raw_css.append` or
- directly in your template
Returns:
str: The css string
"""<line_sep><return>_CSS<block_end>@param.depends("title" watch=<true> )<def_stmt>set_modal_title self <block_start>"""Updates the title of the modal"""<line_sep>self._modal_title.object="# "+self.title<block_end>@param.depends("body" watch=<true> )<def_stmt>set_modal_body self <block_start>"""Updates the body of the modal"""<line_sep>self._modal_body[:]=self.body<block_end><block_end> |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
<import_from_stmt>paddle.fluid core framework unique_name<import_from_stmt>.meta_optimizer_base MetaOptimizerBase<line_sep>__all__=[]<class_stmt>FP16AllReduceOptimizer(MetaOptimizerBase)<block_start><def_stmt>__init__ self optimizer<block_start>super(FP16AllReduceOptimizer self).__init__(optimizer)<line_sep>self.inner_opt=optimizer<line_sep># we do not allow meta optimizer to be inner optimizer currently
self.meta_optimizers_white_list=["LarsOptimizer" "LambOptimizer" "RecomputeOptimizer" "LocalSGDOptimizer" "GradientMergeOptimizer" "GraphExecutionOptimizer" "AdaptiveLocalSGDOptimizer" ]<line_sep>self.meta_optimizers_black_list=["DGCOptimizer"]<block_end><def_stmt>_set_basic_info self loss role_maker user_defined_optimizer user_defined_strategy<block_start>super(FP16AllReduceOptimizer self)._set_basic_info(loss role_maker user_defined_optimizer user_defined_strategy)<block_end><def_stmt>_can_apply self<block_start><if_stmt><not>self.role_maker._is_collective<block_start><return><false><block_end><if_stmt>self.user_defined_strategy.fp16_allreduce<block_start><return><true><block_end><return><false><block_end><def_stmt>_disable_strategy self dist_strategy<block_start>dist_strategy.fp16_allreduce=<false><block_end><def_stmt>_enable_strategy self dist_strategy context=<none><block_start>dist_strategy.fp16_allreduce=<true><block_end>@staticmethod<def_stmt>fp16_compression param_and_grads<block_start>"""
Compress fp32 gradients to fp16 during allreduce.
"""<line_sep>op_maker=core.op_proto_and_checker_maker<line_sep>new_param_and_grads=[]# param, grad, is_cast
# cast grad from fp32->fp16 before allreduce,
<for_stmt>param,grad param_and_grads<block_start><if_stmt>grad<is><none><or>grad.dtype<ne>core.VarDesc.VarType.FP32<block_start>new_param_and_grads.append((param grad <false>))<line_sep><continue><block_end>op=grad.op<line_sep>block=grad.block<line_sep>var_attr=op.all_attrs()[op_maker.kOpRoleVarAttrName()]<if_stmt>param.name<not><in>var_attr<block_start>new_param_and_grads.append((param grad <false>))<line_sep><continue><block_end># remove (param, grad) from op_role_var
var_attr.remove(param.name)<line_sep>var_attr.remove(grad.name)<if_stmt>len(var_attr)<g>1<block_start>op._set_attr(op_maker.kOpRoleVarAttrName() var_attr)<block_end><else_stmt><block_start>op._remove_attr(op_maker.kOpRoleVarAttrName())<block_end>new_grad=block.create_var(name=unique_name.generate(grad.name+".cast_fp16") dtype=core.VarDesc.VarType.FP16 persistable=<false> stop_gradient=<true>)<with_stmt>block.program._backward_role_guard()<block_start>cast_op=block.append_op(type="cast" inputs={"X":grad} outputs={"Out":new_grad} attrs={"in_dtype":core.VarDesc.VarType.FP32 "out_dtype":core.VarDesc.VarType.FP16} stop_gradient=<true>)<line_sep>backward=op_maker.OpRole.Backward<line_sep>cast_op._set_attr(op_maker.kOpRoleAttrName() backward)<line_sep>cast_op._set_attr(op_maker.kOpRoleVarAttrName() [param.name new_grad.name])<line_sep>new_grad.op=cast_op<block_end>new_param_and_grads.append((param new_grad <true>))<block_end>ret_param_and_grads=[]<line_sep># cast grad from fp16->fp32 after allreduce.
# NOTE. Now we split fp16 compression into two for loops,
# if we do not separate them, fuse allreduce will wrong.
# This must be the problem of fuse allreduce pass, need
# fixed in future.
<for_stmt>param,grad,cast new_param_and_grads<block_start><if_stmt><not>cast<block_start>ret_param_and_grads.append((param grad))<line_sep><continue><block_end>block=grad.block<line_sep>new_grad=block.create_var(name=unique_name.generate(grad.name+".cast_fp32") dtype=core.VarDesc.VarType.FP32 persistable=<false> stop_gradient=<true>)<with_stmt>block.program._optimized_guard([param grad]) framework.name_scope('fp16_allreduce')<block_start>cast_op=block.append_op(type="cast" inputs={"X":grad} outputs={"Out":new_grad} attrs={"in_dtype":core.VarDesc.VarType.FP16 "out_dtype":core.VarDesc.VarType.FP32} stop_gradient=<true>)<block_end>ret_param_and_grads.append((param new_grad))<block_end><return>ret_param_and_grads<block_end><def_stmt>apply_optimize self loss startup_program params_grads<block_start>new_params_grads=self.fp16_compression(params_grads)<line_sep><return>self.inner_opt.apply_optimize(loss startup_program=startup_program params_grads=new_params_grads)<block_end><block_end> |
<import_stmt>FWCore.ParameterSet.Config<as>cms<import_from_stmt>CondTools.Geometry.HGCalEEParametersWriter_cfi *<import_from_stmt>Configuration.ProcessModifiers.dd4hep_cff dd4hep<line_sep>dd4hep.toModify(HGCalEEParametersWriter fromDD4Hep=cms.bool(<true>))<line_sep>HGCalHESiParametersWriter=HGCalEEParametersWriter.clone(name=cms.string("HGCalHESiliconSensitive") nameW=cms.string("HGCalHEWafer") nameC=cms.string("HGCalHECell") )<line_sep>HGCalHEScParametersWriter=HGCalEEParametersWriter.clone(name=cms.string("HGCalHEScintillatorSensitive") nameW=cms.string("HGCalWafer") nameC=cms.string("HGCalCell") )<line_sep> |
# Code generated by sqlc. DO NOT EDIT.
<import_stmt>dataclasses<import_from_stmt>typing Optional<line_sep>@dataclasses.dataclass()<class_stmt>Author<block_start>id:int<line_sep>name:str<line_sep>bio:Optional[str]<block_end> |
# The following comments couldn't be translated into the new config version:
#
# keep only muon-related info here
#
<import_stmt>FWCore.ParameterSet.Config<as>cms<line_sep>process=cms.Process("MISO")<line_sep>process.load("Configuration.EventContent.EventContent_cff")<line_sep># service = MessageLogger {
# untracked vstring destinations = { "cout" }
# untracked vstring debugModules = { "muIsoDepositTk",
# "muIsoDepositCalByAssociatorHits",
# "muIsoDepositCalByAssociatorTowers",
# "muIsoDepositCal" }
# untracked vstring categories = { "RecoMuon" , "MuonIsolation" }
#
# untracked PSet cout = {
# untracked string threshold = "DEBUG"
# untracked int32 lineLength = 132
# untracked bool noLineBreaks = true
# untracked PSet DEBUG = {untracked int32 limit = 0 }
# untracked PSet RecoMuon = { untracked int32 limit = 10000000}
# untracked PSet MuonIsolation = { untracked int32 limit = 10000000}
# }
# }
process.load("FWCore.MessageLogger.MessageLogger_cfi")<line_sep>#process.load("RecoLocalMuon.Configuration.RecoLocalMuon_cff")
#process.load("RecoMuon.Configuration.RecoMuon_cff")
process.load("Configuration.StandardSequences.Services_cff")<line_sep>process.load("Configuration.StandardSequences.Geometry_cff")<line_sep>process.load("Configuration.StandardSequences.MagneticField_38T_cff")<line_sep>process.load("Configuration.StandardSequences.FakeConditions_cff")<line_sep>#process.load("Configuration.StandardSequences.RawToDigi_cff")
process.load("Configuration.StandardSequences.Reconstruction_cff")<line_sep>#has everything(?) one needs
# pick muIsolation sequence for "standard" iso reco for tracker and global muons
process.load("RecoMuon.MuonIsolationProducers.muIsolation_cff")<line_sep>process.maxEvents=cms.untracked.PSet(input=cms.untracked.int32(2000))<line_sep>process.source=cms.Source("PoolSource" fileNames=cms.untracked.vstring('/store/mc/2007/12/7/RelVal-RelValBJets_Pt_50_120-1197045102/0002/0A21A5F4-02A5-DC11-89F5-000423DD2F34.root'))<line_sep>process.source=cms.Source("PoolSource" fileNames=cms.untracked.vstring('/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/10438122-2A5F-DD11-A77F-000423D985E4.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/12F34420-2A5F-DD11-AB6E-000423D6CA6E.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/244E7C0B-315F-DD11-ACFC-001617E30F58.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/2ADD8A12-315F-DD11-8AB8-000423D6C8E6.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/34A291FB-305F-DD11-833E-001617C3B6CC.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/383E09CA-2C5F-DD11-9A28-000423D6BA18.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/40F0F8A4-2A5F-DD11-BC72-001617C3B64C.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/4AD39C8C-2A5F-DD11-B935-001617C3B710.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/4C0D4911-315F-DD11-A20D-001617DBD332.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/4C32E425-2A5F-DD11-B819-000423D6C8EE.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/50881CBB-2A5F-DD11-92C6-001617C3B6E8.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/52B83F75-2A5F-DD11-AD56-001617C3B6CC.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/544DC99A-2A5F-DD11-9160-001617C3B6E2.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/62F7698D-2A5F-DD11-907A-001617C3B6DC.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/7C8A2791-2A5F-DD11-814D-001617DBCF6A.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/7EDA5005-315F-DD11-8019-001617C3B706.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/8A91E518-2A5F-DD11-B49A-000423D6B42C.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/8CC497AE-2A5F-DD11-AE43-000423DD2F34.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/9A469FA8-2A5F-DD11-9909-001617C3B6FE.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/9A5BE3A4-2A5F-DD11-A61B-001617DF785A.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/9AC2141C-2A5F-DD11-ADF5-000423D6A6F4.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/9CCFA319-2A5F-DD11-B0AA-000423D94700.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/A0F6C41D-2A5F-DD11-8685-000423D6BA18.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/B0159DAC-2A5F-DD11-98A8-001617E30D00.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/B05C32FC-305F-DD11-A957-001617C3B70E.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/C6ADD999-2A5F-DD11-AF9F-0016177CA7A0.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/C8AEE585-2A5F-DD11-BB37-001617C3B77C.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/CC5178C4-2A5F-DD11-BCE6-001617E30F4C.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/CE9FE020-2A5F-DD11-9846-000423D6CA72.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/D24BFA7E-2A5F-DD11-8F79-001617C3B70E.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/D62761FA-305F-DD11-A108-0016177CA778.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/DA0DDFB6-2A5F-DD11-987A-001617DBD5B2.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/E64386FE-305F-DD11-BA68-0019DB29C614.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/E6BC0D37-2A5F-DD11-9ACB-000423D6B444.root' '/store/relval/CMSSW_2_1_0_pre11/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/STARTUP_V4_v2/0000/F251D794-2A5F-DD11-BA5D-00161757BF42.root') secondaryFileNames=cms.untracked.vstring())<line_sep>process.RECO=cms.OutputModule("PoolOutputModule" process.FEVTSIMEventContent fileName=cms.untracked.string('file:isoTest.root'))<line_sep>process.p1=cms.Path(process.muIsolation)<line_sep>process.outpath=cms.EndPath(process.RECO)<line_sep>process.RECO.outputCommands.append('drop *_*_*_*')<line_sep>process.RECO.outputCommands.extend(process.RecoMuonRECO.outputCommands)<line_sep> |
<import_stmt>pyaf.Bench.TS_datasets<as>tsds<import_stmt>pyaf.Bench.YahooStocks<as>ys<import_stmt>warnings<line_sep>symbol_lists=tsds.get_yahoo_symbol_lists()<line_sep>y_keys=sorted(symbol_lists.keys())<line_sep>print(y_keys)<line_sep>k="nysecomp"<line_sep>tester=ys.cYahoo_Tester(tsds.load_yahoo_stock_prices(k) "YAHOO_STOCKS_"+k)<with_stmt>warnings.catch_warnings()<block_start>warnings.simplefilter("error")<line_sep>tester.testSignals('VRS')<block_end> |
# Generated by Django 2.2.10 on 2020-04-03 19:10
<import_from_stmt>django.db migrations models<class_stmt>Migration(migrations.Migration)<block_start>dependencies=[('events' '0039_event_limits') ]<line_sep>operations=[migrations.AddField(model_name='event' name='team_size' field=models.IntegerField(default=3) ) ]<block_end> |
<import_from_stmt>ray.rllib.contrib.bandits.envs.discrete LinearDiscreteEnv WheelBanditEnv<import_from_stmt>ray.rllib.contrib.bandits.envs.parametric ParametricItemRecoEnv<line_sep>__all__=["LinearDiscreteEnv" "WheelBanditEnv" "ParametricItemRecoEnv"]<line_sep> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.