index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
997,800 | 9cf88b792884979d9cb68442b244364c63c53ebc | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from flaskblog.config import Config
# Initialize Application
app = Flask(__name__)
app.config.from_object(Config)
# Extensions
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
mail = Mail(app)
# Configuration
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'
from flaskblog import routes, models
|
997,801 | d3d5999561aa9808c5442ed8bb0d3bc35f9f6344 | from ZeroScenarioHelper import *
def main():
SetCodePage("ms932")
CreateScenaFile(
"c0450.bin", # FileName
"c0450", # MapName
"c0450", # Location
0x0024, # MapIndex
"ed7113",
0x00002000, # Flags
("", "", "", "", "", ""), # include
0x00, # PlaceNameNumber
0x00, # PreInitFunctionIndex
b'\x00\xff\xff', # Unknown_51
# Information
[0, 0, -1000, 0, 0, 2500, 34000, 262, 30, 45, 0, 360, 0, 0, 0, 0, 0, 1, 36, 0, 4, 0, 5],
)
BuildStringList((
"c0450", # 0
"受付カイル", # 1
"ドリス", # 2
"アーロン", # 3
"レティシア支配人", # 4
"ガンツ", # 5
"ビクセン町長", # 6
"ロバーツ主任", # 7
"トロント", # 8
))
AddCharChip((
"chr/ch22000.itc", # 00
"chr/ch25700.itc", # 01
"chr/ch27500.itc", # 02
"chr/ch27900.itc", # 03
"apl/ch50409.itc", # 04
"chr/ch23200.itc", # 05
"chr/ch29300.itc", # 06
"chr/ch24400.itc", # 07
))
DeclNpc(65440, 0, 59970, 270, 261, 0x0, 0, 0, 0, 0, 0, 0, 9, 255, 0)
DeclNpc(4090, 9, 59900, 225, 261, 0x0, 0, 1, 0, 0, 2, 0, 11, 255, 0)
DeclNpc(50740, 0, 9750, 90, 261, 0x0, 0, 2, 0, 0, 1, 0, 10, 255, 0)
DeclNpc(-3990, 0, 7000, 90, 261, 0x0, 0, 3, 0, 0, 0, 0, 7, 255, 0)
DeclNpc(162000, 649, 5900, 90, 406, 0x0, 0, 4, 0, 255, 255, 0, 15, 255, 0)
DeclNpc(162000, 0, 4500, 0, 389, 0x0, 0, 5, 0, 255, 255, 0, 16, 255, 0)
DeclNpc(3549, 0, 4360, 45, 389, 0x0, 0, 6, 0, 0, 0, 0, 12, 255, 0)
DeclNpc(114809, 0, 61029, 180, 389, 0x0, 0, 7, 0, 0, 0, 0, 13, 255, 0)
DeclActor(-3500, 0, 7000, 1500, -3990, 1500, 7000, 0x007E, 0, 6, 0x0000)
DeclActor(64300, 0, 59970, 1500, 65440, 1500, 59970, 0x007E, 0, 8, 0x0000)
DeclActor(68130, 10, 11650, 1200, 68130, 1500, 11650, 0x007C, 0, 14, 0x0000)
DeclActor(162620, 0, 6480, 1200, 161500, 1500, 5570, 0x007E, 0, 15, 0x0000)
ScpFunction((
"Function_0_28C", # 00, 0
"Function_1_344", # 01, 1
"Function_2_3A5", # 02, 2
"Function_3_3D0", # 03, 3
"Function_4_3FB", # 04, 4
"Function_5_64E", # 05, 5
"Function_6_76C", # 06, 6
"Function_7_770", # 07, 7
"Function_8_1A04", # 08, 8
"Function_9_1A08", # 09, 9
"Function_10_2738", # 0A, 10
"Function_11_31B5", # 0B, 11
"Function_12_3C6C", # 0C, 12
"Function_13_45AA", # 0D, 13
"Function_14_4A29", # 0E, 14
"Function_15_4A59", # 0F, 15
"Function_16_4B94", # 10, 16
"Function_17_4F07", # 11, 17
"Function_18_71D1", # 12, 18
"Function_19_721B", # 13, 19
"Function_20_7237", # 14, 20
"Function_21_7253", # 15, 21
"Function_22_726F", # 16, 22
"Function_23_728B", # 17, 23
"Function_24_72A7", # 18, 24
"Function_25_7B37", # 19, 25
))
def Function_0_28C(): pass
label("Function_0_28C")
RunExpression(0x2, (scpexpr(EXPR_RAND), scpexpr(EXPR_PUSH_LONG, 0x8), scpexpr(EXPR_IMOD), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Switch(
(scpexpr(EXPR_GET_RESULT, 0x2), scpexpr(EXPR_END)),
(0, "loc_2CC"),
(1, "loc_2D8"),
(2, "loc_2E4"),
(3, "loc_2F0"),
(4, "loc_2FC"),
(5, "loc_308"),
(6, "loc_314"),
(SWITCH_DEFAULT, "loc_320"),
)
label("loc_2CC")
OP_A0(0xFE, 1450, 0x0, 0xFB)
Jump("loc_32C")
label("loc_2D8")
OP_A0(0xFE, 1550, 0x0, 0xFB)
Jump("loc_32C")
label("loc_2E4")
OP_A0(0xFE, 1600, 0x0, 0xFB)
Jump("loc_32C")
label("loc_2F0")
OP_A0(0xFE, 1400, 0x0, 0xFB)
Jump("loc_32C")
label("loc_2FC")
OP_A0(0xFE, 1650, 0x0, 0xFB)
Jump("loc_32C")
label("loc_308")
OP_A0(0xFE, 1350, 0x0, 0xFB)
Jump("loc_32C")
label("loc_314")
OP_A0(0xFE, 1500, 0x0, 0xFB)
Jump("loc_32C")
label("loc_320")
OP_A0(0xFE, 1500, 0x0, 0xFB)
Jump("loc_32C")
label("loc_32C")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_343")
OP_A0(0xFE, 1500, 0x0, 0xFB)
Jump("loc_32C")
label("loc_343")
Return()
# Function_0_28C end
def Function_1_344(): pass
label("Function_1_344")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_3A4")
OP_95(0xFE, 72280, 0, 9750, 1000, 0x0)
OP_95(0xFE, 72280, 0, 5580, 1000, 0x0)
OP_95(0xFE, 50740, 0, 5580, 1000, 0x0)
OP_95(0xFE, 50740, 0, 9750, 1000, 0x0)
Jump("Function_1_344")
label("loc_3A4")
Return()
# Function_1_344 end
def Function_2_3A5(): pass
label("Function_2_3A5")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_3CF")
OP_94(0xFE, 0x604, 0xD714, 0x17C0, 0xFB9A, 0x3E8)
Sleep(300)
Jump("Function_2_3A5")
label("loc_3CF")
Return()
# Function_2_3A5 end
def Function_3_3D0(): pass
label("Function_3_3D0")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_3FA")
OP_94(0xFE, 0xFAD1, 0x141E, 0x11B66, 0x2652, 0x3E8)
Sleep(300)
Jump("Function_3_3D0")
label("loc_3FA")
Return()
# Function_3_3D0 end
def Function_4_3FB(): pass
label("Function_4_3FB")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x5C, 0)), scpexpr(EXPR_END)), "loc_40A")
ClearScenarioFlags(0x5C, 0)
Event(0, 17)
label("loc_40A")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xE0, 0)), scpexpr(EXPR_END)), "loc_428")
ClearChrFlags(0xD, 0x80)
ClearChrBattleFlags(0xD, 0x8000)
BeginChrThread(0xD, 0, 0, 0)
Jump("loc_64D")
label("loc_428")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC3, 6)), scpexpr(EXPR_END)), "loc_446")
ClearChrFlags(0xD, 0x80)
ClearChrBattleFlags(0xD, 0x8000)
BeginChrThread(0xD, 0, 0, 0)
Jump("loc_64D")
label("loc_446")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 2)), scpexpr(EXPR_END)), "loc_48E")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 7)), scpexpr(EXPR_END)), "loc_489")
SetChrPos(0xA, -2009, 0, 9290, 270)
BeginChrThread(0xA, 0, 0, 0)
ClearChrFlags(0xC, 0x80)
ClearChrBattleFlags(0xC, 0x8000)
ClearChrFlags(0xD, 0x80)
ClearChrBattleFlags(0xD, 0x8000)
BeginChrThread(0xD, 0, 0, 0)
label("loc_489")
Jump("loc_64D")
label("loc_48E")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC1, 6)), scpexpr(EXPR_END)), "loc_4B0")
SetChrFlags(0xB, 0x80)
SetChrFlags(0x8, 0x80)
SetChrFlags(0xA, 0x80)
SetChrFlags(0x9, 0x80)
Jump("loc_64D")
label("loc_4B0")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA7, 6)), scpexpr(EXPR_END)), "loc_4BE")
Jump("loc_64D")
label("loc_4BE")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 0)), scpexpr(EXPR_END)), "loc_4E0")
SetChrFlags(0xB, 0x80)
SetChrFlags(0x8, 0x80)
SetChrFlags(0xA, 0x80)
SetChrFlags(0x9, 0x80)
Jump("loc_64D")
label("loc_4E0")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x83, 7)), scpexpr(EXPR_END)), "loc_4EE")
Jump("loc_64D")
label("loc_4EE")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 0)), scpexpr(EXPR_END)), "loc_553")
SetChrPos(0xA, 4550, 0, 5360, 225)
BeginChrThread(0xA, 0, 0, 0)
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x15, 0x0, 0x10)"), scpexpr(EXPR_END)), "loc_524")
ClearChrFlags(0xE, 0x80)
Jump("loc_54E")
label("loc_524")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x95, 7)), scpexpr(EXPR_END)), "loc_537")
ClearChrFlags(0xE, 0x80)
Jump("loc_54E")
label("loc_537")
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x15, 0x1, 0x1)"), scpexpr(EXPR_END)), "loc_549")
Jump("loc_54E")
label("loc_549")
ClearChrFlags(0xE, 0x80)
label("loc_54E")
Jump("loc_64D")
label("loc_553")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_END)), "loc_561")
Jump("loc_64D")
label("loc_561")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 7)), scpexpr(EXPR_END)), "loc_5AC")
ClearChrFlags(0xE, 0x80)
SetChrFlags(0xE, 0x10)
SetChrPos(0xA, 4550, 0, 5360, 225)
SetChrPos(0x9, 68150, 0, 7780, 225)
SetChrFlags(0xA, 0x10)
BeginChrThread(0xA, 0, 0, 0)
BeginChrThread(0x9, 0, 0, 3)
Jump("loc_64D")
label("loc_5AC")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 0)), scpexpr(EXPR_END)), "loc_5ED")
ClearChrFlags(0xE, 0x80)
SetChrPos(0xA, 4550, 0, 5360, 225)
SetChrPos(0x9, 68150, 0, 7780, 225)
BeginChrThread(0xA, 0, 0, 0)
BeginChrThread(0x9, 0, 0, 3)
Jump("loc_64D")
label("loc_5ED")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x64, 1)), scpexpr(EXPR_END)), "loc_5FB")
Jump("loc_64D")
label("loc_5FB")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x61, 1)), scpexpr(EXPR_END)), "loc_620")
SetChrPos(0x9, 114570, 0, 61510, 270)
BeginChrThread(0x9, 0, 0, 0)
Jump("loc_64D")
label("loc_620")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x60, 0)), scpexpr(EXPR_END)), "loc_62E")
Jump("loc_64D")
label("loc_62E")
ClearChrFlags(0xF, 0x80)
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x2, 0x1, 0x0)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_64D")
SetChrFlags(0xF, 0x10)
OP_93(0xF, 0x0, 0x0)
label("loc_64D")
Return()
# Function_4_3FB end
def Function_5_64E(): pass
label("Function_5_64E")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 7)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_66A")
OP_50(0x1, (scpexpr(EXPR_PUSH_LONG, 0x67), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Jump("loc_6D0")
label("loc_66A")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 6)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_686")
OP_50(0x1, (scpexpr(EXPR_PUSH_LONG, 0x66), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Jump("loc_6D0")
label("loc_686")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA7, 6)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA9, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_6A2")
OP_50(0x1, (scpexpr(EXPR_PUSH_LONG, 0x69), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Jump("loc_6D0")
label("loc_6A2")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 2)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xE0, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_6BE")
OP_50(0x1, (scpexpr(EXPR_PUSH_LONG, 0x67), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Jump("loc_6D0")
label("loc_6BE")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xE0, 1)), scpexpr(EXPR_END)), "loc_6D0")
OP_50(0x1, (scpexpr(EXPR_PUSH_LONG, 0xCB), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
label("loc_6D0")
OP_65(0x3, 0x1)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 7)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC3, 6)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_6F3")
SetMapObjFrame(0xFF, "futon", 0x0, 0x1)
OP_66(0x3, 0x1)
label("loc_6F3")
OP_65(0x2, 0x1)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 0)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 2)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_70F")
OP_66(0x2, 0x1)
ClearMapObjFlags(0x1, 0x10)
label("loc_70F")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 0)), scpexpr(EXPR_END)), "loc_71D")
Jump("loc_76B")
label("loc_71D")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 0)), scpexpr(EXPR_END)), "loc_76B")
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x15, 0x0, 0x10)"), scpexpr(EXPR_END)), "loc_737")
Jump("loc_76B")
label("loc_737")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x95, 7)), scpexpr(EXPR_END)), "loc_745")
Jump("loc_76B")
label("loc_745")
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x15, 0x1, 0x1)"), scpexpr(EXPR_END)), "loc_76B")
OP_1B(0x3, 0x0, 0x13)
OP_1B(0x4, 0x0, 0x14)
OP_1B(0xB, 0x0, 0x15)
OP_1B(0xD, 0x0, 0x16)
OP_1B(0xF, 0x0, 0x17)
label("loc_76B")
Return()
# Function_5_64E end
def Function_6_76C(): pass
label("Function_6_76C")
Call(0, 7)
Return()
# Function_6_76C end
def Function_7_770(): pass
label("Function_7_770")
TalkBegin(0xB)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x4B, 4)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_8E8")
#C0001
ChrTalk(
0xB,
"《ホテル・ミレニアム》へようこそ。\x02",
)
CloseMessageWindow()
#C0002
ChrTalk(
0xB,
(
"うふふ、当ホテルでは\x01",
"様々なサービスをご用意しております。\x02",
)
)
CloseMessageWindow()
#C0003
ChrTalk(
0xB,
(
"歓楽の都クロスベルでの\x01",
"極上の一日を約束致しますわ。\x02",
)
)
CloseMessageWindow()
OP_5A()
FadeToDark(300, 0, 100)
SetMessageWindowPos(-1, -1, -1, -1)
Sound(828, 0, 100, 0)
SetChrName("")
#A0004
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"ホテルや宿酒場に宿泊すると\x01",
"CPを回復する事ができます。\x02",
)
)
CloseMessageWindow()
#A0005
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"通常の宿酒場ではCP100、\x01",
"高級ホテルではCP200が回復します。\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
FadeToBright(300, 0)
SetMessageWindowPos(14, 280, 60, 3)
OP_5A()
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x42, 5)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_8E5")
SetScenarioFlags(0x0, 0)
label("loc_8E5")
SetScenarioFlags(0x4B, 4)
label("loc_8E8")
RunExpression(0x0, (scpexpr(EXPR_PUSH_LONG, 0x63), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
label("loc_8F2")
Jc((scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_PUSH_LONG, 0x63), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_1A00")
FadeToDark(300, 0, 100)
Menu(
0,
-1,
-1,
1,
(
"話をする\x01", # 0
"休憩をする\x01", # 1
"やめる\x01", # 2
)
)
MenuEnd(0x0)
Jc((scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_94E")
OP_60(0x0)
FadeToBright(300, 0)
OP_0D()
label("loc_94E")
Jc((scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_96E")
OP_AF(0x3C)
RunExpression(0x0, (scpexpr(EXPR_PUSH_LONG, 0x63), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Jump("loc_19FB")
label("loc_96E")
Jc((scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_982")
Jump("loc_19FB")
label("loc_982")
Jc((scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_19FB")
RunExpression(0x0, (scpexpr(EXPR_PUSH_LONG, 0x63), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xE0, 0)), scpexpr(EXPR_END)), "loc_A20")
#C0006
ChrTalk(
0xB,
(
"噂で聞きましたが、ガンツ様だけでなく\x01",
"街の人間も何人か失踪しているとか。\x02",
)
)
CloseMessageWindow()
#C0007
ChrTalk(
0xB,
"何かが起こっているのでしょうか……?\x02",
)
CloseMessageWindow()
Jump("loc_19FB")
label("loc_A20")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC3, 6)), scpexpr(EXPR_END)), "loc_B6F")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_AAF")
#C0008
ChrTalk(
0xB,
(
"こういった場合の対応は\x01",
"ホテル側としても難しいところです。\x02",
)
)
CloseMessageWindow()
#C0009
ChrTalk(
0xB,
(
"ガンツ様がお怪我など\x01",
"していなければよいのですけど。\x02",
)
)
CloseMessageWindow()
Jump("loc_B6A")
label("loc_AAF")
#C0010
ChrTalk(
0xB,
(
"今朝早く、ガンツ様は\x01",
"一人で出て行かれてしまいました。\x02",
)
)
CloseMessageWindow()
#C0011
ChrTalk(
0xB,
(
"泥酔してらしたと伺っていたので\x01",
"アーロンさんが\x01",
"声をお掛けしたのですが……\x02",
)
)
CloseMessageWindow()
#C0012
ChrTalk(
0xB,
(
"お怪我などしていなければ\x01",
"よいのですけど。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 0)
label("loc_B6A")
Jump("loc_19FB")
label("loc_B6F")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 2)), scpexpr(EXPR_END)), "loc_E33")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 7)), scpexpr(EXPR_END)), "loc_D71")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_BFB")
#C0013
ChrTalk(
0xB,
(
"ふふ、ガンツさんは\x01",
"よほど酔ってしまわれたのですね。\x02",
)
)
CloseMessageWindow()
#C0014
ChrTalk(
0xB,
(
"あとでお部屋の方に\x01",
"水を持って行かせましょう。\x02",
)
)
CloseMessageWindow()
Jump("loc_D6C")
label("loc_BFB")
#C0015
ChrTalk(
0xB,
(
"あの……ガンツ様は\x01",
"一体どうなされたのでしょう。\x02",
)
)
CloseMessageWindow()
#C0016
ChrTalk(
0xB,
(
"よろしければ、\x01",
"ウルスラ病院に連絡して\x01",
"救急車に来て頂きますけれど……\x02",
)
)
CloseMessageWindow()
#C0017
ChrTalk(
0x101,
(
"#0003F(ガンツさんは心配だけど、\x01",
" 大事にする訳にはいかない……)\x02\x03",
"#0012Fえ、えっと……\x01",
"ちょっと酔っぱらって\x01",
"しまったみたいです。\x02\x03",
"#0000F付き添いの方も一緒ですし\x01",
"多分大丈夫だと思います。\x02",
)
)
CloseMessageWindow()
#C0018
ChrTalk(
0xB,
(
"あら、そうでしたか。\x01",
"安心いたしましたわ。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 0)
label("loc_D6C")
Jump("loc_E2E")
label("loc_D71")
#C0019
ChrTalk(
0xB,
(
"宿泊なさっていたガンツ様……\x01",
"今日も気分よく出かけて行かれましたわ。\x02",
)
)
CloseMessageWindow()
#C0020
ChrTalk(
0xB,
(
"マインツの方から迎えの方が来ると\x01",
"伺っていたのですが……\x02",
)
)
CloseMessageWindow()
#C0021
ChrTalk(
0xB,
(
"お部屋でお待ちにならなくて\x01",
"よかったのでしょうか。\x02",
)
)
CloseMessageWindow()
label("loc_E2E")
Jump("loc_19FB")
label("loc_E33")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 0)), scpexpr(EXPR_END)), "loc_F33")
#C0022
ChrTalk(
0xB,
(
"2ヶ月前に整備が整った\x01",
"導力ネットの予約システムが\x01",
"ようやく軌道に乗りだしましたわ。\x02",
)
)
CloseMessageWindow()
#C0023
ChrTalk(
0xB,
"あとはネットワークの拡大を待つのみ……\x02",
)
CloseMessageWindow()
#C0024
ChrTalk(
0xB,
(
"こちらは時間がかかるでしょうが、\x01",
"先んじてシステムを導入した当ホテルなら\x01",
"適宜対応していけることでしょう。\x02",
)
)
CloseMessageWindow()
Jump("loc_19FB")
label("loc_F33")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA7, 6)), scpexpr(EXPR_END)), "loc_FAD")
#C0025
ChrTalk(
0xB,
"いらっしゃいませ。\x02",
)
CloseMessageWindow()
#C0026
ChrTalk(
0xB,
(
"今年で創業60周年の当ホテル、\x01",
"誠心誠意をもって\x01",
"お客様に尽くさせて頂きますわ。\x02",
)
)
CloseMessageWindow()
Jump("loc_19FB")
label("loc_FAD")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x83, 7)), scpexpr(EXPR_END)), "loc_1276")
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x15, 0x1, 0x1)"), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x95, 7)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_EXEC_OP, "OP_2A(0x15, 0x0, 0x10)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x95, 5)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_10E9")
#C0027
ChrTalk(
0xB,
"お、お客様……!?\x02",
)
CloseMessageWindow()
#C0028
ChrTalk(
0xB,
(
"ペットのお持込みは\x01",
"ご遠慮いただきたいのですが……\x02",
)
)
CloseMessageWindow()
#C0029
ChrTalk(
0x101,
"#0006Fすみません、ウチの警察犬でして。\x02",
)
CloseMessageWindow()
#C0030
ChrTalk(
0x103,
(
"#0203Fちょっとした捜査中です。\x01",
"どうかお気になさらず。\x02",
)
)
CloseMessageWindow()
#C0031
ChrTalk(
0xB,
"そ、そうでしたか。\x02",
)
CloseMessageWindow()
#C0032
ChrTalk(
0xB,
(
"失礼いたしました。\x01",
"どうぞ、ご自由に見ていらしてください。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x95, 5)
TalkEnd(0xB)
Return()
label("loc_10E9")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_117B")
#C0033
ChrTalk(
0xB,
(
"サービスの本質は困っている人に\x01",
"手を差し伸べること……\x02",
)
)
CloseMessageWindow()
#C0034
ChrTalk(
0xB,
(
"当ホテルもリベール王国ホテルの\x01",
"サービス精神を見習いたいものですわ。\x02",
)
)
CloseMessageWindow()
Jump("loc_1271")
label("loc_117B")
#C0035
ChrTalk(
0xB,
(
"以前、リベール王国の方で\x01",
"ボースという街が竜に襲われる\x01",
"大事件があったそうですわ。\x02",
)
)
CloseMessageWindow()
#C0036
ChrTalk(
0xB,
(
"その時は、街のホテルが先陣を切って\x01",
"被災者の宿の確保にあたったとか。\x02",
)
)
CloseMessageWindow()
#C0037
ChrTalk(
0xB,
(
"まさに究極のサービス精神……\x01",
"当ホテル・ミレニアムも\x01",
"かくありたいものですわね。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 0)
label("loc_1271")
Jump("loc_19FB")
label("loc_1276")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 0)), scpexpr(EXPR_END)), "loc_1304")
#C0038
ChrTalk(
0xB,
(
"カジノを目当てに観光にいらっしゃる\x01",
"お客様も多数いらっしゃいますわ。\x02",
)
)
CloseMessageWindow()
#C0039
ChrTalk(
0xB,
(
"まさに歓楽の都クロスベル\x01",
"ならではの客層ですわね。\x02",
)
)
CloseMessageWindow()
Jump("loc_19FB")
label("loc_1304")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_END)), "loc_1384")
#C0040
ChrTalk(
0xB,
(
"本日もご予約のお客様で\x01",
"当ホテルはほぼ満室でございます。\x02",
)
)
CloseMessageWindow()
#C0041
ChrTalk(
0xB,
(
"お部屋をご所望なら\x01",
"お早めにお願いいたしますわ。\x02",
)
)
CloseMessageWindow()
Jump("loc_19FB")
label("loc_1384")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 7)), scpexpr(EXPR_END)), "loc_1440")
#C0042
ChrTalk(
0xB,
(
"導力ネットはクロスベル市内と\x01",
"ミシュラム、後はウルスラ病院にしか\x01",
"通っていないのです。\x02",
)
)
CloseMessageWindow()
#C0043
ChrTalk(
0xB,
(
"当ホテルに引かれた導力ネットも、\x01",
"当面はビジネスでの\x01",
"利用が多くなるでしょうね。\x02",
)
)
CloseMessageWindow()
Jump("loc_19FB")
label("loc_1440")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 0)), scpexpr(EXPR_END)), "loc_14D4")
#C0044
ChrTalk(
0xB,
(
"本日はエプスタイン財団の方に\x01",
"導力ネットを引きにきてもらいました。\x02",
)
)
CloseMessageWindow()
#C0045
ChrTalk(
0xB,
(
"これでホテルのサービスを\x01",
"より充実させる事ができますわね。\x02",
)
)
CloseMessageWindow()
Jump("loc_19FB")
label("loc_14D4")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x64, 1)), scpexpr(EXPR_END)), "loc_1604")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_156D")
#C0046
ChrTalk(
0xB,
(
"近日中に導力ネットワークを通じた\x01",
"ご予約サービスを開始いたしますの。\x02",
)
)
CloseMessageWindow()
#C0047
ChrTalk(
0xB,
(
"サービスの開始まで\x01",
"もうしばらくお待ちくださいませ。\x02",
)
)
CloseMessageWindow()
Jump("loc_15FF")
label("loc_156D")
#C0048
ChrTalk(
0xB,
(
"当ホテルでは、近日中に\x01",
"導力ネットワークを通じての\x01",
"ご予約が可能になる予定ですの。\x02",
)
)
CloseMessageWindow()
#C0049
ChrTalk(
0xB,
(
"サービスの開始まで\x01",
"もうしばらくお待ちくださいませ。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 0)
label("loc_15FF")
Jump("loc_19FB")
label("loc_1604")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x61, 1)), scpexpr(EXPR_END)), "loc_16F6")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_165F")
#C0050
ChrTalk(
0xB,
(
"例のサービスが始まれば\x01",
"水を開けることも\x01",
"出来るのですけれど……\x02",
)
)
CloseMessageWindow()
Jump("loc_16F1")
label("loc_165F")
#C0051
ChrTalk(
0xB,
(
"お陰様で当ホテルは\x01",
"この歓楽街でもトップレベルの\x01",
"売り上げを誇っておりますわ。\x02",
)
)
CloseMessageWindow()
#C0052
ChrTalk(
0xB,
(
"しかしライバルも多いのです。\x01",
"決して気が抜けませんわね。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 0)
label("loc_16F1")
Jump("loc_19FB")
label("loc_16F6")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x60, 0)), scpexpr(EXPR_END)), "loc_1866")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_1790")
#C0053
ChrTalk(
0xB,
(
"クロスベルは再来月に\x01",
"創立記念祭と劇団アルカンシェルの\x01",
"新作公演を控えております。\x02",
)
)
CloseMessageWindow()
#C0054
ChrTalk(
0xB,
(
"きっとこの時期は\x01",
"大変混雑いたしますわ。\x02",
)
)
CloseMessageWindow()
Jump("loc_1861")
label("loc_1790")
#C0055
ChrTalk(
0xB,
(
"クロスベルは再来月に\x01",
"大きなイベントを控えてございます。\x02",
)
)
CloseMessageWindow()
#C0056
ChrTalk(
0xB,
(
"自治州の創立記念祭……\x01",
"そして劇団アルカンシェルの\x01",
"新作公演もありますわね。\x02",
)
)
CloseMessageWindow()
#C0057
ChrTalk(
0xB,
(
"大変混雑が予想されますので\x01",
"ご予約は早めにお願い致しますわ。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 0)
label("loc_1861")
Jump("loc_19FB")
label("loc_1866")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x42, 5)), scpexpr(EXPR_END)), "loc_18D6")
#C0058
ChrTalk(
0xB,
(
"当ホテルでは\x01",
"コンシェルジェサービスも\x01",
"行っております。\x02",
)
)
CloseMessageWindow()
#C0059
ChrTalk(
0xB,
"ご活用いただけると嬉しいですわ。\x02",
)
CloseMessageWindow()
Jump("loc_19FB")
label("loc_18D6")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_1958")
#C0060
ChrTalk(
0xB,
(
"ガイド、エステ、サロン、\x01",
"各種ブッキングサービス……\x02",
)
)
CloseMessageWindow()
#C0061
ChrTalk(
0xB,
(
"歓楽の都クロスベルでの\x01",
"極上の一日をお約束致しますわ。\x02",
)
)
CloseMessageWindow()
Jump("loc_19FB")
label("loc_1958")
#C0062
ChrTalk(
0xB,
"《ホテル・ミレニアム》へようこそ。\x02",
)
CloseMessageWindow()
#C0063
ChrTalk(
0xB,
(
"うふふ、当ホテルでは\x01",
"様々なサービスをご用意しております。\x02",
)
)
CloseMessageWindow()
#C0064
ChrTalk(
0xB,
(
"歓楽の都クロスベルでの\x01",
"極上の一日を約束致しますわ。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 0)
label("loc_19FB")
Jump("loc_8F2")
label("loc_1A00")
TalkEnd(0xB)
Return()
# Function_7_770 end
def Function_8_1A04(): pass
label("Function_8_1A04")
Call(0, 9)
Return()
# Function_8_1A04 end
def Function_9_1A08(): pass
label("Function_9_1A08")
TalkBegin(0x8)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x4B, 4)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_1B50")
#C0065
ChrTalk(
0x8,
(
"いらっしゃいませ。\x01",
"《ホテル・ミレニアム》へようこそ。\x02",
)
)
CloseMessageWindow()
#C0066
ChrTalk(
0x8,
(
"お部屋のご予約なら\x01",
"当フロントをご利用ください。\x02",
)
)
CloseMessageWindow()
OP_5A()
FadeToDark(300, 0, 100)
SetMessageWindowPos(-1, -1, -1, -1)
Sound(828, 0, 100, 0)
SetChrName("")
#A0067
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"ホテルや宿酒場に宿泊すると\x01",
"CPを回復する事ができます。\x02",
)
)
CloseMessageWindow()
#A0068
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"通常の宿酒場ではCP100、\x01",
"高級ホテルではCP200が回復します。\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
FadeToBright(300, 0)
SetMessageWindowPos(14, 280, 60, 3)
OP_5A()
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x42, 5)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_1B4D")
SetScenarioFlags(0x0, 1)
label("loc_1B4D")
SetScenarioFlags(0x4B, 4)
label("loc_1B50")
RunExpression(0x0, (scpexpr(EXPR_PUSH_LONG, 0x63), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
label("loc_1B5A")
Jc((scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_PUSH_LONG, 0x63), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_2734")
FadeToDark(300, 0, 100)
Menu(
0,
-1,
-1,
1,
(
"話をする\x01", # 0
"休憩をする\x01", # 1
"やめる\x01", # 2
)
)
MenuEnd(0x0)
Jc((scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_1BB6")
OP_60(0x0)
FadeToBright(300, 0)
OP_0D()
label("loc_1BB6")
Jc((scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_1BD6")
OP_AF(0x3C)
RunExpression(0x0, (scpexpr(EXPR_PUSH_LONG, 0x63), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Jump("loc_272F")
label("loc_1BD6")
Jc((scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_1BEA")
Jump("loc_272F")
label("loc_1BEA")
Jc((scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_272F")
RunExpression(0x0, (scpexpr(EXPR_PUSH_LONG, 0x63), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xE0, 0)), scpexpr(EXPR_END)), "loc_1C82")
#C0069
ChrTalk(
0x8,
"このような夕暮れ時までお疲れ様です。\x02",
)
CloseMessageWindow()
#C0070
ChrTalk(
0x8,
(
"お部屋をご利用でしょうか?\x01",
"チェックインは常時受け付けていますよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_1C82")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC3, 6)), scpexpr(EXPR_END)), "loc_1D30")
#C0071
ChrTalk(
0x8,
(
"ビジネスマンの方などが\x01",
"先程チェックアウトを\x01",
"済まされたところです。\x02",
)
)
CloseMessageWindow()
#C0072
ChrTalk(
0x8,
(
"チェックインは午後からですが……\x01",
"休憩とあらばお部屋をご用意させて\x01",
"いただきますよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_1D30")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 2)), scpexpr(EXPR_END)), "loc_1DDF")
#C0073
ChrTalk(
0x8,
(
"ガンツ様はデラックスルームに\x01",
"長期滞在契約で宿泊されてます。\x02",
)
)
CloseMessageWindow()
#C0074
ChrTalk(
0x8,
(
"なかなかわがままの多い方ですが……\x01",
"プロとして誠意をもって\x01",
"対応させていただいておりますよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_1DDF")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 0)), scpexpr(EXPR_END)), "loc_1E98")
#C0075
ChrTalk(
0x8,
(
"当店はカジノ帰りのお客様も\x01",
"多数いらっしゃいます。\x02",
)
)
CloseMessageWindow()
#C0076
ChrTalk(
0x8,
(
"ホステスをはべらせて\x01",
"帰ってくるお客様もいまして……\x01",
"いやはや、うらやま……\x02",
)
)
CloseMessageWindow()
#C0077
ChrTalk(
0x8,
"……コホン、なんでもないです。\x02",
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_1E98")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA7, 6)), scpexpr(EXPR_END)), "loc_1F56")
#C0078
ChrTalk(
0x8,
(
"記念祭の期間中は\x01",
"大変忙しかったですが、\x01",
"やりがいはありました。\x02",
)
)
CloseMessageWindow()
#C0079
ChrTalk(
0x8,
(
"やはりクロスベルの活気は\x01",
"他の国とは一味違いますね。\x02",
)
)
CloseMessageWindow()
#C0080
ChrTalk(
0x8,
(
"こちらのホテルに勤めて\x01",
"良かったと思いますよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_1F56")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x83, 7)), scpexpr(EXPR_END)), "loc_200F")
#C0081
ChrTalk(
0x8,
(
"当ホテルは、隅々まで手が行き届く\x01",
"献身的なサービスを信条としております。\x02",
)
)
CloseMessageWindow()
#C0082
ChrTalk(
0x8,
(
"レティシア支配人が\x01",
"百貨店タイムズの支配人から学んだ、\x01",
"客商売で最も大切なことなのですよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_200F")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 0)), scpexpr(EXPR_END)), "loc_2091")
#C0083
ChrTalk(
0x8,
(
"当ホテルのお部屋には\x01",
"内線用の通信器が備え付けてあります。\x02",
)
)
CloseMessageWindow()
#C0084
ChrTalk(
0x8,
(
"御用がありましたら\x01",
"フロントまでご連絡ください。\x02",
)
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_2091")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_END)), "loc_20FA")
#C0085
ChrTalk(
0x8,
(
"そろそろ団体客の皆さんが\x01",
"戻ってくる頃ですね。\x02",
)
)
CloseMessageWindow()
#C0086
ChrTalk(
0x8,
"受け入れの準備をしておかなければ。\x02",
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_20FA")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 7)), scpexpr(EXPR_END)), "loc_2193")
#C0087
ChrTalk(
0x8,
(
"当ホテルは3台の\x01",
"導力車を所有しております。\x02",
)
)
CloseMessageWindow()
#C0088
ChrTalk(
0x8,
(
"駅や空港までの\x01",
"送迎サービスも行っておりますので\x01",
"ご利用の際は声をお掛けくださいませ。\x02",
)
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_2193")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 0)), scpexpr(EXPR_END)), "loc_2247")
#C0089
ChrTalk(
0x8,
(
"導力ネットワークは\x01",
"クロスベルにとってまだまだ\x01",
"未知数の代物だといえます。\x02",
)
)
CloseMessageWindow()
#C0090
ChrTalk(
0x8,
(
"それをいち早く取り入れる事は\x01",
"必ず将来の為になる……\x01",
"支配人の策はそこにあるのです。\x02",
)
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_2247")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x64, 1)), scpexpr(EXPR_END)), "loc_23A1")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_22DB")
#C0091
ChrTalk(
0x8,
(
"導力ネットワークを\x01",
"使用した予約サービスは\x01",
"支配人の肝いりなのです。\x02",
)
)
CloseMessageWindow()
#C0092
ChrTalk(
0x8,
(
"サービス開始の暁には\x01",
"どうぞご利用くださいませ。\x02",
)
)
CloseMessageWindow()
Jump("loc_239C")
label("loc_22DB")
#C0093
ChrTalk(
0x8,
(
"導力ネットワークを\x01",
"使用した予約サービスは\x01",
"支配人の肝いりなのです。\x02",
)
)
CloseMessageWindow()
#C0094
ChrTalk(
0x8,
(
"市内のどこからでも利用できる\x01",
"非常に便利なサービスですからね。\x02",
)
)
CloseMessageWindow()
#C0095
ChrTalk(
0x8,
(
"運用が始まった暁には\x01",
"ぜひご利用くださいませ。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 1)
label("loc_239C")
Jump("loc_272F")
label("loc_23A1")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x61, 1)), scpexpr(EXPR_END)), "loc_24BE")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_2428")
#C0096
ChrTalk(
0x8,
(
"クロスベル市には観光業を\x01",
"優遇する法律があるのです。\x02",
)
)
CloseMessageWindow()
#C0097
ChrTalk(
0x8,
(
"観光に携わる者として\x01",
"大変光栄なことでございます。\x02",
)
)
CloseMessageWindow()
Jump("loc_24B9")
label("loc_2428")
#C0098
ChrTalk(
0x8,
(
"クロスベル市には\x01",
"観光業振興のための\x01",
"様々な優遇策があるのですよ。\x02",
)
)
CloseMessageWindow()
#C0099
ChrTalk(
0x8,
(
"観光業は商業と並ぶ\x01",
"市の主要産業……\x01",
"大変光栄なことでございますね。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 1)
label("loc_24B9")
Jump("loc_272F")
label("loc_24BE")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x60, 0)), scpexpr(EXPR_END)), "loc_2563")
#C0100
ChrTalk(
0x8,
(
"お早うございます。\x01",
"本日もご利用ありがとうございます。\x02",
)
)
CloseMessageWindow()
#C0101
ChrTalk(
0x8,
(
"丁度チェックアウトのお客様も\x01",
"お出掛けになられた所です。\x01",
"お部屋にも空きがございますよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_2563")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x42, 5)), scpexpr(EXPR_END)), "loc_2657")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_25BB")
#C0102
ChrTalk(
0x8,
(
"やりがいのある職場を与えて頂き\x01",
"支配人には感謝しております。\x02",
)
)
CloseMessageWindow()
Jump("loc_2652")
label("loc_25BB")
#C0103
ChrTalk(
0x8,
(
"私は帝国のホテルにおりましたが、\x01",
"現支配人に声を掛けて頂いたのです。\x02",
)
)
CloseMessageWindow()
#C0104
ChrTalk(
0x8,
(
"ふふ、当ホテルはお客様の数も多く\x01",
"やりがいのある職場と思っております。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 1)
label("loc_2652")
Jump("loc_272F")
label("loc_2657")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_26BC")
#C0105
ChrTalk(
0x8,
"現在、空き部屋もございます。\x02",
)
CloseMessageWindow()
#C0106
ChrTalk(
0x8,
(
"お部屋のご予約なら\x01",
"当フロントをご利用ください。\x02",
)
)
CloseMessageWindow()
Jump("loc_272F")
label("loc_26BC")
#C0107
ChrTalk(
0x8,
(
"いらっしゃいませ。\x01",
"《ホテル・ミレニアム》へようこそ。\x02",
)
)
CloseMessageWindow()
#C0108
ChrTalk(
0x8,
(
"お部屋のご予約なら\x01",
"当フロントをご利用ください。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 1)
label("loc_272F")
Jump("loc_1B5A")
label("loc_2734")
TalkEnd(0x8)
Return()
# Function_9_1A08 end
def Function_10_2738(): pass
label("Function_10_2738")
TalkBegin(0xFE)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xE0, 0)), scpexpr(EXPR_END)), "loc_27DA")
#C0109
ChrTalk(
0xA,
(
"ビクセン様がガンツ様を\x01",
"随分心配して待っているようです。\x02",
)
)
CloseMessageWindow()
#C0110
ChrTalk(
0xA,
(
"ふむ……あのままでは体を壊します。\x01",
"ルームサービスの案内でも\x01",
"してきましょうか。\x02",
)
)
CloseMessageWindow()
Jump("loc_31B1")
label("loc_27DA")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC3, 6)), scpexpr(EXPR_END)), "loc_287C")
#C0111
ChrTalk(
0xA,
(
"ううむ……\x01",
"ガンツ様はどうも\x01",
"様子がおかしかったようです。\x02",
)
)
CloseMessageWindow()
#C0112
ChrTalk(
0xA,
(
"心、ここに在らずといいますか……\x01",
"どうも二日酔いのそれには\x01",
"見えなかったのですが。\x02",
)
)
CloseMessageWindow()
Jump("loc_31B1")
label("loc_287C")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 2)), scpexpr(EXPR_END)), "loc_297D")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 7)), scpexpr(EXPR_END)), "loc_28F9")
#C0113
ChrTalk(
0xA,
(
"ようやく導力ネットワークでの\x01",
"予約件数を纏められました。\x02",
)
)
CloseMessageWindow()
#C0114
ChrTalk(
0xA,
(
"……はて。\x01",
"なにかあったのですかな?\x02",
)
)
CloseMessageWindow()
Jump("loc_2978")
label("loc_28F9")
#C0115
ChrTalk(
0xA,
(
"さて、今日の導力ネットの予約を\x01",
"チェックしなくては。\x02",
)
)
CloseMessageWindow()
#C0116
ChrTalk(
0xA,
(
"あの複雑な機械も、\x01",
"一度操作を覚えると\x01",
"なかなか楽しいものですな。\x02",
)
)
CloseMessageWindow()
label("loc_2978")
Jump("loc_31B1")
label("loc_297D")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 0)), scpexpr(EXPR_END)), "loc_2A56")
#C0117
ChrTalk(
0xFE,
(
"近頃、デラックスルームを\x01",
"借り切ってらっしゃる\x01",
"お客様がいるのですよ。\x02",
)
)
CloseMessageWindow()
#C0118
ChrTalk(
0xFE,
(
"非常に気前のよい方で、\x01",
"私どもも最高のおもてなしを\x01",
"させて頂いております。\x02",
)
)
CloseMessageWindow()
#C0119
ChrTalk(
0xFE,
(
"ふふ、どうか皆様も\x01",
"廊下はお静かに願いますよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_31B1")
label("loc_2A56")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA7, 6)), scpexpr(EXPR_END)), "loc_2ADD")
#C0120
ChrTalk(
0xA,
(
"近頃、歓楽街をうろつく\x01",
"ルバーチェ商会の者たちを\x01",
"見かけませんな。\x02",
)
)
CloseMessageWindow()
#C0121
ChrTalk(
0xA,
(
"ふむ……記念祭の間に\x01",
"何かあったのでしょうか。\x02",
)
)
CloseMessageWindow()
Jump("loc_31B1")
label("loc_2ADD")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x83, 7)), scpexpr(EXPR_END)), "loc_2BAB")
#C0122
ChrTalk(
0xA,
(
"劇団アルカンシェルは、\x01",
"私が使用人頭になった年に\x01",
"創設されたのです。\x02",
)
)
CloseMessageWindow()
#C0123
ChrTalk(
0xA,
"かれこれ20年になるでしょうか。\x02",
)
CloseMessageWindow()
#C0124
ChrTalk(
0xA,
(
"ふふ、アルカンシェルの\x01",
"今日びの人気にはどうしても\x01",
"嬉しくなってしまいますな。\x02",
)
)
CloseMessageWindow()
Jump("loc_31B1")
label("loc_2BAB")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 0)), scpexpr(EXPR_END)), "loc_2C3C")
#C0125
ChrTalk(
0xA,
(
"いやはや、難しい操作は\x01",
"専門の方にほとんど\x01",
"やっていただきましたよ。\x02",
)
)
CloseMessageWindow()
#C0126
ChrTalk(
0xA,
(
"しかしまぁ、機械の保全くらいは\x01",
"私でも出来そうですな。\x02",
)
)
CloseMessageWindow()
Jump("loc_31B1")
label("loc_2C3C")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_END)), "loc_2CB6")
#C0127
ChrTalk(
0xA,
(
"さてと、そろそろ厨房の\x01",
"確認してまいりますか。\x02",
)
)
CloseMessageWindow()
#C0128
ChrTalk(
0xA,
(
"本日は団体客の方が多く、\x01",
"給仕に手間取りそうですよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_31B1")
label("loc_2CB6")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 7)), scpexpr(EXPR_END)), "loc_2CD6")
#C0129
ChrTalk(
0xA,
"ふむふむ……\x02",
)
CloseMessageWindow()
Jump("loc_31B1")
label("loc_2CD6")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 0)), scpexpr(EXPR_END)), "loc_2DCE")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 2)), scpexpr(EXPR_END)), "loc_2D41")
#C0130
ChrTalk(
0xA,
(
"わたくしも歳ですかな。\x01",
"オンライン予約システムというものは\x01",
"よくわかりませんよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_2DC9")
label("loc_2D41")
#C0131
ChrTalk(
0xA,
(
"支配人が進めておられる\x01",
"オンライン予約システム、でしたか……\x02",
)
)
CloseMessageWindow()
#C0132
ChrTalk(
0xA,
(
"大変結構なのですが、\x01",
"わたくしには詳しい事は\x01",
"とんと判りません。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 2)
label("loc_2DC9")
Jump("loc_31B1")
label("loc_2DCE")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x64, 1)), scpexpr(EXPR_END)), "loc_2E8B")
#C0133
ChrTalk(
0xA,
(
"この最上階のお部屋はすべて\x01",
"デラックスルームとなっております。\x02",
)
)
CloseMessageWindow()
#C0134
ChrTalk(
0xA,
(
"少々宿泊代金は張ってしまうのですが、\x01",
"通常の部屋とは比べ物にならない\x01",
"極上のサービスを提供いたしますよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_31B1")
label("loc_2E8B")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x61, 1)), scpexpr(EXPR_END)), "loc_2F3D")
#C0135
ChrTalk(
0xA,
(
"現在のスタッフは、一昨年に\x01",
"レティシア様が支配人になられてから\x01",
"集められた者たちなのです。\x02",
)
)
CloseMessageWindow()
#C0136
ChrTalk(
0xA,
(
"ふふ……\x01",
"個性的なスタッフもいますが\x01",
"非常に優秀な者ばかりですよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_31B1")
label("loc_2F3D")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x60, 0)), scpexpr(EXPR_END)), "loc_30C5")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 2)), scpexpr(EXPR_END)), "loc_2FD4")
#C0137
ChrTalk(
0xA,
(
"不戦条約が締結された一昨年以降、\x01",
"お客様が随分と増えました。\x02",
)
)
CloseMessageWindow()
#C0138
ChrTalk(
0xA,
(
"やはり周辺諸国の動向には\x01",
"気を配っておかねばなりませんな。\x02",
)
)
CloseMessageWindow()
Jump("loc_30C0")
label("loc_2FD4")
#C0139
ChrTalk(
0xA,
(
"当ホテルのお客様は\x01",
"大半が外国からの観光の方……\x01",
"周辺諸国の動向には気を配りますよ。\x02",
)
)
CloseMessageWindow()
#C0140
ChrTalk(
0xA,
(
"例えば……昨年は\x01",
"エレボニア・カルバード・リベール間で\x01",
"不戦条約が締結されました。\x02",
)
)
CloseMessageWindow()
#C0141
ChrTalk(
0xA,
(
"人の行き来が激しくなり\x01",
"お客様がどっと増えたのですよ。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 2)
label("loc_30C0")
Jump("loc_31B1")
label("loc_30C5")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x42, 5)), scpexpr(EXPR_END)), "loc_313F")
#C0142
ChrTalk(
0xA,
(
"そろそろ観光客の方々が\x01",
"チェックインを始められる頃……\x02",
)
)
CloseMessageWindow()
#C0143
ChrTalk(
0xA,
(
"万全の体制で\x01",
"お迎えしなければいけませんな。\x02",
)
)
CloseMessageWindow()
Jump("loc_31B1")
label("loc_313F")
#C0144
ChrTalk(
0xA,
(
"当ホテルは本年で\x01",
"開業60周年となります。\x02",
)
)
CloseMessageWindow()
#C0145
ChrTalk(
0xA,
(
"近年はツアー企画なども運営し\x01",
"ますますご好評頂いておりますよ。\x02",
)
)
CloseMessageWindow()
label("loc_31B1")
TalkEnd(0xFE)
Return()
# Function_10_2738 end
def Function_11_31B5(): pass
label("Function_11_31B5")
TalkBegin(0xFE)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xE0, 0)), scpexpr(EXPR_END)), "loc_3273")
#C0146
ChrTalk(
0x9,
(
"ガンツ様、カジノのほうにも\x01",
"行ってないみたいなんです。\x02",
)
)
CloseMessageWindow()
#C0147
ChrTalk(
0x9,
(
"もう夕方……ですね。\x01",
"さすがに警察に届けた方が……\x02",
)
)
CloseMessageWindow()
#C0148
ChrTalk(
0x9,
(
"……えっ、皆様が警察なんですか?\x01",
"し、失礼しました……\x02",
)
)
CloseMessageWindow()
Jump("loc_3C68")
label("loc_3273")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC3, 6)), scpexpr(EXPR_END)), "loc_335E")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_END)), "loc_32BB")
#C0149
ChrTalk(
0x9,
(
"はぁ……自分の配慮のなさが\x01",
"いやになります。\x02",
)
)
CloseMessageWindow()
Jump("loc_3359")
label("loc_32BB")
#C0150
ChrTalk(
0x9,
(
"昨日はガンツ様、\x01",
"とても静かでした……\x02",
)
)
CloseMessageWindow()
#C0151
ChrTalk(
0x9,
(
"ううん、悪いものでも\x01",
"食べてしまったのでしょうか。\x02",
)
)
CloseMessageWindow()
#C0152
ChrTalk(
0x9,
(
"……ふ、不謹慎でしたかね。\x01",
"失踪してしまったのに……\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 3)
label("loc_3359")
Jump("loc_3C68")
label("loc_335E")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 2)), scpexpr(EXPR_END)), "loc_34CF")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_END)), "loc_33FE")
#C0153
ChrTalk(
0x9,
(
"ガンツ様から頂いたチップ……\x01",
"額が大きいものですから\x01",
"市庁舎のほうに寄付してきました。\x02",
)
)
CloseMessageWindow()
#C0154
ChrTalk(
0x9,
(
"……ちょ、ちょっと\x01",
"勿体無かったかしら……\x02",
)
)
CloseMessageWindow()
Jump("loc_34CA")
label("loc_33FE")
#C0155
ChrTalk(
0x9,
(
"ガンツ様から額の大きい\x01",
"チップを頂いてしまって……\x02",
)
)
CloseMessageWindow()
#C0156
ChrTalk(
0x9,
(
"手元においておくのが怖いので、\x01",
"市庁舎のほうに寄付してきました。\x02",
)
)
CloseMessageWindow()
#C0157
ChrTalk(
0x9,
(
"……何に使われるか分かりませんけど、\x01",
"私の手元にあるよりはいいですよね。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 3)
label("loc_34CA")
Jump("loc_3C68")
label("loc_34CF")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 0)), scpexpr(EXPR_END)), "loc_3580")
#C0158
ChrTalk(
0x9,
(
"最上階に宿泊しているお客様……\x01",
"少し騒がしくて苦情が来てるんです。\x02",
)
)
CloseMessageWindow()
#C0159
ChrTalk(
0x9,
(
"でも、ホテル側としては\x01",
"どちらも大事なお客様ですから\x01",
"一方的には言及できないんですよね。\x02",
)
)
CloseMessageWindow()
Jump("loc_3C68")
label("loc_3580")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA7, 6)), scpexpr(EXPR_END)), "loc_35C9")
#C0160
ChrTalk(
0x9,
(
"おはようございます。\x01",
"……ご家族さまで宿泊でしょうか?\x02",
)
)
CloseMessageWindow()
Jump("loc_3C68")
label("loc_35C9")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x83, 7)), scpexpr(EXPR_END)), "loc_3767")
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x15, 0x1, 0x1)"), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x95, 7)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_EXEC_OP, "OP_2A(0x15, 0x0, 0x10)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_36F4")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_END)), "loc_363E")
TurnDirection(0x9, 0x11C, 0)
#C0161
ChrTalk(
0x9,
(
"こ、こっちへ来ないで下さい!\x01",
"わたし犬は苦手なんです……\x02",
)
)
CloseMessageWindow()
Jump("loc_36F0")
label("loc_363E")
TurnDirection(0x9, 0x11C, 0)
OP_63(0x9, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
Sound(28, 0, 100, 0)
Sleep(1000)
#C0162
ChrTalk(
0x9,
"い、犬……!?\x02",
)
CloseMessageWindow()
#C0163
ChrTalk(
0x9,
(
"こ、こっちへ来ないで下さい!\x01",
"わたし犬は苦手なんです……\x02",
)
)
CloseMessageWindow()
#C0164
ChrTalk(
0x101,
"#0012Fはは、それはすみません。\x02",
)
CloseMessageWindow()
#C0165
ChrTalk(
0x11C,
"#1203Fグルルル……\x02",
)
CloseMessageWindow()
SetScenarioFlags(0x0, 3)
label("loc_36F0")
TalkEnd(0x9)
Return()
label("loc_36F4")
#C0166
ChrTalk(
0x9,
(
"外出の際は、\x01",
"フロントに鍵をお預けください。\x02",
)
)
CloseMessageWindow()
#C0167
ChrTalk(
0x9,
(
"お出かけの間にきちんと\x01",
"ベッドメイクさせていただきます。\x02",
)
)
CloseMessageWindow()
Jump("loc_3C68")
label("loc_3767")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 0)), scpexpr(EXPR_END)), "loc_37DF")
#C0168
ChrTalk(
0x9,
(
"お部屋にあるお飲み物などは\x01",
"宿泊料金のうちに入っております。\x02",
)
)
CloseMessageWindow()
#C0169
ChrTalk(
0x9,
(
"どうぞご自由に\x01",
"お取り下さいませね。\x02",
)
)
CloseMessageWindow()
Jump("loc_3C68")
label("loc_37DF")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x81, 5)), scpexpr(EXPR_END)), "loc_385E")
#C0170
ChrTalk(
0x9,
(
"部屋と廊下の掃除も\x01",
"一通り終わりました。\x02",
)
)
CloseMessageWindow()
#C0171
ChrTalk(
0x9,
(
"デラックスルームは\x01",
"整備するところが多くて\x01",
"やっぱり大変ですね。\x02",
)
)
CloseMessageWindow()
Jump("loc_3C68")
label("loc_385E")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 7)), scpexpr(EXPR_END)), "loc_397D")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_END)), "loc_38C2")
#C0172
ChrTalk(
0x9,
(
"あとでアーロンさんに叱られないように、\x01",
"念入りに掃除をしておかなくちゃ。\x02",
)
)
CloseMessageWindow()
Jump("loc_3978")
label("loc_38C2")
#C0173
ChrTalk(
0x9,
"お掃除はこんなところかしら……\x02",
)
CloseMessageWindow()
#C0174
ChrTalk(
0x9,
(
"あとでアーロンさんに叱られないように、\x01",
"念入りにやっておかなくちゃ。\x02",
)
)
CloseMessageWindow()
#C0175
ChrTalk(
0x9,
(
"アーロンさんは\x01",
"怒っているときもあの調子なので\x01",
"逆に怖いんですよ。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 3)
label("loc_3978")
Jump("loc_3C68")
label("loc_397D")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 0)), scpexpr(EXPR_END)), "loc_39BE")
#C0176
ChrTalk(
0x9,
(
"最上階は廊下も部屋も広くて\x01",
"お掃除が大変です。\x02",
)
)
CloseMessageWindow()
Jump("loc_3C68")
label("loc_39BE")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x64, 1)), scpexpr(EXPR_END)), "loc_3A9D")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_END)), "loc_3A1B")
#C0177
ChrTalk(
0x9,
(
"アルカンシェルの公演を\x01",
"観にいらっしゃるお客様が\x01",
"増えそうですね。\x02",
)
)
CloseMessageWindow()
Jump("loc_3A98")
label("loc_3A1B")
#C0178
ChrTalk(
0x9,
(
"アルカンシェルの新作公演、\x01",
"ついに発表されるそうですね。\x02",
)
)
CloseMessageWindow()
#C0179
ChrTalk(
0x9,
(
"またお客様が増えそうです。\x01",
"気を引き締めておかなくちゃ。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 3)
label("loc_3A98")
Jump("loc_3C68")
label("loc_3A9D")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x61, 1)), scpexpr(EXPR_END)), "loc_3B0F")
#C0180
ChrTalk(
0x9,
(
"そろそろ観光ツアーのお客様が\x01",
"お戻りになられるんです。\x02",
)
)
CloseMessageWindow()
#C0181
ChrTalk(
0x9,
(
"お出迎えの準備を\x01",
"しておかなくちゃ。\x02",
)
)
CloseMessageWindow()
Jump("loc_3C68")
label("loc_3B0F")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x60, 0)), scpexpr(EXPR_END)), "loc_3B98")
#C0182
ChrTalk(
0x9,
(
"お早うございます。\x01",
"《ホテル・ミレニアム》へようこそ。\x02",
)
)
CloseMessageWindow()
#C0183
ChrTalk(
0x9,
(
"お出かけの際は\x01",
"お忘れ物などないよう\x01",
"お気をつけ下さいませ。\x02",
)
)
CloseMessageWindow()
Jump("loc_3C68")
label("loc_3B98")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x42, 5)), scpexpr(EXPR_END)), "loc_3C06")
#C0184
ChrTalk(
0x9,
(
"今年は例年になく\x01",
"お客様が多いようですね。\x02",
)
)
CloseMessageWindow()
#C0185
ChrTalk(
0x9,
(
"お部屋もすぐに\x01",
"満室になってしまうんですよ。\x02",
)
)
CloseMessageWindow()
Jump("loc_3C68")
label("loc_3C06")
#C0186
ChrTalk(
0x9,
(
"おはようございます。\x01",
"宿泊客の方でしょうか?\x02",
)
)
CloseMessageWindow()
#C0187
ChrTalk(
0x9,
(
"よろしければお荷物を\x01",
"部屋までお運びします。\x02",
)
)
CloseMessageWindow()
label("loc_3C68")
TalkEnd(0xFE)
Return()
# Function_11_31B5 end
def Function_12_3C6C(): pass
label("Function_12_3C6C")
TalkBegin(0xFE)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x92, 6)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_3F37")
TurnDirection(0xFE, 0x0, 0)
#C0188
ChrTalk(
0x101,
(
"#0005Fあ、あなたは確か\x01",
"ティオの上司の……\x02",
)
)
CloseMessageWindow()
#C0189
ChrTalk(
0x102,
(
"#0100Fエプスタイン財団の方が\x01",
"どうしてホテルに……?\x02",
)
)
CloseMessageWindow()
#C0190
ChrTalk(
0xFE,
(
"ああ、このホテルに\x01",
"導力ネットを引くことになったから\x01",
"監督に来ているんだよ。\x02",
)
)
CloseMessageWindow()
#C0191
ChrTalk(
0xFE,
(
"企業やホテルなんかは、\x01",
"申請を出せば導力ネットの試験運用に\x01",
"参加が出来るんだよ。\x02",
)
)
CloseMessageWindow()
#C0192
ChrTalk(
0x104,
(
"#0300Fなるほど、それで……\x02\x03",
"#0301F……でも導力ネットってのは\x01",
"随分と簡単に引ける物なんスね?\x02",
)
)
CloseMessageWindow()
#C0193
ChrTalk(
0x103,
(
"#0203Fまあ業種や用途などの\x01",
"一定の審査はありますが……\x02\x03",
"#0200F端末装置の費用も\x01",
"IBCが全額負担してくれますし、\x01",
"試験環境としては恵まれているかと。\x02",
)
)
CloseMessageWindow()
#C0194
ChrTalk(
0xFE,
(
"そうなんだよねぇ。\x01",
"お陰でやりたかったテストが沢山できて\x01",
"本当にIBC様様だよ。\x02",
)
)
CloseMessageWindow()
#C0195
ChrTalk(
0xFE,
(
"ははは、まあ\x01",
"まだ端末を使える人が少ないから\x01",
"指導するのも大変なんだけどね。\x02",
)
)
CloseMessageWindow()
TurnDirection(0xFE, 0xA, 0)
SetScenarioFlags(0x92, 6)
Jump("loc_45A6")
label("loc_3F37")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x82, 0)), scpexpr(EXPR_END)), "loc_4230")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x93, 6)), scpexpr(EXPR_END)), "loc_3FAD")
#C0196
ChrTalk(
0xFE,
"さて、ここの端末の設定も完了したよ。\x02",
)
CloseMessageWindow()
#C0197
ChrTalk(
0xFE,
(
"まあ僕は専門家だから\x01",
"お茶の子さいさいだけどね。\x02",
)
)
CloseMessageWindow()
Jump("loc_422B")
label("loc_3FAD")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 4)), scpexpr(EXPR_END)), "loc_403D")
#C0198
ChrTalk(
0xFE,
(
"あどけないティオ君に\x01",
"邪念なんてある訳がないな。\x02",
)
)
CloseMessageWindow()
#C0199
ChrTalk(
0xFE,
(
"うんうん、やっぱり僕の気のせいだ。\x01",
"支援課のみんな、ティオ君を頼んだよ!\x02",
)
)
CloseMessageWindow()
Jump("loc_422B")
label("loc_403D")
#C0200
ChrTalk(
0xFE,
"さて、ここの端末の設定も完了したよ。\x02",
)
CloseMessageWindow()
#C0201
ChrTalk(
0xFE,
(
"まあ僕は専門家だから\x01",
"お茶の子さいさいだけどね。\x02",
)
)
CloseMessageWindow()
#C0202
ChrTalk(
0x103,
(
"#0203Fこんな人間ですが、主任は\x01",
"『導力ネットワーク構想』の\x01",
"開発主任の一人なんですよね。\x02\x03",
"#0200Fクロスベルの導力ネットは\x01",
"一応、主任の功績だとか。\x02",
)
)
CloseMessageWindow()
TurnDirection(0xFE, 0x103, 500)
#C0203
ChrTalk(
0xFE,
(
"そ、そうだけど……\x01",
"あのティオ君、何かトゲがない?\x02",
)
)
CloseMessageWindow()
#C0204
ChrTalk(
0x103,
(
"#0211F……そうですか?\x01",
"いつも通りですが。\x02",
)
)
CloseMessageWindow()
#C0205
ChrTalk(
0xFE,
(
"そ…………そうだよね!\x01",
"ハハ、やっぱり僕の気のせいかぁ~。\x02",
)
)
CloseMessageWindow()
OP_63(0x101, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x104, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x102, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
Sleep(1000)
SetScenarioFlags(0x0, 4)
label("loc_422B")
Jump("loc_45A6")
label("loc_4230")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 7)), scpexpr(EXPR_END)), "loc_42E7")
#C0206
ChrTalk(
0xFE,
(
"それではまた明日\x01",
"設定にお伺いしますので。\x02",
)
)
CloseMessageWindow()
#C0207
ChrTalk(
0xFE,
(
"ああ……まだ端末は起動しないように。\x01",
"初期化作業が必要ですからね。\x02",
)
)
CloseMessageWindow()
#C0208
ChrTalk(
0x103,
(
"#0200F(仕事しているときは\x01",
" 普通なのに……)\x02",
)
)
CloseMessageWindow()
Jump("loc_45A6")
label("loc_42E7")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x80, 0)), scpexpr(EXPR_END)), "loc_45A6")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 4)), scpexpr(EXPR_END)), "loc_43AC")
TurnDirection(0xFE, 0x103, 0)
#C0209
ChrTalk(
0xFE,
(
"……ティオ君、\x01",
"端末が壊れたら僕に言ってね!\x01",
"すぐに直すから!!\x02",
)
)
CloseMessageWindow()
OP_63(0x0, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x1, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x2, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x3, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
Sleep(1000)
Jump("loc_45A6")
label("loc_43AC")
#C0210
ChrTalk(
0xFE,
(
"ちなみに端末装置をまともに買うと\x01",
"150万ミラはするよ。\x02",
)
)
CloseMessageWindow()
#C0211
ChrTalk(
0xFE,
(
"まだまだ一般市民には\x01",
"手が届かないんだろうなぁ。\x02",
)
)
CloseMessageWindow()
OP_63(0x101, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x102, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x104, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
Sleep(1000)
#C0212
ChrTalk(
0x101,
(
"#0003F支援課の端末、\x01",
"いつもぞんざいに扱ってたよ。\x02",
)
)
CloseMessageWindow()
#C0213
ChrTalk(
0x103,
(
"#0200Fまあ、物理的な故障は\x01",
"大した問題ではありません。\x01",
"気にしなくてもいいかと。\x02",
)
)
CloseMessageWindow()
TurnDirection(0xFE, 0x103, 500)
#C0214
ChrTalk(
0xFE,
(
"……ティオ君、\x01",
"端末が壊れたら僕に言ってね!\x02",
)
)
CloseMessageWindow()
#C0215
ChrTalk(
0xFE,
(
"すぐに直すから!\x01",
"全力で直すから!!\x02",
)
)
CloseMessageWindow()
OP_63(0x103, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
Sleep(1000)
#C0216
ChrTalk(
0x103,
(
"#0200Fいえ……多分\x01",
"自分で直せるのでいいです。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 4)
label("loc_45A6")
TalkEnd(0xFE)
Return()
# Function_12_3C6C end
def Function_13_45AA(): pass
label("Function_13_45AA")
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x2, 0x1, 0x0)"), scpexpr(EXPR_EXEC_OP, "OP_2A(0x2, 0x0, 0x10)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_EXEC_OP, "GetItemNumber(0x337, 0x0)"), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_EXEC_OP, "GetItemNumber(0x338, 0x0)"), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_EXEC_OP, "GetItemNumber(0x339, 0x0)"), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_EXEC_OP, "OP_2A(0x2, 0x0, 0x40)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_45E9")
TurnDirection(0x0, 0xF, 0)
Call(0, 25)
Return()
label("loc_45E9")
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x2, 0x0, 0x2)"), scpexpr(EXPR_EXEC_OP, "OP_2A(0x2, 0x1, 0x0)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_EXEC_OP, "OP_2A(0x2, 0x0, 0x40)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_4611")
TurnDirection(0x0, 0xF, 0)
Call(0, 24)
Return()
label("loc_4611")
TalkBegin(0xFE)
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x2, 0x0, 0x10)"), scpexpr(EXPR_END)), "loc_4845")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 7)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_477D")
#C0217
ChrTalk(
0xFE,
"これでようやく国に帰れるよ~。\x02",
)
CloseMessageWindow()
#C0218
ChrTalk(
0xFE,
"みんな、ありがと~!\x02",
)
CloseMessageWindow()
#C0219
ChrTalk(
0x101,
(
"#0006Fトロントさん、とりあえず\x01",
"新しいカバンを買ってください。\x02",
)
)
CloseMessageWindow()
#C0220
ChrTalk(
0xFE,
(
"え、う、うん。\x01",
"そうだね~。\x02",
)
)
CloseMessageWindow()
#C0221
ChrTalk(
0xFE,
"あはは、ありがと~!\x02",
)
CloseMessageWindow()
OP_63(0x0, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x1, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x2, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x3, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
Sleep(1000)
#C0222
ChrTalk(
0x103,
"#0200F(……どこまでも陽気な人です。)\x02",
)
CloseMessageWindow()
SetScenarioFlags(0x0, 7)
Jump("loc_4840")
label("loc_477D")
#C0223
ChrTalk(
0xFE,
(
"お財布よし、お土産よし、\x01",
"チケットよし!\x02",
)
)
CloseMessageWindow()
#C0224
ChrTalk(
0xFE,
(
"あ、でも入れるカバンがないや。\x01",
"あはははは~!\x02",
)
)
CloseMessageWindow()
OP_63(0x0, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x1, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x2, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x3, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
Sleep(1000)
label("loc_4840")
Jump("loc_4A25")
label("loc_4845")
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x2, 0x1, 0x0)"), scpexpr(EXPR_END)), "loc_49BE")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 7)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_4950")
#C0225
ChrTalk(
0xFE,
(
"クロスベルを観光するのが\x01",
"夢だったからさー。\x01",
"つい夢中になっちゃったんだよね。\x02",
)
)
CloseMessageWindow()
#C0226
ChrTalk(
0xFE,
(
"はあ、もう探すのは疲れたよ~。\x01",
"クロスベル市、広すぎだよ~。\x02",
)
)
CloseMessageWindow()
#C0227
ChrTalk(
0xFE,
(
"……あ、でも僕って\x01",
"今日で帰国する予定なんだよね。\x02",
)
)
CloseMessageWindow()
#C0228
ChrTalk(
0xFE,
"警察の人、急ぎで頼むよ~っ!\x02",
)
CloseMessageWindow()
SetScenarioFlags(0x0, 7)
Jump("loc_49B9")
label("loc_4950")
#C0229
ChrTalk(
0xFE,
(
"はあ、僕は疲れちゃったよ~。\x01",
"クロスベル市、広すぎだよ~。\x02",
)
)
CloseMessageWindow()
#C0230
ChrTalk(
0xFE,
"警察の人、とにかく急ぎで頼むよ~っ!\x02",
)
CloseMessageWindow()
label("loc_49B9")
Jump("loc_4A25")
label("loc_49BE")
Jc((scpexpr(EXPR_EXEC_OP, "OP_2A(0x2, 0x0, 0x2)"), scpexpr(EXPR_END)), "loc_49CF")
Jump("loc_4A25")
label("loc_49CF")
#C0231
ChrTalk(
0xFE,
(
"はあぁ~……\x01",
"もう歩くのやだよ~。\x02",
)
)
CloseMessageWindow()
#C0232
ChrTalk(
0xFE,
(
"困ったな~……\x01",
"諦めて帰っちゃおうかな~。\x02",
)
)
CloseMessageWindow()
label("loc_4A25")
TalkEnd(0xFE)
Return()
# Function_13_45AA end
def Function_14_4A29(): pass
label("Function_14_4A29")
EventBegin(0x2)
Sound(810, 0, 100, 0)
SetChrName("")
#A0233
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"鍵が掛かっているようだ。\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
OP_5A()
EventEnd(0x3)
Return()
# Function_14_4A29 end
def Function_15_4A59(): pass
label("Function_15_4A59")
TalkBegin(0xC)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 6)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_4B34")
#C0234
ChrTalk(
0xC,
"……………………………………\x02",
)
CloseMessageWindow()
#C0235
ChrTalk(
0x101,
"#0001Fすっかり気を失っているみたいだ。\x02",
)
CloseMessageWindow()
#C0236
ChrTalk(
0x104,
"#0301Fこいつも薬の副作用ってとこかねぇ。\x02",
)
CloseMessageWindow()
#C0237
ChrTalk(
0x102,
"#0108Fまだ断定は出来ないけど……\x02",
)
CloseMessageWindow()
#C0238
ChrTalk(
0x103,
"#0208F………………………………\x02",
)
CloseMessageWindow()
SetScenarioFlags(0x0, 6)
Jump("loc_4B90")
label("loc_4B34")
#C0239
ChrTalk(
0xC,
"……………………………………\x02",
)
CloseMessageWindow()
FadeToDark(300, 0, 100)
SetChrName("")
#A0240
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"ガンツは気を失っている。\x07\x00\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
FadeToBright(300, 0)
OP_5A()
label("loc_4B90")
TalkEnd(0xC)
Return()
# Function_15_4A59 end
def Function_16_4B94(): pass
label("Function_16_4B94")
TalkBegin(0xD)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xE0, 0)), scpexpr(EXPR_END)), "loc_4C19")
#C0241
ChrTalk(
0xFE,
"ガンツはまだ戻らないようだ……\x02",
)
CloseMessageWindow()
#C0242
ChrTalk(
0xFE,
(
"おお、女神よ……\x01",
"マインツの大切な若者をどうか、\x01",
"どうか無事に帰したまえ……\x02",
)
)
CloseMessageWindow()
Jump("loc_4F03")
label("loc_4C19")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC3, 6)), scpexpr(EXPR_END)), "loc_4D20")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 5)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_4CAB")
#C0243
ChrTalk(
0xFE,
"おお、君たちか……\x02",
)
CloseMessageWindow()
#C0244
ChrTalk(
0xFE,
(
"まったく……ガンツめ、\x01",
"よく心配をかけてくれるよ。\x02",
)
)
CloseMessageWindow()
#C0245
ChrTalk(
0xFE,
"一体どこに行ってしまったんだ……?\x02",
)
CloseMessageWindow()
SetScenarioFlags(0x0, 5)
Jump("loc_4D1B")
label("loc_4CAB")
#C0246
ChrTalk(
0xFE,
(
"ガンツ……\x01",
"一体どこに行ってしまったんだ……?\x02",
)
)
CloseMessageWindow()
#C0247
ChrTalk(
0xFE,
(
"忙しいところすまないが、\x01",
"彼の事も気にかけてやってくれ。\x02",
)
)
CloseMessageWindow()
label("loc_4D1B")
Jump("loc_4F03")
label("loc_4D20")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC2, 2)), scpexpr(EXPR_END)), "loc_4F03")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 5)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_4E64")
#C0248
ChrTalk(
0xFE,
"……………………\x02",
)
CloseMessageWindow()
#C0249
ChrTalk(
0xFE,
(
"……すまない、\x01",
"やはりショックは隠しきれないな。\x02",
)
)
CloseMessageWindow()
#C0250
ChrTalk(
0x101,
"#0008F町長……\x02",
)
CloseMessageWindow()
#C0251
ChrTalk(
0xFE,
(
"……ガンツは決して薬物などに\x01",
"安易に手を出すような若者ではない。\x02",
)
)
CloseMessageWindow()
#C0252
ChrTalk(
0xFE,
(
"その薬が本当に、\x01",
"そういった物なのかは知らないが……\x02",
)
)
CloseMessageWindow()
#C0253
ChrTalk(
0xFE,
(
"もしそうだとしたら、\x01",
"ガンツにそれを渡した人物を\x01",
"私は許す事はできんよ。\x02",
)
)
CloseMessageWindow()
SetScenarioFlags(0x0, 5)
Jump("loc_4F03")
label("loc_4E64")
#C0254
ChrTalk(
0xFE,
"……ガンツは任せてくれたまえ。\x02",
)
CloseMessageWindow()
#C0255
ChrTalk(
0xFE,
(
"もし目を覚ましたら\x01",
"改めて事情を聞いてみよう。\x02",
)
)
CloseMessageWindow()
#C0256
ChrTalk(
0xFE,
(
"……その薬が何物でもない\x01",
"普通の医薬品であることを\x01",
"願うばかりだよ。\x02",
)
)
CloseMessageWindow()
label("loc_4F03")
TalkEnd(0xD)
Return()
# Function_16_4B94 end
def Function_17_4F07(): pass
label("Function_17_4F07")
EventBegin(0x0)
FadeToDark(0, 0, -1)
OP_68(163000, 1000, 7200, 0)
MoveCamera(307, 27, 0, 0)
OP_6E(380, 0)
SetCameraDistance(24000, 0)
SetChrPos(0x101, 164300, 0, 3900, 270)
SetChrPos(0x102, 164300, 0, 5000, 270)
SetChrPos(0x103, 165200, 0, 3600, 270)
SetChrPos(0x104, 165200, 0, 5300, 270)
SetChrPos(0x13D, 164300, 0, 7600, 225)
SetChrPos(0xC, 162000, 650, 5900, 90)
ClearChrFlags(0xC, 0x80)
ClearChrBattleFlags(0xC, 0x8000)
SetChrPos(0xD, 162000, 0, 4500, 0)
ClearChrFlags(0xD, 0x80)
ClearChrBattleFlags(0xD, 0x8000)
OP_4B(0xA, 0xFF)
SetChrFlags(0xA, 0x80)
SetChrBattleFlags(0xA, 0x8000)
SetMapObjFrame(0xFF, "futon", 0x0, 0x1)
CreatePortrait(0, 112, 8, 368, 264, 0, 0, 256, 256, 0, 0, 256, 256, 0xFFFFFF, 0x1, "c_vis087.itp")
OP_68(163000, 1000, 5200, 4000)
FadeToBright(2000, 0)
OP_0D()
OP_6F(0x1)
#C0257
ChrTalk(
0xD,
(
"#5Pおお女神よ……\x01",
"一体どうしてこんな事に……\x02",
)
)
CloseMessageWindow()
#C0258
ChrTalk(
0xD,
(
"#5Pだらしないが気のいい、\x01",
"誰からも好かれる男だったのに……\x02",
)
)
CloseMessageWindow()
#C0259
ChrTalk(
0x102,
"#0108F#12P町長さん……\x02",
)
CloseMessageWindow()
#C0260
ChrTalk(
0x104,
(
"#12P#0306Fしかしまあ、とんでもない\x01",
"暴れっぷりだったよな……\x02\x03",
"#0301Fまさか俺とロイドの2人がかりで\x01",
"取り押さえる羽目になるとは\x01",
"思わなかったぜ。\x02",
)
)
CloseMessageWindow()
#C0261
ChrTalk(
0x101,
(
"#6P#0006Fああ……\x01",
"正直、物凄い力だった。\x02",
)
)
CloseMessageWindow()
#C0262
ChrTalk(
0x103,
"#12P#0201F#N……………………………………\x02",
)
CloseMessageWindow()
OP_63(0x13D, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0)
Sleep(2000)
OP_64(0x13D)
TurnDirection(0x13D, 0x101, 500)
Sleep(300)
#C0263
ChrTalk(
0x13D,
(
"#2103F#11Pねえ……\x01",
"これは率直な印象なんだけど。\x02\x03",
"#2101Fその人、何か危ない\x01",
"クスリでもやってるんじゃない?\x02",
)
)
CloseMessageWindow()
OP_63(0xD, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
Sound(28, 0, 100, 0)
Sleep(50)
OP_63(0x102, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
Sound(28, 0, 100, 0)
Sleep(50)
OP_63(0x104, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
Sound(28, 0, 100, 0)
Sleep(50)
OP_63(0x101, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1)
OP_63(0x103, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1)
Sleep(1000)
def lambda_52BA():
TurnDirection(0xFE, 0x13D, 500)
ExitThread()
QueueWorkItem(0xD, 2, lambda_52BA)
def lambda_52C7():
TurnDirection(0xFE, 0x13D, 500)
ExitThread()
QueueWorkItem(0x101, 2, lambda_52C7)
Sleep(50)
def lambda_52D7():
TurnDirection(0xFE, 0x13D, 500)
ExitThread()
QueueWorkItem(0x102, 2, lambda_52D7)
def lambda_52E4():
TurnDirection(0xFE, 0x13D, 500)
ExitThread()
QueueWorkItem(0x103, 2, lambda_52E4)
Sleep(50)
TurnDirection(0x104, 0x13D, 500)
OP_82(0x64, 0x0, 0xBB8, 0x12C)
#C0264
ChrTalk(
0xD,
"#5P#4Sな……!?\x02",
)
CloseMessageWindow()
#C0265
ChrTalk(
0x102,
"#6P#0105Fそ、それは……\x02",
)
CloseMessageWindow()
#C0266
ChrTalk(
0x104,
"#6P#0305Fマジかよ……!?\x02",
)
CloseMessageWindow()
#C0267
ChrTalk(
0x13D,
(
"#2100F#11Pあら、ロイド君とティオちゃんは\x01",
"あたしと同意見かしら?\x02",
)
)
CloseMessageWindow()
#C0268
ChrTalk(
0x103,
"#0208F#6P#N………それは……………\x02",
)
CloseMessageWindow()
OP_5A()
#C0269
ChrTalk(
0x101,
(
"#0006F#6P……あまり滅多なことを\x01",
"言うつもりはないんですが……\x02\x03",
"#0001F可能性はあるかもしれません。\x02",
)
)
CloseMessageWindow()
#C0270
ChrTalk(
0xD,
(
"#5Pば、馬鹿な……\x01",
"薬物なんてあり得るものか!\x02",
)
)
CloseMessageWindow()
#C0271
ChrTalk(
0xD,
(
"#5Pただの普通の鉱員だぞ!?\x01",
"そんな物に手を出すはずが──\x02",
)
)
CloseMessageWindow()
TurnDirection(0x13D, 0xD, 500)
#C0272
ChrTalk(
0x13D,
(
"#2100F#11Pでも、こちらに来てから\x01",
"半月近く経ってるんでしょう?\x02\x03",
"相当ミラも儲けていたはずだし、\x01",
"そこに付け込まれた可能性は\x01",
"無いとは言い切れないのでは?\x02",
)
)
CloseMessageWindow()
#C0273
ChrTalk(
0xD,
"#5Pい、いい加減にしたまえ!\x02",
)
CloseMessageWindow()
#C0274
ChrTalk(
0xD,
(
"#5P君はクロスベルタイムズの\x01",
"記者という話だったな……\x02",
)
)
CloseMessageWindow()
#C0275
ChrTalk(
0xD,
(
"#5P憶測で記事を書いたりしたら\x01",
"厳重に抗議させてもらうぞ!?\x02",
)
)
CloseMessageWindow()
#C0276
ChrTalk(
0x13D,
(
"#2106F#11Pあー、別に記事に\x01",
"するつもりは無いんですが。\x02",
)
)
CloseMessageWindow()
OP_63(0x101, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0)
Sleep(1500)
OP_64(0x101)
Fade(500)
OP_68(163000, 1000, 4700, 0)
MoveCamera(330, 19, 0, 0)
OP_6E(380, 0)
SetCameraDistance(23500, 0)
SetChrPos(0xC, 162000, 600, 5900, 90)
SetChrSubChip(0xC, 0x1)
OP_0D()
TurnDirection(0x101, 0xD, 500)
#C0277
ChrTalk(
0x101,
(
"#12P#0003F──ビクセン町長。\x02\x03",
"#0001F念のため、ガンツさんの私物を\x01",
"確かめても構いませんか?\x02",
)
)
CloseMessageWindow()
OP_63(0xD, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
Sound(28, 0, 100, 0)
Sleep(1000)
def lambda_56FB():
TurnDirection(0xFE, 0x101, 500)
ExitThread()
QueueWorkItem(0xD, 2, lambda_56FB)
Sleep(100)
def lambda_570B():
TurnDirection(0xFE, 0x101, 500)
ExitThread()
QueueWorkItem(0x102, 2, lambda_570B)
def lambda_5718():
TurnDirection(0xFE, 0x101, 500)
ExitThread()
QueueWorkItem(0x104, 2, lambda_5718)
def lambda_5725():
TurnDirection(0xFE, 0x101, 500)
ExitThread()
QueueWorkItem(0x103, 2, lambda_5725)
Sleep(50)
TurnDirection(0x13D, 0x101, 500)
#C0278
ChrTalk(
0xD,
"#5Pロイド君、君まで!?\x02",
)
CloseMessageWindow()
#C0279
ChrTalk(
0x101,
(
"#12P#0006F決め付けるつもりはありませんが\x01",
"色々と符合する事も多いんです。\x02\x03",
"#0008Fあの暴れ方、凄まじい力、\x01",
"そして変わってしまった性格……\x02\x03",
"#0013F過去、幾つかあった薬物事件と\x01",
"似たような反応が見られるんです。\x02\x03",
"それに、比べ物にならないくらい\x01",
"ギャンブルの腕が上がったのも……\x02",
)
)
CloseMessageWindow()
#C0280
ChrTalk(
0x104,
(
"#0303F#11P……クスリのせいで知覚が異常に\x01",
"過敏になったせいかもしれねぇな。\x02\x03",
"#0301Fそれで相手の心理を読み取ったり、\x01",
"カンが働いてたのかもしれねぇ。\x02",
)
)
CloseMessageWindow()
#C0281
ChrTalk(
0x103,
(
"#12P#0206F…………そうですね。\x02\x03",
"#0200F多分、わたしが賭け事をすれば、\x01",
"他の人よりも有利になるはずです。\x02",
)
)
CloseMessageWindow()
TurnDirection(0x102, 0x103, 500)
Sleep(300)
#C0282
ChrTalk(
0x102,
"#0105F#5Pティオちゃん……\x02",
)
CloseMessageWindow()
#C0283
ChrTalk(
0x104,
(
"#0306F#11P……悪ぃ。\x01",
"んなつもりじゃ無かったが。\x02",
)
)
CloseMessageWindow()
#C0284
ChrTalk(
0x103,
(
"#12P#0204Fいえ、気にしてません。\x02\x03",
"#0201F──町長さん。\x01",
"ガンツさんの名誉のことを\x01",
"気にするのは分かります。\x02\x03",
"でも、もし本当に\x01",
"何らかの薬物だった場合……\x02\x03",
"このまま放置しておいたら\x01",
"どんな危険があるか分かりません。\x02",
)
)
CloseMessageWindow()
OP_63(0xD, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
Sound(28, 0, 100, 0)
Sleep(1000)
def lambda_5ABB():
TurnDirection(0xFE, 0xD, 500)
ExitThread()
QueueWorkItem(0x102, 2, lambda_5ABB)
Sleep(50)
def lambda_5ACB():
TurnDirection(0xFE, 0xD, 500)
ExitThread()
QueueWorkItem(0x104, 2, lambda_5ACB)
#C0285
ChrTalk(
0xD,
"#5Pそ、それは……\x02",
)
CloseMessageWindow()
#C0286
ChrTalk(
0x13D,
(
"#11P#2106F中毒症状に後遺症……\x01",
"まあ、色々と考えられそうね。\x02",
)
)
CloseMessageWindow()
#C0287
ChrTalk(
0x101,
(
"#12P#0006Fええ、薬物による被害で\x01",
"一番怖いのはそこだと思います。\x02",
)
)
CloseMessageWindow()
OP_63(0xD, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0)
Sleep(2000)
OP_64(0xD)
#C0288
ChrTalk(
0xD,
(
"#5P判った……\x01",
"思慮が足りなかったようだ。\x02",
)
)
CloseMessageWindow()
#C0289
ChrTalk(
0xD,
"#5Pロイド君、お願いする。\x02",
)
CloseMessageWindow()
#C0290
ChrTalk(
0x101,
"#12P#0003F……はい。\x02",
)
CloseMessageWindow()
def lambda_5BF4():
label("loc_5BF4")
TurnDirection(0xFE, 0x101, 500)
Yield()
Jump("loc_5BF4")
QueueWorkItem2(0x13D, 2, lambda_5BF4)
def lambda_5C06():
label("loc_5C06")
TurnDirection(0xFE, 0x101, 500)
Yield()
Jump("loc_5C06")
QueueWorkItem2(0x102, 2, lambda_5C06)
def lambda_5C18():
label("loc_5C18")
TurnDirection(0xFE, 0x101, 500)
Yield()
Jump("loc_5C18")
QueueWorkItem2(0x103, 2, lambda_5C18)
def lambda_5C2A():
label("loc_5C2A")
TurnDirection(0xFE, 0x101, 500)
Yield()
Jump("loc_5C2A")
QueueWorkItem2(0x104, 2, lambda_5C2A)
def lambda_5C3C():
label("loc_5C3C")
TurnDirection(0xFE, 0x101, 500)
Yield()
Jump("loc_5C3C")
QueueWorkItem2(0xD, 2, lambda_5C3C)
OP_68(162700, 1000, 4930, 1200)
def lambda_5C5F():
OP_96(0xFE, 0x27B8C, 0x0, 0x1194, 0x7D0, 0x0)
ExitThread()
QueueWorkItem(0x101, 1, lambda_5C5F)
Sleep(300)
def lambda_5C7C():
OP_96(0xFE, 0x278D0, 0x0, 0xC80, 0x5DC, 0x0)
ExitThread()
QueueWorkItem(0xD, 1, lambda_5C7C)
WaitChrThread(0x101, 1)
OP_93(0x101, 0x14A, 0x1F4)
WaitChrThread(0xD, 1)
EndChrThread(0x13D, 0x2)
EndChrThread(0x102, 0x2)
EndChrThread(0x103, 0x2)
EndChrThread(0x104, 0x2)
EndChrThread(0xD, 0x2)
Sleep(300)
FadeToDark(300, 0, 100)
SetChrName("")
#A0291
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"ロイドはガンツを起こさないよう、\x01",
"注意して懐などを探って行った。\x07\x00\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
OP_5A()
FadeToBright(300, 0)
OP_63(0x101, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0)
Sound(804, 0, 100, 0)
Sleep(2000)
OP_64(0x101)
OP_63(0x101, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1)
Sleep(1000)
#C0292
ChrTalk(
0x101,
"#6P#0013F(………これは…………)\x02",
)
CloseMessageWindow()
OP_C9(0x0, 0x3, 0xFFFFFFFF, 0x1F4, 0x0)
OP_C9(0x0, 0x0, 0x0, 0xFFFFD8F0, 0x1F4)
OP_CA(0x0, 0x0, 0x3)
OP_CA(0x0, 0x0, 0x0)
Sleep(500)
FadeToDark(300, 0, 100)
SetMessageWindowPos(-1, -1, -1, -1)
SetChrName("")
Sound(17, 0, 100, 0)
#A0293
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_ITEM, 0x32B),
scpstr(SCPSTR_CODE_COLOR, 0x0),
"を手に入れた。\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
FadeToBright(300, 0)
SetMessageWindowPos(14, 280, 60, 3)
OP_5A()
AddItemNumber(0x32B, 1)
#A0294
AnonymousTalk(
0x102,
"#0105Fそ、それは……\x02",
)
CloseMessageWindow()
OP_57(0x0)
OP_5A()
#A0295
AnonymousTalk(
0xD,
"おお、女神よ……\x02",
)
CloseMessageWindow()
OP_57(0x0)
OP_5A()
#A0296
AnonymousTalk(
0x13D,
"#2101Fまさか本当にあったなんて……\x02",
)
CloseMessageWindow()
OP_57(0x0)
OP_5A()
#A0297
AnonymousTalk(
0x104,
(
"#0301F綺麗な色をしてやがるが……\x01",
"いったい、どんなクスリなんだ?\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
OP_5A()
#A0298
AnonymousTalk(
0x103,
"#0201F……………………………………\x02",
)
CloseMessageWindow()
OP_57(0x0)
OP_5A()
OP_C9(0x0, 0x3, 0xFFFFFF, 0x1F4, 0x0)
OP_C9(0x0, 0x0, 0x0, 0x0, 0x1F4)
OP_CA(0x0, 0x0, 0x3)
OP_CA(0x0, 0x0, 0x0)
OP_63(0x101, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0)
Sleep(1500)
OP_64(0x101)
#C0299
ChrTalk(
0x101,
(
"#0006F#5P──まだこの薬が\x01",
"原因と決まったわけじゃない。\x02\x03",
"ひょっとしたら\x01",
"何か持病の薬かもしれないし。\x02",
)
)
CloseMessageWindow()
TurnDirection(0x101, 0xD, 500)
#C0300
ChrTalk(
0x101,
"#11P#0001F町長、ガンツさんに持病は?\x02",
)
CloseMessageWindow()
#C0301
ChrTalk(
0xD,
(
"#6P……知る限り無かったはずだ。\x01",
"もちろん断言は出来ないが……\x02",
)
)
CloseMessageWindow()
#C0302
ChrTalk(
0x101,
(
"#11P#0003F判りました。\x02\x03",
"#0001F……この薬はいったん、\x01",
"こちらで預からせて頂いても?\x02",
)
)
CloseMessageWindow()
#C0303
ChrTalk(
0xD,
"#6Pああ……よろしくお願いする。\x02",
)
CloseMessageWindow()
#C0304
ChrTalk(
0xD,
(
"#6Pだが、どうか……!\x01",
"どうか事を大きくするのは……!\x02",
)
)
CloseMessageWindow()
#C0305
ChrTalk(
0x101,
(
"#11P#0004Fええ、ガンツさんの名誉には\x01",
"配慮させていただきます。\x02\x03",
"#0001Fガンツさん自身については\x01",
"そちらにお任せしても……?\x02",
)
)
CloseMessageWindow()
#C0306
ChrTalk(
0xD,
"#6Pああ……任せてくれたまえ。\x02",
)
CloseMessageWindow()
#C0307
ChrTalk(
0xD,
(
"#6Pもし目を覚ましたら\x01",
"改めて話を聞いてみるつもりだ。\x02",
)
)
CloseMessageWindow()
#C0308
ChrTalk(
0x101,
"#11P#0000Fええ、よろしくお願いします。\x02",
)
CloseMessageWindow()
SetCameraDistance(24000, 2000)
FadeToDark(2000, 0, -1)
OP_0D()
OP_6F(0x10)
Sleep(500)
OP_68(68000, 1000, 9700, 0)
MoveCamera(310, 20, 0, 0)
OP_6E(400, 0)
SetCameraDistance(24000, 0)
SetChrPos(0x101, 73600, 0, 7400, 180)
SetChrPos(0x102, 72400, 0, 7400, 180)
SetChrPos(0x103, 73700, 0, 8600, 180)
SetChrPos(0x104, 72300, 0, 8600, 180)
SetChrPos(0x13D, 73000, 0, 5500, 0)
OP_68(72710, 1000, 7410, 4000)
SetCameraDistance(22500, 4000)
FadeToBright(2000, 0)
OP_0D()
OP_6F(0x11)
#C0309
ChrTalk(
0x13D,
(
"#6P#2106F──ふう、それにしても\x01",
"クロスベルで薬物疑惑とはねぇ。\x02\x03",
"珍しいこともあるもんだわ。\x02",
)
)
CloseMessageWindow()
OP_63(0x104, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1)
Sleep(1000)
#C0310
ChrTalk(
0x104,
(
"#11P#0305Fそうなんスか?\x02\x03",
"#0301Fてっきりマフィアあたりが\x01",
"色々扱ってると思ってたんだが。\x02",
)
)
CloseMessageWindow()
#C0311
ChrTalk(
0x13D,
(
"#6P#2104Fところがどっこい、\x01",
"クロスベルで違法薬物ってのは\x01",
"あんまり出回ることはないのよ。\x02\x03",
"#2100F何しろ他の犯罪とは違って、\x01",
"周辺諸国にも広がりかねない\x01",
"影響力のある犯罪だからね。\x02\x03",
"帝国や共和国からの圧力もあって\x01",
"捜査一課の手で違法薬物は\x01",
"厳重に取り締まられてるらしいの。\x02\x03",
"#2104Fそしてルバーチェなんかも\x01",
"その辺の空気は読んでるわけよ。\x02",
)
)
CloseMessageWindow()
#C0312
ChrTalk(
0x102,
"#11P#0105Fそうだったんですか……\x02",
)
CloseMessageWindow()
#C0313
ChrTalk(
0x101,
(
"#11P#0003Fそのあたりの事情は俺も\x01",
"警察学校で教えてもらいました。\x02\x03",
"#0008Fでも、この錠剤は……\x02",
)
)
CloseMessageWindow()
OP_C9(0x0, 0x3, 0xFFFFFFFF, 0x1F4, 0x0)
OP_C9(0x0, 0x0, 0x0, 0xFFFFD8F0, 0x1F4)
OP_CA(0x0, 0x0, 0x3)
OP_CA(0x0, 0x0, 0x0)
Sleep(500)
#A0314
AnonymousTalk(
0x102,
(
"#0101F蒼色の錠剤……\x01",
"見た目は綺麗な感じだけど。\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
OP_5A()
#A0315
AnonymousTalk(
0x104,
(
"#0301Fなんつーか……\x01",
"やたらと怪しげな感じだな。\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
OP_5A()
#A0316
AnonymousTalk(
0x103,
"#0208F#40W……………………………………\x02",
)
CloseMessageWindow()
OP_57(0x0)
OP_5A()
OP_C9(0x0, 0x3, 0xFFFFFF, 0x1F4, 0x0)
OP_C9(0x0, 0x0, 0x0, 0x0, 0x1F4)
OP_CA(0x0, 0x0, 0x3)
OP_CA(0x0, 0x0, 0x0)
OP_63(0x101, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1)
Sleep(1000)
TurnDirection(0x101, 0x103, 500)
#C0317
ChrTalk(
0x101,
"#6P#0005Fティオ、何か心当たりが?\x02",
)
CloseMessageWindow()
def lambda_6633():
TurnDirection(0xFE, 0x103, 500)
ExitThread()
QueueWorkItem(0x102, 2, lambda_6633)
Sleep(50)
TurnDirection(0x104, 0x103, 500)
#C0318
ChrTalk(
0x103,
(
"#0206F#11Pいえ……すみません。\x01",
"ただの気のせいだと思います。\x02\x03",
"#0201Fでも、その錠剤……\x01",
"一体どうするつもりなんですか?\x02",
)
)
CloseMessageWindow()
#C0319
ChrTalk(
0x101,
(
"#6P#0006Fそうだな……\x02\x03",
"俺たちだけで決めるのは\x01",
"ちょっと大事#4Rおおごと#すぎるかもしれない。\x02\x03",
"#0001Fいったん戻って課長に相談しよう。\x02",
)
)
CloseMessageWindow()
def lambda_674C():
TurnDirection(0xFE, 0x101, 500)
ExitThread()
QueueWorkItem(0x102, 2, lambda_674C)
Sleep(100)
TurnDirection(0x104, 0x101, 500)
#C0320
ChrTalk(
0x102,
(
"#5P#0103Fええ、それがいいと思うわ。\x02\x03",
"#0101F《黒月》の襲撃事件についても\x01",
"報告した方がいいでしょうし。\x02",
)
)
CloseMessageWindow()
#C0321
ChrTalk(
0x104,
(
"#5P#0306Fマフィア同士の抗争に加えて\x01",
"クスリ絡みの事件の可能性か……\x02\x03",
"#0301Fったく、とんでもなく\x01",
"忙しくなりそうな気がしてきたぜ。\x02",
)
)
CloseMessageWindow()
#C0322
ChrTalk(
0x13D,
"#6P#2102Fふふっ……\x02",
)
CloseMessageWindow()
OP_63(0x101, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1)
OP_63(0x102, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1)
OP_63(0x103, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1)
OP_63(0x104, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1)
Sleep(1000)
def lambda_68B6():
TurnDirection(0xFE, 0x13D, 500)
ExitThread()
QueueWorkItem(0x101, 2, lambda_68B6)
Sleep(50)
def lambda_68C6():
TurnDirection(0xFE, 0x13D, 500)
ExitThread()
QueueWorkItem(0x102, 2, lambda_68C6)
Sleep(50)
def lambda_68D6():
TurnDirection(0xFE, 0x13D, 500)
ExitThread()
QueueWorkItem(0x103, 2, lambda_68D6)
Sleep(50)
TurnDirection(0x104, 0x13D, 500)
#C0323
ChrTalk(
0x13D,
(
"#6P#2109Fいや~、あなたたちと\x01",
"知り合って4ヶ月になるけど……\x02\x03",
"ずいぶん成長したな~って、\x01",
"お姉さん感慨に浸っちゃうなぁ。\x02",
)
)
CloseMessageWindow()
#C0324
ChrTalk(
0x101,
"#11P#0005Fグレイスさん……?\x02",
)
CloseMessageWindow()
#C0325
ChrTalk(
0x102,
(
"#11P#0105Fい、いきなり\x01",
"どうしたんですか?\x02",
)
)
CloseMessageWindow()
#C0326
ChrTalk(
0x103,
"#0211F#11P誉めても何も出ませんが……\x02",
)
CloseMessageWindow()
#C0327
ChrTalk(
0x13D,
(
"#6P#2104Fいやいや、マジな話、\x01",
"あなた達には期待してるのよ。\x02\x03",
"#2100Fロイド君のお兄さん……\x01",
"ガイ・バニングスと同じくらいね。\x02",
)
)
CloseMessageWindow()
OP_63(0x101, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
Sound(28, 0, 100, 0)
Sleep(50)
OP_63(0x102, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
Sound(28, 0, 100, 0)
Sleep(50)
OP_63(0x103, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
Sound(28, 0, 100, 0)
Sleep(50)
OP_63(0x104, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
Sound(28, 0, 100, 0)
Sleep(1000)
#C0328
ChrTalk(
0x101,
(
"#11P#0011Fそ、そういえば……\x01",
"前にも言ってましたけど。\x02\x03",
"グレイスさんは兄貴と\x01",
"知り合いだったんですか?\x02",
)
)
CloseMessageWindow()
#C0329
ChrTalk(
0x13D,
(
"#6P#2104Fあたしが新米記者だった頃、\x01",
"色々とお世話になったのよね~。\x02\x03",
"#2106F結局、ガイさんの事件については\x01",
"迷宮入りになっちゃったけど……\x02\x03",
"#2102Fそれでも、彼の遺志を継ぐ部署が\x01",
"警察に出来て凄く嬉しかったわ。\x02",
)
)
CloseMessageWindow()
#C0330
ChrTalk(
0x101,
"#11P#0005Fえ……\x02",
)
CloseMessageWindow()
#C0331
ChrTalk(
0x102,
(
"#11P#0105Fロイドのお兄さんの遺志を\x01",
"受け継ぐ部署……?\x02",
)
)
CloseMessageWindow()
#C0332
ChrTalk(
0x13D,
(
"#6P#2104Fおっと、これ以上喋ると\x01",
"課長さんに怒られちゃうかな。\x02\x03",
"#2100Fあたしも取材があるし、\x01",
"今日の所はこれで失礼するわね。\x02\x03",
"#2105Fあ、クスリの件については\x01",
"勝手に記事にしないから安心して。\x02\x03",
"#2109Fそれじゃあ、バハハーイ!\x02",
)
)
CloseMessageWindow()
OP_93(0x13D, 0x5A, 0x1F4)
OP_68(76000, 0, 6900, 2000)
def lambda_6D55():
OP_98(0xFE, 0x1F40, 0x0, 0x0, 0xBB8, 0x0)
ExitThread()
QueueWorkItem(0x13D, 1, lambda_6D55)
def lambda_6D6F():
label("loc_6D6F")
TurnDirection(0xFE, 0x13D, 500)
Yield()
Jump("loc_6D6F")
QueueWorkItem2(0x101, 2, lambda_6D6F)
def lambda_6D81():
label("loc_6D81")
TurnDirection(0xFE, 0x13D, 500)
Yield()
Jump("loc_6D81")
QueueWorkItem2(0x102, 2, lambda_6D81)
def lambda_6D93():
label("loc_6D93")
TurnDirection(0xFE, 0x13D, 500)
Yield()
Jump("loc_6D93")
QueueWorkItem2(0x103, 2, lambda_6D93)
def lambda_6DA5():
label("loc_6DA5")
TurnDirection(0xFE, 0x13D, 500)
Yield()
Jump("loc_6DA5")
QueueWorkItem2(0x104, 2, lambda_6DA5)
Sleep(1500)
def lambda_6DBA():
OP_A7(0xFE, 0xFF, 0xFF, 0xFF, 0x0, 0x1F4)
ExitThread()
QueueWorkItem(0x13D, 2, lambda_6DBA)
WaitChrThread(0x13D, 1)
WaitChrThread(0x13D, 2)
EndChrThread(0x101, 0x2)
EndChrThread(0x102, 0x2)
EndChrThread(0x103, 0x2)
EndChrThread(0x104, 0x2)
OP_6F(0x1)
Sleep(500)
OP_68(73000, 1000, 8000, 2500)
OP_63(0x101, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0)
OP_63(0x102, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0)
OP_63(0x103, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0)
OP_63(0x104, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0)
Sleep(2000)
OP_64(0x101)
OP_64(0x102)
OP_64(0x103)
OP_64(0x104)
OP_6F(0x1)
#C0333
ChrTalk(
0x101,
"#5P#0008F……………………………………\x02",
)
CloseMessageWindow()
#C0334
ChrTalk(
0x104,
(
"#5P#0306Fったく、思わせぶりなことを\x01",
"言うだけ言って行きやがったな。\x02",
)
)
CloseMessageWindow()
#C0335
ChrTalk(
0x102,
(
"#5P#0106Fはぁ……ただでさえ\x01",
"考えることが山ほどあるのに。\x02",
)
)
CloseMessageWindow()
#C0336
ChrTalk(
0x103,
"#0206F#5P……ですね。\x02",
)
CloseMessageWindow()
TurnDirection(0x103, 0x101, 500)
Sleep(300)
#C0337
ChrTalk(
0x103,
(
"#0200F#11Pロイドさん……\x01",
"ガイさんの話、気になります?\x02",
)
)
CloseMessageWindow()
TurnDirection(0x101, 0x103, 500)
Sleep(150)
#C0338
ChrTalk(
0x101,
"#6P#0005Fああ、いや……\x02",
)
CloseMessageWindow()
OP_63(0x101, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0)
Sleep(1500)
OP_64(0x101)
#C0339
ChrTalk(
0x101,
(
"#6P#0006F──確かに気になるけど\x01",
"どう考えても今は後回しだ。\x02\x03",
"#0008F黒月の襲撃、ルバーチェの状況、\x01",
"そしてこの蒼い錠剤……\x02\x03",
"#0000F一通り課長に報告した上で\x01",
"どうするか検討してみよう。\x02",
)
)
CloseMessageWindow()
#C0340
ChrTalk(
0x103,
"#0202F#11P……はい。\x02",
)
CloseMessageWindow()
#C0341
ChrTalk(
0x102,
"#5P#0100Fええ、分かったわ。\x02",
)
CloseMessageWindow()
#C0342
ChrTalk(
0x104,
(
"#5P#0300Fよし、それじゃあとっとと\x01",
"支援課に戻るとしようぜ!\x02",
)
)
CloseMessageWindow()
FadeToDark(1000, 0, -1)
OP_0D()
StopBGM(0xBB8)
OP_50(0x4C, (scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
WaitBGM()
Sleep(10)
PlayBGM("ed7103", 0)
OP_CA(0x1, 0xFF, 0x0)
OP_68(73000, 1500, 9000, 0)
MoveCamera(315, 26, 0, 0)
OP_6E(400, 0)
SetCameraDistance(25000, 0)
SetChrPos(0x0, 74120, 0, 6470, 90)
SetChrPos(0x1, 74120, 0, 6470, 90)
SetChrPos(0x2, 74120, 0, 6470, 90)
SetChrPos(0x3, 74120, 0, 6470, 90)
RemoveParty(0x3C, 0x0)
SetChrSubChip(0xC, 0x0)
SetChrPos(0xC, 162000, 650, 5900, 90)
SetChrPos(0xD, 162000, 0, 4500, 0)
OP_4C(0xA, 0xFF)
ClearChrFlags(0xA, 0x80)
ClearChrBattleFlags(0xA, 0x8000)
SetChrPos(0xA, -2009, 0, 9290, 270)
BeginChrThread(0xA, 0, 0, 0)
SetScenarioFlags(0xC2, 7)
OP_C7(0x1, 0x1000)
OP_29(0x4A, 0x1, 0x9)
OP_66(0x3, 0x1)
BeginChrThread(0xD, 0, 0, 0)
EventEnd(0x5)
Return()
# Function_17_4F07 end
def Function_18_71D1(): pass
label("Function_18_71D1")
#C0343
ChrTalk(
0x11C,
"#1200F……ウォンウォン!\x02",
)
CloseMessageWindow()
#C0344
ChrTalk(
0x101,
(
"#0003F……こっちじゃ\x01",
"無いみたいだな。\x02",
)
)
CloseMessageWindow()
Return()
# Function_18_71D1 end
def Function_19_721B(): pass
label("Function_19_721B")
EventBegin(0x1)
Call(0, 18)
Sleep(50)
SetChrPos(0x0, 56000, 0, 11250, 180)
EventEnd(0x4)
Return()
# Function_19_721B end
def Function_20_7237(): pass
label("Function_20_7237")
EventBegin(0x1)
Call(0, 18)
Sleep(50)
SetChrPos(0x0, 68000, 0, 11250, 180)
EventEnd(0x4)
Return()
# Function_20_7237 end
def Function_21_7253(): pass
label("Function_21_7253")
EventBegin(0x1)
Call(0, 18)
Sleep(50)
SetChrPos(0x0, 1000, 0, 66250, 180)
EventEnd(0x4)
Return()
# Function_21_7253 end
def Function_22_726F(): pass
label("Function_22_726F")
EventBegin(0x1)
Call(0, 18)
Sleep(50)
SetChrPos(0x0, 7250, 0, 60000, 270)
EventEnd(0x4)
Return()
# Function_22_726F end
def Function_23_728B(): pass
label("Function_23_728B")
EventBegin(0x1)
Call(0, 18)
Sleep(50)
SetChrPos(0x0, 1000, 0, 53750, 0)
EventEnd(0x4)
Return()
# Function_23_728B end
def Function_24_72A7(): pass
label("Function_24_72A7")
EventBegin(0x0)
OP_4B(0xF, 0xFF)
FadeToDark(1000, 0, -1)
OP_0D()
OP_68(115550, 1400, 59480, 0)
MoveCamera(315, 27, 0, 0)
OP_6E(400, 0)
SetCameraDistance(20900, 0)
SetChrPos(0x101, 115750, 0, 59450, 0)
SetChrPos(0x103, 115750, 0, 58030, 0)
SetChrPos(0x102, 114340, 0, 59450, 0)
SetChrPos(0x104, 114340, 0, 58030, 0)
FadeToBright(1000, 0)
OP_0D()
#N0345
NpcTalk(
0xF,
"青年",
(
"#11Pはあぁ~……\x01",
"もう歩くのやだよ~。\x02",
)
)
CloseMessageWindow()
#N0346
NpcTalk(
0xF,
"青年",
"#11P諦めて帰っちゃおうかな~。\x02",
)
CloseMessageWindow()
#C0347
ChrTalk(
0x101,
(
"#12P#0000Fあの、すいません。\x01",
"依頼を出された\x01",
"トロントさんですか?\x02",
)
)
CloseMessageWindow()
OP_63(0xF, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1)
Sleep(500)
OP_93(0xF, 0xB4, 0x1F4)
Sleep(300)
#C0348
ChrTalk(
0xF,
"#11Pおっ、警察の人?\x02",
)
CloseMessageWindow()
#C0349
ChrTalk(
0xF,
(
"#11Pおお~、まさか\x01",
"来てくれるとは思わなかったよ~!\x02",
)
)
CloseMessageWindow()
#C0350
ChrTalk(
0x101,
"#12P#0012Fははは、どうも……\x02",
)
CloseMessageWindow()
#C0351
ChrTalk(
0x102,
(
"#5P#0100Fえっと、落し物を\x01",
"されたということですが、\x01",
"お話を聞かせて頂けますか?\x02",
)
)
CloseMessageWindow()
#C0352
ChrTalk(
0xF,
(
"#11Pそれがね、聞くも涙、\x01",
"語るも涙なわけで……\x02",
)
)
CloseMessageWindow()
OP_63(0x0, 0x0, 2000, 0x0, 0x1, 0xFA, 0x2)
Sound(29, 0, 100, 0)
Sleep(10)
OP_63(0x1, 0x0, 2000, 0x0, 0x1, 0xFA, 0x2)
Sound(29, 0, 100, 0)
OP_63(0x2, 0x0, 2000, 0x0, 0x1, 0xFA, 0x2)
Sound(29, 0, 100, 0)
Sleep(20)
OP_63(0x3, 0x0, 2000, 0x0, 0x1, 0xFA, 0x2)
Sound(29, 0, 100, 0)
Sleep(1200)
#C0353
ChrTalk(
0xF,
(
"#11P僕は買い物大好きなわけで、\x01",
"クロスベルのあちこちを\x01",
"見て回ってたわけさ。\x02",
)
)
CloseMessageWindow()
#C0354
ChrTalk(
0xF,
(
"#11Pでも……ふと気付いたら\x01",
"カバンに穴が開いててさ。\x01",
"ポロポロこぼしてたわけ!\x02",
)
)
CloseMessageWindow()
#C0355
ChrTalk(
0xF,
(
"#11P僕も必死に探し回ったんだけど\x01",
"いくつかはどうしても\x01",
"見つからないんだよねぇ~。\x02",
)
)
CloseMessageWindow()
#C0356
ChrTalk(
0x104,
(
"#0306Fなるほどなぁ……\x02\x03",
"#0301Fだが昨日の今日じゃ\x01",
"路上に落ちたまんまってのは\x01",
"考えにくいな。\x02",
)
)
CloseMessageWindow()
#C0357
ChrTalk(
0x103,
(
"#12P#0200F付近のどなたかが\x01",
"拾ってくれているかもしれませんね。\x02\x03",
"ショッピングで\x01",
"立ち寄った場所を伺っても?\x02",
)
)
CloseMessageWindow()
#C0358
ChrTalk(
0xF,
"#11Pうん、まずは当然百貨店さ!\x02",
)
CloseMessageWindow()
#C0359
ChrTalk(
0xF,
(
"#11P最新のブランド物が揃っててさ~、\x01",
"じっくり堪能させてもらったよ~。\x02",
)
)
CloseMessageWindow()
#C0360
ChrTalk(
0xF,
(
"#11Pそれから東通りの市場を\x01",
"ながめて回って……\x02",
)
)
CloseMessageWindow()
#C0361
ChrTalk(
0xF,
(
"#11P港湾区にある公園に来た辺りで\x01",
"カバンの破れに気付いたんだよね~。\x02",
)
)
CloseMessageWindow()
OP_63(0xF, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x1)
Sleep(1800)
#C0362
ChrTalk(
0xF,
(
"#11P……はあ、どうしても\x01",
"見つからないんだよな~。\x02",
)
)
CloseMessageWindow()
#C0363
ChrTalk(
0xF,
(
"#11Pお財布と土産物と……\x01",
"あともう1つ、何だったかなぁ……\x02",
)
)
CloseMessageWindow()
#C0364
ChrTalk(
0xF,
(
"#11P絶対に3つ、\x01",
"足りないと思うんだけどなぁ……\x02",
)
)
CloseMessageWindow()
OP_63(0x0, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x1, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x2, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x3, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
Sleep(1000)
#C0365
ChrTalk(
0x101,
(
"#12P#0003F……最後の1つは\x01",
"思い出せないわけですね。\x02\x03",
"#0001F分かりました、ともかくこちらで\x01",
"周辺を捜索してみましょう。\x02",
)
)
CloseMessageWindow()
#C0366
ChrTalk(
0x102,
(
"#5P#0103F中央広場の百貨店に\x01",
"東通り、港湾区……\x02\x03",
"#0100Fどこも商店の多い地区だし\x01",
"お店の人を中心に\x01",
"聞いて回るのが良さそうね。\x02",
)
)
CloseMessageWindow()
#C0367
ChrTalk(
0xF,
"#11Pよろしく頼んだよ~っ!\x02",
)
CloseMessageWindow()
FadeToDark(300, 0, 100)
Sound(80, 0, 100, 0)
SetMessageWindowPos(-1, -1, -1, -1)
SetChrName("")
#A0368
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_COLOR, 0x2),
"クエスト【紛失物の捜索願い】\x07\x00",
"を開始した!\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
FadeToBright(300, 0)
SetMessageWindowPos(14, 280, 60, 3)
FadeToDark(1000, 0, -1)
OP_0D()
OP_68(115090, 1500, 58830, 0)
MoveCamera(315, 26, 0, 0)
OP_6E(400, 0)
SetCameraDistance(25000, 0)
SetChrPos(0x0, 115090, 0, 58830, 0)
SetChrPos(0x1, 115090, 0, 58830, 0)
SetChrPos(0x2, 115090, 0, 58830, 0)
SetChrPos(0x3, 115090, 0, 58830, 0)
OP_4C(0xF, 0xFF)
ClearChrFlags(0xF, 0x10)
OP_29(0x2, 0x1, 0x0)
Sleep(500)
EventEnd(0x5)
Return()
# Function_24_72A7 end
def Function_25_7B37(): pass
label("Function_25_7B37")
EventBegin(0x0)
OP_4B(0xF, 0xFF)
FadeToDark(1000, 0, -1)
OP_0D()
OP_68(115550, 1400, 59480, 0)
MoveCamera(315, 27, 0, 0)
OP_6E(400, 0)
SetCameraDistance(20900, 0)
SetChrPos(0x101, 115750, 0, 59450, 0)
SetChrPos(0x103, 115750, 0, 58030, 0)
SetChrPos(0x102, 114340, 0, 59450, 0)
SetChrPos(0x104, 114340, 0, 58030, 0)
OP_93(0xF, 0xB4, 0x0)
FadeToBright(1000, 0)
OP_0D()
#C0369
ChrTalk(
0x101,
(
"#12P#0000Fトロントさん、確か\x01",
"落し物は3つでしたよね。\x02",
)
)
CloseMessageWindow()
#C0370
ChrTalk(
0x102,
(
"#5P#0100F全て見つけてきました。\x02\x03",
"……はいどうぞ。\x01",
"もう落とさないでくださいね。\x02",
)
)
CloseMessageWindow()
OP_95(0x102, 114480, 0, 60290, 1000, 0x0)
OP_93(0x102, 0x0, 0x1F4)
Sleep(500)
FadeToDark(300, 0, 100)
SetMessageWindowPos(-1, -1, -1, -1)
SetChrName("")
#A0371
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_ITEM, 0x337),
scpstr(SCPSTR_CODE_COLOR, 0x0),
"を渡した。\x02",
)
)
Sound(17, 0, 100, 0)
CloseMessageWindow()
OP_5A()
#A0372
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_ITEM, 0x338),
scpstr(SCPSTR_CODE_COLOR, 0x0),
"を渡した。\x02",
)
)
Sound(17, 0, 100, 0)
CloseMessageWindow()
OP_5A()
#A0373
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_ITEM, 0x339),
scpstr(SCPSTR_CODE_COLOR, 0x0),
"を渡した。\x02",
)
)
Sound(17, 0, 100, 0)
CloseMessageWindow()
OP_5A()
FadeToBright(300, 0)
OP_57(0x0)
SetMessageWindowPos(14, 280, 60, 3)
OP_5A()
SubItemNumber(0x337, 1)
SubItemNumber(0x338, 1)
SubItemNumber(0x339, 1)
OP_96(0x102, 0x1BEA4, 0x0, 0xE83A, 0x3E8, 0x0)
OP_63(0xF, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1)
Sleep(500)
#C0374
ChrTalk(
0xF,
"#11Pおお、確かに僕の持ち物だ!\x02",
)
CloseMessageWindow()
#C0375
ChrTalk(
0xF,
(
"#11Pいやあ良かったぁ~。\x01",
"もう諦めて国に帰ろうかと\x01",
"思ってたんだよ~。\x02",
)
)
CloseMessageWindow()
#C0376
ChrTalk(
0x103,
(
"#12P#0200Fお財布もチケットも無くては\x01",
"帰れないのでは……?\x02",
)
)
CloseMessageWindow()
OP_63(0xF, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
Sleep(1200)
#C0377
ChrTalk(
0xF,
(
"#11Pうっ……そ、それもそうだね。\x01",
"あはは、気付かなかったよ~!\x02",
)
)
CloseMessageWindow()
#C0378
ChrTalk(
0xF,
(
"#11Pでも本当にありがとうね~。\x01",
"念のために警察に\x01",
"連絡してはみたものの……\x02",
)
)
CloseMessageWindow()
#C0379
ChrTalk(
0xF,
(
"#11Pクロスベルの警察って\x01",
"対応が悪いって聞いてたし。\x02",
)
)
CloseMessageWindow()
#C0380
ChrTalk(
0xF,
(
"#11Pまさか対応してもらえるとは\x01",
"思ってなかったよ~。\x02",
)
)
CloseMessageWindow()
OP_63(0x0, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x1, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x2, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
OP_63(0x3, 0x0, 2000, 0x10, 0x13, 0xFA, 0x1)
Sound(23, 0, 100, 0)
Sleep(1200)
#C0381
ChrTalk(
0x101,
"#12P#0012Fそ、そうですか……\x02",
)
CloseMessageWindow()
#C0382
ChrTalk(
0x104,
(
"#0306F何となく特務支援課って場所の\x01",
"意義が判ってきた気がするなぁ。\x02",
)
)
CloseMessageWindow()
#C0383
ChrTalk(
0x102,
(
"#5P#0100Fまあいいじゃない、\x01",
"1人の人を助けたわけだし。\x02\x03",
"これで依頼達成よね。\x02",
)
)
CloseMessageWindow()
FadeToDark(300, 0, 100)
Sound(9, 0, 100, 0)
SetMessageWindowPos(-1, -1, -1, -1)
SetChrName("")
#A0384
AnonymousTalk(
0xFF,
(
scpstr(SCPSTR_CODE_COLOR, 0x2),
"クエスト【紛失物の捜索願い】\x07\x00",
"を達成した!\x02",
)
)
CloseMessageWindow()
OP_57(0x0)
FadeToBright(300, 0)
SetMessageWindowPos(14, 280, 60, 3)
FadeToDark(1000, 0, -1)
OP_0D()
OP_68(115090, 1500, 58830, 0)
MoveCamera(315, 26, 0, 0)
OP_6E(400, 0)
SetCameraDistance(25000, 0)
SetChrPos(0x0, 115090, 0, 58830, 0)
SetChrPos(0x1, 115090, 0, 58830, 0)
SetChrPos(0x2, 115090, 0, 58830, 0)
SetChrPos(0x3, 115090, 0, 58830, 0)
OP_4C(0xF, 0xFF)
OP_29(0x2, 0x2, 0x1F)
OP_29(0x2, 0x1, 0x5)
OP_29(0x2, 0x4, 0x10)
Sleep(500)
EventEnd(0x5)
Return()
# Function_25_7B37 end
SaveToFile()
Try(main)
|
997,802 | e0fa315f80ff2d25a72f7fcaa3436e4632cb83e7 | import FWCore.ParameterSet.Config as cms
###########################################################
##### Set up process #####
###########################################################
process = cms.Process ('ANA2')
process.load ('FWCore.MessageService.MessageLogger_cfi')
process.MessageLogger.cerr.FwkReport.reportEvery = 1
process.maxEvents = cms.untracked.PSet (
input = cms.untracked.int32 (-1)
)
process.source = cms.Source ("PoolSource",
fileNames = cms.untracked.vstring (
"file:/data/users/hart/weirdData/weirdMuons.root",
),
)
process.TFileService = cms.Service ('TFileService',
fileName = cms.string ('dEdx.root')
)
###########################################################
##### Set up the producer and the end path #####
###########################################################
process.dEdxAnalyzer = cms.EDAnalyzer ("DEdxAnalyzer",
tracks = cms.InputTag ("generalTracks", ""),
electrons = cms.InputTag ("gedGsfElectrons", ""),
muons = cms.InputTag ("muons", ""),
dEdxPixel = cms.InputTag ("dedxPixelHarmonic2", ""),
dEdxStrip = cms.InputTag ("dedxHarmonic2", ""),
minPt = cms.double (55.0),
minNMissOut = cms.int32(-1),
requiredNumLayers = cms.int32 (-1),
vetoElectronsOrMuons = cms.string ("both")
)
process.myPath = cms.Path (process.dEdxAnalyzer)
|
997,803 | bd1d5bc65ceac832c78a24bc253a01f7e918a435 | from django.db import models
from django.core.validators import MaxValueValidator
# Create your models here.
class Semester(models.Model):
sem = (
('1st Semester', '1st Semester'),
('2nd Semester', '2nd Semester'),
('3rd Semester', '3rd Semester'),
('4th Semester', '4th Semester'),
('5th Semester', '5th Semester'),
('6th Semester', '6th Semester'),
('7th Semester', '7th Semester'),
('8th Semester', '8th Semester')
)
student_semester = models.CharField(max_length=15, choices=sem,unique=True)
def __str__(self):
return self.student_semester
class Informations(models.Model):
department = (
('CSE', 'CSE'),
('ECE', 'ECE'),
('BBA', 'BBA')
)
student_roll = models.PositiveIntegerField(default=0)
student_department = models.CharField(max_length=4, choices=department)
class Meta:
unique_together = (('student_roll', 'student_department'),)
def __str__(self):
return self.student_department+', '+self.student_roll.__str__()
class Marks(models.Model):
student_info = models.ForeignKey(Informations, on_delete=models.CASCADE)
all_semester = models.ForeignKey(Semester, on_delete=models.CASCADE)
subject_name = models.CharField(max_length=50)
subject_marks = models.PositiveIntegerField(default=0,validators=[MaxValueValidator(100)])
assignment_marks = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(5)])
midterm_marks = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(10)])
class_test_marks = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(5)])
class Meta(object):
unique_together = (('student_info','subject_name'),)
ordering = ['all_semester']
def __str__(self):
return self.subject_name+', '+self.subject_marks.__str__()+', '+self.assignment_marks.__str__()+', '+self.midterm_marks.__str__()+', '+self.class_test_marks.__str__()+', '+self.student_info.student_roll.__str__()+', '+self.all_semester.student_semester+', '+self.student_info.student_department
|
997,804 | c52a38da78bfc9cef3e57ee949be2c2201ad291d | from typing import NamedTuple
class VGATiming(NamedTuple):
x: int
y: int
refresh_rate: float
pixel_freq: int
h_front_porch: int
h_sync_pulse: int
h_back_porch: int
v_front_porch: int
v_sync_pulse: int
v_back_porch: int
vga_timings = {
'640x350@70Hz': VGATiming(
x = 640,
y = 350,
refresh_rate = 70.0,
pixel_freq = 25_175_000,
h_front_porch = 16,
h_sync_pulse = 96,
h_back_porch = 48,
v_front_porch = 37,
v_sync_pulse = 2,
v_back_porch = 60),
'640x350@85Hz': VGATiming(
x = 640,
y = 350,
refresh_rate = 85.0,
pixel_freq = 31_500_000,
h_front_porch = 32,
h_sync_pulse = 64,
h_back_porch = 96,
v_front_porch = 32,
v_sync_pulse = 3,
v_back_porch = 60),
'640x400@70Hz': VGATiming(
x = 640,
y = 400,
refresh_rate = 70.0,
pixel_freq = 25_175_000,
h_front_porch = 16,
h_sync_pulse = 96,
h_back_porch = 48,
v_front_porch = 12,
v_sync_pulse = 2,
v_back_porch = 35),
'640x400@85Hz': VGATiming(
x = 640,
y = 400,
refresh_rate = 85.0,
pixel_freq = 31_500_000,
h_front_porch = 32,
h_sync_pulse = 64,
h_back_porch = 96,
v_front_porch = 1,
v_sync_pulse = 3,
v_back_porch = 41),
'640x480@60Hz': VGATiming(
x = 640,
y = 480,
refresh_rate = 60.0,
pixel_freq = 25_175_000,
h_front_porch = 16,
h_sync_pulse = 96,
h_back_porch = 48,
v_front_porch = 10,
v_sync_pulse = 2,
v_back_porch = 33),
'720x400@85Hz': VGATiming(
x = 720,
y = 400,
refresh_rate = 85.0,
pixel_freq = 35_500_000,
h_front_porch = 36,
h_sync_pulse = 72,
h_back_porch = 108,
v_front_porch = 1,
v_sync_pulse = 3,
v_back_porch = 42),
'768x576@60Hz': VGATiming(
x = 758,
y = 576,
refresh_rate = 60.0,
pixel_freq = 34_960_000,
h_front_porch = 24,
h_sync_pulse = 80,
h_back_porch = 104,
v_front_porch = 1,
v_sync_pulse = 3,
v_back_porch = 17),
'768x576@72Hz': VGATiming(
x = 758,
y = 576,
refresh_rate = 72.0,
pixel_freq = 42_930_000,
h_front_porch = 32,
h_sync_pulse = 80,
h_back_porch = 112,
v_front_porch = 1,
v_sync_pulse = 3,
v_back_porch = 21),
'768x576@75Hz': VGATiming(
x = 758,
y = 576,
refresh_rate = 75.0,
pixel_freq = 45_510_000,
h_front_porch = 40,
h_sync_pulse = 80,
h_back_porch = 120,
v_front_porch = 1,
v_sync_pulse = 3,
v_back_porch = 22),
'800x600@60Hz': VGATiming(
x = 800,
y = 600,
refresh_rate = 60.0,
pixel_freq = 40_000_000,
h_front_porch = 40,
h_sync_pulse = 128,
h_back_porch = 88,
v_front_porch = 1,
v_sync_pulse = 4,
v_back_porch = 23),
'848x480@60Hz': VGATiming(
x = 848,
y = 480,
refresh_rate = 60.0,
pixel_freq = 33_750_000,
h_front_porch = 16,
h_sync_pulse = 112,
h_back_porch = 112,
v_front_porch = 6,
v_sync_pulse = 8,
v_back_porch = 23),
'1024x768@60Hz': VGATiming(
x = 1024,
y = 768,
refresh_rate = 60.0,
pixel_freq = 65_000_000,
h_front_porch = 24,
h_sync_pulse = 136,
h_back_porch = 160,
v_front_porch = 3,
v_sync_pulse = 6,
v_back_porch = 29),
'1152x864@60Hz': VGATiming(
x = 1152,
y = 864,
refresh_rate = 60.0,
pixel_freq = 81_620_000,
h_front_porch = 64,
h_sync_pulse = 120,
h_back_porch = 184,
v_front_porch = 1,
v_sync_pulse = 3,
v_back_porch = 27),
'1280x720@60Hz': VGATiming(
x = 1280,
y = 720,
refresh_rate = 60.0,
pixel_freq = 74_250_000,
h_front_porch = 110,
h_sync_pulse = 40,
h_back_porch = 220,
v_front_porch = 5,
v_sync_pulse = 5,
v_back_porch = 20),
'1280x768@60Hz': VGATiming(
x = 1280,
y = 768,
refresh_rate = 60.0,
pixel_freq = 79_500_000,
h_front_porch = 64,
h_sync_pulse = 128,
h_back_porch = 192,
v_front_porch = 3,
v_sync_pulse = 7,
v_back_porch = 20),
'1280x768@60Hz CVT-RB': VGATiming(
x = 1280,
y = 768,
refresh_rate = 60.0,
pixel_freq = 68_250_000,
h_front_porch = 48,
h_sync_pulse = 32,
h_back_porch = 80,
v_front_porch = 3,
v_sync_pulse = 7,
v_back_porch = 12),
'1280x800@60Hz': VGATiming(
x = 1280,
y = 800,
refresh_rate = 60.0,
pixel_freq = 83_500_000,
h_front_porch = 72,
h_sync_pulse = 128,
h_back_porch = 200,
v_front_porch = 3,
v_sync_pulse = 6,
v_back_porch = 22),
'1280x800@60Hz CVT-RB': VGATiming(
x = 1280,
y = 800,
refresh_rate = 60.0,
pixel_freq = 71_000_000,
h_front_porch = 48,
h_sync_pulse = 32,
h_back_porch = 80,
v_front_porch = 3,
v_sync_pulse = 6,
v_back_porch = 14),
'1280x1024@60Hz': VGATiming(
x = 1280,
y = 1024,
refresh_rate = 60.0,
pixel_freq = 108e6,
h_front_porch = 48,
h_sync_pulse = 112,
h_back_porch = 248,
v_front_porch = 1,
v_sync_pulse = 3,
v_back_porch = 38),
'1366x768@60Hz': VGATiming(
x = 1366,
y = 768,
refresh_rate = 60.0,
pixel_freq = 85_500_000,
h_front_porch = 70,
h_sync_pulse = 143,
h_back_porch = 213,
v_front_porch = 3,
v_sync_pulse = 3,
v_back_porch = 24),
'1920x1080@30Hz': VGATiming(
x = 1920,
y = 1080,
refresh_rate = 30.0,
pixel_freq = 148_500_000//2,
h_front_porch = 88,
h_sync_pulse = 44,
h_back_porch = 148,
v_front_porch = 4,
v_sync_pulse = 5,
v_back_porch = 36),
'1920x1080@30Hz CVT-RB': VGATiming(
x = 1920,
y = 1080,
refresh_rate = 30.0,
pixel_freq = 73_000_000,
h_front_porch = 48,
h_sync_pulse = 32,
h_back_porch = 80,
v_front_porch = 3,
v_sync_pulse = 5,
v_back_porch = 9),
'1920x1080@30Hz CVT-RB2': VGATiming(
x = 1920,
y = 1080,
refresh_rate = 30.0,
pixel_freq = 70_208_000,
h_front_porch = 8,
h_sync_pulse = 32,
h_back_porch = 40,
v_front_porch = 3,
v_sync_pulse = 8,
v_back_porch = 6),
'1920x1080@60Hz': VGATiming(
x = 1920,
y = 1080,
refresh_rate = 60.0,
pixel_freq = 148_500_000,
h_front_porch = 88,
h_sync_pulse = 44,
h_back_porch = 148,
v_front_porch = 4,
v_sync_pulse = 5,
v_back_porch = 36),
}
|
997,805 | 3ca71fb72777a91b07f6bbb77d2a1db9216ca317 | import requests
import os, shutil
import json
import jsonpath
# 导入requests_toolbelt库使用MultipartEncoder
from requests_toolbelt import MultipartEncoder
url = "http://shibietu.wwei.cn/fileupload.html?op=shibietu_zhiwu"
headers = {
"Content-Type":"multipart/form-data",
"Referer":"http://shibietu.wwei.cn/zhiwu.html",
"Origin":"http://shibietu.wwei.cn",
"Host":"shibietu.wwei.cn",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763",
"Connection":"Keep-Alive"}
if __name__=='__main__':
work_dir = input('输入图片所在的文件夹名称\n')
print('遍历整个文件夹\n')
for parent, dirnames, filenames in os.walk(work_dir, followlinks=True):
for filename in filenames:
fr=open('result.txt','a',encoding='utf-8')
file_path = os.path.join(parent, filename)
fr.write('文件名:%s\n' % filename)
print('文件名:%s' % filename)
#print('文件完整路径:%s\n' % file_path)
files = {'file':(filename,open(file_path,'rb'),'image/png',{})}
m=MultipartEncoder(files)
# 自动生成Content-Type类型和随机码
headers['Content-Type'] = m.content_type
print(m.content_type)
# 使用data上传文件
html = requests.post(url, headers=headers, data=m)
fw =open('data.json','w',encoding='utf-8')
json.dump(html.json(),fw,ensure_ascii=False,indent=4)#字典转成json,字典转换成字符串
data=json.loads(json.dumps(html.json()))
fr.write("植物名 可能性\n")
print("植物名 可能性")
for v in data['data']['result']:
print("%s;%s"%(v['name'],v['score']))
fr.write("%s;%s\n"%(v['name'],v['score']))
fr.write("\n")
print("\n")
#print(html.json()) |
997,806 | 9f836525c5e6bb7d4c0cde388131e8ccac84200e | '''
Description: Copyright © 1999 - 2021 Winter. All Rights Reserved.
Author: Winter
Email: 837950571@qq.com
Date: 2021-04-16 15:15:43
LastEditTime: 2021-04-16 19:15:00
'''
import functools
from flask import jsonify, request
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from config import AUTH_SECRET_KEY
def login_required(view_func):
@functools.wraps(view_func)
def verify_token(*args,**kwargs):
try:
#在请求头上拿到token
token = request.headers["token"]
except Exception:
#没接收的到token,给前端抛出错误
#这里的code推荐写一个文件统一管理。这里为了看着直观就先写死了。
print("没接收的到token")
return jsonify(code = 4103,msg = '缺少参数token')
s = Serializer(AUTH_SECRET_KEY)
try:
s.loads(token)
except Exception:
print("登录已过期")
return jsonify(code = 4101,msg = "登录已过期")
return view_func(*args,**kwargs)
return verify_token
|
997,807 | 91882be31c763859496a74cb5fc559006833a83a |
# This array shows the index positions, and category types/names, of our different kinds of ingredients in a recipe
KINDS = ["sugar", "flour", "salt", "butter", "baking powder", "milk", "egg", "vanilla", "chips", "baking soda", "other"]
'''
The recipe class reperesents a recipe which contains a name and a list of ingredient. It has string
representation method, and check_for_ingredients method. Check_for_ingrediens checks if an ingredient
type is in the recipe
'''
class Recipe(object):
def __init__(self, name, ingredient_arr):
self.name = name #name of recipe string
self.ingredient_arr = ingredient_arr #array of ingredients
'''
check_for_ingredients iterates through all the ingredients and returns true if the input string matches
any of the names of the ingredients and false otherwise.
'''
def check_for_ingredient(self, name):
for ingredient in self.ingredient_arr:
if name == ingredient.name:
return True
return False
'''
This string funtion returns the name of the recipe and the ingredients that are in that racipe. Iterates
through all ingredients to print their name and quantity.
'''
def __str__(self):
# allows you to use print(Recipe)
final_string = self.name + " contains the ingredients below:" + "\n"
for ingredient in self.ingredient_arr:
str_to_add = str(ingredient.quantity) + " oz of " + ingredient.name + "\n"
final_string += str_to_add
return final_string
'''
Overridden __repr__ method that returns the object representation in string format
'''
def __repr__(self):
final_string = ''
final_string += "Recipe('" + self.name + "', ["
for ingredient in self.ingredient_arr:
final_string += ingredient.__repr__()
final_string += ", "
final_string += "])"
print(final_string)
'''
Ingredient class represents ingredients in a recipe. An Ingredient has a name, quanity and kind, as well as
two setter methods
'''
class Ingredient(object):
def __init__(self, name, quantity):
self.name = name # string
self.quantity = quantity # float
self.kind = get_kind(name) # string
'''
Sets the quantity of the Ingredient
'''
def set_quantity(self, amount):
self.quantity = amount
'''
Sets the name of the Ingredient
'''
def set_name(self, name):
self.name = name
self.kind = get_kind(name)
'''
Overridden __str__method that allows you to use print(Ingredient)
'''
def __str__(self):
return str(self.quantity) + " oz of " + self.name
'''
Overridden __repr__ method that returns the object representation in string format
'''
def __repr__(self):
return "Ingredient('" + self.name + "', " + str(self.quantity) + ")"
'''Helper Function to assign ingredient kinds from names. There are edge cases that
we have added in the form of extra if statements.
Params:
@string name: name of ingredient
Return:
String --> more general type of ingredient
'''
def get_kind(name):
if "sugar" in name:
if "refrigerated" not in name:
return "sugar"
if "flour" in name:
return "flour"
if "salt" in name and "salted" not in name:
return "salt"
if "butter" in name:
if "butterscotch" not in name and "buttermilk" not in name and "peanut" not in name: #exclude edge case
return "butter"
if "baking powder" in name:
return "baking powder"
if "milk" in name:
if "chocolate" not in name: #exclude edge case
return "milk"
if "egg" in name:
return "egg"
if "vanilla" in name:
if "french" not in name or "French" not in name: #exclude edge case
return "vanilla"
if "chips" in name:
return "chips"
if "baking soda" in name:
return "baking soda"
else:
return "other"
|
997,808 | 9a7392bdb67e676a824edf1c99c0745e5ef0a49d | # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from csdn.items import CsdnItem
from scrapy.selector import Selector
class CsdnaSpider(CrawlSpider):
name = 'csdna'
allowed_domains = ['blog.csdn.net']
start_urls = ['http://blog.csdn.net/peihaozhu/article/list/1',]
rules = (
Rule(LinkExtractor(allow=r'/peihaozhu/article/list/\d+'), callback='parse_item', follow=True),
)
def parse_item(self, response):
sel = response.selector
posts = sel.xpath('//*[@id="article_list"]/div[@class="list_item article_item"]')
items = []
for p in posts:
item = CsdnItem()
item['title'] = p.xpath('.//span[@class="link_title"]/a/text()').extract_first()
item['pdate'] = p.xpath('.//span[@class="link_postdate"]/text()').extract_first()
item['url'] = response.url
item['description'] = p.xpath('.//*[@class="article_description"]/text()').extract_first()
items.append(item)
return items
|
997,809 | 8b4e76e6ca1332612bea16c0a2e2d0e4f99ee6c4 | #!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
from requests_futures.sessions import FuturesSession
from concurrent.futures import wait
import requests
import re
import os
import sys
if(len(sys.argv)>1):
n = int(sys.argv[1])
if(len(sys.argv)>2):
p = True
else:
p = False
else:
n = 9
p = False
session = FuturesSession(max_workers=100)
def main(sess, resp):
match = re.search(r'file:\"([^\"]+m3u8[^\"]+)\"', resp.text)
if(match):
src = match.group(1)
#print(src)
r = requests.get(src)
if(r.status_code == requests.codes.ok and r.headers['Content-Type'] < 'applications'):
if(p):
print(src)
else:
os.system('open -a Safari ' + src)
# get html sources
futures = [
session.get('http://widestream.io/embed-' + str(num), background_callback=main)
for num in range(1000*n, 1000*(n+1))
]
done, incomplete = wait(futures)
|
997,810 | 0f8cfcf3dd662ef53cb8d5fe087f69a8717b5836 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/15 18:27
# @Author : AsiHacker
# @File : __class__.py
# @Software: PyCharm
# @notice : True masters always have the heart of an apprentice.
from python笔记.aaa基础内置.类相关.抽象类定义 import C
obj = C()
print(obj.__module__) # 输出 lib.aa,即:输出模块
print(obj.__class__) # 输出 lib.aa.C,即:输出类
|
997,811 | 8958e3d28b6ff72f7da04c9172a6ecdfa4ef0abd | import numpy as np
import cv2
import imutils
import sys
import pytesseract
import pandas as pd
import time
import pymysql.cursors
from PIL import Image
from pyzbar.pyzbar import decode
print(cv2.__version__)
image = cv2.imread('cartest18.jpg')
image = imutils.resize(image, width=500)
# * . : )
cv2.imshow("Original Image", image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
edged = cv2.Canny(gray, 170, 200)
cv2.imshow("bilateral filter",gray)
(new, cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts=sorted(cnts, key = cv2.contourArea, reverse = True)[:30]
NumberPlateCnt = None
count = 0
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx) == 4:
NumberPlateCnt = approx
break
mask = np.zeros(gray.shape,np.uint8)
new_image = cv2.drawContours(mask,[NumberPlateCnt],0,255,-1)
new_image = cv2.bitwise_and(image,image,mask=mask)
cv2.namedWindow("Final_image",cv2.WINDOW_NORMAL)
cv2.imshow("Final_image",new_image)
config = ('-l eng --oem 1 --psm 3')
text = pytesseract.image_to_string(new_image, config=config)
raw_data = {'date': [time.asctime( time.localtime(time.time()) )],
'v_number': [text]}
df = pd.DataFrame(raw_data, columns = ['date', 'v_number'])
df.to_csv('data.csv')
text=text.replace(" ","")
text=text.replace("-","")
text=text.replace(".","")
text=text.replace("*","")
text=text.replace(":","")
text=text.replace(")","")
text=text.replace("}","")
print('Number plate detected : ',text)
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='mysql',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT count(*) FROM empvehiclerecord WHERE vehicleno= %s"
mum= cursor.execute(sql, (text,))
result = cursor.fetchone()
#print('result',result)
for i in result:
b=result[i]
if b==0 :
#print("Valid Employee open the gate")
sql1 = "SELECT count(*) FROM empvehiclerecord WHERE alternatevehicle= %s"
mum1 = cursor.execute(sql1, (text,))
result1 = cursor.fetchone()
#print('result', result1)
for i in result1:
b1 = result[i]
if b1>0:
print("valid emp open the gate")
else:
print("scan your id")
cap = cv2.VideoCapture(0)
while (True):
ret, frame = cap.read()
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
# eturn_value, image = camera.read()
cv2.imwrite('opencv' + str(1) + '.png', frame)
break
cap.release()
cv2.destroyAllWindows()
data = decode(Image.open('opencv1.png'))
print(data)
a = ''.join(map(str, data))
empid = a[15:16]
print('scanned emp id is',empid)
sql = "SELECT count(*) FROM empvehiclerecord WHERE empid= %s"
mum = cursor.execute(sql, (empid,))
result = cursor.fetchone()
#print('result', result)
for i in result:
b3= result[i]
print(b3)
if b3>0:
print("valid employee open the gate \n alternate vehicle registered")
sql2 = "UPDATE empvehiclerecord SET alternatevehicle = %s WHERE empid = %s"
cursor.execute(sql2,(text,empid))
else:
print("Invaild Id.. Entry Restricted")
elif b>0:
print("vaild emp open the gate")
else:
print("Vehicle Not Registered")
finally:
connection.close()
cv2.waitKey(0)
|
997,812 | af03b14a6eea12a89e1c926764d4bd5894e01c29 | import os
import unittest
import datetime
import tempfile
from cStringIO import StringIO
from mock import Mock, sentinel, call, patch
from stock_pricer import StockPricer
from util import Money
from invest import *
stock1 = Stock('SYM1', 'bond')
stock2 = Stock('SYM2', 'bond')
stock3 = Stock('SYM3', 'world')
stock4 = Stock('SYM4', 'emerging')
class FakePricer(StockPricer):
def __init__(self):
self.price_dict = {stock1: Money(4), stock2: Money(10), stock3: Money(3),
stock4: Money(7)}
def get_price(self, stock):
return self.price_dict[stock]
def get_name(self, stock):
return stock.symbol
class TestCaseWithPortfolio(unittest.TestCase):
def setUp(self):
self.pricer = FakePricer()
StockPricer.set_pricer(self.pricer)
self.portfolio = Portfolio()
self.portfolio.add_stock(stock1, 10)
self.portfolio.add_stock(stock2, 2)
self.portfolio.add_stock(stock3, 100)
self.target_allocation = Allocation({'bond': 20, 'world': 70, 'emerging': 10})
self.available_stocks = [stock2, stock3, stock4]
class AcceptanceTest(unittest.TestCase):
def setUp(self):
StockPricer.set_pricer(FakePricer())
handle, self.portfolio_path = tempfile.mkstemp()
open(self.portfolio_path, 'w').write('''[portfolio]
SYM1=10
SYM2=2
SYM3=100
[target_allocation]
bond=20
world=70
emerging=10
[SYM1]
asset_class=bond
available=no
[SYM2]
asset_class=bond
available=yes
[SYM3]
asset_class=world
available=yes
[SYM4]
asset_class=emerging
available=yes''')
self.expected_portfolio = Portfolio()
self.expected_portfolio.add_stock(stock1, 10)
self.expected_portfolio.add_stock(stock2, 4)
self.expected_portfolio.add_stock(stock3, 100)
self.expected_portfolio.add_stock(stock4, 4)
def tearDown(self):
os.remove(self.portfolio_path)
def test_saved_portfolio(self):
portfolio, target_allocation, available_stocks = read_invest_file(open(self.portfolio_path))
new_portfolio, money_remaining = main(portfolio, target_allocation, available_stocks, Money(50))
self.assertEqual(self.expected_portfolio, new_portfolio)
self.assertEqual(Money(2), money_remaining)
class MainTest(TestCaseWithPortfolio):
def setUp(self):
super(MainTest, self).setUp()
self.new_portfolio, self.money_remaining = main(
self.portfolio, self.target_allocation, self.available_stocks, Money(50))
def test_returned_portfolio(self):
expected_portfolio = Portfolio()
expected_portfolio.add_stock(stock1, 10)
expected_portfolio.add_stock(stock2, 4)
expected_portfolio.add_stock(stock3, 100)
expected_portfolio.add_stock(stock4, 4)
self.assertEqual(expected_portfolio, self.new_portfolio)
def test_remaining_money(self):
self.assertEqual(Money(2), self.money_remaining)
class GetNextBuysTest(TestCaseWithPortfolio):
def test(self):
portfolio = Portfolio()
portfolio.add_stock(stock1, 10)
portfolio.add_stock(stock2, 2)
portfolio.add_stock(stock3, 100)
target_allocation = Allocation({'bond': 20, 'world': 70, 'emerging': 10})
available_stocks = [stock2, stock3, stock4]
buys, new_portfolio, money_remaining = get_next_buys(
portfolio, target_allocation, available_stocks, Money(50), self.pricer)
self.assertItemsEqual([Buy(stock2, 2), Buy(stock4, 4)], buys)
self.assertEqual(Money(2), money_remaining)
class ReadInvestFileTest(unittest.TestCase):
def setUp(self):
invest_file = StringIO('''[portfolio]
SYM1=2
SYM3=10
[target_allocation]
bond=30
world=70
[SYM1]
asset_class=bond
available=yes
[SYM2]
asset_class=bond
available=yes
[SYM3]
asset_class=world
available=no''')
self.portfolio, self.target_allocation, self.available_stocks = read_invest_file(invest_file)
def test_portfolio(self):
expected_portfolio = Portfolio()
expected_portfolio.add_stock(stock1, 2)
expected_portfolio.add_stock(stock3, 10)
self.assertEqual(expected_portfolio, self.portfolio)
def test_target_allocation(self):
self.assertEqual(Allocation({'bond': 30, 'world': 70}), self.target_allocation)
def test_available_stocks(self):
expected = [Stock('SYM1', 'bond'), Stock('SYM2', 'bond')]
self.assertItemsEqual(expected, self.available_stocks)
if __name__ == '__main__':
unittest.main()
|
997,813 | 138ef47f7ff9579a1d622907ddff5869e7fda458 | #Author:Zhao fei
file1="j1226_1"
file="./data/j12.mm/"+file1+".mm"
print(file) |
997,814 | 86b33b7e7c31e15694ad5fe25c763815dccfea0c | import pandas as pd
def import_data_from_files(tickers, path):
df_list = []
sym_list = []
for ticker in tickers:
file = path + '/' + ticker + '.csv'
df = pd.read_csv(file, index_col=0)
df.index = pd.to_datetime(df.index)
df_list.append(df)
sym_list.append(ticker)
# print('Retreived all data from files')
return df_list, sym_list
|
997,815 | 138cc6c4f36c5de0804b5eec68d428be534359e8 | import sqlite3
from bottle import *
import api.users
import api.messages
class ConnectionHandler():
def __init__(self, loc='main.db'):
self.connection = sqlite3.connect(loc)
self.semaphore = threading.Semaphore()
def get(self):
self.semaphore.acquire()
return self.connection
def release(self):
self.semaphore.release()
connHandler = ConnectionHandler()
userHandler = api.users.UserHandler(connHandler)
#VIEWS#
@route('/')
def homepage():
return static_file('home.html',root='views')
#Public-API#
@route('/usersubmit', method = 'POST')
def registerUser():
fullname = request.forms.get('fullname')
username = request.forms.get('username')
password = request.forms.get('password')
userHandler.create(username,password,fullname)
@route('/newuser')
def newuserPage():
return static_file('newuser.html', root='')
run(host='localhost', port=8080)
|
997,816 | 21f3944325c09b4a4ac989d260111e0c60258a0f | import time
import math
from selenium import webdriver
from selenium.webdriver.support.ui import Select
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
try:
link = "http://suninjuly.github.io/selects1.html"
new_link = "http://suninjuly.github.io/selects2.html"
browser = webdriver.Chrome()
browser.get(new_link)
num1 = browser.find_element_by_id("num1")
num2 = browser.find_element_by_id("num2")
summ = int(num1.text) + int(num2.text)
select = Select(browser.find_element_by_id("dropdown"))
select.select_by_value(str(summ))
# Отправляем заполненную форму
button = browser.find_element_by_css_selector("button.btn")
button.click()
# Печать "Passed", если тест прошел успешно
print("--- PASSED ---")
# Печать "Failed" и ошибки, если тест провален
except Exception as ex:
print("--- FAILED ---")
print(ex)
finally:
# ожидание чтобы визуально оценить результаты прохождения скрипта
time.sleep(10)
# закрываем браузер после всех манипуляций
browser.quit()
|
997,817 | 16b5b71ef98c3b3d307447f9b9e664b04a05af73 | class Solution:
def maximumNumberOfOnes(self, width: int, height: int, sideLength: int, maxOnes: int) -> int:
count = [[0] * width for _ in range(height)]
for r in range(height - sideLength + 1):
for c in range(width - sideLength + 1):
for ro in range(sideLength):
for co in range(sideLength):
count[r + ro][c + co] += 1
print(count)
sol = Solution()
width = 100
height = 100
sideLength = 2
maxOnes = 2
sol.maximumNumberOfOnes(width, height, sideLength, maxOnes)
|
997,818 | 6e83992271b476298b92fb62aeceffc09f72dba1 | import calendar
import concurrent
import datetime
import time
from concurrent.futures.thread import ThreadPoolExecutor
from QUANTAXIS import QA_util_code_tolist, QA_util_time_stamp, QA_util_log_info, QA_util_to_datetime, \
QA_util_datetime_to_strdate
from dateutil.relativedelta import relativedelta
import tushare as ts
import numpy as np
import pandas as pd
import pymongo
import QUANTAXIS as QA
import asyncio
# pd全局设置
pd.set_option('display.max_rows', 5000)
pd.set_option('display.max_columns', 100)
pd.set_option('display.width', 300)
# tushare 账户设置
ts.set_token('d79c15feb3718d16953d1524f8076a076a33f55efb9eafa0d5484310')
pro = ts.pro_api()
# 本地mongodb连接
mydbclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = mydbclient['mt']
def get_month_trade_date(start,end):
'''
从tushare获取交易日历
@param start:
@param end:
@return: lsit 类型的交易日期
'''
stock_trade_date = pro.trade_cal(exchange='', start_date=start, end_date=end)
stock_trade_date_month = stock_trade_date[stock_trade_date["is_open"] == 1]
stock_trade_date_month['cal_date'] = stock_trade_date_month['cal_date'].apply(lambda x : pd.to_datetime(x, format='%Y%m%d'))
stock_trade_date_month.index = stock_trade_date_month['cal_date']
dfg = stock_trade_date_month.resample('M')
business_end_day = dfg.apply({'cal_date': np.min})
return business_end_day["cal_date"].reset_index(drop=True).tolist()
tread_date_df = pd.DataFrame()
def get_starttm_trade_date_by_count(count,end_date):
'''
根据输入的count获取指定日期end_tm之前的日期
@param count: 输入的指定数量
@param end_tm: 输入的指定日期
@return: df
'''
global tread_date_df
if tread_date_df.empty:
today = datetime.date.today().strftime("%Y%m%d")
tread_date_df = pro.trade_cal(exchange='', start_date='19930101', end_date=today)
tread_date_df = tread_date_df[tread_date_df['is_open'] == 1]
tread_date_df['index'] = range(tread_date_df.shape[0])
tread_date_df.set_index('index',inplace=True)
print("给交易日期赋值")
end_date = end_date.strftime("%Y%m%d")
end_tm_index = tread_date_df[tread_date_df['cal_date'] == end_date].index.values[0]
start_date = tread_date_df.iloc[end_tm_index - count]['cal_date']
start_date = datetime.datetime.strptime(start_date, '%Y%m%d')
return start_date
def stock_data_add_ind(func,date,stock_day_data,res_adv):
'''
通过输入数据,计算参数
用于选股银子比如pe等的计算
@param func:apply中应用的方法
@param date:日期,用来选择stock日线数据
@param stock_day_data:股票日线数据
@param res_adv:选股用的金融数据
@return:返回通过func 计算的某个因子
'''
if func is None:
raise RuntimeError('func is None')
if stock_day_data is None:
raise RuntimeError('stock_day_data is None')
if date is None:
raise RuntimeError('date is None')
try:
result = stock_day_data.data.xs(date,level=0).apply(func,axis=1,args=(date,res_adv,))
except:
result = stock_day_data.xs(date,level=0).apply(func,axis=1,args=(date,res_adv,))
return result
def func_map_pe(x, date, res_adv):
try:
# date = datetime.datetime.strptime(date, '%Y-%m-%d')
last_year_final_day = datetime.date(year=date.year - 1, month=12, day=31)
result = x['close'] / res_adv.data['EPS'].xs(x.name, level=1).loc[last_year_final_day]
return result
except Exception :
print('Exception')
return 0
def func_map_pb(x,date,res_adv):
try:
# date = datetime.datetime.strptime(date, '%Y-%m-%d')
last_year_final_day = datetime.date(year=date.year - 1, month=12, day=31)
result = x['close'] / res_adv.data['netAssetsPerShare'].xs(x.name, level=1).loc[last_year_final_day]
return result
except Exception:
print('Exception')
return 0
def func_map_marketcap(x,date,res_adv):
try:
# date = datetime.datetime.strptime(date, '%Y-%m-%d')
last_year_final_day = datetime.date(year=date.year - 1, month=12, day=31)
result = x['close'] * res_adv.data['totalCapital'].xs(x.name, level=1).loc[last_year_final_day]
return result
except Exception:
print('Exception')
return 0
def func_map_ROIC(x,date,res_adv):
try:
last_quarter_final_day = date - pd.tseries.offsets.QuarterEnd()
result = res_adv.data['rateOfReturnOnInvestmentIncome'].xs(x.name, level=1).loc[last_quarter_final_day]
return result
except Exception:
print('Exception')
return 0
def func_map_NPGR(x,date,res_adv):
try:
last_quarter_final_day = date - pd.tseries.offsets.QuarterEnd()
result = res_adv.data['netProfitGrowthRate'].xs(x.name, level=1).loc[last_quarter_final_day]
return result
except Exception:
print('Exception')
return 0
def func_map_ORS(x,date,res_adv):
try:
last_quarter_final_day = date - pd.tseries.offsets.QuarterEnd()
result = res_adv.data['operatingRevenueSingle'].xs(x.name, level=1).loc[last_quarter_final_day]
return result
except Exception:
print('Exception')
return 0
def select_stocklist(factors_data,stock_counts):
"""
首先处理NaN值情况.选股时的日线数据不能是复权的数据,否则计算的pe等值是不正确的
打分的具体步骤、返回股票池
因子升序从小到大分10组,第几组为所在组得分
市值-market_cap、市盈率-pe_ratio、市净率-pb_ratio
因子降序从大到小分10组,第几组为所在组得分
ROIC-return_on_invested_capital、inc_revenue-营业总收入 和inc_profit_before_tax-利润增长率
@param stock_counts: 排名前多少个
@param factors_data:
@return:
"""
factors_data.to_csv('factor.csv', mode='a')
# 循环每个因子去处理
factors_data = factors_data.dropna(axis=0,how='all')
sort_up = ['market_cap', 'pe_ratio', 'pb_ratio']
for name in factors_data.columns:
if name in sort_up:
factor = factors_data.sort_values(by=name)[name]
else:
factor = factors_data.sort_values(by=name, ascending=False)[name]
factor = pd.DataFrame(factor)
factor[name + '_score'] = 0
# 进行打分
# 先求出每组数量,然后根据数量一次给出分数
stock_groupnum = len(factors_data) // 10
for i in range(10):
if i == 9:
factor.loc[(i + 1) * stock_groupnum:,name + '_score'] = i + 1
factor.loc[i * stock_groupnum: (i + 1) * stock_groupnum,name + '_score'] = i + 1
factors_data = pd.concat([factors_data, factor[name + '_score']], axis=1,sort=False)
all_score = factors_data[
['marketcap_score', 'pe_score', 'pb_score', 'roic_score', 'ors_score',
'npgr_score']].sum(1).sort_values()
# tem_df = pd.DataFrame([factors_data])
# tem_df["date"] = str(self.running_time)[:10]
factors_data.to_csv('all_score.csv', mode='a')
hold_list = all_score.index[:stock_counts].tolist()
return hold_list
def cal_market_value(positions):
'''
计算账户市值。要计算资产需要加上cash
@param positions: 传入的是模拟账户的position。比如self.acc.positions
@return: 市值
'''
cost_value = 0
profit_value = 0
for key in positions:
cost_value += positions[key].position_cost_long
profit_value += positions[key].position_profit_long
# if positions[key].open_cost_long + positions[key].position_profit_long > 0:
# print("code is :%s , market_value is :%s" %(key,positions[key].open_cost_long + positions[key].position_profit_long))
return cost_value + profit_value
def cal_buy_volume(money,comissions_coeff,price):
'''
计算可以购买的手数
每手100股
交易佣金最少5元
@param money: 购买股票的资金
@param comissions_coeff: 交易佣金费率
@param price: 股票价格
@return: 可以购买手数
'''
volume = money / (price * (1 + comissions_coeff))
volume = int(volume / 100) * 100
# 交易佣金最少5元
if volume * comissions_coeff * price < 5:
volume = (money - 5) / price
volume = int(volume / 100) * 100
return volume
# return money * ( 1 - comissions_coeff) / price
def get_index_code(index,date, suffix=False):
'''
获取指数权重股
MSCI:
CSI:中证指数
SSE:上交所指数
SZSE:深交所指数
CICC:中金所指数
沪深300 : '399300.SZ'
SW:申万指数
@param index: 指数代码,需要加上交易所缩写。比如沪深300 399300.SZ
@param date: 查询日期
@param suffix: 是否包含后缀名
@return: 返回指数list
'''
date = datetime.datetime.strptime(date, '%Y-%m-%d')
monthRange = calendar.monthrange(date.year, date.month)[1]
firstDay = datetime.date(year=date.year, month=date.month, day=1).strftime("%Y%m%d")
lastDay = datetime.date(year=date.year, month=date.month, day=monthRange).strftime("%Y%m%d")
df = pro.index_weight(index_code=index, start_date=firstDay, end_date=lastDay)
if suffix:
code_list = df['con_code'].to_list()
else:
# 只保留股票代码,不保留小数点后的英文字母
# df['con_code'].apply(lambda x:re.sub('\..+','',x),axis=1)
code_list = df['con_code'].apply(lambda x:x.split('.')[0]).to_list()
return code_list
def result_analysis_stock_profit(positions):
'''
分析回测结果,包括各股票的profit、持仓时间、交易次数
@param position: 账户的positions
@return: df
'''
result_df = pd.DataFrame(columns=['code','profit'])
cost_value = 0
profit_value = 0
for key in positions:
profit_value += positions[key].position_profit_long
result_df = result_df.append({'code':key,'profit':profit_value},ignore_index=True)
result_df = result_df.sort_values(by='profit', ascending=False)
result_df.to_excel("profit.xls")
return result_df
def test_repeat():
'''
测试沪深300权重股票的变化
@return:
'''
begin = datetime.date(2010, 6, 1)
end = datetime.date(2019, 6, 7)
day = begin
code_list_last = []
while(day < end):
day += relativedelta(months=+1)
print(day)
code_list = get_index_code('399300.SZ', day.strftime("%Y-%m-%d"))
if len(code_list_last) == 0:
code_list_last = code_list
diff_list = set(code_list).difference(set(code_list_last))
if len(diff_list) > 0:
print("交集: ", set(code_list).intersection(set(code_list_last)))
print("新增: ", diff_list)
print("删除: ", set(code_list_last).difference(set(code_list)))
code_list_last = code_list
code_df = pd.DataFrame()
def add_suffix_name(code, rule=1):
'''
给rqalpha添加后缀名,比如000651返回000651.xshe
如果传入的code是包含后缀名的,则直接返回
.xshe:深证 SZ
.xshg:上海 SH
@param code: 股票的string
@return: 返回带有后缀名的string
@param rule: rule=1,则添加后缀名为.XSHE XSHG .
rule=2,则添加后缀名为SZ,SH
'''
global code_df
if code_df.empty:
code_df = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol')
def func(x):
code_str = x['ts_code']
if '.SZ' in code_str:
result = code_str.replace('.SZ', '.XSHE')
elif '.SH' in code_str:
result = code_str.replace('.SH', '.XSHG')
return result
if rule == 1:
code_df['suffix_name'] = code_df.apply(func,axis=1,args=())
elif rule == 2:
code_df['suffix_name'] = code_df['ts_code']
if isinstance(code, list):
code_suffix = code_df.loc[code_df['symbol'].isin(code)]['suffix_name'].to_list()
elif isinstance(code, str):
if ".XSH" in code:
return code
code_suffix = code_df[code_df['symbol'] == code]['suffix_name'].values[0]
return code_suffix
def mt_get_stock_min(code, start, end, frequence='1min', collections=mydb.stock_min):
'获取股票分钟线'
_data = []
code = QA_util_code_tolist(code)
cursor = collections.find({
'code': {'$in': code},
"time_stamp": {"$gte": QA_util_time_stamp(start), "$lte": QA_util_time_stamp(end)},
'type': frequence},
{"_id": 0},
batch_size=10000)
# for item in cursor:
_data = pd.DataFrame([item for item in cursor])
# print(_data)
_data = _data.assign(datetime=pd.to_datetime(_data['datetime']))
_data = _data.set_index('datetime', drop=False)
return _data
def remove_mongodb_duplicate_data():
'''
删除QA数据库中的重复数据
该重复数据是由于通过tick数据生成分钟数据时所产生。(错误操作)
删除代码留下供未来参考
@return:
'''
# 条件删除
QA.DATABASE.stock_min.delete_many({'type': {"$exists": False}})
# 删除结果验证
date = QA.DATABASE.stock_min.find({'type': {"$exists": False}})
for index in date:
print(index)
# stock_list_df = QA.QA_fetch_stock_list_adv()
def mt_download_min_data(code, start_time):
'''
下载指数的分钟线的数据,保存到QA数据库中
不占内存,下载完就保存到数据库
@param start_time: 开始时间
@param code: 指数代码
@return:
'''
if code.isdigit():
print("Pleace input suffix name.")
return
code_front= code.split(".")[0]
code_back = code.split(".")[1]
if 'XSHG' in code_back or 'SH' in code_back:
code_back = 'sh'
elif ('XSHE' in code_back) or ('SZ' in code_back):
code_back = 'sz'
tmp = stock_list_df[(stock_list_df['code'] == code_front) & (stock_list_df['sse'] == code_back)]
if tmp.empty:
# index
mydb = QA.DATABASE.index_min
fetch_1min_func = QA.QA_fetch_index_min_adv
fetch_trans_func = QA.QA_fetch_get_index_transaction
else:
# stock
mydb = QA.DATABASE.stock_min
fetch_1min_func = QA.QA_fetch_stock_min_adv
fetch_trans_func = QA.QA_fetch_get_stock_transaction
code = str(code)[0:6]
for type in ['1min', '5min', '15min', '30min', '60min']:
def save2mongodb(data_1min, type):
data_1min = data_1min.reset_index().set_index('datetime').sort_index()
data = QA.QA_data_min_resample(data_1min, type)
data = data.reset_index()
data = data.assign(time_stamp=data.datetime.apply(QA.QA_util_time_stamp), type=type)
if 'volume' in data.columns:
# QA的内部方法会识别是否包含名称为volume的列,不包含的话就不能获取到值
data.rename(columns={'volume': 'vol'}, inplace=True)
mydb.insert_many(QA.QA_util_to_json_from_pandas(data))
ref_ = mydb.find({'code': str(code)[0:6], 'type': type})
if ref_.count() > 0:
# start_time = ref_[ref_.count() - 1]['datetime']
end_time = ref_[0]['datetime']
print("end_time is :", end_time)
end_time = QA.QA_util_to_datetime(end_time) + datetime.timedelta(days=-1) # 减去一天
end_time = QA.QA_util_datetime_to_strdate(end_time)
print("end_time - 1 is :", end_time)
if start_time >= end_time:
print(print(
"code : %s , type : %s ,start_time is bigger than end_time,check please." % (type, code)))
else:
try:
# 1.先从数据库中取1min数据
data_1min = fetch_1min_func(code, start_time, end_time, frequence='1min').data
except:
end_time = QA.QA_util_to_datetime(end_time)
start_time = QA.QA_util_to_datetime(start_time)
for i in range((end_time - start_time).days + 1):
download_time = end_time - datetime.timedelta(i)
print("download_time :", download_time)
download_time = QA.QA_util_datetime_to_strdate(download_time)
tick_data = fetch_trans_func('tdx', code, download_time, download_time)
if tick_data is not None:
# 2.如果数据为空,则下载并保存到数据库。(此条件仅在1min条件下进入)
data_1min = QA.QA_data_tick_resample_1min(tick_data, '1min').reset_index()
save2mongodb(data_1min, type)
start_time = QA.QA_util_datetime_to_strdate(start_time)
save2mongodb(data_1min, type)
def cal_father_question():
x = 1
while(True):
x += 1
if ( x % 2 == 1 \
and x % 3 == 0 \
and x % 4 == 1 \
and x % 5 == 1 \
and x % 6 == 3 \
and x % 7 == 0 \
and x % 8 == 1 \
and x % 9 == 0):
print(x)
if x > 100000:
return
if __name__ == '__main__':
cal_father_question()
# df = pro.index_weight(index_code='000016.SH', start_date='20180901', end_date='20180930')
# df = pro.index_basic(market='SSE')
# print(df)
# df = pro.index_weight(index_code='000016.SH', start_date='20190910', end_date='20190920')
# df = pro.index_basic(market='SZSE')
# print(df)
# print(get_index_code('399300.SZ','2019-10-06'))
# test_repeat()
#
# print(get_start_trade_date_by_count(3,'19930201'))
# print('============================')
# mt_download_min_data('000651.XSHE', '2017-01-03')
# # 条件删除
# QA.DATABASE.stock_min.delete_many({'type': {"$in": ['5min', '15min', '30min', '60min']}, 'code': '000651','volume': {"$exists": True}})
# # 删除结果验证
# date = QA.DATABASE.stock_min.find({'type': {"$in": ['5min', '15min', '30min', '60min']}, 'code': '000651','volume': {"$exists": True}})
# for index in date:
# print(index)
# ref_ = QA.DATABASE.stock_day.find({'code': str('000651')[0:6], "date_stamp": {
# "$gte": QA_util_time_stamp('2017-01-03'),
# "$lte": QA_util_time_stamp('2018-01-01')
# }, })
# for index in ref_:
# print(index)
# data = QA.QA_fetch_stock_day_adv('000651',end='2020-01-05')
# # print(data.data)
# tushare_start_date = '2018-01-06'
# end_date = '2018-02-01'
# print(end_date.replace('-', ''))
# df = pro.adj_factor(ts_code='000651.SZ', start_date=tushare_start_date.replace('-', ''), end_date=end_date.replace('-', ''))
# print(df)
# code_list = get_index_code('399300.SZ', '2019-10-26')
# print(code_list)
# if '600100' in code_list:
# print('yes')
# mt_get_bars('000001.XSHG')
# def count():
# print("One")
# time.sleep(1)
# print("Two")
# return "over"
#
#
# for _, pos in self._curPos.items():
# if not pos.onOpen(date, self._dataEngine):
# return False
#
# import concurrent.futures as cf
#
# async def async_account_open():
# with cf.ThreadPoolExecutor(max_workers=2) as executor:
# loop = asyncio.get_event_loop()
# futures = (loop.run_in_executor(None, pos.onOpen,date, self._dataEngine ) for _, pos in self._curPos.items())
# for result in await asyncio.gather(*futures):
# if not result:
# return False
#
#
# loop = asyncio.get_event_loop()
# loop.run_until_complete(async_account_open())
#
#
# import concurrent.futures as cf
#
# async def main():
# with cf.ThreadPoolExecutor(max_workers=2) as executor:
# loop = asyncio.get_event_loop()
# futures = (loop.run_in_executor(None, count, ) for i in range(10))
# for result in await asyncio.gather(*futures):
# print(result)
# pass
# ref_ = QA.DATABASE.stock_min.find({'code': str('000651')[0:6], 'type': "1min"})
# for index in ref_:
# print(index)
# a = mt_get_stock_min('000651',("2019-01-03"),("2019-05-01"))
# print(a)
# print(df)
# mt_download_min_data('000651.SZ','2019-01-01')
# df.apply(func,axis=1)
# df = pro.index_weight(index_code='000015.sh', start_date='20200101', end_date='20200201')[:300]
# a = df["con_code"].apply(lambda x: x[:6]).to_list()
# # for i in range(len(a)):
# # a[i] = int(a[i])
# b = str(a)
#
# print(b.replace("'", ""))
# str_list = "603888, 603883, 603877, 603868, 603816, 603806, 603766, 603658, 603589, 603569, 603568, 603556, 603528, 603515, 603444, 603377, 603369, 603355, 603328, 603228, 603225, 603198, 603188, 603169, 603077, 603025, 603019, 603001, 603000, 601969, 601928, 601880, 601811, 601777, 601717, 601699, 601689, 601678, 601311, 601233, 601231, 601200, 601168, 601128, 601127, 601020, 601016, 601002, 601001, 601000, 600996, 600993, 600978, 600971, 600970, 600967, 600939, 600936, 600917, 600908, 600894, 600885, 600884, 600881, 600880, 600879, 600875, 600874, 600872, 600869, 600863, 600862, 600859, 600848, 600839, 600835, 600826, 600823, 600811, 600808, 600801, 600787, 600776, 600773, 600770, 600765, 600759, 600757, 600755, 600754, 600751, 600750, 600748, 600743, 600737, 600729, 600718, 600717, 600694, 600687, 600673, 600664, 600657, 600655, 600651, 600648, 600645, 600643, 600642, 600640, 600639, 600635, 600633, 600628, 600623, 600618, 600614, 600611, 600600, 600598, 600597, 600594, 600587, 600584, 600582, 600580, 600578, 600575, 600572, 600158, 600155, 600151, 600143, 600141, 600138, 600126, 600125, 600122, 600120, 600108, 600098, 600094, 600086, 600079, 600073, 600064, 600062, 600060, 600059, 600058, 600056, 600053, 600039, 600037, 600026, 600022, 600017, 600006, 600004, 300383, 300376, 300324, 300297, 300291, 300287, 300274, 300273, 300266, 300257, 300253, 300244, 300202, 300199, 300197, 300182, 300166, 300159, 300147, 300146, 300134, 300133, 300116, 300115, 300113, 300088, 300058, 300055, 300043, 300039, 300032, 300026, 300010, 300002, 300001, 002818, 002815, 002807, 002745, 002709, 002707, 002701, 002699, 002690, 002681, 002672, 002670, 002665, 002663, 002657, 002642, 002640, 002635, 002603, 002589, 002588, 002583, 002573, 002551, 002544, 002517, 002512, 002506, 002505, 002503, 002491, 002489, 002482, 002479, 002477, 002463, 002444, 002440, 002439, 002437, 002434, 002431, 002428, 002422, 002416, 002414, 002410, 002408, 002407, 002405, 002400, 002392, 002390, 002384, 002375, 002373, 002371, 002368, 002366, 002359, 002358, 002354, 002353, 002345, 002344, 002342, 002340, 002332, 002325, 002317, 002311, 002308, 002299, 002285, 002281, 002280, 002277, 002276, 002273, 002271, 002269, 002268, 002266, 002261, 002254, 002251, 002250, 002249, 002244, 002242, 002233, 002223, 002221, 002195, 002191, 002190, 002183, 002179, 002176, 002155, 002152, 002147, 002131, 002128, 002127, 002123, 002122, 002118, 002106, 002093, 002092, 002078, 002073, 002064, 002063, 002056, 002051, 002050, 002049, 002048, 002041, 002038, 002032, 002030, 002028, 002022, 002019, 002018, 002013, 002011, 002005, 002004, 002002, 002001, 001696, 000999, 000998, 000997, 000990, 000988, 000987, 000981, 000979, 000977, 000975, 000970, 000969, 000960, 000939, 000937, 000930, 000926, 000897, 000887, 000878, 000877, 000860, 000848, 000830, 000829, 000825, 000816, 000807, 000806, 000786, 000778, 000777, 000766, 000762, 000761, 000758, 000732, 000729, 000727, 000718, 000712, 000703, 000690, 000685, 000681, 000680, 000669, 000667, 000662, 000661, 000656, 000652, 000636, 000612, 000600, 000598, 000596, 000592, 000587, 000581, 000572, 000566, 000563, 000552, 000547, 000543, 000541, 000536, 600566, 600565, 600563, 600557, 600545, 600536, 600525, 600521, 600517, 600516, 600511, 600503, 600500, 600499, 600481, 600478, 600466, 600460, 600458, 600438, 600435, 600428, 600426, 600422, 600418, 600416, 600410, 600409, 600395, 600393, 600392, 600388, 600380, 600366, 600348, 600346, 600338, 600335, 600329, 600325, 600317, 600316, 600315, 600312, 600307, 600300, 600298, 600292, 600291, 600289, 600284, 600282, 600280, 600277, 600270, 600267, 600266, 600260, 600259, 600256, 600240, 600216, 600201, 600195, 600187, 600184, 600183, 600179, 600176, 600171, 600169, 600166, 600161, 600160, 000528, 000519, 000513, 000501, 000488, 000426, 000418, 000401, 000400, 000158, 000156, 000099, 000090, 000089, 000078, 000066, 000062, 000061, 000050, 000049, 000039, 000031, 000028, 000027, 000025, 000021, 000012, 000009, 000006"
# print(str_list.replace(" ",""))
# a = QA.QA_fetch_financial_report_adv('000651', '2018-12-01', '2019-12-01')
# print(a.data)
# trade_date = pro.trade_cal(exchange='', start_date='20150101', end_date='20181231')
#
# trade_date = trade_date[trade_date['is_open'] == 1]
#
# for index, row in trade_date['cal_date'].iteritems():
# print("trade date is :",row,"=====================")
# result = pro.daily_basic(trade_date=row)
# print(result)
# result = pro.daily_basic(start_date='20151010' , end_date="20161010")
# print(result)
pass
# {'_id': ObjectId('5e3d619d15dd7f15edc4ae39'), 'datetime': '2017-01-03 10:30:00', 'code': '000651', 'open': 24.7, 'high': 25.22, 'low': 24.7, 'close': 25.03, 'volume': 26236000.0, 'amount': 6559418.6000000015, 'time_stamp': 1483410600.0, 'type': '60min'}
# {'_id': ObjectId('5e3a44bbc3f46294cbcc1e37'), 'open': 61.45, 'close': 61.36, 'high': 61.48, 'low': 60.66, 'vol': 10755300.0, 'amount': 656681984.0, 'datetime': '2020-02-04 14:00:00', 'code': '000651', 'date': '2020-02-04', 'date_stamp': 1580745600.0, 'time_stamp': 1580796000.0, 'type': '60min'}
|
997,819 | 6c2d16e22313666ee3293276fb2f8ffa4850785e | from os import path
import yaml
from kubernetes import client, config
def main():
# Configs can be set in Configuration class directly or using helper
# utility. If no argument provided, the config will be loaded from
# default location.
config.load_kube_config()
body = client.V1Service(
api_version= "v1",
kind= "Service",
metadata=client.V1ObjectMeta(
name= "ws-service",
labels={"app": "ws"}
),
spec=client.V1ServiceSpec(
ports=[client.V1ServicePort(
port=8080,
target_port=8080
)],
selector={"app": "ws"},
type="NodePort"
)
)
k8s_core_v1 = client.CoreV1Api()
resp = k8s_core_v1.create_namespaced_service(
body=body, namespace="default")
print("Service created. status='%s'" % resp.metadata.name)
if __name__ == '__main__':
main()
|
997,820 | a57c6f6bef52c134139108449795b379f0880a81 | from editlive.adaptors.base import BaseAdaptor
class TextAdaptor(BaseAdaptor):
"""The TextAdaptor is used for Text fields.
"""
def __init__(self, *args, **kwargs):
super(TextAdaptor, self).__init__(*args, **kwargs)
if self.form_field:
self.attributes.update({'data-type': 'textField'})
|
997,821 | e68a26e12f59ad8cac2a38bbed4b7481326d949c | # -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from __future__ import print_function as _
from __future__ import division as _
from __future__ import absolute_import as _
import os
import tempfile
import shutil
import unittest
import turicreate
from turicreate.toolkits._main import ToolkitError
from turicreate.toolkits.topic_model import topic_model
from turicreate.toolkits.text_analytics import parse_sparse
from turicreate.toolkits.text_analytics import parse_docword
from turicreate.toolkits.topic_model import perplexity
from . import util as test_util
import time
import random
import numpy as np
import itertools as _itertools
DELTA = 0.0000001
examples = {}
def generate_bar_example(
num_topics=10, num_documents=500, num_words_per_doc=100, alpha=1, beta=1, seed=None
):
"""
Generate the classic "bars" example, a synthetic data set of small
black 5x5 pixel images with a single white bar that is either horizontal
or vertical.
See Steyvers' MATLAB Topic Modeling Toolbox,
http://psiexp.ss.uci.edu/research/programs_data/exampleimages1.html,
and the original paper:
Griffiths, T., & Steyvers, M. (2004). Finding Scientific Topics.
Proceedings of the National Academy of Sciences, 101 (suppl. 1), 5228-5235.
Returns
-------
out : SArray
Each element represents a 'document' where the words are strings that
represent a single pixel in the image in a colon-separated format.
For example, 'horizontal_location:vertical_location'. Each word is
associated with a count of the number of generated occurrences.
"""
width = 5
vocab_size = width * width
rng = random.Random()
if seed is not None:
rng.seed(seed)
zeros = [[0 for i in range(width)] for j in range(width)]
topic_squares = [zeros for i in range(num_topics)]
for i in range(width):
for j in range(width):
topic_squares[i][i][j] = 1.0 / width
for i in range(width):
for j in range(width):
topic_squares[width + i][j][i] = 1.0 / width
topics = []
for k in range(num_topics):
topics.append(list(_itertools.chain(*topic_squares[k])))
def weighted_choice(probs):
total = sum(probs)
r = rng.uniform(0, total)
upto = 0
for i, w in enumerate(probs):
if upto + w > r:
return i
upto += w
assert False, "Shouldn't get here"
documents = []
thetas = []
for d in range(num_documents):
doc = [0 for i in range(width * width)]
topic_dist = [rng.gammavariate(1, 1) for k in range(num_topics)]
topic_dist = [z / sum(topic_dist) for z in topic_dist]
for i in range(num_words_per_doc):
k = weighted_choice(topic_dist)
w = weighted_choice(topics[k])
doc[w] += 1
thetas.append(topic_dist)
documents.append(doc)
sparse_documents = []
for d in documents:
sd = {}
for i in range(width):
for j in range(width):
k = str(i) + "," + str(j)
sd[k] = d[i * width + j]
sparse_documents.append(sd)
bow_documents = turicreate.SArray(sparse_documents)
return bow_documents
class BasicTest(unittest.TestCase):
@classmethod
def setUpClass(self):
# Create an example containing synthetic data along
# with fitted models (with default parameters).
docs = generate_bar_example(num_documents=1000, seed=12345)
models = []
# Test a model that used CGS
m = topic_model.create(docs, num_topics=10)
models.append(m)
# Test a model with many topics
m = topic_model.create(docs, method="cgs", num_topics=100, num_iterations=2)
models.append(m)
m = topic_model.create(docs, method="alias", num_topics=100, num_iterations=2)
models.append(m)
# Test a model serialized after using CGS
with test_util.TempDirectory() as f:
m.save(f)
m2 = turicreate.load_model(f)
models.append(m2)
# Save
examples["synthetic"] = {"docs": docs, "models": models}
self.docs = examples["synthetic"]["docs"]
self.models = examples["synthetic"]["models"]
def test_set_burnin(self):
m = topic_model.create(self.docs, num_burnin=25, num_iterations=1)
self.assertTrue(m.num_burnin == 25)
def test_no_validation_print(self):
m = topic_model.create(
self.docs, num_burnin=25, num_iterations=2, print_interval=0
)
self.assertTrue(m is not None)
self.assertEqual(m.num_burnin, 25)
def test_validation_set(self):
m = topic_model.create(self.docs, validation_set=self.docs)
self.assertTrue("validation_perplexity" in m._list_fields())
# Test that an SFrame can be used
sf = turicreate.SFrame({"text": self.docs})
m = topic_model.create(self.docs, validation_set=sf)
self.assertTrue("validation_perplexity" in m._list_fields())
def test_set_associations(self):
associations = turicreate.SFrame()
associations["word"] = ["1,1", "1,2", "1,3"]
associations["topic"] = [0, 0, 0]
m = topic_model.create(self.docs, associations=associations)
# In this context, the "words" '1,1', '1,2', '1,3' should be
# the first three words in the vocabulary.
self.assertEqual(list(m.topics["vocabulary"].head(3)), ["1,1", "1,2", "1,3"])
# For each of these words, the probability of topic 0 should
# be largest.
probs = m.topics["topic_probabilities"]
largest = probs.apply(lambda x: np.argmax(x))
self.assertEqual(list(largest.head(3)), [0, 0, 0])
def test_model_runs(self):
"""
Test that the model runs and returns the proper type of object.
"""
for m in self.models:
self.assertTrue(m is not None)
self.assertTrue(isinstance(m, topic_model.TopicModel))
def test_get_topics(self):
"""
Test that we can retrieve the topic probabilities from the model.
"""
for m in self.models:
topics = m.topics
self.assertTrue(isinstance(topics, turicreate.SFrame))
self.assertEqual(topics.num_rows(), 25)
self.assertEqual(topics.num_columns(), 2)
z = m.topics["topic_probabilities"]
for k in range(m.num_topics):
self.assertTrue(
abs(sum(z.vector_slice(k)) - 1) < DELTA,
"Returned probabilities do not sum to 1.",
)
# Make sure returned object is an SFrame of the right size
topics = m.get_topics()
self.assertTrue(isinstance(topics, turicreate.SFrame))
self.assertTrue(
topics.num_columns() == 3,
"Returned SFrame should have a topic, word, and probs.",
)
# Make sure that requesting a single topic returns only that topic
num_words = 8
topics = m.get_topics([5], num_words=num_words)
self.assertTrue(
all(topics["topic"] == 5), "Returned topics do not have the right id."
)
self.assertEqual(topics.num_rows(), num_words)
topics = m.get_topics([2, 4], num_words=num_words)
self.assertEqual(set(list(topics["topic"])), set([2, 4]))
self.assertEqual(topics.num_rows(), num_words + num_words)
# Make sure the cumulative probability of the returned words is
# is less than the cutoff we provided.
# A cutoff of 1.0 should return num_words for every topic.
cutoff = 1.0
topics = m.get_topics(cdf_cutoff=cutoff, num_words=len(m.vocabulary))
totals = topics.groupby(
"topic", {"total_score": turicreate.aggregate.SUM("score")}
)
self.assertTrue(
all(totals["total_score"] <= (cutoff + DELTA)),
"More words were returned than expected for this cutoff.",
)
# Make sure we raise errors for bad input
with self.assertRaises(ValueError):
m.get_topics([-1])
with self.assertRaises(ValueError):
m.get_topics([10000])
with self.assertRaises(ToolkitError):
topics = m.get_topics(output_type="other")
# Test getting topic_words
topic_words = m.get_topics(output_type="topic_words", num_words=5)
self.assertEqual(type(topic_words), turicreate.SFrame)
# Test words are sorted correctly for the first topic
# TODO: Make this more deterministic.
# topic_probs = m.get_topics(num_words=5)
# expected = [w for w in topic_probs['word'][:5]]
# observed = topic_words['words'][0]
# self.assertEqual(observed[0], expected[0])
def test_get_vocabulary(self):
"""
Test that we can retrieve the vocabulary from the model.
"""
for m in self.models:
vocab = m.vocabulary
self.assertTrue(isinstance(vocab, turicreate.SArray))
self.assertEqual(len(vocab), 25)
def test_predict(self):
"""
Test that we can make predictions using the model.
"""
docs = self.docs
for m in self.models:
preds = m.predict(docs)
self.assertTrue(isinstance(preds, turicreate.SArray))
self.assertEqual(len(preds), len(docs))
self.assertEqual(preds.dtype, int)
preds = m.predict(docs, output_type="probability")
self.assertTrue(isinstance(preds, turicreate.SArray))
self.assertTrue(len(preds) == len(docs))
s = preds.apply(lambda x: sum(x))
self.assertTrue((s.apply(lambda x: abs(x - 1)) < 0.000001).all())
# Test predictions when docs have new words
new_docs = turicreate.SArray([{"-1,-1": 3.0, "0,4": 5.0, "0,3": 2.0}])
preds = m.predict(new_docs)
self.assertEqual(len(preds), len(new_docs))
# Test additional burnin. Ideally we could show that things
# converge as you increase burnin.
preds_no_burnin = m.predict(docs, output_type="probability", num_burnin=0)
self.assertEqual(len(preds_no_burnin), len(docs))
def test_save_load(self):
for i, m in enumerate(self.models):
with test_util.TempDirectory() as f:
m.save(f)
m2 = turicreate.load_model(f)
self.assertTrue(m2 is not None)
self.assertEqual(m.__str__(), m2.__str__())
diff = (
m.topics["topic_probabilities"] - m2.topics["topic_probabilities"]
)
zeros = diff * 0
for i in range(len(zeros)):
observed = np.array(diff[i])
expected = np.array(zeros[i])
np.testing.assert_array_almost_equal(observed, expected)
topics = m2.get_topics()
self.assertEqual(topics.num_columns(), 3)
def test_initialize(self):
"""
The initial_topics argument allows one to fit a model from a
particular set of parameters.
"""
for m in self.models:
start_docs = turicreate.SArray(self.docs.tail(3))
m = topic_model.create(
start_docs,
num_topics=20,
method="cgs",
alpha=0.1,
beta=0.01,
num_iterations=1,
print_interval=1,
)
start_topics = turicreate.SFrame(m.topics.head(100))
m2 = topic_model.create(
self.docs,
num_topics=20,
initial_topics=start_topics,
method="cgs",
alpha=0.1,
beta=0.01,
num_iterations=0,
print_interval=1,
)
# Check that the vocabulary of the new model is the same as
# the one we used to initialize the model.
self.assertTrue(
(start_topics["vocabulary"] == m2.topics["vocabulary"]).all()
)
# Check that the previously most probable word is still the most
# probable after 0 iterations, i.e. just initialization.
old_prob = start_topics["topic_probabilities"].vector_slice(0)
new_prob = m2.topics["topic_probabilities"].vector_slice(0)
self.assertTrue(np.argmax(list(old_prob)) == np.argmax(list(new_prob)))
def test_exceptions(self):
good1 = turicreate.SArray([{"a": 5, "b": 7}])
good2 = turicreate.SFrame({"bow": good1})
good3 = turicreate.SArray([{}])
bad1 = turicreate.SFrame({"x": [0, 1, 2, 3]})
bad2 = turicreate.SFrame({"x": [{"0": 3}], "y": [{"3": 5}]})
bad3 = turicreate.SArray([{"a": 5, "b": 3}, None, {"a": 10}])
bad4 = turicreate.SArray([{"a": 5, "b": None}, {"a": 3}])
for d in [good1, good2, good3]:
m = topic_model.create(d)
self.assertTrue(m is not None)
# Test that create() throws on bad input
with self.assertRaises(Exception):
m = topic_model.create(bad1)
with self.assertRaises(Exception):
m = topic_model.create(bad2)
with self.assertRaises(ToolkitError):
m = topic_model.create(bad3)
with self.assertRaises(ToolkitError):
m = topic_model.create(bad4)
m = self.models[0]
with self.assertRaises(Exception):
pr = m.predict(bad1)
with self.assertRaises(Exception):
pr = m.predict(bad2)
with self.assertRaises(Exception):
pr = m.predict(bad3)
def test_evaluate(self):
for m in self.models:
# Check evaluate on the training set returns an answer
perp = m.evaluate(self.docs)
self.assertTrue(isinstance(perp, dict))
self.assertTrue(isinstance(perp["perplexity"], float))
# Check that the answer is within 5% of the one reported
# by the model during training.
if "validation_perplexity" in m._list_fields():
perp2 = m.validation_perplexity
# TEMP: Disable since we now only compute this if validatino set is provided
# assert abs(perp - perp2)/perp < .05
# Check evaluate on the test set returns an answer
perp = m.evaluate(self.docs, self.docs)
self.assertTrue(isinstance(perp, dict))
def test__training_stats(self):
expected_fields = ["training_iterations", "training_time"]
for m in self.models:
actual_fields = m._training_stats()
for f in expected_fields:
self.assertTrue(f in actual_fields)
self.assertTrue(m._get(f) is not None)
def test_summary(self):
expected_fields = [
"num_topics", # model parameters
"alpha",
"beta",
"topics",
"vocabulary",
"num_iterations", # stats and options
"print_interval",
"training_time",
"training_iterations",
"num_burnin",
]
for m in self.models:
actual_fields = m._list_fields()
for f in expected_fields:
self.assertTrue(f in actual_fields)
self.assertTrue(m._get(f) is not None)
class ParsersTest(unittest.TestCase):
def setUp(self):
self.tmpfile_a = tempfile.NamedTemporaryFile(delete=False).name
with open(self.tmpfile_a, "w") as o:
o.write("3 1:5 2:10 5:353\n")
o.write("0 0:7 6:3 3:100")
self.tmpfile_vocab = tempfile.NamedTemporaryFile(delete=False).name
with open(self.tmpfile_vocab, "w") as o:
o.write("\n".join(["a", "b", "c", "d", "e", "f", "g"]))
self.tmpfile_b = tempfile.NamedTemporaryFile(delete=False).name
with open(self.tmpfile_b, "w") as o:
o.write("2\n5\n6\n")
o.write("1 2 5\n")
o.write("1 3 10\n")
o.write("1 6 353\n")
o.write("2 1 7\n")
o.write("2 7 3\n")
o.write("2 4 100")
def test_parse_sparse(self):
d = parse_sparse(self.tmpfile_a, self.tmpfile_vocab)
self.assertTrue(d[0] == {"b": 5, "c": 10, "f": 353})
self.assertTrue(d[1] == {"a": 7, "g": 3, "d": 100})
def test_parse_docword(self):
d = parse_docword(self.tmpfile_b, self.tmpfile_vocab)
self.assertTrue(d[0] == {"b": 5, "c": 10, "f": 353})
self.assertTrue(d[1] == {"a": 7, "g": 3, "d": 100})
def tearDown(self):
os.remove(self.tmpfile_a)
os.remove(self.tmpfile_b)
os.remove(self.tmpfile_vocab)
class UtilitiesTest(unittest.TestCase):
def setUp(self):
docs = turicreate.SArray([{"b": 5, "a": 3}, {"c": 7, "b": 5}, {"a": 2, "d": 3}])
doc_topics = turicreate.SArray([[0.9, 0.1], [0.7, 0.3], [0.1, 0.9]])
word_topics = turicreate.SArray([[0.5, 0.5], [0.1, 0.9], [0.25, 0.75]])
vocabulary = turicreate.SArray(["a", "b", "c"])
self.docs = docs
self.word_topics = word_topics
self.doc_topics = doc_topics
self.vocabulary = vocabulary
self.num_topics = 2
def test_perplexity(self):
prob_0_a = 0.9 * 0.5 + 0.1 * 0.5
prob_0_b = 0.9 * 0.1 + 0.1 * 0.9
prob_1_b = 0.7 * 0.1 + 0.3 * 0.9
prob_1_c = 0.7 * 0.25 + 0.3 * 0.75
prob_2_a = 0.1 * 0.5 + 0.9 * 0.5
prob_2_d = 0
perp = 0.0
perp += 3 * np.log(prob_0_a) + 5 * np.log(prob_0_b)
perp += 5 * np.log(prob_1_b) + 7 * np.log(prob_1_c)
perp += 2 * np.log(prob_2_a)
perp = np.exp(-perp / (3 + 5 + 5 + 7 + 2))
observed_perp = perplexity(
self.docs, self.doc_topics, self.word_topics, self.vocabulary
)
self.assertAlmostEqual(perp, observed_perp, delta=0.0001)
|
997,822 | 51bf2d50852e5b6d91a77557ec56e2012f5c4365 | # -*- coding: utf-8 -*-
import numpy as np
import pytest
from nata.utils.formatting import array_format
from nata.utils.formatting import make_as_identifier
@pytest.mark.parametrize(
"input_, expected",
[
(np.array(1), "1"),
(np.array(None), "None"),
(np.array([1]), "[1]"),
(np.array([None]), "[None]"),
(np.array([1, 2, 3]), "[1, 2, 3]"),
(np.array([1, 2, 3, 4]), "[1, 2, ... 4]"),
],
ids=(
"zero-dim",
"None, zero-dim",
"single-element",
"None, single-element",
"shape==(3,)",
"shape==(4,)",
),
)
def test_array_format(input_, expected):
assert array_format(input_) == expected
@pytest.mark.parametrize(
"actual, expected",
[
(" abc", "abc"),
("_abc", "abc"),
("ab c", "ab_c"),
("ab c d", "ab_c_d"),
("$abc", "abc"),
],
)
def test_make_as_identifier(actual, expected):
assert make_as_identifier(actual) == expected
|
997,823 | 185034fea89f17e0d3ad0e40d9dffdd0a559cb28 | # if we enter string it will throw error
# ValueError Exception
age = int(input("Age:"))
list_item = [1, 2]
print(list_item[3]) # IndexError
|
997,824 | 076e2b8c8597ba34b2c4bfbe2c9bba9dbf3e3464 | # The following iterative sequence is defined for the set of positive integers:
# n → n/2 (n is even)
# n → 3n + 1 (n is odd)
# Using the rule above and starting with 13, we generate the following sequence:
# 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
# It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.
# Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
# Which starting number, under one million, produces the longest chain?
# NOTE: Once the chain starts the terms are allowed to go above one million.
import threading
NUM = (0, 0)
class NewThread(threading.Thread):
def __init__(self, fromNum, toNum):
threading.Thread.__init__(self)
self.fromNum = fromNum
self.toNum = toNum
def run(self):
global NUM
for i in range(self.fromNum, self.toNum):
count = 0
n = i
while n > 1:
if n % 2 == 0:
n /= 2
else:
n = (3 * n) + 1
count += 1
if count > NUM[1]:
NUM = (i, count)
print(NUM)
for i in range(0, 10):
thread = NewThread(i * 100_000, ((i + 1) * 100_000) + 1)
thread.start() |
997,825 | 063f367f05cc5cd1b5943dc758450ed937e6d81c | from django.utils import unittest
from django.test import TestCase
from django.test import Client
class SimpleTest(unittest.TestCase):
fixtures = ['test_data.json']
def setUp(self):
self.client = Client()
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
def test_login(self):
c = Client()
self.assertTrue(self.client.login(username='ravip',password='coriolis'))
class OrgListTestCase(TestCase):
def test_index(self):
resp = self.client.get('/org/list/')
self.assertEqual(resp.status_code, 200)
|
997,826 | f13e706415e9e63209f8dd32a822697d11db2700 | # coding: utf-8
from __future__ import unicode_literals, print_function, division
#!/usr/bin/env python
__author__ = 'setten'
import timeit
import os
def test_write(m):
"""
file write test function
"""
l = []
for i in range(m):
l.append(i)
f = open('test', 'w')
f.write(str(l))
f.close()
def test_read():
"""
file read test function
"""
f = open('test', mode='r')
line = f.read()
f.close()
def test_make_folders():
"""
creating and removing test function
"""
for i in range(0, 100, 1):
os.mkdir('test_folder_%s' % i)
os.rmdir('test_folder_%s' % i)
def test_cd():
"""
filesystems navigation test function
"""
for i in range(0, 100, 1):
os.mkdir('test_folder_%s' % i)
os.chdir('test_folder_%s' % i)
os.chdir('..')
os.rmdir('test_folder_%s' % i)
if __name__ == '__main__':
"""
Testing file writing and reading and folder operations, an asserion error is raised when the filesystem seems to be
too slow
"""
n = 100
mk_folders = timeit.timeit("test_make_folders()", setup="from __main__ import test_make_folders", number=n)
cd_folders = timeit.timeit("test_cd()", setup="from __main__ import test_cd", number=n)
print('made and removed 100 folders in', mk_folders, 's')
print('made, moved to, returned and removed 100 folders in', cd_folders, 's')
for my_m in [50000, 100000, 200000]:
test_write(my_m)
size = os.path.getsize('test')
print('file size', size)
setup = "from __main__ import test_write\nmy_m =" + str(my_m)
write = timeit.timeit("test_write(my_m)", setup=setup, number=n)
read = timeit.timeit("test_read()", setup="from __main__ import test_read", number=n*200)
print(n, 'times written in ', write, 's, ', size * n / write / 1000000, 'MB/s')
print(n*200, 'times read in ', read, 's, ', size * 200 * n / read / 1000000, 'MB/s')
# assert write < 10 * n / 100 * my_m / 100000
# assert read < 10 * n / 100 * my_m / 100000
# assert mk_folders < 1 * n / 100
# assert cd_folders < 1 * n / 100
|
997,827 | 4e55b9697d6600f0fcc837c52a4c84286fcf6ee3 | import re
def create_index(messages, user_info):
user_words, user_channels, channel_words, user_msgs = {}, {}, {}, {}
for user, channel, message, n_reactions in messages:
if user in user_words:
user_channels[user][channel] = user_channels[user][channel]+1.0 if channel in user_channels[user] else 1.0
user_msgs[user][message] = float(n_reactions)
u_word_freq = user_words[user]
else:
user_channels[user] = {channel:1.0}
user_msgs[user] = {message:float(n_reactions)}
u_word_freq = {}
c_word_freq = channel_words[channel] if channel in channel_words else {}
for word in re.findall(r"[\w'-]+", message):
word = word.lower()
u_word_freq[word] = u_word_freq[word]+1.0 if word in u_word_freq else 1.0
c_word_freq[word] = c_word_freq[word]+1.0 if word in c_word_freq else 1.0
user_words[user] = u_word_freq
channel_words[channel] = c_word_freq
return normalize_freq(user_words), user_channels, user_msgs, normalize_freq(channel_words), user_info
def normalize_freq(user_words):
norm_user_words = {}
for user in user_words:
u_word_freq = user_words[user]
sum_word_freq = sum(u_word_freq.values())
for word in u_word_freq:
u_word_freq[word] = u_word_freq[word]/sum_word_freq
norm_user_words[user] = u_word_freq
return norm_user_words
if __name__ == "__main__":
msgs = [("user1", "fruits", "I love fruits love", 3),
("user2", "veggies", "what's kale", 5),
("user5", "engineering", "what's python?", 0),
("user7", "veggies", "where do i buy kale. where?", 1),
("user2", "fruits", "what's watermelon", 2),
("user1", "fruits", "where can I buy watermelon?", 2),
("user5", "engineering", "I am a full-stack engineer.", 3)]
user_words, user_channels, user_msgs, channel_words, user_info = create_index(msgs, None)
print(user_words)
print(user_channels)
print(user_msgs)
print(channel_words)
|
997,828 | 11ce1465a4fc674902f39c60d2d9edb7610e0275 | """freshmenu URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from orders.api import views
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register(r'',views.OrderItemsView)
urlpatterns = [
url(r'^create/$', views.OrdersCreateView.as_view()),
# url(r'^orderitems/$', views.OrderItemsView.as_view()),
url(r'^orderitem/$', include(router.urls))
]
|
997,829 | 655fab90800e5b3705db6304efc66b9d9e98d75d | # coding=utf-8
"""
Contains functions to manage the catalog table, locally (client side requests) and remotely (server
side actions).
Usage: LocalCatalog.create_dtable(catalog_database_filename)
LocalCatalog.record_ddl(socket, command_list)
LocalCatalog.record_partition(socket, command_list)
LocalCatalog.return_node_uris(socket, command_list)
RemoteCatalog.ping(node_URI)
RemoteCatalog.record_ddl(catalog_node_URI, node_list, executed_DDL)
RemoteCatalog.return_node_uris(catalog_node_URI, table_name)
RemoteCatalog.update_partition(catalog_node_URI, partition_dictionary, number_of_nodes)
"""
import sqlite3 as sql
from lib.database import Database
from lib.dissect import SQLFile, ClusterCFG
from lib.error import ErrorHandle
from lib.network import Network
class LocalCatalog:
"""
All catalog operations for the catalog node itself (operating locally). Errors here are handled
by raising an exception. parDBd is meant to catch these errors and send these over to
the client.
"""
@staticmethod
def create_dtable(f):
""" Given the name of the database file, create the table. This information is specified in
the homework assignment.
:param f: Location of the database file to store this table on.
:return: None.
"""
conn, cur = Database.connect(f, ErrorHandle.raise_handler)
Database.execute(cur, 'CREATE TABLE IF NOT EXISTS dtables ('
'tname CHARACTER(32), '
'nodedriver CHARACTER(64), ' # Unused here.
'nodeurl CHARACTER(128), '
'nodeuser CHARACTER(16), ' # Unused here.
'nodepasswd CHARACTER(16), ' # Unused here.
'partmtd INT, '
'nodeid INT, '
'partcol CHARACTER(32), '
'partparam1 CHARACTER(128), '
'partparam2 CHARACTER(128)); ', ErrorHandle.raise_handler)
@staticmethod
def _perform_ddl(cur, ddl, table, node_uris):
""" Helper method to execute the a given DDL.
:param cur: Cursor to the catalog database.
:param ddl: The executed DDL across the entire cluster.
:param table: Name of the table associated with the given DDL.
:param node_uris: URIs of all nodes the DDL was executed on.
:return: None.
"""
# Perform the DROP DDL.
if SQLFile.is_drop_ddl(ddl):
Database.execute(cur, 'DELETE FROM dtables '
'WHERE tname = ?', ErrorHandle.raise_handler, (table,))
return
# If the table exists, do not proceed. Exit with an error.
e = Database.execute(cur, 'SELECT 1 '
'FROM dtables '
'WHERE tname = ? '
'LIMIT 1', ErrorHandle.raise_handler, (table,), True)
if len(e) != 0:
raise sql.Error(ErrorHandle.wrap_error_tag('Table exists in cluster.'))
# Perform the INSERTION DDL.
tuples = [(table, node_uris[i], i + 1) for i in range(len(node_uris))]
Database.executemany(cur, 'INSERT INTO dtables '
'VALUES (?, NULL, ?, NULL, NULL, NULL, ?, NULL, NULL, NULL)',
tuples, ErrorHandle.raise_handler)
@staticmethod
def record_ddl(k, r):
""" Given node URIs of the cluster and the DDL statement that was executed, insert metadata
about which nodes and which tables are affected.
:param k: Socket connection to send response through.
:param r: Command list passed through the same socket.
:return: None.
"""
f, node_uris, ddl = r[1], r[2], r[3]
# Connect to SQLite database using the filename.
conn, cur = Database.connect(f, ErrorHandle.raise_handler)
# Create the table if it does not exist.
LocalCatalog.create_dtable(f)
# Determine the table being operated on in the DDL.
table = ErrorHandle.act_upon_error(SQLFile.table(ddl), ErrorHandle.raise_handler, True)
# Assemble our tuples and perform the insertion/deletion.
LocalCatalog._perform_ddl(cur, ddl, table, node_uris)
conn.commit()
# If we have reached this point, we are successful. Send the appropriate message.
Network.write(k, ['EC', 'Success'])
@staticmethod
def _record_specific_partition(r_d, numnodes, cur):
""" Helper method for updating the catalog node with partition information.
:param r_d: Dictionary associated with all partition operations.
:param numnodes: Number of nodes an operation was partitioned across.
:param cur: Cursor to the catalog database.
:return:
"""
# No partitioning has been specified. Create the appropriate entries.
if r_d['partmtd'] == 0:
for i in range(1, numnodes + 1):
Database.execute(cur, 'UPDATE dtables '
'SET partmtd = 0 '
'WHERE nodeid = ? AND tname = ?',
ErrorHandle.raise_handler, (i, r_d['tname']))
# Range partitioning has been specified. Create the appropriate entries.
elif r_d['partmtd'] == 1:
for i in range(1, numnodes + 1):
Database.execute(cur, 'UPDATE dtables '
'SET partcol = ?, partparam1 = ?, '
'partparam2 = ?, partmtd = 1 '
'WHERE nodeid = ? AND tname = ?',
ErrorHandle.raise_handler,
(r_d['partcol'], r_d['param1'][i - 1], r_d['param2'][i - 1], i,
r_d['tname']))
# Hash partitioning has been specified. Create the appropriate entries.
elif r_d['partmtd'] == 2:
for i in range(1, numnodes + 1):
Database.execute(cur, 'UPDATE dtables '
'SET partcol = ?, partparam1 = ?, partmtd = 2 '
'WHERE nodeid = ? AND tname = ?',
ErrorHandle.raise_handler,
(r_d['partcol'], r_d['param1'], i, r_d['tname']))
@staticmethod
def record_partition(k, r):
""" Record the partition to catalog database, assuming the working node is the catalog
node. Using the catalog database filename, the partition dictionary, and the specified
number of nodes from the received command list. Return an acknowledgement through the
given socket.
:param k: Socket to send acknowledgement through.
:param r: Command list passed through the same socket.
:return: None.
"""
f, r_d, numnodes = r[1], r[2], r[3]
# Connect to SQLite database using the filename.
conn, cur = Database.connect(f, ErrorHandle.raise_handler)
sql_handler = lambda e_n: Database.rollback_wrapper(e_n, ErrorHandle.raise_handler, conn)
# Record the partition.
e = lambda: LocalCatalog._record_specific_partition(r_d, numnodes, cur)
ErrorHandle.attempt_operation(e, sql.Error, sql_handler)
# No errors have occurred. Send the success message.
conn.commit(), conn.close()
Network.write(k, ['EK', 'Success'])
@staticmethod
def return_node_uris(k, r):
""" Return a list of node URIs stored in the 'dtables' table, which gives the client
machine access to the cluster.
:param k: Socket to send node URI list to.
:param r: Command list passed through the same socket.
:return: None.
"""
f, tname = r[1], r[2]
# Connect to the catalog.
conn, cur = Database.connect(f, ErrorHandle.raise_handler)
sql_handler = lambda e_n: Database.rollback_wrapper(e_n, ErrorHandle.raise_handler, conn)
# Grab the node URIs belonging to the given table. Return the results.
p = Database.execute(cur, 'SELECT nodeurl '
'FROM dtables '
'WHERE tname = ?', sql_handler, (tname,), True)
conn.close()
# If there exist no tables here, throw an error.
if len(p) == 0:
raise sql.Error(ErrorHandle.wrap_error_tag('Table ' + tname + ' not found.'))
else:
Network.write(k, ['EU', p])
class RemoteCatalog:
"""
All catalog operations on general nodes (i.e. calls the catalog node). These are non-fatal, and
a string or boolean error is returned instead.
"""
@staticmethod
def ping(c):
""" Attempt to connect and send a message to a node, given it's URI.
:param c: Node URI of the desired node to reach.
:return: True if a connection can be achieved. False otherwise.
"""
host, port, f = ClusterCFG.parse_uri(c)
# Create our socket and attempt to connect.
sock = Network.open_client(host, port)
if ErrorHandle.is_error(sock):
return False
# Send a dummy message. Response must not be an error.
response = Network.write(sock, ['YY'])
if ErrorHandle.is_error(response):
return response
sock.close()
return True
@staticmethod
def record_ddl(c, nodes, ddl):
""" Store a DDL that was executed in the catalog node.
:param c: Node URI of the catalog node to store to.
:param nodes: List of nodes the DDL was executed across.
:param ddl: The DDL that was executed.
:return The resulting error if the appropriate response is not returned successfully. True
otherwise.
"""
host, port, f = ClusterCFG.parse_uri(c)
# Only proceed if there exists at least one successful node.
if len(nodes) == 0:
return ErrorHandle.wrap_error_tag('No nodes were successful.')
# Create our socket.
sock = Network.open_client(host, port)
if ErrorHandle.is_error(sock):
sock.close()
return ErrorHandle.wrap_error_tag('Socket could not be established.')
# Otherwise, record the DDl.
Network.write(sock, ['C', f, nodes, ddl])
# Wait for a response to be sent back, and return the appropriate message.
net_handler = lambda e: Network.close_wrapper(e, ErrorHandle.default_handler, sock)
if not ErrorHandle.is_error(Network.read(sock, net_handler)):
sock.close()
return 'Success.'
@staticmethod
def return_node_uris(c, tname):
""" Given the catalog URI and the name of table, grab the node URIs from the catalog node.
:param c: Node URI of the catalog node to read from.
:param tname: Name of the table in the cluster to search for.
:return: The resulting error if the appropriate response is not returned successfully.
Otherwise, a list of node URIs.
"""
host, port, f = ClusterCFG.parse_uri(c)
# Create our socket.
sock = Network.open_client(host, port)
if ErrorHandle.is_error(sock):
return ErrorHandle.wrap_error_tag('Socket could not be established.')
# Pickle our command list ('U', filename, and tname), and send our message.
Network.write(sock, ['U', f, tname])
# Wait for a response to be sent back, and record this response.
net_handler = lambda e: Network.close_wrapper(e, ErrorHandle.default_handler, sock)
response = Network.read(sock, net_handler)
# If an error exists, return the error.
if ErrorHandle.is_error(response):
return response
# Otherwise, return the node URIs.
return [x[0] for x in response[1]]
@staticmethod
def update_partition(c, r_d, numnodes):
""" Update the partition information in the catalog node, after performing the runLCSV
operation.
:param c: Node URI of the catalog node to read from.
:param r_d: Partition dictionary used to execute runLCSV.
:param numnodes: Number of nodes an operation was partitioned across.
:return: The resulting error if the appropriate response is not returned successfully.
Otherwise, a success message.
"""
host, port, f = ClusterCFG.parse_uri(c)
# Create our socket.
sock = Network.open_client(host, port)
if ErrorHandle.is_error(sock):
return ErrorHandle.wrap_error_tag('Socket could not be established.')
# Pickle our command list ('K', f, r_d, numnodes), and send our message.
Network.write(sock, ['K', f, r_d, numnodes])
# Wait for a response to be sent back, and record this response.
net_handler = lambda e: Network.close_wrapper(e, ErrorHandle.default_handler, sock)
response = Network.read(sock, net_handler)
# If an error exists, return the error.
if ErrorHandle.is_error(response):
return response
# Otherwise, return the success message.
return 'Success'
|
997,830 | 44ea6c902cd6d4f24fc2f723e7bcb71ccd793e97 | import threading, time, random, Queue
TIME_TO_RUN = 10
class Producer:
def __init__(self):
self.product = ['a','b','c','d','e','f','g']
self.next = 0
def run(self):
global q
while time.clock() < TIME_TO_RUN:
if self.next < time.clock():
f = self.product[random.randrange(len(self.product))]
q.put(f)
print "Added -- %s\n" % f
self.next += random.random()
class Consumer:
def __init__(self):
self.next = 0
def run(self):
global q
while time.clock() < TIME_TO_RUN:
if self.next < time.clock():
if not q.empty():
f = q.get()
print "Removed ---- %s\n" % f
self.next += random.random()
else:
print "Consumer is waiting \n"
if __name__ == '__main__':
q = Queue.Queue(10)
p = Producer()
c = Consumer()
pt = threading.Thread(target=p.run, args=())
pt.daemon = True
ct = threading.Thread(target=c.run, args=())
pt.start()
ct.start()
|
997,831 | 865ab052edfeb3ce96c047a93bd2bb336d368949 | from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.http.response import JsonResponse
from django.views.generic import View # 通用类视图 as_view的使用
from .models import cateType,UserInfo
import json,re
from django.core import serializers
class asyData(View):
"""异步数据获取"""
def get(self,request):
data = {}
cid = request.GET.get('cid',None)
catedata = cateType.objects.get(id=cid)
userisdf = UserInfo.objects.filter(type=cid, is_default=1)
print(userisdf)
userdf = UserInfo.objects.filter(is_default=0)
def object_to_json(obj):
return dict([(kk, obj.__dict__[kk]) for kk in obj.__dict__.keys() if kk != "_state"])
data["cate"]=object_to_json(catedata)
data["userisdf"] = json.loads(serializers.serialize("json", userisdf))
data["userdf"] = json.loads(serializers.serialize("json", userdf))
return JsonResponse(data,safe=False)
class newYear(View):
"""新年活动类"""
def get(self,request):
"""报名展示页"""
cate = cateType.objects.all().order_by("-index")
# isdata = UserInfo.objects.filter(is_default=1)
# otdata = UserInfo.objects.filter(is_default=0)
# con = {"otdata":otdata,"isdata":isdata,"cate":cate}
con = {"cate":cate}
return render(request, "newyear/index.html", con)
# def post(self,request):
# """报名提交页"""
# print(request)
# data = {}
# data["name"] = request.POST.get('name',None)
# data["phone"] = request.POST.get('phone',None)
# user = User(**data)
# user.save()
# con={"color":"red","res_title":""}
# return render(request, "newyear/res.html", con)
class User(View):
"""用户等级"""
def get(self,request):
"""报名页展示"""
return render(request,"newyear/user.html")
def post(self,request):
"""报名页内容提交"""
name = request.POST.get('name')
phone = request.POST.get('phone')
ret = re.match(r"^1[35678]\d{9}$", phone)
if ret is None:
con = {"color": "red", "res_title": "登记失败","res_info":"请输入正确的手机号"}
return render(request,"newyear/res.html",con)
user = UserInfo.objects.filter(phone=phone)
if user:
con = {"color": "red", "res_title": "登记失败", "res_info": "该手机号已经注册"}
return render(request, "newyear/res.html", con)
UserInfo.objects.create(name=name,phone=phone)
con = {"color": "green", "res_title": "登记成功", "res_info": "尊敬的%s 先生/女士,您的信息已成功登记,请等待抽奖"%(name)}
return render(request, "newyear/res.html", con) |
997,832 | a99f9098bbeaa409e9886506bccd6c7e00ec9400 | """A simple implementation of a greedy transition-based parser. Released under BSD license."""
from os import path
import os
import sys
from collections import defaultdict
import random
import time
import pickle
import re # For sentence splitting only
SHIFT = 0; RIGHT = 1; LEFT = 2;
MOVES = (SHIFT, RIGHT, LEFT)
START = ['-START-', '-START2-']
END = ['-END-', '-END2-']
class DefaultList(list):
"""A list that returns a default value if index out of bounds."""
def __init__(self, default=None):
self.default = default
list.__init__(self)
def __getitem__(self, index):
try:
return list.__getitem__(self, index)
except IndexError:
return self.default
class Parse(object):
def __init__(self, n):
self.n = n
self.heads = [None] * (n-1)
#self.labels = [None] * (n-1)
self.lefts = []
self.rights = []
for i in range(n+1):
self.lefts.append(DefaultList(0))
self.rights.append(DefaultList(0))
def add(self, head, child, label=None):
self.heads[child] = head
#self.labels[child] = label
if child < head:
self.lefts[head].append(child)
else:
self.rights[head].append(child)
class Parser(object):
def __init__(self, load=True):
model_dir = os.path.join(os.path.dirname(__file__), 'models/')
self.model = Perceptron(MOVES)
if load:
self.model.load(path.join(model_dir, 'parser.pickle'))
self.tagger = PerceptronTagger(load=load)
self.confusion_matrix = defaultdict(lambda: defaultdict(int))
def save(self):
self.model.save(path.join(os.path.dirname(__file__), 'models/parser.pickle'))
self.tagger.save()
def parse(self, words):
n = len(words)
i = 2; stack = [1]; parse = Parse(n)
tags = self.tagger.tag(words)
while stack or (i+1) < n:
features = extract_features(words, tags, i, n, stack, parse)
scores = self.model.score(features)
valid_moves = get_valid_moves(i, n, len(stack))
guess = max(valid_moves, key=lambda move: scores[move])
i = transition(guess, i, stack, parse)
return tags, parse.heads
def train_one(self, itn, words, gold_tags, gold_heads):
n = len(words)
#print "train_one(%d, n=%d, %s)" % (itn, n, words, )
#print " gold_heads = %s" % (gold_heads, )
i = 2; stack = [1]; parse = Parse(n)
tags = self.tagger.tag(words)
while stack or (i + 1) < n:
#print " i/n=%d/%d stack=" % (i,n ), stack
features = extract_features(words, tags, i, n, stack, parse)
scores = self.model.score(features)
valid_moves = get_valid_moves(i, n, len(stack))
guess = max(valid_moves, key=lambda move: scores[move])
gold_moves = get_gold_moves(i, n, stack, parse.heads, gold_heads)
assert gold_moves
best = max(gold_moves, key=lambda move: scores[move])
self.model.update(best, guess, features)
i = transition(guess, i, stack, parse)
self.confusion_matrix[best][guess] += 1
return len([i for i in range(n-1) if parse.heads[i] == gold_heads[i]])
def transition(move, i, stack, parse):
if move == SHIFT:
stack.append(i)
return i + 1
elif move == RIGHT:
parse.add(stack[-2], stack.pop())
return i
elif move == LEFT:
parse.add(i, stack.pop())
return i
assert move in MOVES
def get_valid_moves(i, n, stack_depth):
moves = []
if (i+1) < n:
moves.append(SHIFT)
if stack_depth >= 2:
moves.append(RIGHT)
if stack_depth >= 1:
moves.append(LEFT)
return moves
def get_gold_moves(n0, n, stack, heads, gold):
def deps_between(target, others, gold):
for word in others:
if gold[word] == target or gold[target] == word:
return True
return False
valid = get_valid_moves(n0, n, len(stack))
if not stack or (SHIFT in valid and gold[n0] == stack[-1]):
return [SHIFT]
if gold[stack[-1]] == n0:
return [LEFT]
costly = set([m for m in MOVES if m not in valid])
#print "Costly = ", costly
# If the word behind s0 is its gold head, Left is incorrect
if len(stack) >= 2 and gold[stack[-1]] == stack[-2]:
costly.add(LEFT)
# If there are any dependencies between n0 and the stack,
# pushing n0 will lose them.
if SHIFT not in costly and deps_between(n0, stack, gold):
costly.add(SHIFT)
# If there are any dependencies between s0 and the buffer, popping
# s0 will lose them.
if deps_between(stack[-1], range(n0+1, n-1), gold):
costly.add(LEFT)
costly.add(RIGHT)
return [m for m in MOVES if m not in costly]
def extract_features(words, tags, n0, n, stack, parse):
def get_stack_context(depth, stack, data):
if depth >= 3:
return data[stack[-1]], data[stack[-2]], data[stack[-3]]
elif depth >= 2:
return data[stack[-1]], data[stack[-2]], ''
elif depth == 1:
return data[stack[-1]], '', ''
else:
return '', '', ''
def get_buffer_context(i, n, data):
if i + 1 >= n:
return data[i], '', ''
elif i + 2 >= n:
return data[i], data[i + 1], ''
else:
return data[i], data[i + 1], data[i + 2]
def get_parse_context(word, deps, data):
if word == -1:
return 0, '', ''
deps = deps[word]
valency = len(deps)
if not valency:
return 0, '', ''
elif valency == 1:
return 1, data[deps[-1]], ''
else:
return valency, data[deps[-1]], data[deps[-2]]
features = {}
# Set up the context pieces --- the word (W) and tag (T) of:
# S0-2: Top three words on the stack
# N0-2: First three words of the buffer
# n0b1, n0b2: Two leftmost children of the first word of the buffer
# s0b1, s0b2: Two leftmost children of the top word of the stack
# s0f1, s0f2: Two rightmost children of the top word of the stack
depth = len(stack)
s0 = stack[-1] if depth else -1
Ws0, Ws1, Ws2 = get_stack_context(depth, stack, words)
Ts0, Ts1, Ts2 = get_stack_context(depth, stack, tags)
Wn0, Wn1, Wn2 = get_buffer_context(n0, n, words)
Tn0, Tn1, Tn2 = get_buffer_context(n0, n, tags)
Vn0b, Wn0b1, Wn0b2 = get_parse_context(n0, parse.lefts, words)
Vn0b, Tn0b1, Tn0b2 = get_parse_context(n0, parse.lefts, tags)
Vn0f, Wn0f1, Wn0f2 = get_parse_context(n0, parse.rights, words)
_, Tn0f1, Tn0f2 = get_parse_context(n0, parse.rights, tags)
Vs0b, Ws0b1, Ws0b2 = get_parse_context(s0, parse.lefts, words)
_, Ts0b1, Ts0b2 = get_parse_context(s0, parse.lefts, tags)
Vs0f, Ws0f1, Ws0f2 = get_parse_context(s0, parse.rights, words)
_, Ts0f1, Ts0f2 = get_parse_context(s0, parse.rights, tags)
# Cap numeric features at 5?
# String-distance
Ds0n0 = min((n0 - s0, 5)) if s0 != 0 else 0
features['bias'] = 1
# Add word and tag unigrams
for w in (Wn0, Wn1, Wn2, Ws0, Ws1, Ws2, Wn0b1, Wn0b2, Ws0b1, Ws0b2, Ws0f1, Ws0f2):
if w:
features['w=%s' % w] = 1
for t in (Tn0, Tn1, Tn2, Ts0, Ts1, Ts2, Tn0b1, Tn0b2, Ts0b1, Ts0b2, Ts0f1, Ts0f2):
if t:
features['t=%s' % t] = 1
# Add word/tag pairs
for i, (w, t) in enumerate(((Wn0, Tn0), (Wn1, Tn1), (Wn2, Tn2), (Ws0, Ts0))):
if w or t:
features['%d w=%s, t=%s' % (i, w, t)] = 1
# Add some bigrams
features['s0w=%s, n0w=%s' % (Ws0, Wn0)] = 1
features['wn0tn0-ws0 %s/%s %s' % (Wn0, Tn0, Ws0)] = 1
features['wn0tn0-ts0 %s/%s %s' % (Wn0, Tn0, Ts0)] = 1
features['ws0ts0-wn0 %s/%s %s' % (Ws0, Ts0, Wn0)] = 1
features['ws0-ts0 tn0 %s/%s %s' % (Ws0, Ts0, Tn0)] = 1
features['wt-wt %s/%s %s/%s' % (Ws0, Ts0, Wn0, Tn0)] = 1
features['tt s0=%s n0=%s' % (Ts0, Tn0)] = 1
features['tt n0=%s n1=%s' % (Tn0, Tn1)] = 1
# Add some tag trigrams
trigrams = ((Tn0, Tn1, Tn2), (Ts0, Tn0, Tn1), (Ts0, Ts1, Tn0),
(Ts0, Ts0f1, Tn0), (Ts0, Ts0f1, Tn0), (Ts0, Tn0, Tn0b1),
(Ts0, Ts0b1, Ts0b2), (Ts0, Ts0f1, Ts0f2), (Tn0, Tn0b1, Tn0b2),
(Ts0, Ts1, Ts1))
for i, (t1, t2, t3) in enumerate(trigrams):
if t1 or t2 or t3:
features['ttt-%d %s %s %s' % (i, t1, t2, t3)] = 1
# Add some valency and distance features
vw = ((Ws0, Vs0f), (Ws0, Vs0b), (Wn0, Vn0b))
vt = ((Ts0, Vs0f), (Ts0, Vs0b), (Tn0, Vn0b))
d = ((Ws0, Ds0n0), (Wn0, Ds0n0), (Ts0, Ds0n0), (Tn0, Ds0n0),
('t' + Tn0+Ts0, Ds0n0), ('w' + Wn0+Ws0, Ds0n0))
for i, (w_t, v_d) in enumerate(vw + vt + d):
if w_t or v_d:
features['val/d-%d %s %d' % (i, w_t, v_d)] = 1
return features
class Perceptron(object):
def __init__(self, classes=None):
# Each feature gets its own weight vector, so weights is a dict-of-arrays
self.classes = classes
self.weights = {}
# The accumulated values, for the averaging. These will be keyed by
# feature/clas tuples
self._totals = defaultdict(int)
# The last time the feature was changed, for the averaging. Also
# keyed by feature/clas tuples
# (tstamps is short for timestamps)
self._tstamps = defaultdict(int)
# Number of instances seen
self.i = 0
def predict(self, features):
'''Dot-product the features and current weights and return the best class.'''
scores = self.score(features)
# Do a secondary alphabetic sort, for stability
return max(self.classes, key=lambda clas: (scores[clas], clas))
def score(self, features):
all_weights = self.weights
scores = dict((clas, 0) for clas in self.classes)
for feat, value in features.items():
if value == 0:
continue
if feat not in all_weights:
continue
weights = all_weights[feat]
for clas, weight in weights.items():
scores[clas] += value * weight
return scores
def update(self, truth, guess, features):
def upd_feat(c, f, w, v):
param = (f, c)
self._totals[param] += (self.i - self._tstamps[param]) * w
self._tstamps[param] = self.i
self.weights[f][c] = w + v
self.i += 1
if truth == guess:
return None
for f in features:
weights = self.weights.setdefault(f, {})
upd_feat(truth, f, weights.get(truth, 0.0), 1.0)
upd_feat(guess, f, weights.get(guess, 0.0), -1.0)
def average_weights(self):
for feat, weights in self.weights.items():
new_feat_weights = {}
for clas, weight in weights.items():
param = (feat, clas)
total = self._totals[param]
total += (self.i - self._tstamps[param]) * weight
averaged = round(total / float(self.i), 3)
if averaged:
new_feat_weights[clas] = averaged
self.weights[feat] = new_feat_weights
def save(self, path):
print "Saving model to %s" % path
pickle.dump(self.weights, open(path, 'w'))
def load(self, path):
self.weights = pickle.load(open(path))
class PerceptronTagger(object):
'''Greedy Averaged Perceptron tagger'''
model_loc = os.path.join(os.path.dirname(__file__), 'models/tagger.pickle')
def __init__(self, classes=None, load=True):
self.tagdict = {}
if classes:
self.classes = classes
else:
self.classes = set()
self.model = Perceptron(self.classes)
if load:
self.load(PerceptronTagger.model_loc)
def tag(self, words, tokenize=True):
prev, prev2 = START
tags = DefaultList('')
context = START + [self._normalize(w) for w in words] + END
for i, word in enumerate(words):
tag = self.tagdict.get(word)
if not tag:
features = self._get_features(i, word, context, prev, prev2)
tag = self.model.predict(features)
tags.append(tag)
prev2 = prev; prev = tag
return tags
def start_training(self, sentences):
self._make_tagdict(sentences)
self.model = Perceptron(self.classes)
""" UNUSED : THERE IS NO end_training here...
def train(self, sentences, save_loc=None, nr_iter=5):
'''Train a model from sentences, and save it at save_loc. nr_iter
controls the number of Perceptron training iterations.'''
self.start_training(sentences)
for iter_ in range(nr_iter):
for words, tags in sentences:
self.train_one(words, tags)
random.shuffle(sentences)
self.end_training(save_loc)
"""
def save(self):
# Pickle as a binary file
pickle.dump((self.model.weights, self.tagdict, self.classes),
open(PerceptronTagger.model_loc, 'wb'), -1)
def train_one(self, words, tags):
prev, prev2 = START
context = START + [self._normalize(w) for w in words] + END
for i, word in enumerate(words):
guess = self.tagdict.get(word)
if not guess:
feats = self._get_features(i, word, context, prev, prev2)
guess = self.model.predict(feats)
self.model.update(tags[i], guess, feats)
prev2 = prev; prev = guess
def load(self, loc):
w_td_c = pickle.load(open(loc, 'rb'))
self.model.weights, self.tagdict, self.classes = w_td_c
self.model.classes = self.classes
def _normalize(self, word):
if '-' in word and word[0] != '-':
return '!HYPHEN'
elif word.isdigit() and len(word) == 4:
return '!YEAR'
elif word[0].isdigit():
return '!DIGITS'
else:
return word.lower()
def _get_features(self, i, word, context, prev, prev2):
'''Map tokens into a feature representation, implemented as a
{hashable: float} dict. If the features change, a new model must be
trained.'''
def add(name, *args):
features[' '.join((name,) + tuple(args))] += 1
i += len(START)
features = defaultdict(int)
# It's useful to have a constant feature, which acts sort of like a prior
add('bias')
add('i suffix', word[-3:])
add('i pref1', word[0])
add('i-1 tag', prev)
add('i-2 tag', prev2)
add('i tag+i-2 tag', prev, prev2)
add('i word', context[i])
add('i-1 tag+i word', prev, context[i])
add('i-1 word', context[i-1])
add('i-1 suffix', context[i-1][-3:])
add('i-2 word', context[i-2])
add('i+1 word', context[i+1])
add('i+1 suffix', context[i+1][-3:])
add('i+2 word', context[i+2])
return features
def _make_tagdict(self, sentences):
'''Make a tag dictionary for single-tag words.'''
counts = defaultdict(lambda: defaultdict(int))
for sent in sentences:
#print type(sent[1])
for word, tag in zip(sent[0], sent[1]):
#print " %s : %s" % (word, tag, )
counts[word][tag] += 1
self.classes.add(tag)
freq_thresh = 20
ambiguity_thresh = 0.97
for word, tag_freqs in counts.items():
tag, mode = max(tag_freqs.items(), key=lambda item: item[1])
n = sum(tag_freqs.values())
# Don't add rare words to the tag dictionary
# Only add quite unambiguous words
if n >= freq_thresh and (float(mode) / n) >= ambiguity_thresh:
self.tagdict[word] = tag
print "_make_tagdict added : %10s -> %10s" % (word, tag, )
def _pc(n, d):
return (float(n) / d) * 100
def train_tagger(parser, sentences, nr_iter):
parser.tagger.start_training(sentences)
for itn in range(nr_iter):
random.shuffle(sentences)
for words, gold_tags, gold_parse in sentences:
parser.tagger.train_one(words, gold_tags)
print 'Averaging weights'
parser.model.average_weights()
def train(parser, sentences, nr_iter):
parser.tagger.start_training(sentences)
for itn in range(nr_iter):
corr = 0; total = 0
random.shuffle(sentences)
#for words, gold_tags, gold_parse, gold_label in sentences:
for words, gold_tags, gold_parse in sentences:
corr += parser.train_one(itn, words, gold_tags, gold_parse)
if itn < 5:
parser.tagger.train_one(words, gold_tags)
total += len(words)
print itn, '%.3f' % (float(corr) / float(total))
if itn == 4: ## Why now?
parser.tagger.model.average_weights()
print 'Averaging weights'
parser.model.average_weights()
def read_pos(loc):
for line in open(loc):
if not line.strip():
continue
words = DefaultList('')
tags = DefaultList('')
for token in line.split():
if not token:
continue
word, tag = token.rsplit('/', 1)
#words.append(normalize(word))
words.append(word)
tags.append(tag)
pad_tokens(words); pad_tokens(tags)
yield words, tags
def read_conll(loc):
print "read_conll(%s)" % (loc, )
for sent_str in open(loc).read().strip().split('\n\n'):
lines = [line.split() for line in sent_str.split('\n')]
words = DefaultList('')
tags = DefaultList('')
heads = [None]
labels = [None]
for i, (word, pos, head, label) in enumerate(lines):
#print "%d = %s" % (i, word)
words.append(intern(word))
#words.append(intern(normalize(word)))
tags.append(intern(pos))
heads.append(int(head) + 1 if head != '-1' else len(lines) + 1)
labels.append(label)
pad_tokens(words)
pad_tokens(tags)
yield words, tags, heads, labels
def read_conll_mdda(loc):
print "read_conll_mdda(%s)" % (loc, )
for sent_str in open(loc).read().strip().split('\n\n'):
lines = [line.split() for line in sent_str.split('\n')]
words = DefaultList('')
tags = DefaultList('')
heads = [None]
for i, (word, pos, head) in enumerate(lines):
#print "%d = %s" % (i, word)
words.append(intern(word))
#words.append(intern(normalize(word)))
tags.append(intern(pos))
heads.append(int(head) if head != '0' else len(lines) + 1) # mdda : don't increment our file...
pad_tokens(words)
pad_tokens(tags)
#print "END OF SENTENCE"
yield words, tags, heads
def pad_tokens(tokens):
tokens.insert(0, '<start>')
tokens.append('ROOT')
def main_orig(model_dir, train_loc, heldout_in, heldout_gold):
if not os.path.exists(model_dir):
os.mkdir(model_dir)
input_sents = list(read_pos(heldout_in))
parser = Parser(load=False)
sentences = list(read_conll(train_loc))
train(parser, sentences, nr_iter=15)
parser.save()
c = 0
t = 0
gold_sents = list(read_conll(heldout_gold))
t1 = time.time()
for (words, tags), (_, _, gold_heads, gold_labels) in zip(input_sents, gold_sents):
_, heads = parser.parse(words)
for i, w in list(enumerate(words))[1:-1]:
if gold_labels[i] in ('P', 'punct'):
continue
if heads[i] == gold_heads[i]:
c += 1
t += 1
t2 = time.time()
print 'Parsing took %0.3f ms' % ((t2-t1)*1000.0)
print c, t, float(c)/t
def learn_mdda(model_dir, train_loc, load_if_exists=False):
if not os.path.exists(model_dir):
os.mkdir(model_dir)
random.seed(04) # Has some successes, the failure on assert(gold_moves)
parser = Parser(load=load_if_exists)
sentences = list()
for f in [f for f in os.listdir(train_loc) if os.path.isfile(os.path.join(train_loc, f)) and f.endswith(".dp")]:
sentences.extend(list(read_conll_mdda(os.path.join(train_loc, f))))
#break # Just 1 set of sentences to start
#print sentences
#train_tagger(parser, sentences, nr_iter=10)
train(parser, sentences, nr_iter=15)
#parser.save()
return
#input_sents = list(read_pos(heldout_in))
c = 0
t = 0
gold_sents = list(read_conll(heldout_gold))
t1 = time.time()
for (words, tags), (_, _, gold_heads, gold_labels) in zip(input_sents, gold_sents):
_, heads = parser.parse(words)
for i, w in list(enumerate(words))[1:-1]:
if gold_labels[i] in ('P', 'punct'):
continue
if heads[i] == gold_heads[i]:
c += 1
t += 1
t2 = time.time()
print 'Parsing took %0.3f ms' % ((t2-t1)*1000.0)
print c, t, float(c)/t
def sentence_to_words(sentence):
s = sentence
s = s.replace("...", " #ELIPSIS# ")
s = s.replace(",", " , ").replace(".", " . ").replace(":", " : ").replace(";", " ; ")
s = s.replace("$", " $ ")
s = re.sub(r"(\d+\.?\d*)", r" \1 ", s)
s = s.replace("\"", " \" ").replace("''", " '' ").replace("``", " `` ")
s = s.replace(" #ELIPSIS# ", " ... ")
s = s.replace("'t", " 't ").replace("'m", " 'm ").replace("'ve", " 've ").replace("'d", " 'd ")
words = DefaultList('')
for w in s.split(): # On all whitespace
words.append(w)
return words
"""
## Redshift run parameters (for hints)
./scripts/train.py -x zhang+stack -k 8 -p ~/data/stanford/train.conll ~/data/parsers/tmp
./scripts/parse.py ~/data/parsers/tmp ~/data/stanford/devi.txt /tmp/parse/
./scripts/evaluate.py /tmp/parse/parses ~/data/stanford/dev.conll
"""
if __name__ == '__main__':
#main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
if False :
t1 = time.time()
learn_mdda("models", "/home/andrewsm/nltk_data/corpora/dependency_treebank/")
t2 = time.time()
print 'Tagger Learning took %0.3f s' % ((t2-t1)*1.0)
if True :
t1 = time.time()
learn_mdda("models", "/home/andrewsm/nltk_data/corpora/dependency_treebank/")
t2 = time.time()
print 'Combined Learning took %0.3f s' % ((t2-t1)*1.0)
# But each tagger learning took ~ 7.4sec
print 'Dependecy Learning (without tagger) the took %0.3f s' % ((t2-t1)*1.0 - 5*7.4)
if False :
sentences = [
"Sorry for taking a little longer than just the weekend : Though I think I've now got a good handle on the problem, the given solutions, and have realistic ideas about what you can expect from an implementation...",
"I've attached a ZIP of your originals, plus some derived entities - which I extracted using open source (non-commercial) software that was trained on 'generic' documents. ",
"FWIW, these appear to be Gnosis-level results.",
"Having dug into the area a little, I'm convinced that the greatest gains will come from a system that learns as it goes (and will therefore adapt to your specific datasets). "
"For instance, your Singapore data is very comprehensive, with 'gold standard' entities and relationship already extracted from it. ",
"So for new documents, the system would have a lot of additional data to hone its 'hypotheses' on, and should be expected to do pretty well.",
"For the new Malaysian data (for example), a generic machine learner won't already know that 'Dato'' is a significant marker for Person-hood, but would quickly be able to figure it out once a few examples had been tagged expertly.",
"Similarly, the date/period extraction tasks would be improved quickly, which are plainly more important for your work than for 'generic' documents. "
"Thus, a cooperative system could be expected to rise fairly quickly to Invoxis-level quality, and grow dynamically beyond that.",
"Does it make sense for me to put together some notes in a quick presentation (to send to you ~tonight) - and then to follow up with a quick sit-down sometime soon? ",
"On one hand : I don't have anything specific to sell you.",
"On the other hand : these systems are not a one-size-fits-all kind of thing.",
"Would you be free to meet up and chat some time the week after next? ",
"Might be easier if we have a face to face informal discussion, and save you the need to put together a presentation."
"As discussed here is a sample set of docs for you. ",
"The excel file named POC Sample includes a starting example that we gave to the vendor for them to understand what detail and level of structure we need in our output.",
"Ding Zhigang (the brother of CEO - Ms Ding Zhiying) is our Non-Executive Director and Non-Executive Chairman and was appointed on 8 August 2008. ",
"He oversees the Group's overall business strategies for future development. ",
"From 2005 to the present, he is the general manager of Wuxi Dadi Real Estate Co. ",
"He was the president of Wuxi Xin-Dingqiu Real Estate Co. from June 2002 to 2005. ",
"Between 1999 and 2001, he was the vice-president of Jiangsu Dingqiu Industrial Co. Ltd. ",
"Between 1995 and 1999, he was the general manager of China Trading Resource Inc. in the USA.",
"Ding Zhiying is our CEO and was appointed as Executive Director on 20 April 2004. ",
"She oversees the day-to-day management and operations of the Group as well as the sales and marketing of the Group. ",
"She is also responsible for the Group's overall business strategies and policies. ",
"Prior to joining the Group, Ms Ding was the general manager of Jiangsu Xindingqiu between August 2001 and February 2004. ",
"Between 1994 and 2000, Ms Ding worked in the Shenzhen office of Yixing Silk-Linen Factory and was in charge of regional sales. ",
"Prior to that, she was in charge of finance in Yixing Taihua Silk Weaving Factory from 1990 to 1993. ",
"She obtained an accounting certificate from the Nanjing University, Adult Educational Institute in December 1991.",
]
parser = Parser(load=True)
for s in sentences:
words = sentence_to_words(s)
pad_tokens(words)
tags, structure = parser.parse(words)
for (i, (w,t,s)) in enumerate(zip(words, tags, structure)):
#print i, " : ", w, " - ", t, " - ", s
if s>=len(words)-1: s='ROOT'
print "%2d : %20s : %4s - %2s" % (i+0, w, t, s)
|
997,833 | 337e3f85934b0abe59b526ed90cf0cb965049d5c | import subprocess
import os
import time
status = subprocess.Popen("python status-server.py", shell=True, stdout=subprocess.PIPE)
while 1:
# check every 5 minutes whether nfd is alive
time.sleep(300)
try:
output=subprocess.check_output('nfd-status | grep \"memphis.edu/internal\"', shell=True)
print(output)
except subprocess.CalledProcessError,e:
output=e.output
print("output", output)
if "memphis.edu/internal" not in output:
try:
status.terminate()
status = subprocess.Popen(["python status-server.py"], stdout=subprocess.PIPE)
except:
pass
else:
pass
|
997,834 | c6ede32397cc521e1f40bee78fc9ce6759165143 | '''This file has been used for the research project course (ENGN8601/ENGN8602) by Namas Bhandari of the Australian National University. The file can be found on github.com/namas191297/evaluating_mvs_in_cpc'''
import numpy as np
import matplotlib.pyplot as plt
import cv2
import scipy.ndimage
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
import os
import torch.nn.functional as F
import torch
np.printoptions(precision=2)
def mask_loss(gt_mask, pred_mask):
'''This function is used to calculate the Binary Cross Entropy loss and the IoU between the estimated depthmap
after mask estimation and the ground truth depthmap'''
gt_mask = torch.from_numpy(gt_mask)
pred_mask = torch.from_numpy(pred_mask)
loss = F.binary_cross_entropy(pred_mask.float(), gt_mask.float())
gt_pred = gt_mask > .5
cv_pred = pred_mask > .5
intersection = torch.sum(cv_pred & gt_pred, dtype=torch.float32, dim=[0, 1])
union = torch.sum(cv_pred | gt_pred, dtype=torch.float32, dim=[0, 1])
gt_sum = torch.sum(gt_pred, dtype=torch.float32, dim=[0, 1])
cv_sum = torch.sum(cv_pred, dtype=torch.float32, dim=[0, 1])
acc = torch.mean((cv_pred == gt_pred).to(dtype=torch.float32))
prec = intersection / cv_sum
prec[cv_sum == 0] = 1 - intersection.clamp(0, 1)[cv_sum == 0]
prec = prec.mean()
rec = intersection / gt_sum
rec[gt_sum == 0] = 1 - intersection.clamp(0, 1)[gt_sum == 0]
rec = rec.mean()
iou = intersection / union
iou[union == 0] = 1
iou = iou.mean()
return {
"loss": loss,
"acc": acc,
"prec": prec,
"rec": rec,
"iou": iou
}
def weighted_entropy(entropies, weights):
'''This function is used to calculate the weighted entropy from the given input entropy maps and the weights'''
entropies = np.array(entropies)
entropy = np.zeros((512, 512))
for ix, w in enumerate(weights):
entropy += np.asarray(entropies[ix]) * w
entropy /= np.sum(weights)
return entropy
def plot_grid(ref_img, entropies, op_dir, gt_mask, th_range=10):
'''This function is used to calculate the 10 best estimated masks for each image and plots it into a grid and saves the mask in a .npy file'''
refcopy = ref_img.copy()
w_range = np.linspace(0.3, 0.9, 6)
#Load and upsample the entropies
if entropies == None:
e_64 = np.load('prob_vol_entropy_64.npy')[0].transpose(1,2,0).reshape(64,64)
e_64 = scipy.ndimage.zoom(e_64, 8, order=1)
e_128 = np.load('prob_vol_entropy_128.npy')[0].transpose(1,2,0).reshape(128,128)
e_128 = scipy.ndimage.zoom(e_128, 4, order=1)
e_256 = np.load('prob_vol_entropy_256.npy')[0].transpose(1,2,0).reshape(256,256)
e_256 = scipy.ndimage.zoom(e_256, 2, order=1)
entropies = [e_64, e_128, e_256]
else:
e_64, e_128, e_256 = entropies[0], entropies[1], entropies[2]
# Compute the weighted average of entropies
#weights = weights
# Loop through the weights
max_loss = 1e+5
lowest_losses = []
lowest_ious = []
mds = []
for w1 in w_range:
for w2 in w_range:
for w3 in w_range:
weights = [w1, w2, w3]
entropy = weighted_entropy(entropies, weights)
#Save the entropies
#plt.imsave(f'{op_dir}/{str(w1)+str(w2)+str(w3)}entropy_64.png', e_64)
#plt.imsave(f'{op_dir}/{str(w1)+str(w2)+str(w3)}entropy_128.png', e_128)
#plt.imsave(f'{op_dir}/{str(w1)+str(w2)+str(w3)}entropy_256.png', e_256)
#Initialize masks
mask = np.zeros((512,512))
threshold_range = np.linspace(1.1, 1.8, 20)
#Calculate all masks and plot
for idx, th in enumerate(threshold_range):
mask[np.where(entropy > th)[0], np.where(entropy > th)[1]] = 0
mask[np.where(entropy < th)[0], np.where(entropy < th)[1]] = 1
#Calculate loss dictionary
d = mask_loss(gt_mask, mask)
current_loss = d['loss'].numpy().copy()
md = {
'refcopy':refcopy,
'weights':weights,
'mask':mask,
'entropy':entropy,
'th':th,
'd':d,
}
mds.append(md)
if current_loss < max_loss:
max_loss = current_loss
best = {
'refcopy':refcopy,
'weights':weights,
'mask':mask,
'entropy':entropy,
'th':th,
'd':d,
}
# Calculated occluded pixels
valid_pixels = np.where(md['mask'] == 1)
missing_pixels = np.where(md['mask'] == 0)
# Apply mask
masked_image = cv2.bitwise_and(md['refcopy'], md['refcopy'], mask=md['mask'].astype(np.uint8))
fig = plt.figure(figsize=(20,10))
#plt.title(f'Weights (w1,w2,w3):{weights}, Threshold:{th}')
ax1 = fig.add_subplot(1,4,1)
ax1.title.set_text('Ref Image')
ax1.imshow(md['refcopy'])
plt.axis('off')
ax2 = fig.add_subplot(1,4,2)
ax2.title.set_text('Entropy')
divider = make_axes_locatable(ax2)
cax = divider.append_axes('right', size='5%', pad=0.05)
ent_im = ax2.imshow(md['entropy'])
plt.colorbar(ent_im,fraction=0.04, pad=10)
plt.axis('off')
ax3 = fig.add_subplot(1,4,3)
ax3.title.set_text(f'Mask THR={np.round(md["th"],2)}, Weights={md["weights"]}, Loss:{np.round(md["d"]["loss"],2)}, IoU:{np.round(md["d"]["iou"],2)}')
ax3.imshow(md['mask'])
plt.axis('off')
ax4 = fig.add_subplot(1,4,4)
ax4.title.set_text('Masked Image')
ax4.imshow(masked_image)
plt.axis('off')
plt.savefig(op_dir + 'plot' + '_' + str(w1) + str(w2) + str(w3) + '_' + str(md["th"]) + '.png')
np.save(f'{op_dir}plot_{str(w1)}{str(w2)}{str(w3)}_{str(md["th"])}.npy', md["mask"])
plt.close('all') ##Remove this if any error
'''The following code plots the best mask obtained as per the losses (However, this can result in worse masks sometimes, so check manually)'''
#Calculated occluded pixels
valid_pixels = np.where(best['mask'] == 1)
missing_pixels = np.where(best['mask'] == 0)
# Apply mask
masked_image = cv2.bitwise_and(best['refcopy'], best['refcopy'], mask=best['mask'].astype(np.uint8))
fig = plt.figure(figsize=(20,10))
#plt.title(f'Weights (w1,w2,w3):{weights}, Threshold:{th}')
# Append the best loss
lowest_losses.append(np.round(best["d"]["loss"],2))
lowest_ious.append(np.round(best["d"]["iou"],2))
# Plots
ax1 = fig.add_subplot(1,4,1)
ax1.title.set_text('Ref Image')
ax1.imshow(best['refcopy'])
plt.axis('off')
ax2 = fig.add_subplot(1,4,2)
ax2.title.set_text('Entropy')
divider = make_axes_locatable(ax2)
cax = divider.append_axes('right', size='5%', pad=0.05)
ent_im = ax2.imshow(best['entropy'])
plt.colorbar(ent_im,fraction=0.04, pad=10)
plt.axis('off')
ax3 = fig.add_subplot(1,4,3)
ax3.title.set_text(f'Mask THR={np.round(best["th"],2)}, Weights={best["weights"]}, Loss:{np.round(best["d"]["loss"],2)}, IoU:{np.round(best["d"]["iou"],2)}')
ax3.imshow(best['mask'])
plt.axis('off')
ax4 = fig.add_subplot(1,4,4)
ax4.title.set_text('Masked Image')
ax4.imshow(masked_image)
plt.axis('off')
plt.savefig(op_dir + 'best' + '.png')
plt.close('all') ##Remove this if any error
return np.round(best["d"]["loss"],2), np.round(best["d"]["iou"],2)
if __name__ == '__main__':
print('Starting Mask Estimation.....')
r_dir = 'ref_images/'
lowest_losses = []
lowest_ious = []
for idx, imf in enumerate(os.listdir(r_dir)):
imf_dir = r_dir + imf + '/'
ref_image = None
if os.path.exists(imf_dir + 'grid_outputs'):
for f in os.listdir(imf_dir + 'grid_outputs'):
os.remove(imf_dir + 'grid_outputs' + '/' + f)
os.rmdir(imf_dir + 'grid_outputs')
os.mkdir(imf_dir + 'grid_outputs')
else:
op_dir = os.mkdir(imf_dir + 'grid_outputs')
grid_dir = imf_dir + 'grid_outputs/'
for item in os.listdir(imf_dir):
item_path = imf_dir + item
#gt_path = imf_dir + 'label.png'
gt_path = imf_dir + 'mask.npy'
if 'refimage' in item and 'png' in item:
ref_image = plt.imread(item_path)[:,:,:3]
elif '64' in item:
e_64 = np.load(item_path)[0].transpose(1,2,0).reshape(64,64)
e_64 = scipy.ndimage.zoom(e_64, 8, order=1)
elif '128' in item:
e_128 = np.load(item_path)[0].transpose(1,2,0).reshape(128,128)
e_128 = scipy.ndimage.zoom(e_128, 4, order=1)
elif '256' in item:
e_256 = np.load(item_path)[0].transpose(1,2,0).reshape(256,256)
e_256 = scipy.ndimage.zoom(e_256, 2, order=1)
#gt_mask = cv2.imread(gt_path)[:,:,2]
#gt_mask = np.where(gt_mask == 0, 1, 0)
gt_mask = np.load(gt_path)[0][0]
#plt.imshow(gt_mask)
#plt.colorbar()
#plt.show()
entropies = [e_64, e_128, e_256]
lowest_loss, lowest_iou = plot_grid(ref_image, entropies, grid_dir, gt_mask)
lowest_losses.append(lowest_loss)
lowest_ious.append(lowest_ious)
print(f'Done plotting for Image {idx+1}/{len(os.listdir(r_dir))}: Loss:{lowest_loss}, IoU:{lowest_iou}')
print(f'Average Loss:{np.array(lowest_losses).mean()}, Average IoU:{np.array(lowest_ious).mean()}')
|
997,835 | d51576bdc428a3d138eb33366af6352e01ed811d | from toolz import curry
@curry
def pair(first, second):
"""Takes two arguments, fst and snd, and returns [fst, snd]"""
return [first, second]
|
997,836 | c44798efe82c4be83503d135e0a1a545eecf4b5d | a = [11, 21, 31, 11, 21, 31, 41, 51]
d = {}
for i in a:
d[i] = d.get(i, 0) + 1
print d.items()
|
997,837 | 83d7d8622cfd0d7c6b6ddafeb0ebc08ff9ceb851 | #!/usr/bin/env python
import itertools
import os
import pygame
import random
import sys
import time
import thorpy
from pygame.locals import *
import common
LEFT_MOUSE = 1
RIGHT_MOUSE = 3
class MineCell(common.Cell):
def __init__(self, r, c, w, h, border, font):
super().__init__(r, c, w, h, border, font)
def reset(self):
super().reset()
self.hidden = True
self.mine = False
self.flagged = False
self.mine_count = 0
def count_mines(self):
self.mine_count = len([n for n in self.neighbors if n.mine])
mtw, mth = self.font.size(str(self.mine_count))
mtx = self.bg_rect.width/2 - mtw/2
mty = self.bg_rect.height/2 - mth/2
self.mine_text_rect = pygame.Rect(self.bg_rect.x + mtx, self.bg_rect.y + mty, mtw, mth)
def click(self, button):
if button == LEFT_MOUSE and not self.flagged:
self.reveal()
elif button == RIGHT_MOUSE and self.hidden:
self.flagged = not self.flagged
self.dirty = True
def reveal(self, endgame=False):
if self.hidden:
if endgame:
self.flagged = False # TODO show whether the guess was correct
self.hidden = False
self.dirty = True
if self.mine_count == 0:
for n in self.neighbors:
n.reveal()
def paint(self, surface):
if self.dirty:
self.dirty = False
bg_colour = (120, 120, 120) if self.selected else (0, 0, 0)
button_colour = (100, 80, 80) # dug up soil
if self.flagged:
button_colour = (40, 40, 160) # bright blue
elif self.hidden:
button_colour = (40, 160, 40) # grass
elif self.mine:
button_colour = (200, 20, 20) # red for now, someday use a crater tile
surface.fill(bg_colour, self.bg_rect)
surface.fill(button_colour, self.button_rect)
if not self.hidden and not self.mine and self.mine_count > 0:
mine_text = self.font.render(str(self.mine_count), True, (240, 240, 240), button_colour)
surface.blit(mine_text, self.mine_text_rect)
class Minefield(common.Gameboard):
def __init__(self, parent, screen, background, font, rows, columns, mine_count):
super().__init__(parent, screen, background, font, rows, columns)
self.mine_count = mine_count
self.wins = 0
self.losses = 0
self.reset()
def reset(self):
super().reset_selection()
self.exploded = False
self.victory = False
self.mines = []
def create_cell(self, row, column, width, height, border, font):
return MineCell(row, column, width, height, border, font)
def paint(self):
if self.exploded:
pygame.display.set_caption("Game Over!")
super().paint() # TODO show a game over overlay instead
elif self.victory:
pygame.display.set_caption("Victory!")
super().paint() # TODO show a victory overlay instead
else:
super().paint()
def win(self):
self.victory = True
self.wins += 1
self.reveal_board()
def lose(self):
self.exploded = True
self.losses += 1
self.reveal_board()
def click_selected_cell(self, button):
if button == RIGHT_MOUSE and len(self.mines) == 0:
return
c = self.get_cell(self.kb_row, self.kb_col)
if c is not None:
if len(self.mines) == 0:
self.deploy_mines(c.row, c.column)
c.click(button)
if not c.hidden:
if c.mine:
self.lose()
elif self.mine_count == sum(c.hidden for c in self.cells):
self.win()
def reveal_board(self):
for c in self.cells:
c.reveal(True)
def deploy_mines(self, click_row, click_column):
m = self.mine_count
while m > 0:
next_mine = random.randint(0, self.rows-1), random.randint(0, self.columns-1)
if next_mine != (click_row, click_column) and next_mine not in self.mines:
self.mines.append(next_mine)
self.get_cell(next_mine[0], next_mine[1]).mine = True
m -= 1
for c in self.cells:
c.count_mines()
for (dr, dc) in itertools.product((-1, 0, 1), (-1, 0, 1)):
c = self.get_cell(click_row+dr, click_column+dc)
if c is not None and not c.mine:
c.reveal()
def handle_key(self, key):
if key == K_q:
self.active = False
elif not self.exploded and not self.victory:
if key in (K_UP, K_w):
self.decrement_kb_row()
elif key in (K_DOWN, K_s):
self.increment_kb_row()
elif key in (K_LEFT, K_a):
self.decrement_kb_col()
elif key in (K_RIGHT, K_d):
self.increment_kb_col()
elif key in (K_RETURN, K_SPACE):
self.click_selected_cell(LEFT_MOUSE)
elif key in (K_BACKSPACE, K_r):
self.click_selected_cell(RIGHT_MOUSE)
def handle_mouse_button(self, button, pos):
if not self.exploded and not self.victory:
for c in self.cells:
if c.button_rect.collidepoint(pos):
self.unselect_cell(self.kb_row, self.kb_col)
self.kb_row, self.kb_col = c.row, c.column
c.select()
self.click_selected_cell(button)
elif c.selected:
c.unselect()
def handle_event(self, event):
if event.type == MOUSEBUTTONUP and not self.exploded:
self.handle_mouse_button(event.button, event.pos)
elif event.type == KEYUP:
self.handle_key(event.key)
elif event.type == QUIT:
self.parent.active = False
self.active = False
class OptionMenu(common.Scene):
def __init__(self, parent, screen, background, font, rows, columns):
super().__init__(parent, screen, background, font)
self.quit_button = thorpy.make_button('Return', func=OptionMenu.quit, params={'self': self})
self.varset = thorpy.VarSet()
self.varset.add('rows', value=rows, text='Rows:', limits=(5,20))
self.varset.add('columns', value=columns, text='Columns:', limits=(5,20))
self.box = thorpy.ParamSetter([self.varset], elements=[self.quit_button], size=(screen.get_width(), screen.get_height()))
thorpy.store(self.box)
self.menu = thorpy.Menu(self.box)
for element in self.menu.get_population():
element.surface = self.screen
def handle_event(self, event):
if event.type == KEYUP:
if event.key == K_q:
self.quit()
elif event.type != KEYDOWN:
self.menu.react(event)
def paint(self):
self.box.blit()
self.box.update()
def quit(self):
self.rows = self.varset.get_value('rows')
self.columns = self.varset.get_value('columns')
self.active = False
class MainMenu(common.Scene):
def __init__(self, parent, screen, background, font):
super().__init__(parent, screen, background, font)
self.rows = 15
self.columns = 15
self.mine_count = (self.rows*self.columns)/10
self.gameboard = Minefield(self, screen, background, font, self.rows, self.columns, self.mine_count)
self.title = thorpy.make_text('Minesweeper', font_size=20, font_color=(0, 0, 150))
self.start_button = thorpy.make_button('New Game', func=MainMenu.activate_gameboard, params={'self': self})
self.options_button = thorpy.make_button('Options', func=MainMenu.activate_options, params={'self': self})
self.quit_button = thorpy.make_button('Quit', func=MainMenu.quit, params={'self': self})
self.box = thorpy.Box(elements=[self.title, self.start_button, self.options_button, self.quit_button], size=(screen.get_width(), screen.get_height()))
thorpy.store(self.box)
self.menu = thorpy.Menu(self.box)
for element in self.menu.get_population():
element.surface = self.screen
def handle_event(self, event):
if event.type == KEYUP:
if event.key == K_q:
self.quit()
elif event.key == K_n:
self.activate_gameboard()
elif event.key == K_o:
self.activate_options()
elif event.type != KEYDOWN:
self.menu.react(event)
def paint(self):
pygame.display.set_caption("Minesweeper!")
self.box.blit()
self.box.update()
def quit(self):
self.active = False
print(f'wins {self.gameboard.wins} losses {self.gameboard.losses}')
def activate_gameboard(self):
self.gameboard.activate()
self.gameboard.reset()
self.gameboard.reset_cells()
def activate_options(self):
self.options = OptionMenu(self, self.screen, self.background, self.font, self.rows, self.columns)
self.options.activate()
# TODO need to figure out why rows/columns not being passed up
self.rows = self.options.rows
self.columns = self.options.columns
self.mine_count = (self.rows*self.columns)/10
self.gameboard = Minefield(self, self.screen, self.background, self.font, self.rows, self.columns, self.mine_count)
def window_init(width, height, caption):
pygame.display.set_mode((width, height))
pygame.display.set_caption(caption)
screen = pygame.display.get_surface()
background = pygame.Surface(screen.get_size()).convert()
background.fill((0, 0, 0))
screen.blit(background, (0, 0))
pygame.display.flip()
return screen, background
def main():
pygame.init()
thorpy.set_theme('human')
width = 600
height = 600
font = pygame.font.SysFont("Arial", 18)
screen, background = window_init(width, height, "Minesweeper!")
main_menu = MainMenu(None, screen, background, font)
main_menu.activate()
if __name__ == '__main__':
main()
|
997,838 | c553bd0281b55628e82e1173e315013c0f42c0b5 | from mdp import EpidemicMDP # changed from import mdp
import random
from collections import defaultdict
import matplotlib.pyplot as plt
infections = {'Nigeria' : 1}
resources = 15
# resp_csv = 'data/FR_MAUR_NIG_SA_responseIndicators.csv'
# trans_csv = 'data/FR_MAUR_NIG_SA_transitions.csv'
resp_csv = 'data/country_response_indicators.csv'
#trans_csv = 'data/transitions.csv'
trans_csv = 'data/transitions_7countries.csv'
newmdp = EpidemicMDP(trans_csv, resp_csv, infections, resources) # sorta awk to declare twice but getActions needs instance
print(newmdp.countries)
NUM_COUNTRIES = newmdp.NUM_COUNTRIES
MAX_MDP_REWARD = newmdp.MAX_REWARD
INDEX_RESOURCE = NUM_COUNTRIES*2
num_trials = 1001
max_iterations = 100
#PY PLOT
Xdata = []
Ydata = [[],[],[],[]]
ENDdata = [0,0,0,0]
# Given a number of resources, allocates one to each country.
# If # resources < # countries, then the first (# countries - # resources)
# countries won't receive any resource.
def getUniformActions(state):
resources = state[INDEX_RESOURCE]
action = []
countries = NUM_COUNTRIES-1
for i in range(resources):
if (countries == -1): break
action.append(countries)
countries -= 1
return [action]
# Allocate all resources to all and only infected countries.
# Will use all resources in first time step.
# Allocates equally amongst infected states, so long as
# resources can be divided equally amongst the infected states.
def getEqualActions(state):
action_indices = []
for i in range(0, NUM_COUNTRIES):
if (state[i] == 1):
action_indices.append(i)
resources = state[INDEX_RESOURCE]
action = []
index = len(action_indices)-1
for i in range(resources):
if (index == -1):
index = len(action_indices)-1 #start over, we run until i == resources
action.append(action_indices[index])
index -= 1
return [action]
# Do not allocate any resources
def getNoActions(state):
actions = [[]]
return actions
# Select random action from all possible actions
# (all possible allocations of possible resource quantities at time t)
def getRandomActions(state):
actions = newmdp.getActions(state)
if (actions == []): return []
else:
c = random.choice(actions)
return [c]
def simulate(actionCommand, trial_num, resp_csv, trans_csv, infections, resources, baseline):
grand_total_rewards = 0
mdp = EpidemicMDP(trans_csv, resp_csv, infections, resources)
s = mdp.state
total_reward = 0
resources_depleted_delay = 2
its = 0
for i in range(max_iterations):
if mdp.isEnd(s): break
if resources_depleted_delay == 0: break
if (s[INDEX_RESOURCE] <= 0):
resources_depleted_delay -= 1
actions = actionCommand(s)
max_reward = float("-inf")
max_state = s
for action in actions:
new_s, reward = mdp.sampleNextState(s, action)
if (reward > max_reward):
max_reward = reward
max_state = new_s
s = max_state
total_reward += max_reward
its += 1
if its == 0:
print("TRIAL:", trial_num, '- SIMULATION ITERATIONS EQUALS ZERO')
else:
avg_reward = total_reward/float(its)
# print("End: ", max_reward)
# print("Average: ", avg_reward)
# If virus killed by the end state
if (max_reward == MAX_MDP_REWARD): ENDdata[baseline] += 1
return avg_reward
#Ydata[baseline].append(avg_reward)
### UNIFORM RESOURCE ALLOCATION: EVERYTHING AT T=1, EQUAL NUMBERS TO EACH STATE
print(" ")
print("##### UNIFORM RESOURCE ALLOCATION #####")
r = 0
for i in range(num_trials):
if (i % 20 == 0 or i == 0): Xdata.append(i)
r += simulate(getUniformActions, i, resp_csv, trans_csv, infections, resources, 0)/20.0
if (i % 20 == 0 or i == 0):
Ydata[0].append(r)
r = 0
### EQUAL RESOURCE ALLOCATION: EVERYTHING AT T=1, EQUAL NUMBERS TO EACH INFECTED STATE
print(" ")
print("##### EQUAL RESOURCE ALLOCATION #####")
r = 0
for i in range(num_trials):
r += simulate(getEqualActions, i, resp_csv, trans_csv, infections, resources, 1)/20.0
if (i % 20 == 0 or i == 0):
Ydata[1].append(r)
r = 0
### NO RESOURCE ALLOCATION: DON'T DO ANYTHING
print(" ")
print("##### NO RESOURCE ALLOCATION #####")
r = 0
for i in range(num_trials):
r += simulate(getNoActions, i, resp_csv, trans_csv, infections, resources, 2)/20.0
if (i % 20 == 0 or i == 0):
Ydata[2].append(r)
r = 0
### RANDOM ALLOCATION: RANDOM AMOUNTS ASSIGNED TO RANDOM STATES
print(" ")
print("##### RANDOM RESOURCE ALLOCATION #####")
r = 0
for i in range(num_trials):
r += simulate(getRandomActions, i, resp_csv, trans_csv, infections, resources, 3)/20.0
if (i % 20 == 0 or i == 0):
Ydata[3].append(r)
r = 0
#PRINT NUMBER OF SUCCESSFUL GAMES
print("##### UNIFORM RESOURCE ALLOCATION #####")
print(ENDdata[0])
print("##### EQUAL RESOURCE ALLOCATION #####")
print(ENDdata[1])
print("##### NO RESOURCE ALLOCATION #####")
print(ENDdata[2])
print("##### RANDOM RESOURCE ALLOCATION #####")
print(ENDdata[3])
#PLOT
for i in range(4):
if (i == 0): l = "Uniform"
if (i == 1): l = "Equal"
if (i == 2): l = "No Allocation"
if (i == 3): l = "Random"
plt.plot(Xdata, Ydata[i], label = l)
plt.ylabel('Average Reward')
plt.xlabel('Simulation')
plt.title('Average Rewards for all Baselines')
plt.legend()
plt.show()
|
997,839 | f55ec6af83d35a25f61c826f42fb6bb7ed4a62a5 | shopping_list.remove("milk")
shopping_list.append("brownie")
|
997,840 | a6f557bcfdf7fbc60351c2c9dd5130d2a76f5742 | """
A Python script that runs the fmr.R R script.
"""
# Import the commands module and run the fmr.R script.
import commands
result = commands.getstatusoutput("Rscript --verbose fmr.R")
# Check the exit status to see if the run was successful
# and print the output.
if result[0] == 0:
print "*** Successful run! ***\n"
print result[1]
else:
print "*** Run failed! ****\n"
print result[1]
|
997,841 | 97699d09fdee02cf3ca6ef0e383a60ea6331f109 |
# helperFunction: uses all the other functions
#permList is the final list or array of all possible permutations
def helperFunction(inputString):
permList = [];
permList.append(permutateReverse(inputString))
permList += permutateInitials(inputString)
permList += permutateNumbers(inputString)
permList += firstAndLastName(inputString)
permList += dots(inputString)
return normalize(permList)
# permutateNumbers: inserts #s 1-10 at the end
# Used to have 65-99 and 1965-1999, but not anymore
def permutateNumbers(inputString):
numPermutationList = [];
if(inputString.find(' ') != -1):
space = inputString.find(' ')
noSpaceName = inputString[0:space] + inputString[space+1:-1] + inputString[-1]
for i in range(0, 10):
numPermutationList.append(noSpaceName + str(i));
else:
upperCase = [up for up in inputString if up.isupper()]
space = inputString.find(upperCase[1])
noSpaceName = inputString[0:space] + inputString[space+1:-1] + inputString[-1]
for i in range(0, 10):
numPermutationList.append(noSpaceName + str(i));
for i in range(65, 100):
numPermutationList.append(noSpaceName + str(i));
numPermutationList.append(noSpaceName + '19' + str(i));
return numPermutationList;
#permutateReverse: Switchis first and last name
def permutateReverse(inputString):
if(inputString.find(' ') != -1):
space = inputString.find(' ')
return inputString[space+1:-1]+ inputString[-1] + inputString[0:space]
else:
upperCase = [up for up in inputString if up.isupper()]
space = inputString.find(upperCase[1])
return inputString[space+1:-1]+ inputString[-1] + inputString[0:space]
#permutateInitials: Gets first initial last name, and first name last initial
def permutateInitials(inputString):
if(inputString.find(' ') != -1):
space = inputString.find(' ')
initials = [inputString[0] + inputString[space+1:-1] + inputString[-1], inputString[0:space] + inputString[space+1]]
return initials
else:
upperCase = [up for up in inputString if up.isupper()]
space = inputString.find(upperCase[1])
initials = [inputString[0] + inputString[space+1:-1] + inputString[-1], inputString[0:space] + inputString[space+1]]
return initials
def firstAndLastName(inputString):
firstAndLastNameList = []
if(inputString.find(' ') != -1):
space = inputString.find(' ')
firstAndLastNameList.append(inputString[0:space])
firstAndLastNameList.append(inputString[space+1:-1] + inputString[-1:])
else:
upperCase = [up for up in inputString if up.isupper()]
space = inputString.find(upperCase[1])
firstAndLastNameList.append(inputString[0:space])
firstAndLastNameList.append(inputString[space:-1] + inputString[-1])
return firstAndLastNameList
#dots: Adds dots. **NOT FINISHED**
def dots(inputString):
dotsList = []
if(inputString.find(' ')!= -1):
space = inputString.find(' ')
middleDot = inputString.replace(' ', '.')
dotsList.append(middleDot)
else:
upperCase = [up for up in inputString if up.isupper()]
space = inputString.find(upperCase[1])
middleDot = inputSTring.replace(' ', '.')
dotsList.append(middleDot)
return dotsList
def normalize(l):
result = []
for str in l:
result.append(str.lower().replace(' ','').replace('.',''))
return result
|
997,842 | 7afc53bdbab10831c52a21c3922f25f95b82c85d | from gym.envs.registration import register
register(
id='CrowdSim-v0',
entry_point='crowd_sim.envs:CrowdSim',
)
register(
id='CrowdSim_mixed-v0',
entry_point='crowd_sim.envs:CrowdSim_mixed'
)
|
997,843 | c64ce76c63dfb2c7282d04051be4c994f7c17aa4 | import json
def getCurrentUser():
user = {}
with open("../db.json") as f:
user = json.load(f)
return user["current-user"]
triviaPos = 0
def getNextTrivia():
triv = []
with open("../trivia.txt") as f:
for line in f.readlines():
triv.append(line.strip().split("/"))
triviaPos = (triviaPos + 1) % len(triv)
return triv[triviaPos] |
997,844 | 57f9a718bafa47f58dcfbd5057c7413ffd6de95a | from .classification import ClassificationNetwork
from .configuration import Configuration
from .logging import Logger, TimeLogger, ProgressLogger
from .segmentation import SegmentationNetwork
from .training import TrainingUtils
from .utils import Utility
from .validation import ValidationUtils
from .windowing import PreWindowedSequence, SlidingWindowSequence
|
997,845 | b6b6f114d959cf6601a2be408fb8a8ef0bc559ae | import sys, subprocess
import getpass
try:
import pkg_resources
except ImportError:
raise Exception("you must have setuptools installed to run the tests")
pkg_resources.require('quixote>=2.3')
from quixote.server.simple_server import run
from io import StringIO
import os
import socket
import urllib.request, urllib.parse, urllib.error
_server_url = None
def get_url():
if _server_url is None:
raise Exception("server has not yet been started")
return _server_url
testdir = os.path.dirname(__file__)
print('testdir is:', testdir)
sys.path.insert(0, os.path.abspath(os.path.join(testdir, '..')))
import twill
def cd_testdir():
global cwd
cwd = os.getcwd()
os.chdir(testdir)
def pop_testdir():
global cwd
os.chdir(cwd)
def execute_twill_script(filename, inp=None, initial_url=None):
global testdir
if inp:
def new_getpass(*args):
return ""
inp_fp = StringIO(inp)
old, sys.stdin = sys.stdin, inp_fp
old_getpass, getpass.getpass = getpass.getpass, new_getpass
scriptfile = os.path.join(testdir, filename)
try:
twill.execute_file(filename, initial_url=initial_url)
finally:
if inp:
sys.stdin = old
getpass.getpass = old_getpass
def execute_twill_shell(filename, inp=None, initial_url=None,
fail_on_unknown=False):
# use filename as the stdin *for the shell object only*
scriptfile = os.path.join(testdir, filename)
with open(scriptfile) as fh:
cmd_inp = "%s\nquit\n" % fh.read()
cmd_inp = StringIO(cmd_inp)
# use inp as the std input for the actual script commands.
if inp:
inp_fp = StringIO(inp)
old, sys.stdin = sys.stdin, inp_fp
try:
try:
s = twill.shell.TwillCommandLoop(initial_url=initial_url,
stdin=cmd_inp,
fail_on_unknown=fail_on_unknown)
s.cmdloop()
except SystemExit:
pass
finally:
if inp:
sys.stdin = old
def run_server(create_fn, PORT=None):
"""
Run a Quixote simple_server on localhost:PORT with subprocess.
All output is captured & thrown away.
The parent process returns the URL on which the server is running.
"""
import time, tempfile
global _server_url
if PORT is None:
PORT = int(os.environ.get('TWILL_TEST_PORT', '8080'))
outfd = tempfile.mkstemp('twilltst')[0]
print('STARTING:', sys.executable, 'tests/twilltestserver.py', os.getcwd())
process = subprocess.Popen([sys.executable, '-u', 'twilltestserver.py'],
stderr=subprocess.STDOUT,
stdout=outfd)
time.sleep(1)
_server_url = 'http://localhost:%d/' % (PORT,)
def kill_server():
"""
Kill the previously started Quixote server.
"""
global _server_url
if _server_url != None:
try:
fp = urllib.request.urlopen('%sexit' % (_server_url,))
except:
pass
_server_url = None
|
997,846 | 265c460ca19c07fe867c5a1843890739f2382075 | import sys
ksize = int(sys.stdin.readline().rstrip())
original = str(sys.stdin.readline().rstrip())
kmerlist = list()
for i in range(0, len(original) - ksize + 1):
kmer = original[i:(i+ksize)]
kmerlist.append(kmer)
for kmer in sorted(kmerlist):
print(kmer)
|
997,847 | ddd039dac7ca035d1663aedd730b7d726187e63a | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 19 14:48:44 2019
@author: andy3
"""
#First,we need to download the file on kaggle"cat-vs-dogs"
import os,shutil
original_dataset_dir=r'C:\Users\andy3\train'
base_dir=r"C:\Users\andy3\cats_and_dogs_small"
if not os.path.isdir(base_dir):os.mkdir(base_dir)
train_dir=os.path.join(base_dir,
'train')
if not os.path.isdir(train_dir):os.mkdir(train_dir)
validation_dir=os.path.join(base_dir,
'validation')
if not os.path.isdir(validation_dir):os.mkdir(validation_dir)
test_dir=os.path.join(base_dir,
'test')
if not os.path.isdir(test_dir):os.mkdir(test_dir)
train_cats_dir=os.path.join(train_dir,
'cats')
if not os.path.isdir(train_cats_dir):os.mkdir(train_cats_dir)
train_dogs_dir=os.path.join(train_dir,
'dogs')
if not os.path.isdir(train_dogs_dir):os.mkdir(train_dogs_dir)
validation_cats_dir=os.path.join(validation_dir,
'cats')
if not os.path.isdir(validation_cats_dir):os.mkdir(validation_cats_dir)
validation_dogs_dir=os.path.join(validation_dir,
'dogs')
if not os.path.isdir(validation_dogs_dir):os.mkdir(validation_dogs_dir)
test_cats_dir=os.path.join(test_dir,
'cats')
if not os.path.isdir(test_cats_dir):os.mkdir(test_cats_dir)
test_dogs_dir=os.path.join(test_dir,
'dogs')
if not os.path.isdir(test_dogs_dir):os.mkdir(test_dogs_dir)
#Create the training sets , validation sets ,testing sets of cats
fnames=['cat.{}.jpg'.format(i) for i in range(1000)]
for fname in fnames:
src=os.path.join(original_dataset_dir,
fname)
dst=os.path.join(train_cats_dir,
fname)
shutil.copyfile(src,
dst)
fnames=fnames=['cat.{}.jpg'.format(i) for i in range(1000,1500)]
for fname in fnames:
src=os.path.join(original_dataset_dir,
fname)
dst=os.path.join(validation_cats_dir,
fname)
shutil.copyfile(src,
dst)
fnames=fnames=['cat.{}.jpg'.format(i) for i in range(1500,2000)]
for fname in fnames:
src=os.path.join(original_dataset_dir,
fname)
dst=os.path.join(test_cats_dir,
fname)
shutil.copyfile(src,
dst)
#Create the training sets , validation sets ,testing sets of dogs
fnames=['dog.{}.jpg'.format(i) for i in range(1000)]
for fname in fnames:
src=os.path.join(original_dataset_dir,
fname)
dst=os.path.join(train_dogs_dir,
fname)
shutil.copyfile(src,
dst)
fnames=['dog.{}.jpg'.format(i) for i in range(1000,1500)]
for fname in fnames:
src=os.path.join(original_dataset_dir,
fname)
dst=os.path.join(validation_dogs_dir,
fname)
shutil.copyfile(src,
dst)
fnames=['dog.{}.jpg'.format(i) for i in range(1500,2000)]
for fname in fnames:
src=os.path.join(original_dataset_dir,
fname)
dst=os.path.join(test_dogs_dir,
fname)
shutil.copyfile(src,
dst)
####################################################
#
#
#
#
##################The method 2##################################
#################Feature extraction from VGG16#################
#
#
#
#
#
#
####################################################
#Import the trained CNN ->VGG16
from keras.applications import VGG16
from keras import models
from keras import layers
conv_base=VGG16(weights='imagenet',
include_top=False,
input_shape=(150,150,3))
#The structure of CNN layers can be builded as:
model=models.Sequential()
model.add(conv_base)
model.add(layers.Flatten())
model.add(layers.Dense(256,
activation='relu'))
model.add(layers.Dense(1,
activation='sigmoid'))
model.summary()
######################################################
#
#
#Next, we need to freeze the weights of VGG16,Because we don't want to change its weight.
#
#
######################################################
#Freeze the layers of VGG16.
######################################################
#Before freezing the conv_base
print('this is the number of trainable weights'
'before freezing the conv_base:',len(model.trainable_weights))
#After freezing the conv_base
conv_base.trainable=False
print('this is the number of trainable weights'
'before freezing the conv_base:',len(model.trainable_weights))
from keras.preprocessing.image import ImageDataGenerator
from keras import optimizers
train_datagen=ImageDataGenerator(rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
test_datagen=ImageDataGenerator(rescale=1./255)
train_generator=train_datagen.flow_from_directory(train_dir,
target_size=(150,150),
batch_size=32,
class_mode='binary')
validation_generator=test_datagen.flow_from_directory(validation_dir,
target_size=(150,150),
batch_size=32,
class_mode='binary')
model.compile(loss='binary_crossentropy',
optimizer=optimizers.RMSprop(lr=2e-5),
metrics=['acc'])
history=model.fit_generator(train_generator,
steps_per_epoch=100,
epochs=30,
validation_data=validation_generator,
validation_steps=50)
import matplotlib.pyplot as plt
acc=history.history['acc']
val_acc=history.history['val_acc']
loss=history.history['loss']
val_loss=history.history['val_loss']
epochs=range(1,len(acc)+1)
plt.plot(epochs,
acc,
'bo',
label='Traning accuracy')
plt.plot(epochs,
val_acc,
'b',
label='Validation accuracy')
plt.title('The accuracy of training and validation')
plt.legend()
plt.figure()
plt.plot(epochs,
loss,
'bo',
label='Training loss quantity')
plt.plot(epochs,
val_loss,
'b',
label='Validation loss quantity')
plt.title('Training and validation loss')
plt.legend()
plt.show()
|
997,848 | 9a8ef4e5e654f91b1e1edc190016b2d5f58ada32 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import StudlUser
class StudlUserAdmin(UserAdmin):
list_display = ('id', 'email', 'first_name', 'last_name', 'date_joined', 'last_login', 'is_admin', 'is_staff')
search_fields = ('id', 'email', 'first_name', 'last_name')
readonly_fields = ('date_joined', 'last_login')
ordering = ('email',) # Privzeto ordera po usernamu, cesar v novem modelu ni
filter_horizontal = ()
list_filter = ()
fieldsets = ()
admin.site.register(StudlUser, StudlUserAdmin)
|
997,849 | b238ae2ab9eb9fa645793256d9a554e09968cc90 | tot1 = 0
tot2 = 0
sumtot = 0
for num in range(1, 101):
tot1 += (num*num)
tot2 += num
tot2 *= tot2
sumtot = tot2-tot1
print("tot1: ", tot1, " tot2: ", tot2, " sumtot: ", sumtot)
|
997,850 | 0fb8c5b9a0b23d9d5ad8bf011269eb4bae13b2d0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def book_id(book):
def ord2str(mychr):
return str(ord(mychr))
return ''.join(list(map(ord2str, [mychr for mychr in book])))
def id_lens(book):
return len(book_id(book))
|
997,851 | 1c5c3a191e2e5753d3781c39344e7b793e7f056b | from urllib.request import urlopen, quote
import json
import requests
def get_map_location(address):
"""根据传入的地址返回对应的地址编码
:param address:详细地址
:return:对应地点的地址编码
"""
url = 'https://restapi.amap.com/v3/geocode/geo'
output = 'json'
key = '51087efef5b53e73d939bad91cf21a40'
address = quote(address)
uri = url + '?address=' + address + '&output=' + output + '&key=' + key
# print(uri)
res = requests.get(uri).text
json_text = json.loads(res)
return json_text['geocodes'][0]['location']
|
997,852 | da424381a4c825948089942f32f2b64e6307e78f | def first():
num = int(input("Кратно число:"))
count = int(input("Брой на кратни:"))
for i in range(num, count * num + 1, num):
print(i)
def second():
vocalsstr = str(input("Please type a sentence: "))
vocalseng = "aeiou"
vocalsbg = "аъеиоу"
for v in vocalseng:
if (vocalsstr.lower().count(v)) != 0:
print(v, vocalsstr.lower().count(v))
for v in vocalsbg:
if (vocalsstr.lower().count(v)) != 0:
print(v, vocalsstr.lower().count(v))
def third():
listth = ["Everybody", "1", "is","55", "very", "3", "debel"]
for item in listth:
if item.isdigit():
listth.remove(item)
print(listth)
def fourth():
inpstr = input("Give a number to check if symmetric:")
if (int(inpstr) > 9):
print(str(inpstr) == str(inpstr)[::-1])
else:
print("Not symmetrical")
print("First exercise")
first()
print("Second exercise")
second()
print("Third exercise")
third()
print("Fourth exercise")
fourth()
def Bonus():
stri = "Marto iska da mnogo debel"
words = stri.split()
for i in range(len(words)):
words[i] = str(words[i])[:1] + "*" + str(words[i])[2:]
stri = ' '.join(words)
print(stri)
print("Bonus")
Bonus() |
997,853 | 9ffaa925870aba3b5eace4731980043d72c61786 | from django.shortcuts import render
from .models import suggest_movies
# Create your views here.
def index(request):
login = request.session.get("email")
movies_suggested = suggest_movies(login)
print(movies_suggested)
context = {"recommedation": movies_suggested}
#print(context["recommedation"])
return render(request, 'movies/movies_index.html', context)
|
997,854 | a006f8a5609cf3a675cc91a2e1a06290005d9585 | import re
import sys
import json
import subprocess
import traceback
import xml.etree.ElementTree as ET
import os
import pickle
from io import StringIO
import pdfminer.high_level
import tarfile
import re
import multiprocessing
from functools import partial
import itertools
import signal
import time
def pdf2txt(fp):
output = StringIO()
pdfminer.high_level.extract_text_to_fp(fp, output, laparams=pdfminer.layout.LAParams())
return output.getvalue()
def get_file(fname, out_dir, flags='--force'):
cmd = ['s3cmd', 'get', '--requester-pays', flags,
's3://arxiv/%s' % fname, './%s' % out_dir]
print(' '.join(cmd))
subprocess.call(' '.join(cmd), shell=True)
def load_db(filename):
if not os.path.exists(filename):
# assume that no database exists, initialize one
db = {'processed_tars' : set(), 'pdfs' : {}}
save_db(db, filename)
print('Could not find database, initialized database at ' + filename)
with open(filename, 'rb') as handle:
db = pickle.load(handle)
return db
def save_db(db, filename):
with open(filename, 'wb') as handle:
pickle.dump(db, handle, protocol=pickle.HIGHEST_PROTOCOL)
class Timeout():
"""Timeout class using ALARM signal."""
class Timeout(Exception):
pass
def __init__(self, sec):
self.sec = sec
def __enter__(self):
signal.signal(signal.SIGALRM, self.raise_timeout)
signal.alarm(self.sec)
def __exit__(self, *args):
signal.alarm(0) # disable alarm
def raise_timeout(self, *args):
raise Timeout.Timeout()
def process_file(fname, out_dir, keywords):
keyword_list = keywords.split(',')
return_dict = {}
# download file
out_fname = '%s/%s' % (out_dir, fname)
get_file(fname, out_fname, '--skip-existing')
tar = tarfile.TarFile(out_fname)
tar_members = list(tar.getmembers())
for i, member in zip(range(len(tar_members)), tar.getmembers()):
if re.match('[0-9]*/[0-9]{4}\.[0-9]*\.pdf', member.name):
print("Processing file (%d / %d) in %s : %s: " % (i, len(tar_members), fname, member.name))
return_dict[member.name] = {}
f = tar.extractfile(member)
# timeout of 120 seconds, some pdf2txt calls take way too long
text = ""
try:
with Timeout(120):
text = pdf2txt(f)
except Timeout.Timeout:
print("Failed: Timed out while processing " + member.name)
text = ""
except:
print("Failed: Errored while processing " + member.name)
traceback.print_exc()
# print(str(e))
for keyword in keyword_list:
return_dict[member.name][keyword] = keyword in text.lower()
f.close()
tar.close()
# delete file
print("Finished processing and removing %s" % (fname,))
os.remove(out_fname)
return return_dict
def grouped(iterable, n):
# https://gist.github.com/yoyonel/fb8c9d6fb06871db527492f5144b2e7b
"""
>>> list(grouper(3, 'ABCDEFG'))
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
"""
iterable = iter(iterable)
return iter(lambda: list(itertools.islice(iterable, n)), [])
def main(**args):
db_file = args['database_file']
db = load_db(db_file)
out_dir = args['output_dir']
keywords = args['keywords']
os.makedirs(out_dir, exist_ok=True)
get_file("pdf/arXiv_pdf_manifest.xml", out_dir)
manifest_file = out_dir + '/arXiv_pdf_manifest.xml'
log_file_path = args['log_file']
log_file = open(log_file_path, 'a')
try:
file_list = []
for event, elem in ET.iterparse(manifest_file):
if event == 'end':
if elem.tag == 'filename':
fname = elem.text
if fname not in db['processed_tars']:
file_list += [fname]
except:
traceback.print_exc()
print("Total files to process: ", len(file_list))
pool = multiprocessing.Pool(processes=40)
for files in grouped(file_list, 80):
pool_arg = partial(process_file, out_dir=out_dir, keywords=keywords)
print("Mapping tasks")
counts = pool.map(pool_arg, files, 2)
print("Updating database with counts")
for filen, count in zip(files, counts):
db['processed_tars'].add(filen)
db['pdfs'].update(count)
log_file.write(filen + '\n')
log_file.write(str(count) + '\n')
log_file.flush()
save_db(db, db_file)
pool.close()
pool.join()
print('Finished')
if __name__ == '__main__':
from argparse import ArgumentParser
ap = ArgumentParser()
ap.add_argument('--keywords', '-k', type=str, help="comma separated set of keyword to look for existence in the document. For example: 'apple,bat'")
ap.add_argument('--database_file', '-d', type=str, default='db.pkl', help='keeps track of already downloaded files')
ap.add_argument('--output_dir', '-o', type=str, default='data', help='the output directory')
ap.add_argument('--log_file', default='processed.txt', help='a file that logs the processed txt files')
args = ap.parse_args()
main(**vars(args))
|
997,855 | 3ac3402abeb1396ffadae45e269e46b0c1161d21 | #regular expression
def isphonenumber(a):
if(len(a)!=12):
return False
elif(a.find('-')!=3 and a.rfind('-')!=7 ):
return False
elif(a[:3].isdigit() and a[4:7].isdigit() and a[8:11].isdigit() ):
return True
else:
return False
print(isphonenumber('111-111-1111'))
b=input("enter string ")
for i in range (len(b)):
chunk=b[i:i+12]
if(isphonenumber(chunk)):
print(chunk) |
997,856 | 6719b3c8a56b2856e5861f9b46bf8e6f2ff8e55e | """Dev-Server for model"""
from bottle import route, run, request
from predict import *
import PIL
import urllib
@route('/req', method= "GET")
def index():
res = urllib.request.urlretrieve(request.params["url"], "test.jpg")
im = PIL.Image.open("test.jpg")
return {'result': str(predict(im))}
run(host='localhost', port=5533)
|
997,857 | 00b508cee014d4b0ee0d14edebd78ef04bd06afc | import csv
import time
import numpy as np
import matplotlib.pyplot as plt
def read(filename, date_idx, date_parse, year, bucket=7):
days_in_yr = 365
freq = {}
for period in range(0, int(days_in_yr/bucket)):
freq[period] = 0
with open(filename, 'r') as csv_file:
reader = csv.reader(csv_file)
for row in reader:
if row[date_idx] == '' or reader.line_num == 1:
continue
else:
t = time.strptime(row[date_idx], date_parse)
if t.tm_year == year and t.tm_yday < (days_in_yr - 1):
freq[int(t.tm_yday/bucket)] += 1
return freq
freq = read("./data/311.csv", 1, '%m/%d/%Y %H:%M:%S %p', 2014)
x_train = np.asarray(list(freq.keys()))
y_train = np.asarray(list(freq.values()))
maxY = y_train.max()
ny_train = y_train / maxY
plt.scatter(x_train, ny_train)
#plt.show()
#print(freq)
|
997,858 | 1b48e123dc293bf5a4d169f9dd27b4311563a5ef | #4. If the ages of Mr.X, Mr.Y and Mr.Z are inout through the keyboard, Write a Python program to determine the oldest person among them.
x = int(input("Enter the Age of Mr.X: "))
y = int(input("Enter the Age of Mr.Y: "))
z = int(input("Enter the Age of Mr.Z: "))
if (x>y)and (x>z):
print("The Oldest Person is Mr.X with Age ",x)
elif (y>x) and (y>z):
print("The Oldest Person is Mr.Y with Age ",y)
elif (z>x) and (z>y):
print("The Oldest Person is Mr.Z with Age ",z)
else:
print("Mr.X, Mr.Y and Mr.Z are of same Age ",x)
|
997,859 | 89c67b93423a5f0b3a88d63533ea910fa0275032 | #!/usr/bin/env python
try:
from sugar.activity import bundlebuilder
bundlebuilder.start()
except ImportError:
import os
os.system("find ./ | sed 's,^./,TranslateActivity.activity/,g' > MANIFEST")
os.system('rm TranslateActivity.xo')
os.chdir('..')
os.system('zip -r TranslateActivity.xo TranslateActivity.activity')
os.system('mv TranslateActivity.xo ./TranslateActivity.activity')
os.chdir('TranslateActivity.activity')
|
997,860 | bbdcead657837e9f44139167ed19169e07bbecf7 | import os
import sys
import subprocess
sys.path.append(snakemake.config['args']['mcc_path'])
import scripts.mccutils as mccutils
def main():
mccutils.log("popoolationte2","setting up for PopoolationTE2")
ref_fasta = snakemake.input.ref_fasta
fq1 = snakemake.input.fq1
fq2 = snakemake.input.fq2
log = snakemake.params.log
out_dir = snakemake.params.out_dir
threads = snakemake.threads
# ensures intermediate files from previous runs are removed
for f in os.listdir(out_dir):
mccutils.remove(out_dir+"/"+f)
index_fasta(ref_fasta, log=log)
sam = map_reads(ref_fasta, fq1, fq2, out_dir, threads=threads, log=log)
bam = sam_to_bam(sam, out_dir+"/tmp.bam", threads=threads, log=log)
sorted_bam = sort_bam(bam, snakemake.output.bam, threads=threads, log=log)
mccutils.remove(sam)
mccutils.remove(bam)
def index_fasta(fasta, log=None):
mccutils.log("popoolationte2","indexing reference fasta", log=log)
command = ["bwa", "index", fasta]
mccutils.run_command(command, log=log)
def map_reads(ref, fq1, fq2, out, threads=1, log=None):
mccutils.log("popoolationte2","mapping reads", log=log)
sam = out+"/"+"mapped.sam"
mccutils.run_command_stdout(["bwa","bwasw", "-t", str(threads), ref, fq1, fq2], sam, log=log)
return sam
def sam_to_bam(sam, bam, threads=1, log=None):
mccutils.log("popoolationte2","converting SAM to BAM", log=log)
mccutils.run_command_stdout(["samtools", "view","-@",str(threads), "-Sb", sam], bam, log=log)
return bam
def sort_bam(bam, sorted_bam, threads=1, log=None):
mccutils.log("popoolationte2","sorting BAM", log=log)
mccutils.run_command(["samtools","sort","-@", str(threads), bam, "-o", sorted_bam], log=log)
return sorted_bam
if __name__ == "__main__":
main() |
997,861 | 619688dd822db106756f5b85258d6a740fa53ef7 | from .conversion import mol_to_smiles
def adock(receptor_input,
smiles,
ligand_name,
center_x=7.750,
center_y=-14.556,
center_z=6.747,
size_x=20,
size_y=20,
size_z=20,
vina='qvina2',
seed=None,
cpu=1,
lig_dir = './docking_score/ligand_files/',
out_dir = './docking_score/output/',
log_dir = './docking_score/log/',
conf_dir = './docking_score/config/'):
#Imports
import os
import subprocess
import psutil
import re
timeout_duration = 1000
#mkdir
os.makedirs(out_dir, exist_ok=True)
os.makedirs(conf_dir, exist_ok=True)
os.makedirs(log_dir, exist_ok=True)
os.makedirs(lig_dir, exist_ok=True)
ligand = lig_dir + ligand_name + '.pdbqt'
output = out_dir + ligand_name + '_out.pdbqt'
config = conf_dir + ligand_name + '.conf'
log = log_dir + ligand_name + '_log.txt'
#Convert smiles
if not os.path.isfile(ligand):
with subprocess.Popen('obabel -:"' + smiles + '" -O ' + ligand + ' -h --gen3d' + ' > /dev/null 2>&1', \
shell=True, start_new_session=True) as proc:
try:
proc.wait(timeout=timeout_duration)
except subprocess.TimeoutExpired:
p = psutil.Process(proc.pid)
p.terminate()
else:
print(f'Ligand file: {ligand!r} already exists.')
#Dock
if os.path.isfile(receptor_input):
if not os.path.isfile(output):
#Create conf files
conf = 'receptor = ' + receptor_input + '\n' +\
'ligand = ' + ligand + '\n' + \
'center_x = ' + str(center_x) + '\n' + \
'center_y = ' + str(center_y) + '\n' + \
'center_z = ' + str(center_z) + '\n' + \
'size_x = ' + str(size_x) + '\n' + \
'size_y = ' + str(size_y) + '\n' + \
'size_z = ' + str(size_z) + '\n' + \
'out = ' + output + '\n' + \
'cpu = ' + str(cpu)
if seed is not None:
conf += '\n' \
'seed = ' + str(seed)
with open(config, 'w') as f:
f.write(conf)
with subprocess.Popen('' + vina + \
' --config ' + config + \
' --log ' + log + \
' > /dev/null 2>&1', \
shell=True, start_new_session=True) as proc:
try:
proc.wait(timeout=timeout_duration)
except subprocess.TimeoutExpired:
p = psutil.Process(proc.pid)
p.terminate()
result = 0
try:
score = float("inf")
with open(output, 'r') as f:
for line in f.readlines():
if "REMARK VINA RESULT" in line:
new_score = re.findall(r'([-+]?[0-9]*\.?[0-9]+)', line)[0]
score = min(score, float(new_score))
result = score
except FileNotFoundError:
print('test--', ligand_name)
result = 0
else:
print(f'Protein file: {receptor_input!r} not found!')
result = 0
return (result)
def calculateDockingScore(mol):
protein_surface = './DATA/protein_files/6rqu.pdbqt'
smi = mol_to_smiles(mol)
ligand_name = smi.replace('(', '{').replace(')', '}')
return adock(protein_surface, smi, ligand_name)
|
997,862 | e9ad66ae4af617a8bbfc11538eeaebca0842e1e4 | <<<<<<< HEAD
class TestingConfig(Config):
TESTING = True
SECRET_KEY="GGggjjjfk887856$%kk"
# Disable CSRF protection in the testing configuration
WTF_CSRF_ENABLED = False
SQLALCHEMY_DATABASE_URI = "sqlite:///" + os.path.join(basedir, "test.sqlite")
=======
GOOGLE_CIENT_ID = ${{ secrets.GOOGLE_CLIENT_ID }}
GOOGLE_CLIENT_SECRET = ${{ secrets.GOOGLE_CLIENT_SECRET }}
>>>>>>> f18a6b05ee3e9f24c8452f80d2f540e2dd11d4d2
|
997,863 | 7fd1d4234fdf6bb47be2da870b1514626906030a | """
Задание 1. При старте приложения запускаются три потока. Первый поток заполняет
список случайными числами. Второй поток находит сумму элементов списка,
а третий поток среднеарифметическое значение в списке. Полученный список, сумма и
среднеарифметическое выводятся на экран.
Задание 2. Пользователь с клавиатуры вводит путь к файлу. После чего запускаются
три потока. Первый поток заполняет файл случайными числами. Второй поток находит
все простые числа, а третий поток факториал каждого числа в файле. Результаты поиска
каждый поток должен записать в новый файл.
Подсказка: можно воспользоваться высокоуровневой библиотекой concurrent.futures для
создания пула потоков.
Нюансы реализации разрешаются программистом.
"""
import concurrent.futures as cf
from random import randint
from math import ceil
import time
import threading
# Task-1
def generate_rand_nums(length: int) -> list:
"""Генерирует список со случайными числами от 1 до 1000 заданной длины length"""
return [randint(1, 100) for _ in range(length)]
def multithread_work():
"""
Решение 1го задания. С помощью контекстного менеджера инициализируется многопоточный пул с числом воркеров 3.
Выдаем им 3 задачи:
- С помощью ранее созданной функции generate_rand_nums формируем список и результат записываем в future1;
- Воспользовавшись данными из future1 (future1.result()) считаем среднее арифметическое списка и сумму
его членов и записываем их в переменные future2 и future3 соответственно.
С помощью функции print организован вывод данных.
"""
with cf.ThreadPoolExecutor(max_workers=3) as executor:
future1 = executor.submit(generate_rand_nums, 30)
future2 = executor.submit(lambda lst: sum(lst) / len(lst), future1.result())
future3 = executor.submit(sum, future1.result())
print(f"Сгенерированный список: {future1.result()}")
print(f"Среднее арифметическое значение списка: {future2.result()}")
print(f"Сумма всех членов списка: {future3.result()}")
# Альтернативное решение
def create_file(event: threading.Event):
event.set()
with open('nums.txt', "w", encoding="utf-8") as f:
for _ in range(100000):
num = str(randint(1, 10000)) + "\n"
f.write(num)
event.clear()
def sum_nums(event):
event.wait()
sum = 0
with open("nums.txt") as f:
for line in f:
sum += int(line.strip())
return sum
def mean_nums(event):
event.wait()
sum = 0
count = 0
with open("nums.txt") as f:
for line in f:
sum += int(line.strip())
count += 1
return sum / count
# Task-2
def fact(num: int) -> int:
"""Вычисляет факториал заданного числа num"""
if num == 1:
return 1
return num * fact(num - 1)
def isprime(num: int) -> bool:
"""Проверяет, является ли число, простым"""
if num == 1:
return False
for x in range(2, ceil(num / 2)):
return num % x != 0
# def list_wrapper(func, array: list) -> list:
# """Декоратор, для передачи элементов списка на вход функции, принимающей число"""
# def wrapper(func):
# for num in array:
# func(num)
# return wrapper
def factorials_list(nums: list) -> list:
"""Получает на вход список с числами, отдает список с факториалами чисел"""
return [fact(num) for num in nums]
def primes_list(nums: list) -> list:
"""Получает на вход список с числами, на выходе список с простыми числами"""
return list(filter(lambda num: isprime(num) == True, nums))
def fill_file(file: str) -> None:
"""Заполняет файл строкой со случайными числами"""
with open(file, "w", encoding="utf-8") as f:
f.write(" ".join(map(str, generate_rand_nums(100))))
def read_file(file: str) -> list:
"""Считывает файл и возвращает список чисел"""
with open(file, "r", encoding="utf-8") as f:
result = f.read()
return [int(el) for el in result.split()]
def multithread_work_2(file: str):
"""
Решение 2 задачи ДЗ. Ждём от пользователя ввода имени файла, далее с помощью функции fill_file
создаём файл с заданным названием и записываем туда строку с числами.
Попутно реализуем функцию read_file, которая считывает информацию из файла и преобразует его в список с числами.
Далее инициализируем многопоточный пул и выдаём на исполнение 2 задачи: на вычисление факториалов;
на определение простых чисел из списка чисел.
Результаты вычислений записываем в файл - result.txt.
"""
fill_file(file)
with cf.ThreadPoolExecutor(max_workers=None) as executor:
future1 = executor.submit(primes_list, read_file(file))
future2 = executor.submit(factorials_list, read_file(file))
with open("result.txt", "w", encoding="utf-8") as f:
f.write(f"Список простых чисел: {future1.result()}\n")
f.write(f"Факториалы чисел: {future2.result()}\n")
def main():
# Task-1
# print(generate_rand_nums(30))
# multithread_work()
# Task-2
# print(isprime(11))
# print(fact(58))
# filename = input("Введите имя файла: ")
# multithread_work_2(filename)
# create_file()
start_time = time.time()
# lock = threading.Lock()
event = threading.Event()
with cf.ThreadPoolExecutor() as executor:
future1 = executor.submit(create_file)
future2 = executor.submit(sum_nums)
future3 = executor.submit(mean_nums)
end_time = time.time()
print(future2.result())
print(future3.result())
print(f"Время: {end_time - start_time}")
print(f"Проверка суммы: {sum_nums(event)}")
if __name__ == "__main__":
main()
|
997,864 | 62671266ec66006931d8d5b15f0a08e71c09c460 | import numpy as np
import matplotlib
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
from astropy.stats import sigma_clipped_stats
from image_eval import psf_poly_fit, image_model_eval
def multiband_fourier_templates(imszs, n_terms, show_templates=False):
all_templates = []
for b in range(len(imszs)):
all_templates.append(make_fourier_templates(imszs[b][0], imszs[b][1], n_terms, show_templates=show_templates))
return all_templates
def make_fourier_templates(N, M, n_terms, extradimfac=1.0, show_templates=False):
templates = np.zeros((n_terms, n_terms, 4, N, M))
x = np.arange(N)
y = np.arange(M)
meshx, meshy = np.meshgrid(x, y)
xtemps_cos = np.zeros((n_terms, N, M))
ytemps_cos = np.zeros((n_terms, N, M))
xtemps_sin = np.zeros((n_terms, N, M))
ytemps_sin = np.zeros((n_terms, N, M))
for n in range(n_terms):
xtemps_sin[n] = np.sin((n+1)*np.pi*meshx/(N*extradimfac))
ytemps_sin[n] = np.sin((n+1)*np.pi*meshy/(M*extradimfac))
xtemps_cos[n] = np.cos((n+1)*np.pi*meshx/(N*extradimfac))
ytemps_cos[n] = np.cos((n+1)*np.pi*meshy/(M*extradimfac))
for i in range(n_terms):
for j in range(n_terms):
templates[i,j,0,:,:] = xtemps_sin[i]*ytemps_sin[j]
templates[i,j,1,:,:] = xtemps_sin[i]*ytemps_cos[j]
templates[i,j,2,:,:] = xtemps_cos[i]*ytemps_sin[j]
templates[i,j,3,:,:] = xtemps_cos[i]*ytemps_cos[j]
if show_templates:
for k in range(4):
counter = 1
plt.figure(figsize=(8,8))
for i in range(n_terms):
for j in range(n_terms):
plt.subplot(n_terms, n_terms, counter)
plt.title('i = '+ str(i)+', j = '+str(j))
plt.imshow(templates[i,j,k,:,:])
counter +=1
plt.tight_layout()
plt.show()
return templates
def generate_template(fourier_coeffs, n_terms, fourier_templates=None, N=None, M=None):
# making n_terms explicit as an input in case we want flexibility of calling it for different numbers of terms
if fourier_templates is None:
fourier_templates = make_fourier_templates(N, M, n_terms)
sum_temp = np.sum([fourier_coeffs[i,j,k]*fourier_templates[i,j,k] for i in range(n_terms) for j in range(n_terms) for k in range(4)], axis=0)
return sum_temp
def fit_coeffs_to_observed_comb(observed_comb, obs_noise_sig,ftemplates, true_fcoeffs = None, true_comb=None, n_terms=None, sig_dtemp=0.1, niter=100, init_nsig=1.):
if true_fcoeffs is not None:
init_fcoeffs = np.random.normal(0, obs_noise_sig, size=(true_fcoeffs.shape[0], true_fcoeffs.shape[1], 4))
n_terms = init_fcoeffs.shape[0]
elif n_terms is not None:
init_fcoeffs = np.random.normal(0, obs_noise_sig, size=(n_terms, n_terms, 4))
running_fcoeffs = init_fcoeffs.copy()
all_running_fcoeffs = np.zeros((niter//1000, n_terms, n_terms, 4))
temper_schedule = np.logspace(np.log10(init_nsig), np.log10(1.), niter)
print('temper schedule: ', temper_schedule)
print(init_fcoeffs.shape, n_terms, ftemplates.shape)
lazy_temp = generate_template(init_fcoeffs, n_terms, ftemplates)
running_temp = lazy_temp.copy()
lnLs = np.zeros((niter,))
lnL = -0.5*np.sum((1./obs_noise_sig**2)*(observed_comb - running_temp)*(observed_comb-running_temp))
lnLs[0] = lnL
accepts= np.zeros((niter,))
perts = np.random.normal(0, sig_dtemp, niter)
nsamp = 0
for n in range(niter):
sig_dtemp_it = temper_schedule[n]*sig_dtemp
idxk = np.random.randint(0, 4)
idx0, idx1 = np.random.randint(0, n_terms), np.random.randint(0, n_terms)
prop_dtemp = ftemplates[idx0,idx1,idxk,:,:]*perts[n]
plogL = -0.5*np.sum((1./obs_noise_sig**2)*(observed_comb - running_temp - prop_dtemp)*(observed_comb-running_temp - prop_dtemp))
dlogP = plogL - lnL
accept_or_not = (np.log(np.random.uniform()) < dlogP)
accepts[n] = int(accept_or_not)
if accept_or_not:
running_temp += prop_dtemp
running_fcoeffs[idx0, idx1, idxk] += perts[n]
lnLs[n] = plogL
lnL = plogL
else:
lnLs[n] = lnL
if n%5000==0:
print('n = ', n)
if n%1000==0:
all_running_fcoeffs[nsamp,:,:,:] = running_fcoeffs
nsamp += 1
if n%(niter//10)==0:
plt.figure(figsize=(16, 4))
plt.suptitle('n = '+str(n), fontsize=20, y=1.02)
plt.subplot(1,4,3)
plt.title('model', fontsize=16)
plt.imshow(running_temp)
plt.colorbar()
plt.subplot(1,4,2)
plt.title('observed', fontsize=16)
plt.imshow(observed_comb)
plt.colorbar()
plt.subplot(1,4,1)
if true_comb is not None:
plt.title('truth')
plt.imshow(true_comb - np.mean(true_comb))
else:
plt.title('observed - model')
plt.imshow(observed_comb-running_temp)
plt.colorbar()
plt.subplot(1,4,4)
plt.title('$\\delta b(x,y)/\\sigma(x,y)$', fontsize=16)
if true_comb is not None:
resid = (observed_comb - running_temp)/obs_noise_sig
plt.imshow(resid, vmin=np.percentile(resid, 5), vmax=np.percentile(resid, 95))
plt.colorbar()
plt.tight_layout()
plt.show()
print(np.mean(accepts))
def plot_logL(lnlz, N=100, M=100):
plt.figure(figsize=(8, 5))
plt.plot(np.arange(len(lnlz)), -2*lnlz, label='Chain min $\\chi_{red.}^2 = $'+str(np.round(np.min(-2*lnlz)/(N*M), 2)))
plt.axhline(N*M, linestyle='dashed', label='$\\chi_{red.}^2 = 1$')
plt.legend(fontsize=14)
plt.yscale('log')
plt.ylabel('$-2\\ln\\mathcal{L}$', fontsize=18)
plt.xlabel('Sample iteration', fontsize=18)
plt.tight_layout()
plt.show()
|
997,865 | 50ec9b783d82ca837b0818100d587be673e90a50 | import sys
import unittest
import xmlrunner
import csv
import os
from datetime import datetime, date, timedelta
class TestCovidCsvData(unittest.TestCase):
#first argument: defines where to look for the data
DIRECTORY = "./data/us-ak/ak-dhss"
#second arg: line to start reading headers at
HEADER_LINE = 1
#check that the headers remain the same from yesterday to today
def test_header_changes(self):
print('running test for directory : {}'.format(self.DIRECTORY))
path = os.path
#get today's and yesterday's files to compare headers
todays_file = []
today = datetime.today().strftime('%Y-%m-%d')
todays_file.append(today)
todays_file.append('.csv')
todays_file_name = ''.join(todays_file)
# get yesterday's date name
yesterdays_file = []
yesterday = (datetime.today() - timedelta(days=1)).strftime('%Y-%m-%d')
yesterdays_file.append(yesterday)
yesterdays_file.append('.csv')
yesterdays_file_name = ''.join(yesterdays_file)
for filename in os.listdir(self.DIRECTORY):
if filename == todays_file_name:
with open(f'{self.DIRECTORY}/{filename}', 'r') as file1:
reader1 = csv.DictReader(file1)
headers1 = reader1.fieldnames
if int(self.HEADER_LINE) ==2 :
next(reader1)
headers1 = next(reader1)
print(headers1)
self.assertIsNotNone(headers1, "No headers found in today's data file "+f'{self.DIRECTORY}/{filename}')
if filename == yesterdays_file_name:
with open(f'{self.DIRECTORY}/{filename}', 'r') as file2:
if int(self.HEADER_LINE) ==2 :
next(file2)
reader2 = csv.DictReader(file2)
#get fieldnames from DictReader object and store in list
headers2 = reader2.fieldnames
print(headers2)
self.assertIsNotNone(headers2, "No headers found in yesterday's file"+f'{self.DIRECTORY}/{filename}')
#creates a set of items that are found in only one of the header lists
diff = set(headers1).symmetric_difference(set(headers2))
msg = []
msg.append("these headers were found in one file but not the other: ")
for d in diff:
msg.append(d)
msg.append(',')
result = ''.join(msg)
self.assertEqual(len(diff),0, result)
#check that today's file was imported
def test_todays_file_exists(self):
todays_file = []
today = datetime.today().strftime('%Y-%m-%d')
todays_file.append(today)
todays_file.append('.csv')
todays_file_name = ''.join(todays_file)
self.assertTrue(todays_file_name in os.listdir(self.DIRECTORY),"today's file has not been imported")
if __name__ == '__main__':
#pass in an argument that tells where to find the data dir to test (in this fomrat: './data/us-ak/ak-dhss'),
#and, optionally, if the first line should be skipped to find the header row
if len(sys.argv) > 0:
TestCovidCsvData.HEADER_LINE = sys.argv.pop()
TestCovidCsvData.DIRECTORY = sys.argv.pop()
unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
|
997,866 | b122dd192359b55f82b828ecd24930c392626dae | from multiprocessing import Process
import time
# def timeit(f):
# def wrapper(*args,**kwargs):
# start_time = time.time()
# res = f(*args,**kwargs)
# end_time = time.time()
# print('%s函数执行时间:%.6f'%(f.__nmae__))
def prime_number():
for i in range(2,11):
for j in range(2,i):
if i%j==0:
break
else:
print(i)
prime_number()
class Prime(Process):
def __init__(self,prime,begin,end):
super().__init__()
self.prime = prime
self.begin = begin
self.end = end
# def verif_permissions(func):
# def wrapper(*args, **kwargs):
# start = time.time()
# print("函数运行时间:")
# re = func(*args, **kwargs)
# end = time.time()
# print(end - start)
# return re
# return wrapper
#
# @verif_permissions
# def enter_background():
# res = 0
# for i in range(100000000):
# res += i
# print('进入后台')
#
# @verif_permissions
# def delete_order():
# res = 0
# for i in range(100000000):
# res += i
# print('删除订单') |
997,867 | 28335056e2b8bfce94579996506674d54b5f55db | import curses
from .menu import Application, Stack, CheckBox, msgBox, Text, Menu, TextPanel
from .event import listener
import termcolor
from termcolor import COLORS, ATTRIBUTES
T = """
1. The Zen of Python, by Tim Peters
2. Beautiful is better than ugly.eautiful is better thaeautiful is better tha
3.Explicit is better than impliciplicit is better than plicit is better than t.
Simple is better than complex. le is one two three four five six seven eight night ten
Complex is better than complicatelex is better than comlex is better than comd.
Flat is better than nested. is better than nested is better than nested
Sparse is better than dense. se is better than densse is better than dens
Readability counts. ability counts. ability counts.
Now is better than never. is better than never. is better than never.
Although never is often better though never is often beough never is often bean *right* now.
If the implementation is hard to he implementation is hhe implementation is hexplain, it's a bad idea.
If the implementation is easy to he implementation is ehe implementation is eexplain, it may be a good idea.
Namespaces are one honking great spaces are one honkingspaces are one honkingidea -- let's do more of those!""".split('\n')
T = [str(i) + termcolor.colored(v, list(COLORS.keys())[i % len(COLORS)],attrs=[list(ATTRIBUTES.keys())[i % len(ATTRIBUTES)]] ) for i,v in enumerate(T)]
T = '\n'.join(T)
class Test(Stack):
@listener(10)
def enter(self):
# res = Test.Popup(["hello", "world","more power","awsl", "这个是什么时代的啊啊啊啊","exit"], context=self, exit_key=147)
res = TextPanel.Popup(T, context=self)
msgBox(msg=res)
@listener('i')
def info_item(self):
Text.Popup(content="this is a test !!!",context=self, width=40)
if __name__ =="__main__":
main = Application()
import random
r1 = CheckBox({"hello for no: "+str(i):random.randint(0,1) for i in range(138)}, id='check')
r2 = Test(["random test ... s2"+str(i) for i in range(50)], id='2')
r3 = Test(["you can ? to see"+str(i) for i in range(160)], id='3')
r4 = Test(["vim keymap to move "+str(i) for i in range(270)], id='4')
r5 = Test(["s3"+str(i) for i in range(270)], id='5')
# e = Menu(["a", "b", "c", "exit"], id='s', x=30, y =30)
main.add_widget(r1)
main.add_widget(r2)
main.add_widget(r3)
main.add_widget(r4)
main.add_widget(r5, weight=0.5)
# main.add_widget(t)
# tl = FileTree(os.listdir(os.path.expanduser("~/")), root_path=os.path.expanduser("~/"), id='left')
# tm = FileTree(os.listdir(os.path.expanduser("~/Documents")), path_root=os.path.expanduser("~/Documents"), id='middle')
# tr = FileTree([''], id='right')
# main.add_widget(tl,weight=1)
# main.add_widget(tm,weight=2)
# main.add_widget(tr,weight=3)
# main.add_widget(e)
main.focus("2")
curses.wrapper(main.loop)
print(T)
|
997,868 | 5e79bd31173fa2723fed6fb3bfec3fada0399f44 | Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def add(num1,num2):
return (num1+num2)
>>> add(3,5)
8
>>> add.__doc__
>>> def try(n1):
SyntaxError: invalid syntax
>>> def trytry(n1):
'wendang'
#zhushi
return (n1)
>>> trytry('ajgf')
'ajgf'
>>> trytry.__doc__
'wendang'
>>> help(trytry)
Help on function trytry in module __main__:
trytry(n1)
wendang
>>> print.__doc__
"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
>>> def test(*params):
print('长度:', len(params))
print ('first:',params[0])
>>> test(1,2,3,4,5)
长度: 5
first: 1
>>> def test1(name, *params):
print(name)
print('长度:', len(params))
print ('first:',params[0])
>>> test1(wo, 1, 2, 3, 4)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
test1(wo, 1, 2, 3, 4)
NameError: name 'wo' is not defined
>>> test1('wo', 1, 2, 3, 4)
wo
长度: 4
first: 1
>>> def test1(*params, name):
print(name)
print('长度:', len(params))
print ('first:',params[0])
>>> test1(1, 2, 3, 4, name='wo')
wo
长度: 4
first: 1
>>> def test2(*params, name):
print(name)
print('长度:', len(params))
print ('first:',params[0])
>>> test2(1, 2, 3, 4, name='wo')
wo
长度: 4
first: 1
>>> test2(1, 2, 3, 4, 'wo')
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
test2(1, 2, 3, 4, 'wo')
TypeError: test2() missing 1 required keyword-only argument: 'name'
>>> def test2(*params, name):
print(name)
print('长度:', len(params), end=' ')
print ('first:',params[0])
>>> test2(1, 2, 3, 4, name='wo')
wo
长度: 4 first: 1
>>>
|
997,869 | 8c061fd8f380be6b6cd71f94361b24c2c9b8db53 | countries = ['Romania', 'France', 'Germany', 'Netherlands', 'Spain', 'Portugal']
sexes = ['F', 'M']
years = [2017, 2018]
health_indexes = [3.4, 4, 78, 12, 78.1, 79]
dataset = [
(country, year, sex, health_index)
for country in countries
for year in years
for sex in sexes
for health_index in health_indexes
]
# This implementation will always overwrite the values because we cannot have duplicate key in the same dict
# health_index_2017 = {
# country: [sex, health_index]
# for country, year, sex, health_index in dataset
# if year == 2017
# }
health_index_2017 = {
country_: [
[sex, health_index]
for country, year, sex, health_index in dataset
if year == 2017 and country == country_
]
for country_ in countries
}
# This implementation will always overwrite the values because we cannot have duplicate key in the same dict
# health_index_2018 = {
# country: [sex, health_index]
# for country, year, sex, health_index in dataset
# if year == 2018
# }
health_index_2018 = {
country_: [
[sex, health_index]
for country, year, sex, health_index in dataset
if year == 2018 and country == country_
]
for country_ in countries
}
# print(health_index_2017)
# print(health_index_2018)
# This implementation will always overwrite the values because we cannot have duplicate key in the same dict
# group_by_year = {
# year: [sex, health_index]
# for country, year, sex, health_index in dataset
# if country == 'Germany' and year in years
# }
group_by_year = {
year: [
[sex, health_index]
for country, year, sex, health_index in dataset
if country == 'Germany'
] for year in years
}
# print(group_by_year)
group_by_country_year = {
country_ + '_' + str(year_): [
[year, sex, health_index]
for country, year, sex, health_index in dataset
if country == country_
]
for country_ in countries for year_ in years
}
# print(group_by_country_year)
# Print health_index > 5
for country_year, values_list in group_by_country_year.items():
health_index_greater = {
country_year: [
[year, sex, health_index]
for year, sex, health_index in values_list
if health_index > 5
]
for country_years in group_by_country_year
}
print(health_index_greater)
# Print health_index > 5 and sex == 'female'
for country_year, values_list in group_by_country_year.items():
health_index_sex = {
country_year: [
[year, sex, health_index]
for year, sex, health_index in values_list
if health_index > 5 and sex == 'F'
]
for country_year in group_by_country_year
}
# print(health_index_sex)
# Use for loop for printing the health_index
for country_name, values_list in group_by_country_year.items():
for year, sex, health_index in values_list:
print(health_index)
|
997,870 | 7168fc41e2440e81ee63aa79447e4d7572cf9745 | import math
def mysqrt(a):
estimate = 1
epsilon = 0.0001
while True:
if abs(estimate ** 2 - a) < epsilon:
return float(round(estimate, 1))
else:
estimate = (estimate + a / estimate) / 2
def test_square_root():
print('a ', 'mysqrt(a) ', 'math.sqrt(a)', 'diff')
print('- ', '--------- ', '------------', '----')
for i in range(1, 10):
print(i, ' ', mysqrt(i), ' ', round(math.sqrt(i), 1), ' ', mysqrt(i) - math.sqrt(i))
test_square_root() |
997,871 | 507ae99250db868cda8b0557e403c4ab68fd8899 | # --- Day 5: Sunny with a Chance of Asteroids ---
# You're starting to sweat as the ship makes its way toward Mercury. The Elves suggest that you get the air conditioner working by upgrading
# your ship computer to support the Thermal Environment Supervision Terminal.
# The Thermal Environment Supervision Terminal (TEST) starts by running a diagnostic program (your puzzle input).
# The TEST diagnostic program will run on your existing Intcode computer after a few modifications:
# First, you'll need to add two new instructions:
# Opcode 3 takes a single integer as input and saves it to the position given by its only parameter.
# For example, the instruction 3,50 would take an input value and store it at address 50.
#
# Opcode 4 outputs the value of its only parameter. For example, the instruction 4,50 would output the value at address 50.
# Programs that use these instructions will come with documentation that explains what should be connected to the input and output.
# The program 3,0,4,0,99 outputs whatever it gets as input, then halts.
# Second, you'll need to add support for parameter modes:
# Each parameter of an instruction is handled based on its parameter mode.
# Right now, your ship computer already understands parameter mode 0, position mode,
# which causes the parameter to be interpreted as a position - if the parameter is 50,
# its value is the value stored at address 50 in memory. Until now, all parameters have been in position mode.
# Now, your ship computer will also need to handle parameters in mode 1, immediate mode. In immediate mode,
# a parameter is interpreted as a value - if the parameter is 50, its value is simply 50.
# Parameter modes are stored in the same value as the instruction's opcode.
# The opcode is a two-digit number based only on the ones and tens digit of the value,
# that is, the opcode is the rightmost two digits of the first value in an instruction.
# Parameter modes are single digits, one per parameter, read right-to-left from the opcode: the first parameter's mode is in the hundreds digit,
# the second parameter's mode is in the thousands digit, the third parameter's mode is in the ten-thousands digit,
# and so on. Any missing modes are 0.
# For example, consider the program 1002,4,3,4,33.
# The first instruction, 1002,4,3,4, is a multiply instruction - the rightmost two digits of the first value, 02, indicate opcode 2, multiplication.
# Then, going right to left, the parameter modes are 0 (hundreds digit), 1 (thousands digit), and 0 (ten-thousands digit, not present and therefore zero):
# ABCDE
# 1002
# DE - two-digit opcode, 02 == opcode 2
# C - mode of 1st parameter, 0 == position mode
# B - mode of 2nd parameter, 1 == immediate mode
# A - mode of 3rd parameter, 0 == position mode,
# omitted due to being a leading zero
# This instruction multiplies its first two parameters. The first parameter, 4 in position mode,
# works like it did before - its value is the value stored at address 4 (33).
# The second parameter, 3 in immediate mode, simply has value 3. The result of this operation, 33 * 3 = 99,
# is written according to the third parameter, 4 in position mode, which also works like it did before - 99 is written to address 4.
# Parameters that an instruction writes to will never be in immediate mode.
# Finally, some notes:
# It is important to remember that the instruction pointer should increase by the number of values in the instruction after the instruction finishes.
# Because of the new instructions, this amount is no longer always 4.
# Integers can be negative: 1101,100,-1,4,0 is a valid program (find 100 + -1, store the result in position 4).
# The TEST diagnostic program will start by requesting from the user the ID of the system to test by running an input instruction - provide it 1,
# the ID for the ship's air conditioner unit.
# It will then perform a series of diagnostic tests confirming that various parts of the Intcode computer, like parameter modes, function correctly.
# For each test, it will run an output instruction indicating how far the result of the test was from the expected value,
# where 0 means the test was successful. Non-zero outputs mean that a function is not working correctly;
# check the instructions that were run before the output instruction to see which one failed.
# Finally, the program will output a diagnostic code and immediately halt.
# This final output isn't an error; an output followed immediately by a halt means the program finished.
# If all outputs were zero except the diagnostic code, the diagnostic program ran successfully.
# After providing 1 to the only input instruction and passing all the tests, what diagnostic code does the program produce?
class IntCode():
def __init__(self, instructions: list) -> None:
self.seek_position = 0
self._instructions: list = instructions
self._register: list = self.load_register()
self.value = None
print(self.register)
while True:
self.value = self.operate()
if self.value:
break
self.seek()
self.load_register()
def read(self, location: int) -> int:
return self._instructions[location]
def write(self, location: int, value: int) -> None:
self._instructions[location] = value
def load_register(self) -> None:
self.register = self._instructions[self.seek_position : self.seek_position + 4]
def seek(self) -> None:
self.seek_position += 4
def operate(self) -> None:
op_code = self.register[0]
ops = {
1: self.one,
2: self.two,
99: self.ninetynine
}
if op_code in list(ops.keys()):
return ops[op_code]()
else:
raise AttributeError(f'Unknown Op Code. {op_code}')
def one(self):
self.write(self.register[3], self.read(self.register[1]) + self.read(self.register[2]))
return None
def two(self):
self.write(self.register[3], self.read(self.register[1]) * self.read(self.register[2]))
return None
def three(self):
value = None
location =None
self.write(self.register[location], self.read(self.register[value]))
return None
def four(self):
self.read(location)
return None
def ninetynine(self):
return self._instructions[0]
# prog = IntCode(program)
# print(prog.value)
# num_range = [i for i in range(0, 100)]
# perms = []
# for i in num_range:
# for j in num_range:
# perms.append((i, j))
# num_to_find = 19690720
# for perm in perms:
# program[1], program[2] = perm
# prog = IntCode(program[:])
# if prog.value == num_to_find:
# print(perm)
# print(100 *perm[0] + perm[1])
# break |
997,872 | 585276c3bd26248fe6af1f9ead68e5d0aa19268b | from django.contrib import admin
# Register your models here.
from .models import Member
class Memberadmin(admin.ModelAdmin):
list_display=('id','name','university','age','address') #for admin panel like datebase
list_display_links = ('id','name')
list_filter = ('name',) #for filtering
list_editable = ('age',)
search_fields = ('name',)
list_per_page = 25
admin.site.register(Member,Memberadmin) |
997,873 | e64eed7c4df803048ce106bbd9ee22dfb3ebab0e | import datetime
import os
import random
from collections import defaultdict
import service_file
from service_write_html import fill_html, fill_html2, get_template
BASE_DATE = (
'сегодня',
'вчера',
'2 дня назад',
'3 дня назад',
'4 дня назад',
'5 дней назад',
'6 дней назад',
'7 дней назад'
)
def get_base_orders_id(base_orders_id):
base_orders = service_file.cvs_convert_json('Flyword_DB - ReviewData.csv')
for data_order in base_orders:
if data_order['sectionId'] == '': continue
data_order['date'] = random.choice(BASE_DATE)
base_orders_id[data_order['sectionId']].append(data_order)
def get_base_masters(base_masters):
base_master_about = tuple(sorted(service_file.cvs_convert_json('Flyword_DB - MasterAbout.csv'), key = lambda x: (x['masterDataId'], x['id'])))
base_master_data = service_file.cvs_convert_json('Flyword_DB - MasterData.csv')
base_master_education = service_file.cvs_convert_json('Flyword_DB - MasterEducation.csv')
for master_data in base_master_data:
path = master_data['path']
base_masters[path].update({'education':list(), 'about':list()})
base_masters[path].update(master_data)
experience_days = (datetime.datetime.today() - datetime.datetime.strptime(base_masters[path]['experience'], '%Y-%m-%d')).days
y, experience_days = experience_days // 365, experience_days % 365
y_word = ''
m_word = ''
m = experience_days // 30
if y < 11 or y > 19:
y_ = y % 10
else:
y_ = 5
if y_ == 1:
y_word = f'{y} год '
elif y_ > 1 and y_ < 5:
y_word = f'{y} года '
elif y_ > 4 or (y > 0 and y_ == 0):
y_word = f'{y} лет '
if m == 1:
m_word = f'{m} месяц'
elif m > 1 and m < 5:
m_word = f'{m} месяца'
elif m > 5:
m_word = f'{m} месяцев'
base_masters[path]['experience'] = f'{y_word}{m_word}'
for master_about in base_master_about:
base_masters[master_about['masterDataId']]['about'].append(master_about['aboutText'])
for master_education in base_master_education:
base_masters[master_education['masterDataId']]['education'].append(master_education['education'])
def main():
try:
os.mkdir('result')
except OSError:
pass
base_masters = defaultdict(dict)
base_orders_id = defaultdict(list)
base_containers = service_file.cvs_convert_json('Flyword_DB - Container.csv')
base_geo = service_file.cvs_convert_json('Flyword_DB - Geo.csv')
base_cities_back = service_file.loud_txt('cities')
base_cities = list()
get_base_orders_id(base_orders_id)
get_base_masters(base_masters)
template = get_template()
sitemaps = list()
list_masters = list()
base_containers_selects = list()
for data_container in base_containers:
data_orders = base_orders_id.get(data_container['sectionId'])
if len(data_orders) < 7: continue
d_orders = data_orders[:10]
data_orders = data_orders[10:]
base_orders_id.update({data_container['sectionId']:data_orders})
data_container.update({'data_orders':d_orders})
base_containers_selects.append(data_container)
base_containers = base_containers_selects
for data_container in base_containers:
data_orders = data_container.pop('data_orders') #base_orders_id.get(data_container['sectionId'])
if len(list_masters) < 10:
list_masters = list(base_masters.values())
random.shuffle(list_masters)
index = fill_html(data_container, template['index'], 'Container', ignore = ('linksBlock_3', 'data_orders'))
for i_m in range(10):
master = list_masters.pop()
sh1 = '<p class="education-item hide-item">{text}</p>'
sh2 = '<p class="education-item hide-item">{text}</p>'
master_item = fill_html(master, template['master_item'], 'MasterData', ignore = ('about', 'education'))
master_about = ''
master_education = ''
if len(master['about']):
master_about = fill_html2(master['about'], template['master_about'], sh = sh1, name = 'MasterAbout.aboutText')
if len(master['education']):
master_education = fill_html2(master['education'], template['master_education'], sh = sh2, name = 'MasterEducation.education')
i_insert = master_item.find('"masters-item__content">') + 24
master_item = f'{master_item[:i_insert]}\n{master_about}{master_education}{master_item[i_insert:]}'
if i_m > 4:
i_insert = index.find('"masters-wrap__right">') + 22
else:
i_insert = index.find('"masters-wrap__left">') + 21
index = f'{index[:i_insert]}\n{master_item}{index[i_insert:]}'
for i_m in range(10):
if not len(data_orders): break
data_order = data_orders.pop()
data_order['rate'] = data_order['rate'].replace('.00', '')
post_item = fill_html(data_order, template['post_item'], 'ReviewData')
if data_order['rate'] == '5':
post_item = post_item.replace('icon5', 'img/star-icon.svg')
else:
post_item = post_item.replace('icon5', 'img/star-empty-icon.svg')
if i_m > 4:
i_insert = index.find('"reviews-wrap__left">') + 21
else:
i_insert = index.find('"reviews-wrap__right">') + 22
index = f'{index[:i_insert]}\n{post_item}{index[i_insert:]}'
link_items1 = list()
link_items3 = list()
for data_container2 in base_containers:
if data_container == data_container2: continue
if data_container2['location'] == 'online':
link_items = link_items1
templ_name = 'link_item1'
elif data_container['sectionId'] == data_container2['sectionId']:
link_items = link_items3
templ_name = 'link_item3'
else:
continue
link_items.append(fill_html(data_container2, template[templ_name], 'Container', ignore = ('data_orders',)))
link_items1 = '\n'.join(link_items1)
index = index.replace('Container.listLinks_1', f'\n<ul>{link_items1}</ul>')
list_items2 = list()
for _ in range(15):
if not len(base_cities):
base_cities = base_cities_back.copy()
random.shuffle(base_cities)
list_items2.append(template['link_items2'].replace('city', base_cities.pop()))
index = index.replace('Container.list_items2', '\n'.join(list_items2))
list_items3 = ''
if data_container['linksBlock_3'] != '0':
random.shuffle(link_items3)
link_items3 = '\n'.join(link_items3)
for value in base_geo:
link_items3 = link_items3.replace(f'>{value["location"]}<', f'>{value["name"]}<')
list_items3 = template['list_items3'].replace('Container.listLinks_3', f'\n<ul>{link_items3}</ul>').replace('Container.linksBlock_3', data_container['linksBlock_3'])
index = index.replace('Container.list_items3', list_items3)
index = index.replace('href="/index"', 'href="/"')
sitemaps.append(template['item_sitemap'].replace('>url<', f'>https://flyvord.com/{data_container["urlPath"]}<'))
with open(f'html\\{data_container["urlPath"]}.html', 'w', encoding='utf-8') as f:
f.write(index)
with open(f'result\\{data_container["urlPath"]}.html', 'w', encoding='utf-8') as f:
f.write(index)
sitemaps = '\n'.join(sitemaps).replace('/index', '/')
sitemap = template['sitemap'].replace('items', sitemaps)
with open(f'html\\sitemap.xml', 'w', encoding='utf-8') as f:
f.write(sitemap)
with open(f'result\\sitemap.xml', 'w', encoding='utf-8') as f:
f.write(sitemap)
print('')
# "masters-wrap__left">
# вставлять блок master_item.html
# "masters-item__content">
# вставляем блок из master_about.html и master_education.html
# "reviews-wrap__left">
# вставлять блок post_item.html
# img/star-icon.svg если rate = 5, img/star-empty-icon.svg если rate = 4
if __name__ == '__main__':
main()
|
997,874 | 197ec47f7e51e8dca6337ba0965f764488786a62 | """
Len()-> Retorna o tamanho, ou seja, o número de itens de um iterável
Abs() -> Retorna o valor absoluto de um número sem consideral o seu sinal
Sum()-> Soma total de um iteravel
Round() -> Retorna o número arredondado para o digito de precisão após a casa decimal, se a precisão não for informado retorna o mais próximo
print(around(1.23547, 2))
""" |
997,875 | 20701861d815375fb81f533834d5c367459b95b8 | def eelarve(arv):
return 55+10*arv
var1 = eelarve(int(input("Mitu inimest on kutsutud? ")))
var2 = eelarve(int(input("Mitu inimest tuleb? ")))
print(var1)
print(var2)
|
997,876 | 1294b8444d4606b6817867d75cf90cae1b7214b7 | from typing import Optional, Union
from py262.abstract_ops.value import type_of
from py262.completion import Completion
from py262.environment import (DeclarativeEnvironmentRecord,
FunctionEnvironmentRecord,
GlobalEnvironmentRecord, LexicalEnvironment,
ObjectEnvironmentRecord)
from py262.reference import Reference
from py262.value import Value
def get_identifier_reference(lex: Optional[LexicalEnvironment], name: Value,
strict: Value) -> Union[Completion, Reference]:
if lex is None:
return Reference(base=Value.undefined,
referenced_name=name,
is_strict=strict)
# FIXME: is this assumption accurate?
assert isinstance(lex, LexicalEnvironment)
exists_completion = lex.environment_record.has_binding(name)
if exists_completion.is_abrupt():
return exists_completion
exists = exists_completion.value
if exists is Value.true:
return Reference(base=lex.environment_record,
referenced_name=name,
is_strict=strict)
return get_identifier_reference(lex.outer_lexical_environment, name,
strict)
def new_declarative_environment(outer_env: LexicalEnvironment
) -> LexicalEnvironment:
env = LexicalEnvironment()
env_rec = DeclarativeEnvironmentRecord()
env.environment_record = env_rec
env.outer_lexical_environment = outer_env
return env
def new_object_environment(obj: Value, outer_env: LexicalEnvironment
) -> LexicalEnvironment:
env = LexicalEnvironment()
env_rec = ObjectEnvironmentRecord()
env_rec.binding_object = obj
env.environment_record = env_rec
env.outer_lexical_environment = outer_env
return env
def new_function_environment(fn: Value,
new_target: Value) -> LexicalEnvironment:
assert type_of(fn) == 'function'
assert type_of(new_target) in ('undefined', 'object')
env = LexicalEnvironment()
env_rec = FunctionEnvironmentRecord()
env_rec.function_object = fn
# https://tc39.es/ecma262/#sec-newfunctionenvironment
raise NotImplementedError()
return env
def new_global_environment(g: Value, this_value: Value) -> LexicalEnvironment:
env = LexicalEnvironment()
obj_rec = ObjectEnvironmentRecord()
obj_rec.binding_object = g
decl_rec = DeclarativeEnvironmentRecord()
global_rec = GlobalEnvironmentRecord()
global_rec.object_record = obj_rec
global_rec.global_this_value = this_value
global_rec.declarative_record = decl_rec
global_rec.var_names = []
env.environment_record = global_rec
env.outer_lexical_environment = Value.null
return env
def new_module_environment(env: LexicalEnvironment) -> LexicalEnvironment:
# https://tc39.es/ecma262/#sec-newmoduleenvironment
raise NotImplementedError()
|
997,877 | 40dc3f04b708528f5b24bdc07ec07c46d5e25770 | """
Data models as described by the Trompa CE and Schema.org definitions.
"""
from .sdo_thing import Thing
from .sdo_organization import Organization
from .sdo_person import Person
from .sdo_place import Place
from .sdo_creative_work import CreativeWork
from .sdo_media_object import MediaObject
from .sdo_audio_object import AudioObject
from .sdo_music_recording import MusicRecording
from .sdo_music_playlist import MusicPlaylist
from .sdo_music_album import MusicAlbum
from .ce_base import CE_BaseModel
from .ce_audio_object import CE_AudioObject
from .ce_music_album import CE_MusicAlbum
from .ce_person import CE_Person
from .ce_music_composition import CE_MusicComposition |
997,878 | 3f07d9531c1acc87f0e45965abd2a4464b9cc0a1 | with open('input.txt', 'r') as file:
data = file.read()
def to_coords(input):
result = []
for pair in input.strip().split('\n'):
s = pair.split(',')
result.append((int(s[0]), int(s[1])))
return result
def bounding_box(coords):
return max([c[0] for c in coords]) + 1, max([c[1] for c in coords]) + 1
def taxicab_dist(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def closest(x, y, coords):
minimum = 100000000
min_coord = -1
min_unique = True
dists = []
for i, coord in enumerate(coords):
dist = taxicab_dist((x, y), coord)
dists.append(dist)
#print("({}, {}) dist to {} = {}".format(x, y, coord, dist))
if dist == minimum:
min_unique = False
if dist < minimum:
minimum = dist
min_coord = i
min_unique = True
return (min_coord if min_unique else -1), dists
def debug(dist_map, bb):
letters = list(map(chr, range(ord('a'), ord('z') + 1)))
for y in range(bb[1]):
for x in range(bb[0]):
c = dist_map[x + y * bb[0]]
if c > -1:
print(letters[c], end=" ")
else:
print('.', end=" ")
print('\n')
coords = to_coords(data)
bb = bounding_box(coords)
dist_map = [-1] * bb[0] * bb[1]
areas = [0] * len(coords)
is_infinite = [False] * len(coords)
safe = []
for y in range(bb[1]):
for x in range(bb[0]):
c, dists = closest(x, y, coords)
dist_map[x + y * bb[0]] = c
if c > -1:
areas[c] += 1
if x == 0 or x == bb[0] - 1 or y == 0 or y == bb[1] - 1:
is_infinite[c] = True
total_dist = sum(dists)
if total_dist < 10000: # Limit for test is 32
safe.append(total_dist)
#debug(dist_map, bb)
finite_areas = [x for i, x in enumerate(areas) if not is_infinite[i]]
print("Part 1: largest finite area is {}".format(max(finite_areas)))
print("Part 2: size of safe region is {}".format(len(safe)))
|
997,879 | 57e509feb74cdc4624e704985d6885be0045f19b | from flask import Flask, render_template_string
from sucuri import rendering
app = Flask(__name__)
@app.route("/")
def index():
template = rendering.template('template.suc',{"text": "Hello! I'm here!", "var":[1, 2, 3, 4]})
return render_template_string(template) |
997,880 | 8c193afbb7ecadadcb7a722878d8e9a3e2680923 | # -*- coding: utf-8 -*-
from openerp import models, fields, api
import logging
_logger = logging.getLogger(__name__)
import calendar
import datetime
from openerp.tools import SUPERUSER_ID, DEFAULT_SERVER_DATE_FORMAT
import openerp.addons.decimal_precision as dp
LINE_TYPE_EXCEPTION = 'x'
LINE_TYPE_RECURRENT = 'r'
LINE_TYPE_ONETIME = 'o'
def add_months(sourcedate, months):
month = sourcedate.month - 1 + months
year = sourcedate.year + month // 12
month = month % 12 + 1
day = min(sourcedate.day, calendar.monthrange(year, month)[1])
return datetime.date(year, month, day)
def date_interval(start_date, month_end=True):
if month_end:
end_date = datetime.date(start_date.year,
start_date.month,
calendar.monthrange(start_date.year,
start_date.month)[1])
else:
end_date = add_months(start_date, 1) - datetime.timedelta(days=1)
return start_date, end_date
def format_interval(start, end, date_format=DEFAULT_SERVER_DATE_FORMAT):
return '(%s - %s)' % (start.strftime(date_format),
end.strftime(date_format))
def operation_date(date=None, context=None):
if context is None:
context = {}
if date is None:
date = context.get("operation_date", datetime.date.today())
if not isinstance(date, datetime.date):
date = datetime.datetime.strptime(
date,
DEFAULT_SERVER_DATE_FORMAT,
).date()
return date
LINE_TYPE_EXCEPTION = 'x'
LINE_TYPE_RECURRENT = 'r'
LINE_TYPE_ONETIME = 'o'
L_S = ((LINE_TYPE_RECURRENT, 'Recurrent'),
(LINE_TYPE_EXCEPTION, 'Exception'),
(LINE_TYPE_ONETIME, 'One time'))
CONTRACT_SERVICE_STATES = [('draft', 'Waiting for activating'),
('active', 'Active'),
('inactive', 'Inactive')]
class contract_service(models.Model):
_name = 'contract.service'
@api.model
def _default_price_unit(self):
return 1.0
@api.one
@api.depends('price_unit', 'quantity', 'product_id')
def _compute_price(self):
self.price = self.price_unit * self.quantity
activation_date = fields.Datetime('Activation date')
billed_to_date = fields.Date('Billed until date')
deactivation_date = fields.Datetime('Deactivation date')
duration = fields.Integer('Duration')
product_id = fields.Many2one(comodel_name='product.product', string='Product', required=True)
category_id = fields.Many2one(comodel_name='product.category', string='Product Category')
name = fields.Char('Description', size=64)
analytic_line_type = fields.Selection(L_S,string='Type')
require_activation = fields.Boolean('Require activation')
account_id = fields.Many2one(comodel_name='account.analytic.account', string='Contract')
quantity = fields.Float(string='Quantity', digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
price_unit = fields.Float(string='Unit Price', required=True,
digits=dp.get_precision('Product Price'),
default=_default_price_unit)
price = fields.Float(string='Amount', digits= dp.get_precision('Account'),
store=True, readonly=True, compute='_compute_price')
activation_line_generated = fields.Boolean('Activation Line Generated?')
state = fields.Selection(selection=CONTRACT_SERVICE_STATES, string='State')
@api.model
def create(self, values):
if not values.get('require_activation'):
values['state'] = 'active'
values['activation_date'] = fields.Datetime.now()
return super(contract_service, self).create(values)
@api.multi
def action_deactivate(self):
for obj in self:
obj.state = 'inactive'
obj.deactivation_date = fields.Datetime.now()
@api.one
def on_change_product_id(product_id):
pass
@api.one
def on_change_qty(qty, price_unit):
pass
@api.onchange('product_id')
def _onchange_product_id(self):
product = self.product_id
if product:
self.analytic_line_type = product.analytic_line_type
self.require_activation = product.require_activation
self.category_id = product.categ_id.id
self.price_unit = product.lst_price
if product.analytic_line_type == LINE_TYPE_RECURRENT:
self.duration = 0
else:
self.duration = 1
def _get_price(self):
self.price = self.qty * self.price_unit
def _get_product_price2(self):
if self.product_id:
self.price_unit = self.product_id.lst_price
else:
self.price_unit = -1.0
def _get_product_price(self, cr, uid, ids, field_name, arg, context=None):
product_pricelist_obj = self.pool.get('product.pricelist')
partner_id = self.browse(
cr, uid, ids[0],
context=context).account_id.partner_id.id
pricelist_id = self.browse(
cr, uid, ids[0],
context=context
).account_id.partner_id.property_product_pricelist.id
ret = {}
for line in self.browse(cr, uid, ids, context=context):
if line.product_id:
ret[line.id] = product_pricelist_obj.price_get(
cr, uid, [pricelist_id],
line.product_id.id, 1, partner_id,
context=context)[pricelist_id]
else:
ret[line.id] = None
return ret
def _get_total_product_price(self, cr, uid, ids, field_name, arg,
context=None):
ret = {}
for line in self.browse(cr, uid, ids, context=context):
if line.qty:
ret[line.id] = line.price_unit * line.qty
else:
ret[line.id] = None
return ret
_defaults = {
'state':'draft',
'activation_line_generated': False,
'category_id': 1,
'name':'',
'qty':1
}
def _prorata_rate(self, days_used, days_in_month):
""" Returns a rate to compute prorata invoices.
Current method is days_used / days_in_month, rounded DOWN
to 2 digits
"""
return (100 * days_used // days_in_month) / 100.0
def _get_prorata_interval_rate(self, cr, uid, change_date, context=None):
""" Get the prorata interval and price rate.
Returns a tuple (start_date, end_date, price percent)
"""
month_days = calendar.monthrange(change_date.year,
change_date.month)[1]
start_date = add_months(change_date, 1)
end_date = start_date.replace(day=month_days)
used_days = month_days - change_date.day
ptx = self._prorata_rate(used_days, month_days)
return start_date, end_date, ptx
def _get_prorata_interval_rate_deactivate(self, cr, uid, change_date,
context=None):
start_date, end_date, ptx = self._get_prorata_interval_rate(
cr, uid, change_date, context=context)
ptx = ptx * -1
return start_date, end_date, ptx
def _get_date_format(self, cr, uid, obj, context):
partner_lang = obj.account_id.partner_id.lang
res_lang_obj = self.pool['res.lang']
query = [
('code', '=', partner_lang),
('active', '=', True)
]
lang_id = res_lang_obj.search(cr, uid, query, context=context)
if lang_id:
date_format = res_lang_obj.browse(cr, uid,
lang_id[0],
context=context).date_format
else:
date_format = '%Y/%m/%d'
return date_format
@api.one
def create_analytic_line(self, mode='manual'):
print "*" * 80
print "create_analytic_line " * 5
ret = []
record = {}
account_analytic_line_obj = self.env['account.analytic.line']
line = self
interval = ''
record = {
'name': ' '.join([line.product_id.name, line.name or '', interval]),
'amount': (line.price * -1),
'account_id': line.account_id.id,
'user_id': self.env.user.id,
'general_account_id': line.product_id.property_account_expense.id,
'product_id': line.product_id.id,
'contract_service_id': line.id,
'to_invoice': 1,
'unit_amount': line.qty,
'is_prorata': mode == 'prorata',
'journal_id': 1
}
account_analytic_line_obj.create(record)
line = self
return
date_format = self._get_date_format(cr, uid, line, context=context)
start, end = None, None
next_month = None
amount = line.price
if line.analytic_line_type == LINE_TYPE_RECURRENT:
if mode == 'prorata':
activation_date = date
start, end, ptx = self._get_prorata_interval_rate(
cr, uid,
activation_date,
context=context,
)
amount = amount * ptx
elif mode == 'cron':
next_month = add_months(date, 1)
next_month = datetime.date(
next_month.year,
next_month.month,
1)
start, end = date_interval(next_month, False)
elif mode == 'manual':
start, end = date_interval(date, False)
elif mode == 'subscription':
line.write({'activation_line_generated': True})
if start and end:
interval = format_interval(start, end, date_format)
else:
interval = ''
general_account_id = line.product_id.property_account_expense.id \
or line.product_id.categ_id.property_account_expense_categ.id
record = {
'name': ' '.join([line.product_id.name,
line.name or '',
interval]),
'amount': (amount * -1),
'account_id': line.account_id.id,
'user_id': uid,
'general_account_id': general_account_id,
'product_id': line.product_id.id,
'contract_service_id': line.id,
'to_invoice': 1,
'unit_amount': line.qty,
'is_prorata': mode == 'prorata',
'date': (next_month or date).strftime(
DEFAULT_SERVER_DATE_FORMAT),
'journal_id': 1
}
if line.analytic_line_type == LINE_TYPE_EXCEPTION:
new_duration = line.duration - 1
line.write({'duration': new_duration})
if new_duration <= 0:
self.unlink(cr, SUPERUSER_ID, line.id)
record['contract_service_id'] = False
elif line.analytic_line_type == LINE_TYPE_ONETIME:
if line.duration > 0:
line.write({'duration': line.duration - 1})
else:
# Do not create an already billed line
return
if 'default_type' in context:
context.pop('default_type')
ret.append(account_analytic_line_obj.create(cr, uid, record,
context))
return ret
def create_refund_line(self, cr, uid, ids,
mode='manual',
date=None,
context=None):
context = context or {}
date = operation_date(date, context)
if type(ids) is int:
ids = [ids]
ret = []
record = {}
account_analytic_line_obj = self.pool.get('account.analytic.line')
for line in self.browse(cr, uid, ids, context):
if any((line.analytic_line_type != LINE_TYPE_RECURRENT,
mode != "prorata")):
# Not handled for now, only pro-rata deactivate
continue
date_format = self._get_date_format(cr, uid, line, context=context)
deactivation_date = date
start, end, ptx = self._get_prorata_interval_rate_deactivate(
cr, uid,
deactivation_date,
context=context,
)
amount = line.product_id.list_price * ptx
interval = format_interval(start, end,
date_format=date_format)
general_account_id = (
line.product_id.property_account_expense.id or
line.product_id.categ_id.property_account_expense_categ.id
)
record = {
'name': ' '.join([line.product_id.name,
line.name or '',
interval]),
'amount': (amount * -1) * line.qty,
'account_id': line.account_id.id,
'user_id': uid,
'general_account_id': general_account_id,
'product_id': line.product_id.id,
'contract_service_id': line.id,
'to_invoice': 1,
'unit_amount': line.qty,
'is_prorata': mode == 'prorata',
'date': date.strftime('%Y-%m-%d'),
'journal_id': 1
}
if 'default_type' in context:
context.pop('default_type')
ret.append(account_analytic_line_obj.create(cr, uid, record,
context))
return ret
|
997,881 | 3974d7e25a6f7b7efca295945cdb5611df2041c8 | import sys
sys.path.append('/Users/zac/Research/muon_g2_2015/nmr/bloch_fit')
import matplotlib.pyplot as plt
from pulse import NMRPulsePhaseFit
import util as u
import math
p = NMRPulsePhaseFit(u.get_pulse_path(),
zc_use_filter = True,
init_signal_cut = 4.0e-4,
zc_stop = 20e-3,
debug=True,
w_ref = 2*math.pi*9685)
plt.figure(facecolor=u.LIGHTGREY)
plt.plot(p.phase_times, (p.phase_data - p.w_ref*p.phase_times) - p.phase_fit.best_values['d'], linestyle="None", marker=".", markeredgecolor = "#4f4f4f")
plt.plot(p.phase_times, (p.phase_fit.best_fit - p.w_ref*p.phase_times) - p.phase_fit.best_values['d'], color=u.RED)
plt.grid()
plt.gca().set_axis_bgcolor(u.GREY)
plt.title("PHASE VS. TIME FIT")
plt.xlabel("Time (s)")
plt.ylabel("PHASE (rad)")
plt.show()
|
997,882 | f2cb0d36d93ee1ede97b6657d652f6f903686fee | # coding:utf-8
# 快速排序的实现方法是设置两个游标,一个从前往后,一个从后往前,如果左侧游标所指数据大于右侧,
# 两数据进行交换,直到两个游标指向同一数据,则第一趟遍历结束。结束时游标所在数据,左侧都比其小
# 右侧都比其大,接下来对游标前后的两个序列进行递归操作。
# 最优时间复杂度: O(nlogn)
# 最坏时间复杂度: O(n²)
# 稳定性: 不稳定
def quick_sort(alist, first, last):
"""
:param alist: 一个列表
:param first: 起始位置
:param last: 结束位置
:return: 排序后的列表
"""
if first >= last:
return
low = first
high = last
middle_value = alist[first]
while low < high:
while low < high and alist[high] >= middle_value:
high -= 1
alist[low] = alist[high]
while low < high and alist[low] < middle_value:
low += 1
alist[low] = alist[high]
alist[low] = middle_value
quick_sort(alist, low+1, last)
quick_sort(alist, first, low-1)
return alist
a = [1,5,4,2,7,4,9,6]
b = quick_sort(a, 0, len(a)-1)
print(b)
|
997,883 | cf737094c833ee327b5b371c423af695976ad479 | from datetime import datetime
from event_data_discovery.activity_identifier_discovery import ActivityIdentifierDiscoverer
from event_data_discovery.activity_identifier_predictors import make_sklearn_pipeline
# ____________________________________________________________________________________________________________________
from sklearn.utils import compute_sample_weight
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.metrics import make_scorer, fbeta_score
from sknn.mlp import Classifier as NNClassifier
from sknn.mlp import Layer
from scipy.stats import randint as sp_randint, expon as sp_expon, uniform as sp_uniform
# ____________________________________________________________________________________________________________________
mimic_files = {
'openslex': 'data/mimic_demo.slexmm',
'timestamps': 'mimic/event_timestamps.json',
'candidates': 'mimic/candidates_in_table.json',
'feature_values': 'mimic/features_in_table.json',
# 'candidates': 'mimic/candidates_lookup.json',
# 'feature_values': 'mimic/features_lookup.json',
'y_true': 'mimic/ground_truth.json',
}
# ____________________________________________________________________________________________________________________
adw_files = {
'openslex': 'data/adw-mm.slexmm',
'timestamps': 'adw/timestamps.json',
'candidates': 'adw/candidates_in_table.json',
'feature_values': 'adw/features_in_table.json',
# 'candidates': 'adw/candidates_lookup.json',
# 'feature_values': 'adw/features_lookup.json',
'y_true': 'adw/adw_ground_truth.json',
}
# ____________________________________________________________________________________________________________________
aid_mimic = ActivityIdentifierDiscoverer(mimic_files['openslex'])
# aid_mimic.generate_candidates(mimic_files['timestamps'], ['in_table'])
# aid_mimic.generate_candidates(mimic_files['timestamps'], ['lookup'])
# aid_mimic.save_candidates(mimic_files['candidates'])
aid_mimic.load_candidates(mimic_files['candidates'])
# aid_mimic.compute_features(features='filtered')
# aid_mimic.save_features(mimic_files['feature_values'])
aid_mimic.load_features(mimic_files['feature_values'])
aid_mimic.load_y_true(mimic_files['y_true'])
# ____________________________________________________________________________________________________________________
sample_weights = compute_sample_weight('balanced', aid_mimic.y_true)
tuning_params = [
{
'name': "Nearest Neighbors",
'predictor': make_sklearn_pipeline(KNeighborsClassifier()),
'parameters': {
'clf__n_neighbors': sp_randint(2, 20),
'clf__weights': ['uniform', 'distance'],
},
'n_iter': 1000,
'fit_params': None,
},
{
'name': "Linear SVM",
'predictor': make_sklearn_pipeline(SVC(kernel="linear", class_weight='balanced', random_state=1)),
'parameters': {
'clf__C': sp_expon(),
},
'n_iter': 1000,
'fit_params': None,
},
{
'name': "RBF SVM",
'predictor': make_sklearn_pipeline(SVC(class_weight='balanced', random_state=1)),
'parameters': {
'clf__C': sp_expon(),
},
'n_iter': 1000,
'fit_params': None,
},
{
'name': "Decision Tree",
'predictor': make_sklearn_pipeline(DecisionTreeClassifier(class_weight='balanced', random_state=1)),
'parameters': {
'clf__min_weight_fraction_leaf': sp_uniform(loc=0, scale=0.5),
},
'n_iter': 1000,
'fit_params': None,
},
{
'name': "Random Forest",
'predictor': make_sklearn_pipeline(RandomForestClassifier(class_weight='balanced', random_state=1)),
'parameters': {
'clf__n_estimators': sp_randint(10, 500),
'clf__max_features': sp_uniform(),
'clf__min_weight_fraction_leaf': sp_uniform(loc=0, scale=0.5),
},
'n_iter': 1000,
'fit_params': None,
},
{
'name': "AdaBoost",
'predictor': make_sklearn_pipeline(
AdaBoostClassifier(DecisionTreeClassifier(class_weight='balanced', random_state=1), random_state=1)),
'parameters': {
'clf__n_estimators': sp_randint(10, 500),
'clf__base_estimator__min_weight_fraction_leaf': sp_uniform(loc=0, scale=0.5),
},
'n_iter': 1000,
'fit_params': None,
},
{
'name': 'Neural Network',
'predictor': make_sklearn_pipeline(
NNClassifier(
layers=[
Layer("Rectifier", units=25),
Layer("Softmax")
],
n_iter=25,
random_state=1
)
),
'parameters': {
'clf__hidden0__units': sp_randint(2, 50),
'clf__learning_rate': sp_expon(scale=.001)
},
'n_iter': 100,
'fit_params': {
'clf__w': sample_weights
},
},
]
scoring = {
'precision': 'precision',
'recall': 'recall',
'f1': 'f1',
'f.5': make_scorer(fbeta_score, beta=2),
'f2': make_scorer(fbeta_score, beta=2),
}
n_splits = 5
refit = 'f1'
verbose = 1
t0 = datetime.now()
print(str(t0) + ': starting parameter tuning')
aid_mimic.tune_params(tuning_params, scoring, n_splits=n_splits, refit=refit,
verbose=verbose)
t1 = datetime.now()
print(str(t1) + ': parameter tuning finished')
print('time elapsed: ' + str(t1 - t0))
# ____________________________________________________________________________________________________________________
aid_mimic.save_tuning_results('tuning_results_all.pkl')
aid_mimic.save_best_predictors('best_predictors_all.pkl')
# ____________________________________________________________________________________________________________________
aid_adw = ActivityIdentifierDiscoverer(adw_files['openslex'])
# aid_adw.generate_candidates(adw_files['timestamps'], ['in_table'])
# aid_adw.generate_candidates(adw_files['timestamps'], ['lookup'])
# aid_adw.save_candidates(adw_files['candidates'])
aid_adw.load_candidates(adw_files['candidates'])
# aid_adw.compute_features(features='filtered')
# aid_adw.save_features(adw_files['feature_values'])
aid_adw.load_features(adw_files['feature_values'])
aid_adw.load_y_true(adw_files['y_true'])
aid_adw.load_predictors('best_predictors_all.pkl')
aid_adw.score()
aid_adw.save_scores('scores_all.pkl')
|
997,884 | 239facd0e281e9c7246fd6880b4e793281d0cc8f | import simplegui
import random
def new_game():
global list_2, exposed, t, state
state = 0
t = 0
list_1 = list(range(0, 8))
list_2 = list_1 * 2
random.shuffle(list_2)
label.set_text("Turns = " + str(t))
exposed = [False] * 16
def mouseclick(pos):
global t, state, click1, click2
choice = pos[0] // 50
if state == 0:
state = 1
click1 = choice
exposed[click1] = True
elif state == 1:
state = 2
click2 = choice
exposed[click2] = True
elif state == 2:
if not exposed[choice]:
state = 1
if not list_2[click1] == list_2[click2]:
exposed[click1] = exposed[click2] = False
click1 = choice
exposed[click1] = True
t += 1
label.set_text("Turns = " + str(t))
def draw(canvas):
global exposed
for i in range(16):
if exposed[i]:
canvas.draw_polygon([(50 * i, 0), (50 * i + 50, 0),
(50 * i + 50, 100), (50 * i, 100)], 3, "White", 'Gray')
canvas.draw_text(str(list_2[i]), (50 * i + 20, 60), 30, "White")
else:
canvas.draw_polygon([(50 * i, 0), (50 * i + 50, 0),
(50 * i + 50, 100), (50 * i, 100)], 3, 'White', 'Green')
frame = simplegui.create_frame('Memory', 800, 100)
frame.add_button('Restart', new_game)
label = frame.add_label('Turns = 0')
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
new_game()
frame.start()
|
997,885 | d60e3487cec11c3dac203a55fc9e528ec5c3518d | #!usr/bin/env python
# coding=utf-8
import os
import sys
# !/usr/bin/python3
import sys
# 跟普通函数不同的是,生成器是一个返回迭代器的函数,
# 只能用于迭代操作,更简单点理解生成器就是一个迭代器。
# 在调用生成器运行的过程中,
# 每次遇到 yield 时函数会暂停并保存当前所有的运行信息,
# 返回yield的值。
# 并在下一次执行 next()方法时从当前位置继续运行。
def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
while True:
try:
print(next(f))
except StopIteration:
sys.exit() |
997,886 | 476ecacfe94c773efab10cb92b96c36b4abdbf0d | import collections
import copy
class Solution:
def minFlips(self, mat: list) -> int:
M, N = len(mat), len(mat[0])
q = collections.deque()
def foo(mat):
return sum([sum(row) for row in mat]), tuple([tuple(row) for row in mat])
summ, t = foo(mat)
if summ == 0:
return 0
q.append((mat, 0))
visited = set()
visited.add(t)
while q:
mat, steps = q.popleft()
for x in range(M):
for y in range(N):
new_mat = copy.deepcopy(mat)
for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1), (0, 0)):
xt, yt = x + dx, y + dy
if 0 <= xt < M and 0 <= yt < N:
new_mat[xt][yt] = new_mat[xt][yt] ^ 1
summ, t = foo(new_mat)
if summ == 0:
return steps + 1
if t not in visited:
visited.add(t)
q.append((new_mat, steps + 1))
return -1
mat=[[0,0],[0,1]]
print(Solution().minFlips(mat)) |
997,887 | 96dcbd4642a44c3fddb5c92ba8110e7ef901c573 | import random
def jogar():
print("*********************************")
print("Bem Vindo no jogo da Adivinhação")
print("*********************************")
numero_random = random.randrange(1, 101)
numero_secreto = (numero_random)
total_de_tentativa = 0
pontos = 100
print('qual nivel de dificuldade?')
print("(1)Facil (2)Médio (3)Difícil ")
nivel = int(input("Define nivel"))
if (nivel == 1):
total_de_tentativa = 20
elif (nivel == 2):
total_de_tentativa = 10
else:
total_de_tentativa = 5
for rodada in range(1, total_de_tentativa + 1):
print("Tentativa {} de {}".format(rodada, total_de_tentativa))
chute_str = input("digite seu numero entre 1 e 100;")
print("Você Digitou", chute_str)
chute = int(chute_str)
if (chute < 1 or chute > 100):
print("voce deve colocar um N entre 1 e 100")
continue
acertou = chute == numero_secreto
maior = chute > numero_secreto
menor = chute < numero_secreto
if (acertou):
print("Você Acertou e fez {} pontos".format(pontos))
break
else:
if (maior):
print("Você errou ! o seu chute foi maior ")
elif (menor):
print("Você errou ! o seu chute foi menor ")
pontos_perdidos = abs(numero_secreto - chute)
pontos = pontos - pontos_perdidos
print("Fim de jogo")
if(__name__ == "__main_"):
jogar() |
997,888 | 6561cd8eb17754b716bb06bf95f624e986cdf49e | from ScrapBooker import ScrapBooker
from ImageProcessor import ImageProcessor
sb = ScrapBooker()
imp = ImageProcessor()
arr = imp.load("42AI.png")
print(arr)
arr = sb.juxtapose(arr, 3, 1)
imp.display(arr)
|
997,889 | d7cb203b9cac1f8cd63f1037826ab4d5b4e6c3eb | import util
import numpy as np
import itertools
test_dimension = ['.#.',
'..#',
'###']
start_dimension = util.parse_file_as_list('input_files/day_17.txt')
def enter_the_matrix_again(dimensions=4):
universe = np.array([[1 if char == '#' else 0 for char in line] for line in start_dimension], ndmin=dimensions)
for loops in range(6):
universe = another_dimension(universe)
return universe.sum()
def expand_the_universe(universe):
# order of position in matrix is z, y, x
z, y, x = universe.shape
expanded_universe = np.array(np.zeros((z + 4, y + 4, x + 4)))
expanded_universe[2: -2, 2: -2, 2: -2] = universe
the_newlyverse = np.array(np.zeros((z + 4, y + 4, x + 4)))
for cube_coords in itertools.product(range(1, z + 3), itertools.product(range(1, x + 3), repeat=2)):
z, y_x = cube_coords
y, x = y_x
cube_value = expanded_universe[z, y, x]
active_cube_neighbours = expanded_universe[z-1:z+2, y-1:y+2, x-1:x+2].sum() - cube_value
if cube_value == 0 and active_cube_neighbours == 3:
new_cube_value = 1
elif cube_value == 1 and active_cube_neighbours in (2, 3):
new_cube_value = 1
else:
new_cube_value = 0
the_newlyverse[z, y, x] = new_cube_value
return the_newlyverse
def another_dimension(universe):
# order of position in matrix is z, y, x
z, w, y, x = universe.shape
expanded_universe = np.array(np.zeros((z + 4, w + 4, y + 4, x + 4)))
expanded_universe[2: -2, 2: -2, 2: -2, 2: -2] = universe
the_newlyverse = np.array(np.zeros((z + 4, w + 4, y + 4, x + 4)))
for cube_coords in itertools.product(itertools.product(range(1, z + 3), repeat=2), itertools.product(range(1, x + 3), repeat=2)):
z_w, y_x = cube_coords
z, w = z_w
y, x = y_x
cube_value = expanded_universe[z, w, y, x]
active_cube_neighbours = expanded_universe[z-1:z+2, w-1:w+2, y-1:y+2, x-1:x+2].sum() - cube_value
if cube_value == 0 and active_cube_neighbours == 3:
new_cube_value = 1
elif cube_value == 1 and active_cube_neighbours in (2, 3):
new_cube_value = 1
else:
new_cube_value = 0
the_newlyverse[z, w, y, x] = new_cube_value
return the_newlyverse
|
997,890 | 0692da1f2f79aba81391776deb7b8d8bd50a04a3 | /Users/hm/anaconda3/lib/python3.6/sre_compile.py |
997,891 | 6305e90de998b0dd767cc5ba035afa6829438e3a | from setuptools import setup, find_packages
setup(name='thesis', version='1.0', packages=find_packages())
|
997,892 | 7faf76ad1d2d22e0c611da3d3f8588cbba8faf78 | from setuptools import setup
setup(
name="project2",
version="0.1",
scripts=["data2.py"],
) |
997,893 | a734cb0c9f3ec6c93b869fc7cd5735bbdf539aca | class Keyboard:
def keyboard():
pass |
997,894 | aa13400ab86ba142ec4057b20c2639fcfbef64df | from subprocess import call
if __name__ == '__main__':
N = [1, 2, 3, 1, 2, 3, 3, 3, 3, 2, 2, 2]
deltas = [0, 0, 0, 0.05, 0.05, 0.05, 0.05, 0.005, 0.0005, 0.05, 0.05, 0.05]
sentenceLengths = [50, 50, 50, 50, 50, 50, 50, 50, 50, 10, 50, 100]
for n, delta, sentenceLength in zip(N, deltas, sentenceLengths):
print 'P6 {:d} {:.4f} {:d}'.format(n, delta, sentenceLength)
call(['../Release/P6.exe', str(n), str(delta), str(sentenceLength)])
|
997,895 | 10de7d067573e22ca76a3fce56c5bdefdb8e32f4 | from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.config import Config
Config.set('graphics', 'resizable', False)
Config.set('graphics', 'width','300')
Config.set('graphics', 'height','400')
from kivy.core.window import Window
Window.clearcolor = (1, 1, 1, 1)
class TestApp(App):
label1=Label(color=(1,0,0,1),text='|',size_hint=(1,0.4))
label2=Label(color=(0,0,1,1),text='',size_hint=(1,0.6),font_size=30)
val=''
def number(self,instance):
val=instance.text
if val in '123456789+-/*':
self.val+=val
self.label1.text=self.val
if val == '=':
try:result=str(eval(self.val))
except:result='Sytanx Error'
self.label2.text=result
self.label1.text=''
self.val=''
def _quit(self,inst):
quit()
def _clear(self,inst):
self.label2.text=''
self.label1.text=''
self.val=''
def display(self):
row=BoxLayout()
display=BoxLayout(orientation='vertical',size_hint=(0.6,1))
display.add_widget(self.label1)
display.add_widget(self.label2)
row.add_widget(display)
row.add_widget(Button(text='C',size_hint=(0.2,1),on_press=self._clear))
row.add_widget(Button(text='X',size_hint=(0.2,1),on_press=self._quit))
return row
def row(self,a,b,c,d):
row=BoxLayout(size_hint=(1,1))
row.add_widget(Button(text=a,on_press=self.number))
row.add_widget(Button(text=b,on_press=self.number))
row.add_widget(Button(text=c,on_press=self.number))
row.add_widget(Button(text=d,on_press=self.number))
return row
def build(self):
layout=BoxLayout(orientation='vertical',size_hint=(1,1))
layout.add_widget(self.display())
layout.add_widget(self.row('7','8','9','/'))
layout.add_widget(self.row('4','5','6','*'))
layout.add_widget(self.row('1','2','3','-'))
layout.add_widget(self.row('0','.','=','+'))
return layout
TestApp().run()
|
997,896 | 7685bd3dda3c061e91aeff673a03a21a897ec0df | from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import pandas as pd
import pylab
"""
Discussion: Recall the article on Interest Rate Swap Valuation available at http://tinyurl.com/mnan8ok,
we assumed that the Swap Fixed Rate was already interpolated. The aim of this post is
to examine different interpolation techniques namely linear, cubic spline, zero, quadratic
and nearest using a simple example and explain how to fit a curve. Subsequently, we will
apply the knowledge to interpolate the swap rate over a 30 year period. The gist is that
certain rates are available at commonly quoted intervals. However, in order to value a security
or bootstrap the zero rate we need to interpolate between the available rates for periods for which
there are no quoted rates.
SOURCE:
(a) Boston University School of Management Research Paper Series (No.2012-‐11)
Valuing Interest Rate Swaps Using OIS Discounting By Donald J. Smith
Electronic copy available at: http://ssrn.com/abstract=2036979
(b) Introduction to Computational Thinking and Data Science - John Guttag
Software: Canopy Free by Enthought
scipy (Scientific Python) library (open source)
Consider the example from the above post:
Time Description Rate
3-month LIBOR 0.50%
6-month LIBOR 1.00%
9-month LIBOR 1.60%
12-month LIBOR 2.10%
24-month SFR 3.40%
As you can see, rates are missing for the 15th, 18th, and 21st months and we need
those rates because cashflow payments are due on a quarterly basis which is every 3 months.
So we need to interpolate those rates. Fortunately, there is an open source python library -
Scipy that can be used to perform different types of interpolation as enumerated above.
"""
#store available data for maturities and rates in list
x = [3, 6, 9,12,24]
y = [0.50/100,1/100.0,1.60/100,2.10/100,3.40/100]
#Use scipy 1 dimensional interpolation function to interpolate
f = interp1d(x,y, kind='linear') #the kind can be changed to slinear, quadratic, zero, cubic, nearest
#interpolate with piecewise constant function (p=0) #kind='nearest'
#interpolate with piecewise linear function(p=1) #kind='linear'
#interpolate with piecewise constant function (p=2) - kind='quadratic'
#interpolate with cubic = cubic spline
#Create a list for the missing dates
xint = [15,18,21]
#Use the interpolation function we created above to find the rates for the missing dates
yint = f(xint)
#Expand our original rates to include both missing and available information
y = y + list(yint)
y.sort()
##Expand our original maturities to include both missing and available information
x = x + xint
x.sort()
#TO DISPLAY INTERPOLATED DATA
print ""
rateTable = pd.DataFrame.from_items([('Period', x),('Rate', y)])
print(rateTable.to_string())
"""
Result of Python Code:
# Period Rate (Interpolated)
0 3 0.00500
1 6 0.01000
2 9 0.01600
3 12 0.02100
4 15 0.02425
5 18 0.02750
6 21 0.03075
7 24 0.03400
Interpolated Rates from Source (Original article):
Time Description Rate
3-month LIBOR 0.50%
6-month LIBOR 1.00%
9-month LIBOR 1.60%
12-month LIBOR 2.10%
15-month SFR 2.44%
18-month SFR 2.76%
21-month SFR 3.08%
24-month SFR 3.40%
"""
##Fit the curve by plotting original information over the interpolated one.
##If you run the code and change kind on line 34 above from linear to cubic
##you will realize that only slinear and linear interpolation techniques
#fitted the original data very well.
##very well.
#Orignal Data to benchmark interpolated data - curve fitting
x = [3, 6, 9,12,24]
y = [0.50/100,1/100.0,1.60/100,2.10/100,3.40/100]
x.sort()
y.sort()
pylab.plot(x, y, 'b--')
pylab.plot(xint, yint, '--ro')
pylab.title('Linear Interpolation of Interest Rates')
pylab.show()
"""
CONCLUSION: This technique will be used to discuss interpolation & curve fitting techniques for
long dated securities (30 years) shortly. Subsequently, we will use the techniques to bootstrap zero rates
and value securities - see you next time!!!
"""
|
997,897 | 4cdcfd342ad5586c48f69cdf332dfdded17a28e2 | from setuptools import setup
setup(
name='per_level_logging',
version="0.1.0",
author="Akira Tanimura",
author_email="autopp.inc@gmail.com",
description="Implementation of logging.Handler to change the output per level.",
license="Apache Software License 2.0",
keywords="logging",
url="https://github.com/autopp/python_per_level_logging",
packages=[
'per_level_logging',
],
extras_require={
'twisted': ['twisted'],
},
test_suite="tests",
classifiers=[
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: System :: Logging"
"License :: OSI Approved :: Apache Software License",
],
)
|
997,898 | ad9b30b440f0672b567cf077a7b5b92e98535bf8 | #! python3
# -*- coding: utf-8 -*-
#
# Solution to Practice Project "Mad Libs"
# from "Automate The Boring Stuff", by Al Sweigart,
# Chapter 8.
#
# "Create a Mad Libs program that reads in text files and lets the user add
# their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears
# in the text file."
#
# Nadia Borsch misc@nborsch.com May/2018
import re
# Open and read template file
madlibs = open('madlibs.txt', 'r')
template = madlibs.read()
print('{0:>30}'.format('MAD LIBS TIME!'))
# Set the lists to hold words
replaceables = [re.compile('ADJECTIVE'), re.compile('NOUN'), re.compile('VERB'), re.compile('NOUN')]
words = []
items = ['n adjective', ' noun', ' verb (past tense)', ' noun']
# Obtain and save user input
for word in items:
words.append(input(f'Enter a{word}: ').lower())
# Replace words in string
for i in range(len(replaceables)):
template = replaceables[i].sub(words[i], template, 1)
print(template)
madlibs.close() |
997,899 | 7777e1364bb60e58800a655c34202b7ef4db7c3c | import asyncio
from typing import Iterable, AsyncIterable, Union, Optional, Dict, Any, Tuple
import websockets
from bxcommon.rpc.provider.abstract_ws_provider import AbstractWsProvider
from bxcommon.rpc.rpc_errors import RpcError
from bxcommon.rpc.ws.ws_client import WsClient
class MockWebSocket(websockets.WebSocketClientProtocol):
def __init__(self):
super().__init__()
self.alive_event = asyncio.Event()
self.send_messages = []
self.recv_messages: 'asyncio.Queue[websockets.Data]' = asyncio.Queue()
self.transfer_data_exc = None
async def wait_closed(self) -> None:
await self.alive_event.wait()
async def close(self, code: int = 1000, reason: str = "") -> None:
self.alive_event.set()
async def send(
self,
message: Union[websockets.Data, Iterable[websockets.Data], AsyncIterable[websockets.Data]],
) -> None:
self.send_messages.append(message)
async def recv(self) -> websockets.Data:
return await self.recv_messages.get()
class MockWsProvider(AbstractWsProvider):
def __init__(self, uri: str):
super().__init__(uri)
self.fail_connect = False
async def subscribe(self, channel: str, options: Optional[Dict[str, Any]] = None) -> str:
pass
async def unsubscribe(self, subscription_id: str) -> Tuple[bool, Optional[RpcError]]:
pass
async def connect_websocket(self) -> websockets.WebSocketClientProtocol:
if self.fail_connect:
raise ConnectionRefusedError
return MockWebSocket()
# just for autocompletion
def get_test_websocket(self) -> Optional[websockets.client.WebSocketClientProtocol]:
return self.ws
class MockWsClient(WsClient):
def __init__(self, uri: str):
super().__init__(uri)
self.fail_connect = False
async def subscribe(self, channel: str, options: Optional[Dict[str, Any]] = None) -> str:
pass
async def unsubscribe(self, subscription_id: str) -> Tuple[bool, Optional[RpcError]]:
pass
async def connect_websocket(self) -> websockets.WebSocketClientProtocol:
self.ws = MockWebSocket()
self.connected_event.set()
wait_event = asyncio.Event()
self.ws_status_check = asyncio.create_task(
wait_event.wait()
)
ws = self.ws
assert ws is not None
return ws
async def close(self) -> None:
self.running = False
super().close()
# just for autocompletion
def get_test_websocket(self) -> Optional[websockets.client.WebSocketClientProtocol]:
return self.ws
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.