text stringlengths 81 112k |
|---|
Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not
Args:
tag: a bs4.element.Tag
Returns:"
bs4.element.Tag: A bs4 tag representing a full html document
def create_html_from_fragment(tag):
"""
Creates full html tree from a fragment.... |
Sanitizes HTML. Tags not contained as keys in the tag_dictionary input are
removed, and child nodes are recursively moved to parent of removed node.
Attributes not contained as arguments in tag_dictionary are removed.
Doctype is set to <!DOCTYPE html>.
Args:
input_string (basestring): A (possib... |
Trims leadings and trailing whitespace between tags in an html document
Args:
input_string: A (possible unicode) string representing HTML.
Returns:
A (possibly unicode) string representing HTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string.
def conde... |
Converts html to xhtml
Args:
html_unicode_string: A (possible unicode) string representing HTML.
Returns:
A (possibly unicode) string representing XHTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string.
def html_to_xhtml(html_unicode_string):
"""
... |
merges dict2 into dict1
def _merge_dicts(self, dict1, dict2, path=[]):
"merges dict2 into dict1"
for key in dict2:
if key in dict1:
if isinstance(dict1[key], dict) and isinstance(dict2[key], dict):
self._merge_dicts(dict1[key], dict2[key], path + [str(key... |
statement : OPTION_AND_VALUE
def p_statement(self, p):
"""statement : OPTION_AND_VALUE
"""
p[0] = ['statement', p[1][0], p[1][1]]
if self.options.get('lowercasenames'):
p[0][1] = p[0][1].lower()
if (not self.options.get('nostripvalues') and
not hasa... |
statements : statements statement
| statement
def p_statements(self, p):
"""statements : statements statement
| statement
"""
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
elif n == 2:
p[0] = ['statements', p[1]] |
contents : contents statements
| contents comment
| contents include
| contents includeoptional
| contents block
| statements
| comment
| include
| includeoptio... |
block : OPEN_TAG contents CLOSE_TAG
| OPEN_TAG CLOSE_TAG
| OPEN_CLOSE_TAG
def p_block(self, p):
"""block : OPEN_TAG contents CLOSE_TAG
| OPEN_TAG CLOSE_TAG
| OPEN_CLOSE_TAG
"""
n = len(p)
if n == 4:
p[0] = [... |
config : config contents
| contents
def p_config(self, p):
"""config : config contents
| contents
"""
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
elif n == 2:
p[0] = ['config', p[1]] |
r'\/\*
def t_CCOMMENT(self, t):
r'\/\*'
t.lexer.code_start = t.lexer.lexpos
t.lexer.ccomment_level = 1 # Initial comment level
t.lexer.begin('ccomment') |
r'\*\/
def t_ccomment_close(self, t):
r'\*\/'
t.lexer.ccomment_level -= 1
if t.lexer.ccomment_level == 0:
t.value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos + 1 - 3]
t.type = "CCOMMENT"
t.lexer.lineno += t.value.count('\n')
t.lexer.begin... |
r'[^ \n\r\t=#]+[ \t=]+[^\r\n#]+
def t_OPTION_AND_VALUE(self, t):
r'[^ \n\r\t=#]+[ \t=]+[^\r\n#]+' # TODO(etingof) escape hash
if t.value.endswith('\\'):
t.lexer.multiline_newline_seen = False
t.lexer.code_start = t.lexer.lexpos - len(t.value)
t.lexer.begin('multilin... |
r'[^\r\n]+
def t_multiline_OPTION_AND_VALUE(self, t):
r'[^\r\n]+'
t.lexer.multiline_newline_seen = False
if t.value.endswith('\\'):
return
t.type = "OPTION_AND_VALUE"
t.lexer.begin('INITIAL')
value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos + 1]
... |
r'\r\n|\n|\r
def t_multiline_NEWLINE(self, t):
r'\r\n|\n|\r'
if t.lexer.multiline_newline_seen:
return self.t_multiline_OPTION_AND_VALUE(t)
t.lexer.multiline_newline_seen = True |
r'[^\r\n]+
def t_heredoc_OPTION_AND_VALUE(self, t):
r'[^\r\n]+'
if t.value.lstrip() != t.lexer.heredoc_anchor:
return
t.type = "OPTION_AND_VALUE"
t.lexer.begin('INITIAL')
value = t.lexer.lexdata[t.lexer.code_start + 1:t.lexer.lexpos - len(t.lexer.heredoc_anchor)]
... |
Replaces the current application default depot
def set_default(cls, name):
"""Replaces the current application default depot"""
if name not in cls._depots:
raise RuntimeError('%s depot has not been configured' % (name,))
cls._default_depot = name |
Gets the application wide depot instance.
Might return ``None`` if :meth:`configure` has not been
called yet.
def get(cls, name=None):
"""Gets the application wide depot instance.
Might return ``None`` if :meth:`configure` has not been
called yet.
"""
if name ... |
Retrieves a file by storage name and fileid in the form of a path
Path is expected to be ``storage_name/fileid``.
def get_file(cls, path):
"""Retrieves a file by storage name and fileid in the form of a path
Path is expected to be ``storage_name/fileid``.
"""
depot_name, file_... |
Configures an application depot.
This configures the application wide depot from a settings dictionary.
The settings dictionary is usually loaded from an application configuration
file where all the depot options are specified with a given ``prefix``.
The default ``prefix`` is *depot.*... |
Creates the application WSGI middleware in charge of serving local files.
A Depot middleware is required if your application wants to serve files from
storages that don't directly provide and HTTP interface like
:class:`depot.io.local.LocalFileStorage` and :class:`depot.io.gridfs.GridFSStorage`... |
Creates a new depot from a settings dictionary.
Behaves like the :meth:`configure` method but instead of configuring the application
depot it creates a new one each time.
def from_config(cls, config, prefix='depot.'):
"""Creates a new depot from a settings dictionary.
Behaves like the... |
This is only for testing pourposes, resets the DepotManager status
This is to simplify writing test fixtures, resets the DepotManager global
status and removes the informations related to the current configured depots
and middleware.
def _clear(cls):
"""This is only for testing pourpos... |
Place any commands to setup depotexample here
def setup_schema(command, conf, vars):
"""Place any commands to setup depotexample here"""
# Load the models
# <websetup.websetup.schema.before.model.import>
from depotexample import model
# <websetup.websetup.schema.after.model.import>
# <we... |
Return a set with all permissions granted to the user.
def permissions(self):
"""Return a set with all permissions granted to the user."""
perms = set()
for g in self.groups:
perms = perms | set(g.permissions)
return perms |
Return the user object whose email address is ``email``.
def by_email_address(cls, email):
"""Return the user object whose email address is ``email``."""
return DBSession.query(cls).filter_by(email_address=email).first() |
Return the user object whose user name is ``username``.
def by_user_name(cls, username):
"""Return the user object whose user name is ``username``."""
return DBSession.query(cls).filter_by(user_name=username).first() |
Check the password against existing credentials.
:param password: the password that was provided by the user to
try and authenticate. This is the clear text version that we will
need to match against the hashed one in the database.
:type password: unicode object.
:return... |
Render the error document
def document(self, *args, **kwargs):
"""Render the error document"""
resp = request.environ.get('pylons.original_response')
default_message = ("<p>We're sorry but we weren't able to process "
" this request.</p>")
values = dict(prefix... |
Set depotexample up with the settings found in the PasteDeploy configuration
file used.
:param global_conf: The global settings for depotexample (those
defined under the ``[DEFAULT]`` section).
:type global_conf: dict
:param full_stack: Should the whole TG2 stack be set up?
:type full_s... |
Standard implementation of :meth:`.DepotFileInfo.process_content`
This is the standard depot implementation of files upload, it will
store the file on the default depot and will provide the standard
attributes.
Subclasses will need to call this method to ensure the standard
set... |
Place any commands to setup depotexample here
def bootstrap(command, conf, vars):
"""Place any commands to setup depotexample here"""
# <websetup.bootstrap.before.auth
from sqlalchemy.exc import IntegrityError
try:
u = model.User()
u.user_name = 'manager'
u.display_name = 'Exam... |
Provides a real file object from file content
Converts ``FileStorage``, ``FileIntent`` and
``bytes`` to an actual file.
def file_from_content(content):
"""Provides a real file object from file content
Converts ``FileStorage``, ``FileIntent`` and
``bytes`` to an actual file.
"""
f = conten... |
Tries to extract from the given input the actual file object, filename and content_type
This is used by the create and replace methods to correctly deduce their parameters
from the available information when possible.
def fileinfo(fileobj, filename=None, content_type=None, existing=None):
"""T... |
Start the user login.
def login(self, came_from=lurl('/')):
"""Start the user login."""
login_counter = request.environ.get('repoze.who.logins', 0)
if login_counter > 0:
flash(_('Wrong credentials'), 'warning')
return dict(page='login', login_counter=str(login_counter),
... |
Redirect the user to the initially requested page on successful
authentication or redirect her back to the login page if login failed.
def post_login(self, came_from=lurl('/')):
"""
Redirect the user to the initially requested page on successful
authentication or redirect her back to th... |
Returns a datetime.strptime-compliant format string for parsing the *most likely* date format
used in examples. examples is a list containing example date strings.
def infer(examples, alt_rules=None):
"""
Returns a datetime.strptime-compliant format string for parsing the *most likely* date format
used... |
Return a list of date elements by applying rewrites to the initial date element list
def _apply_rewrites(date_classes, rules):
"""
Return a list of date elements by applying rewrites to the initial date element list
"""
for rule in rules:
date_classes = rule.execute(date_classes)
return da... |
Find the mode (most common element) in list elems. If there are ties, this function returns the least value.
If elems is an empty list, returns None.
def _mode(elems):
"""
Find the mode (most common element) in list elems. If there are ties, this function returns the least value.
If elems is an empty... |
Return the date_elem that has the most restrictive range from date_elems
def _most_restrictive(date_elems):
"""
Return the date_elem that has the most restrictive range from date_elems
"""
most_index = len(DATE_ELEMENTS)
for date_elem in date_elems:
if date_elem in DATE_ELEMENTS and DATE_EL... |
For each date class, return the percentage of tokens that the class matched (floating point [0.0 - 1.0]). The
returned value is a tuple of length patterns. Tokens should be a list.
def _percent_match(date_classes, tokens):
"""
For each date class, return the percentage of tokens that the class matched (flo... |
Return a list of date elements by choosing the most likely element for a token within examples (context-free).
def _tag_most_likely(examples):
"""
Return a list of date elements by choosing the most likely element for a token within examples (context-free).
"""
tokenized_examples = [_tokenize_by_charac... |
Return a list of strings by splitting s (tokenizing) by character class.
For example:
_tokenize_by_character_class('Sat Jan 11 19:54:52 MST 2014') => ['Sat', ' ', 'Jan', ' ', '11', ' ', '19', ':',
'54', ':', '52', ' ', 'MST', ' ', '2014']
_tokenize_by_character_class('2013-08-14') => ['2013', '-', ... |
If condition, return a new elem_list provided by executing action.
def execute(self, elem_list):
"""
If condition, return a new elem_list provided by executing action.
"""
if self.condition.is_true(elem_list):
return self.action.act(elem_list)
else:
retur... |
Return True if elem (an element of elem_list) matches seq_expr, an element in self.sequence
def match(elem, seq_expr):
"""
Return True if elem (an element of elem_list) matches seq_expr, an element in self.sequence
"""
if type(seq_expr) is str: # wild-card
if seq_expr == '.... |
Return the first position in elem_list where find_seq starts
def find(find_seq, elem_list):
"""
Return the first position in elem_list where find_seq starts
"""
seq_pos = 0
for index, elem in enumerate(elem_list):
if Sequence.match(elem, find_seq[seq_pos]):
... |
根据成绩判断绩点
:param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩
:return: 成绩绩点
:rtype: float
def get_point(grade_str):
"""
根据成绩判断绩点
:param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩
:return: 成绩绩点
:rtype: float
"""
try:
grade = float(grade_str)
assert 0 <= grade <= 100
if 95 <=... |
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考
:param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组
:return: 包含了课程平均绩点和 gpa 的元组
def cal_gpa(grades):
"""
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考
:param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组
:return: 包含了课程... |
计算对应的学期代码
:param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012
:param is_first_term: 是否为第一学期
:type is_first_term: bool
:return: 形如 "022" 的学期代码
def cal_term_code(year, is_first_term=True):
"""
计算对应的学期代码
:param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012
:param is_first_term: 是否为第一学期
:typ... |
将学期字符串转换为对应的学期代码串
:param term_str: 形如 "2012-2013学年第二学期" 的学期字符串
:return: 形如 "022" 的学期代码
def term_str2code(term_str):
"""
将学期字符串转换为对应的学期代码串
:param term_str: 形如 "2012-2013学年第二学期" 的学期字符串
:return: 形如 "022" 的学期代码
"""
result = ENV['TERM_PATTERN'].match(term_str).groups()
year = int(resul... |
测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000
:param method: 请求方法
:param path: 默认的访问路径
:param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']`
:param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖
:param kwargs: 其他传递到 ``requests.request`` 的参数
:return: 形如 ``[(访问耗时, 地址)]`` 的排名数据
def sort_host... |
筛选出指定星期[和指定星期几]的课程
:param curriculum: 课程表数据
:param week: 需要筛选的周数, 是一个代表周数的正整数
:param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日
:return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程
def filter_curriculum(curriculum, week, weekday=None):
"""
筛选出指定星期[和指定星期几]的课程
:param curricul... |
将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表
:param curriculum: 课表
:param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29)
:param compress: 压缩连续的课时为一个
:param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵
:return: [(datetime.datetime, str) ...]
def ... |
Main function for Mine Sweeper Game.
Parameters
----------
board_width : int
the width of the board (> 0)
board_height : int
the height of the board (> 0)
num_mines : int
the number of mines, cannot be larger than
(board_width x board_height)
port : int
U... |
将上课时间表转换为 icalendar
:param schedule: 上课时间表
:param name: 日历名称
:param using_todo: 使用 ``icalendar.Todo`` 而不是 ``icalendar.Event`` 作为活动类
:return: icalendar.Calendar()
def schedule2calendar(schedule, name='课表', using_todo=True):
"""
将上课时间表转换为 icalendar
:param schedule: 上课时间表
:param name: 日历... |
Init a new game.
Parameters
----------
board : MSBoard
define a new board.
game_status : int
define the game status:
0: lose, 1: win, 2: playing
moves : int
how many moves carried out.
def init_new_game(self, with_tcp=True):
... |
Check if a move is valid.
If the move is not valid, then shut the game.
If the move is valid, then setup a dictionary for the game,
and update move counter.
TODO: maybe instead of shut the game, can end the game or turn it into
a valid move?
Parameters
--------... |
Updat board by a given move.
Parameters
----------
move_type : string
one of four move types:
"click", "flag", "unflag", "question"
move_x : int
X position of the move
move_y : int
Y position of the move
def play_move(self, move_t... |
Parse a move from a string.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]"
Returns
-------
def parse_move(self, move_msg):
"""Parse a move from a string.
Parameters
----------
... |
Another play move function for move message.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]"
def play_move_msg(self, move_msg):
"""Another play move function for move message.
Parameters
----------
... |
Waiting for a TCP connection.
def tcp_accept(self):
"""Waiting for a TCP connection."""
self.conn, self.addr = self.tcp_socket.accept()
print("[MESSAGE] The connection is established at: ", self.addr)
self.tcp_send("> ") |
Receive data from TCP port.
def tcp_receive(self):
"""Receive data from TCP port."""
data = self.conn.recv(self.BUFFER_SIZE)
if type(data) != str:
# Python 3 specific
data = data.decode("utf-8")
return str(data) |
将没有值但有必须要的单元格的值设置为 None
将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表
:param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象
:return: 二维列表
def parse_tr_strs(trs):
"""
将没有值但有必须要的单元格的值设置为 None
将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表
:param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象
:return: 二维列表
"... |
碾平 list::
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten_list(a)
[1, 2, 3, 4, 5, 6, 7, 8]
:param multiply_list: 混淆的多层列表
:return: 单层的 list
def flatten_list(multiply_list):
"""
碾平 list::
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten_list(a)
... |
>>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b'))
[[1, 2], [3, 4]]
:param dict_list: 字典列表
:param columns: 字典的键
def dict_list_2_matrix(dict_list, columns):
"""
>>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b'))
[[1, 2], [3, 4]]
:para... |
解析课程表里的课程
:param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据
def parse_course(course_str):
"""
解析课程表里的课程
:param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据
"""
# 解析课程单元格
# 所有情况
# 机械原理[一教416 (1-14周)]/
# 程序与算法综合设计[不占用... |
教学班查询, 查询指定教学班的所有学生
@structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号
def get_class_students(self, xqdm, kcdm, jxbh):
"""
教学班查询, 查询指定教学班的所有学生
@structure {'学期': str, '班级名称': str, '学生': [{'姓... |
获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息
@structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str,
'时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号
de... |
课程查询
@structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}]
:param xqdm: 学期代码
:param kcdm: 课程代码
:param kcmc: 课程名称
def search_course(self, xqdm, kcdm=None, kcmc=None):
"""
课程查询
@structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': ... |
专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm`
@structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}]
:param xqdm: 学期代码
:param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课
:param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得
def get_teaching_plan(self, xqdm, kclx='b', zyd... |
修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错
@structure bool
:param new_password: 新密码
def change_password(self, new_password):
"""
修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错
@structure bool
:param new_password: ... |
更新电话
@structure bool
:param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567'
def set_telephone(self, tel):
"""
更新电话
@structure bool
:param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567'
"""
return type(tel)(self.query(SetT... |
课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好.
默认都是最好的选项
:param kcdm: 课程代码
:param jxbh: 教学班号
:param r101: 教学态度认真,课前准备充分
:param r102: 教授内容充实,要点重点突出
:param r103: 理论联系实际,反映最新成果
:param r104: 教学方法灵活,师生互动得当
:param r105: 运用现代技术,教学手段多样
:param r... |
修改个人的课程
@structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}]
:param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表,
jxbhs 可以为空代表选择所有可选班级
:param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}``
:retur... |
检查课程是否被选
@structure [bool]
:param kcdms: 课程代码列表
:return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False
def check_courses(self, kcdms):
"""
检查课程是否被选
@structure [bool]
:param kcdms: 课程代码列表
:return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False
"""
selected_co... |
获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选.
由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告.
@structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int,
'教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '... |
所有接口用来发送请求的方法, 只是 :meth:`requests.sessions.Session.send` 的一个钩子方法, 用来处理请求前后的工作
def send(self, request, **kwargs):
"""
所有接口用来发送请求的方法, 只是 :meth:`requests.sessions.Session.send` 的一个钩子方法, 用来处理请求前后的工作
"""
response = super(BaseSession, self).send(request, **kwargs)
if ENV['RAISE_FOR_ST... |
Init a valid board by given settings.
Parameters
----------
mine_map : numpy.ndarray
the map that defines the mine
0 is empty, 1 is mine
info_map : numpy.ndarray
the map that presents to gamer
0-8 is number of mines in srrounding.
... |
Click one grid by given position.
def click_field(self, move_x, move_y):
"""Click one grid by given position."""
field_status = self.info_map[move_y, move_x]
# can only click blank region
if field_status == 11:
if self.mine_map[move_y, move_x] == 1:
self.inf... |
Discover region from given location.
def discover_region(self, move_x, move_y):
"""Discover region from given location."""
field_list = deque([(move_y, move_x)])
while len(field_list) != 0:
field = field_list.popleft()
(tl_idx, br_idx, region_sum) = self.get_region(fie... |
Get region around a location.
def get_region(self, move_x, move_y):
"""Get region around a location."""
top_left = (max(move_y-1, 0), max(move_x-1, 0))
bottom_right = (min(move_y+1, self.board_height-1),
min(move_x+1, self.board_width-1))
region_sum = self.mine_m... |
Flag a grid by given position.
def flag_field(self, move_x, move_y):
"""Flag a grid by given position."""
field_status = self.info_map[move_y, move_x]
# a questioned or undiscovered field
if field_status != 9 and (field_status == 10 or field_status == 11):
self.info_map[mov... |
Unflag or unquestion a grid by given position.
def unflag_field(self, move_x, move_y):
"""Unflag or unquestion a grid by given position."""
field_status = self.info_map[move_y, move_x]
if field_status == 9 or field_status == 10:
self.info_map[move_y, move_x] = 11 |
Question a grid by given position.
def question_field(self, move_x, move_y):
"""Question a grid by given position."""
field_status = self.info_map[move_y, move_x]
# a questioned or undiscovered field
if field_status != 10 and (field_status == 9 or field_status == 11):
self.... |
Check the board status and give feedback.
def check_board(self):
"""Check the board status and give feedback."""
num_mines = np.sum(self.info_map == 12)
num_undiscovered = np.sum(self.info_map == 11)
num_questioned = np.sum(self.info_map == 10)
if num_mines > 0:
ret... |
Structure a board as in print_board.
def board_msg(self):
"""Structure a board as in print_board."""
board_str = "s\t\t"
for i in xrange(self.board_width):
board_str += str(i)+"\t"
board_str = board_str.expandtabs(4)+"\n\n"
for i in xrange(self.board_height):
... |
生成响应报告
:param response: ``requests.models.Response`` 对象
:param request_headers: 是否加入请求头
:param request_body: 是否加入请求体
:param response_headers: 是否加入响应头
:param response_body: 是否加入响应体
:param redirection: 是否加入重定向响应
:return: str
def report_response(response,
request_headers=T... |
Setup control widget UI.
def init_ui(self):
"""Setup control widget UI."""
self.control_layout = QHBoxLayout()
self.setLayout(self.control_layout)
self.reset_button = QPushButton()
self.reset_button.setFixedSize(40, 40)
self.reset_button.setIcon(QtGui.QIcon(WIN_PATH))
... |
Init game interface.
def init_ui(self):
"""Init game interface."""
board_width = self.ms_game.board_width
board_height = self.ms_game.board_height
self.create_grid(board_width, board_height)
self.time = 0
self.timer = QtCore.QTimer()
self.timer.timeout.connect(se... |
Create a grid layout with stacked widgets.
Parameters
----------
grid_width : int
the width of the grid
grid_height : int
the height of the grid
def create_grid(self, grid_width, grid_height):
"""Create a grid layout with stacked widgets.
Parame... |
Timing game.
def timing_game(self):
"""Timing game."""
self.ctrl_wg.game_timer.display(self.time)
self.time += 1 |
Reset game board.
def reset_game(self):
"""Reset game board."""
self.ms_game.reset_game()
self.update_grid()
self.time = 0
self.timer.start(1000) |
Update grid according to info map.
def update_grid(self):
"""Update grid according to info map."""
info_map = self.ms_game.get_info_map()
for i in xrange(self.ms_game.board_height):
for j in xrange(self.ms_game.board_width):
self.grid_wgs[(i, j)].info_label(info_map[... |
Init the ui.
def init_ui(self):
"""Init the ui."""
self.id = 11
self.setFixedSize(self.field_width, self.field_height)
self.setPixmap(QtGui.QPixmap(EMPTY_PATH).scaled(
self.field_width*3, self.field_height*3))
self.setStyleSheet("QLabel {background-color: blue;}"... |
Define mouse press event.
def mousePressEvent(self, event):
"""Define mouse press event."""
if event.button() == QtCore.Qt.LeftButton:
# get label position
p_wg = self.parent()
p_layout = p_wg.layout()
idx = p_layout.indexOf(self)
loc = p_layo... |
Set info label by given settings.
Parameters
----------
indicator : int
A number where
0-8 is number of mines in srrounding.
12 is a mine field.
def info_label(self, indicator):
"""Set info label by given settings.
Parameters
-------... |
Thread behavior.
def run(self):
"""Thread behavior."""
self.ms_game.tcp_accept()
while True:
data = self.ms_game.tcp_receive()
if data == "help\n":
self.ms_game.tcp_help()
self.ms_game.tcp_send("> ")
elif data == "exit\n":
... |
Register commandline options.
def options(self, parser, env):
"""Register commandline options.
"""
parser.add_option(
"--epdb", action="store_true", dest="epdb_debugErrors",
default=env.get('NOSE_EPDB', False),
help="Drop into extended debugger on errors")
... |
Configure which kinds of exceptions trigger plugin.
def configure(self, options, conf):
"""Configure which kinds of exceptions trigger plugin.
"""
self.conf = conf
self.enabled = options.epdb_debugErrors or options.epdb_debugFailures
self.enabled_for_errors = options.epdb_debugE... |
Sets a condition for set_trace statements that have the
specified marker. A condition can either callable, in
which case it should take one argument, which is the
number of times set_trace(marker) has been called,
or it can be a number, in which case the break will
only be calle... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.