function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def fix_number(target_type):
return lambda value: None if isinstance(value, (str, six.text_type)) and len(value) == 0 else target_type(value) | anjianshi/flask-restful-extend | [
43,
14,
43,
5,
1381660417
] |
def test_lengths_top_k_op(self, N, K, gc, dc):
lens = np.random.randint(low=1, high=2 * K + 1, size=N).astype(np.int32)
X = []
for i in lens:
X.extend(map(lambda x: x / 100.0, range(0, 6 * i, 6)))
X = np.array(X, dtype=np.float32)
op = core.CreateOperator("LengthsTopK", ["X", "Y"], ["values", "indices"], k=K)
def lengths_top_k(X, lens):
N, si = lens.shape[0], 0
values, indices = [], []
for i in range(N):
cur_indices = X[si:si + lens[i]].argsort()[-K:][::-1]
cur_values = X[si:si + lens[i]][cur_indices]
values.extend(cur_values)
indices.extend(cur_indices)
si += lens[i]
if lens[i] < K:
values.extend([0] * (K - lens[i]))
indices.extend([-1] * (K - lens[i]))
return (np.array(values, dtype=np.float32).reshape(-1, K),
np.array(indices, dtype=np.int32).reshape(-1, K))
self.assertDeviceChecks(dc, op, [X, lens], [0, 1])
self.assertReferenceChecks(gc, op, [X, lens], lengths_top_k)
self.assertGradientChecks(gc, op, [X, lens], 0, [0]) | ryfeus/lambda-packs | [
1086,
234,
1086,
13,
1476901359
] |
def setUp(self) -> None:
mock_client = mock.Mock(paper_trade=False)
self.mock_trade = mock.Mock(
client=mock_client, market_id="1.1", selection_id=123, info={}
)
self.mock_order_type = mock.Mock(info={})
self.order = BaseOrder(
self.mock_trade, "BACK", self.mock_order_type, 1, context={1: 2}
) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test__update_status(self, mock_info, mock__is_complete):
self.mock_trade.complete = True
self.order._update_status(OrderStatus.EXECUTION_COMPLETE)
self.assertEqual(self.order.status_log, [OrderStatus.EXECUTION_COMPLETE])
self.assertEqual(self.order.status, OrderStatus.EXECUTION_COMPLETE)
self.mock_trade.complete_trade.assert_called()
mock__is_complete.assert_called() | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_placing(self, mock__update_status):
self.order.placing()
mock__update_status.assert_called_with(OrderStatus.PENDING) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_executable(self, mock__update_status):
self.order.update_data = {123: 456}
self.order.executable()
mock__update_status.assert_called_with(OrderStatus.EXECUTABLE)
self.assertEqual(self.order.update_data, {}) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_execution_complete(self, mock__update_status):
self.order.update_data = {123: 456}
self.order.execution_complete()
mock__update_status.assert_called_with(OrderStatus.EXECUTION_COMPLETE)
self.assertIsNotNone(self.order.date_time_execution_complete)
self.assertEqual(self.order.update_data, {}) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_cancelling(self, mock__update_status):
self.order.cancelling()
mock__update_status.assert_called_with(OrderStatus.CANCELLING) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_updating(self, mock__update_status):
self.order.updating()
mock__update_status.assert_called_with(OrderStatus.UPDATING) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_replacing(self, mock__update_status):
self.order.replacing()
mock__update_status.assert_called_with(OrderStatus.REPLACING) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_violation(self, mock__update_status):
self.order.update_data = {123: 456}
self.order.violation("the murder capital")
mock__update_status.assert_called_with(OrderStatus.VIOLATION)
self.assertEqual(self.order.update_data, {})
self.assertEqual(self.order.violation_msg, "the murder capital") | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_cancel(self):
with self.assertRaises(NotImplementedError):
self.order.cancel() | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_replace(self):
with self.assertRaises(NotImplementedError):
self.order.replace(20.0) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_create_cancel_instruction(self):
with self.assertRaises(NotImplementedError):
self.order.create_cancel_instruction() | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_create_replace_instruction(self):
with self.assertRaises(NotImplementedError):
self.order.create_replace_instruction() | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_current_order(self):
self.assertIsNone(self.order.current_order)
mock_responses = mock.Mock()
mock_responses.current_order = None
self.order.responses = mock_responses
self.assertEqual(self.order.current_order, mock_responses.place_response)
mock_responses.current_order = 1
self.assertEqual(self.order.current_order, 1) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_current_order_simulated(self, mock_config):
mock_config.simulated = True
order = BaseOrder(mock.Mock(), "", mock.Mock())
self.assertTrue(order.simulated)
self.assertTrue(order._simulated) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_average_price_matched(self):
with self.assertRaises(NotImplementedError):
assert self.order.average_price_matched | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_size_remaining(self):
with self.assertRaises(NotImplementedError):
assert self.order.size_remaining | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_size_lapsed(self):
with self.assertRaises(NotImplementedError):
assert self.order.size_lapsed | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_elapsed_seconds(self):
self.assertIsNone(self.order.elapsed_seconds)
mock_responses = mock.Mock()
mock_responses.date_time_placed = datetime.datetime.utcnow()
self.order.responses = mock_responses
self.assertGreaterEqual(self.order.elapsed_seconds, 0) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_elapsed_seconds_executable(self):
self.assertIsNone(self.order.elapsed_seconds_executable)
mock_responses = mock.Mock()
mock_responses.date_time_placed = datetime.datetime.utcnow()
self.order.responses = mock_responses
self.order.date_time_execution_complete = datetime.datetime.utcnow()
self.assertGreaterEqual(self.order.elapsed_seconds_executable, 0) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_lookup(self):
self.assertEqual(
self.order.lookup,
(self.mock_trade.market_id, self.mock_trade.selection_id, 1),
) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_set_and_get_sep(self):
self.order.sep = "a"
self.assertEqual("a", self.order.sep) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_notes_str(self):
self.order.notes = collections.OrderedDict({"1": 1, 2: "2", 3: 3, 4: "four"})
self.assertEqual(self.order.notes_str, "1,2,3,four")
self.order.notes = collections.OrderedDict()
self.assertEqual(self.order.notes_str, "") | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def setUp(self) -> None:
mock_client = mock.Mock(paper_trade=False)
self.mock_trade = mock.Mock(
client=mock_client, market_id="1.1", selection_id=123, info={}
)
self.mock_status = mock.Mock()
self.mock_order_type = mock.Mock(info={}, size=2.0, liability=2.0)
self.order = BetfairOrder(self.mock_trade, "BACK", self.mock_order_type) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_place(self, mock_placing):
self.order.place(123, 456, False)
mock_placing.assert_called_with()
self.assertEqual(self.order.publish_time, 123)
self.assertEqual(self.order.market_version, 456)
self.assertFalse(self.order.async_) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_cancel(self, mock_cancelling, mock_size_remaining):
mock_size_remaining.return_value = 20
self.order.bet_id = 123
self.order.status = OrderStatus.EXECUTABLE
with self.assertRaises(OrderUpdateError):
self.order.cancel(12)
self.mock_order_type.ORDER_TYPE = OrderTypes.LIMIT
self.order.cancel(0.01)
self.assertEqual(self.order.update_data, {"size_reduction": 0.01})
mock_cancelling.assert_called_with()
self.order.cancel()
self.assertEqual(self.order.update_data, {"size_reduction": None}) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_cancel_error_size(self, mock_cancelling, mock_size_remaining):
mock_size_remaining.return_value = 20
self.order.status = OrderStatus.EXECUTABLE
with self.assertRaises(OrderUpdateError):
self.order.cancel(12)
self.mock_order_type.ORDER_TYPE = OrderTypes.LIMIT
with self.assertRaises(OrderUpdateError):
self.order.cancel(21) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_cancel_error(self, mock_size_remaining):
mock_size_remaining.return_value = 20
self.mock_order_type.ORDER_TYPE = OrderTypes.LIMIT
self.order.status = OrderStatus.PENDING
with self.assertRaises(OrderUpdateError):
self.order.cancel(12) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_update(self, mock_updating):
self.order.bet_id = 123
self.order.status = OrderStatus.EXECUTABLE
with self.assertRaises(OrderUpdateError):
self.order.update("PERSIST")
self.mock_order_type.ORDER_TYPE = OrderTypes.LIMIT
self.mock_order_type.persistence_type = "LAPSE"
self.order.update("PERSIST")
self.assertEqual(self.mock_order_type.persistence_type, "PERSIST")
mock_updating.assert_called_with()
with self.assertRaises(OrderUpdateError):
self.order.update("PERSIST") | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_update_error(self):
self.mock_order_type.ORDER_TYPE = OrderTypes.LIMIT
self.mock_order_type.persistence_type = "LAPSE"
self.order.status = OrderStatus.PENDING
with self.assertRaises(OrderUpdateError):
self.order.update("PERSIST") | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_replace(self, mock_replacing):
self.order.bet_id = 123
self.order.status = OrderStatus.EXECUTABLE
with self.assertRaises(OrderUpdateError):
self.order.replace(1.01)
self.mock_order_type.ORDER_TYPE = OrderTypes.LIMIT
self.mock_order_type.price = 2.02
self.order.replace(1.01)
self.assertEqual(self.order.update_data, {"new_price": 1.01})
mock_replacing.assert_called_with()
with self.assertRaises(OrderUpdateError):
self.order.replace(2.02) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_replace_error(self):
self.mock_order_type.ORDER_TYPE = OrderTypes.LIMIT
self.order.status = OrderStatus.PENDING
with self.assertRaises(OrderUpdateError):
self.order.replace(1.52) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_create_cancel_instruction(self):
self.order.update_data = {"size_reduction": 0.02}
self.assertEqual(
self.order.create_cancel_instruction(), {"sizeReduction": 0.02}
) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_create_replace_instruction(self):
self.order.update_data = {"new_price": 2.02}
self.assertEqual(self.order.create_replace_instruction(), {"newPrice": 2.02}) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_size_matched(self):
self.assertEqual(self.order.size_matched, 0)
mock_current_order = mock.Mock(size_matched=10)
self.order.responses.current_order = mock_current_order
self.assertEqual(self.order.size_matched, mock_current_order.size_matched) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_size_remaining_missing(self):
self.mock_order_type.ORDER_TYPE = OrderTypes.LIMIT
self.mock_order_type.size = 2.51
self.assertEqual(self.order.size_remaining, 2.51) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_size_remaining_missing_partial_match(self, mock_size_matched):
self.mock_order_type.ORDER_TYPE = OrderTypes.LIMIT
mock_size_matched.return_value = 2
self.mock_order_type.size = 10
self.assertEqual(self.order.size_remaining, 8) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_size_cancelled(self):
self.assertEqual(self.order.size_cancelled, 0)
mock_current_order = mock.Mock(size_cancelled=10)
self.order.responses.current_order = mock_current_order
self.assertEqual(self.order.size_cancelled, mock_current_order.size_cancelled) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_size_voided(self):
self.assertEqual(self.order.size_voided, 0)
mock_current_order = mock.Mock(size_voided=10)
self.order.responses.current_order = mock_current_order
self.assertEqual(self.order.size_voided, mock_current_order.size_voided) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_json(self):
self.assertTrue(isinstance(self.order.json(), str)) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_letters_True(self):
# ascii_letters contains a-z and A-Z
for c in string.ascii_letters:
self.assertTrue(BetfairOrder.is_valid_customer_order_ref_character(c)) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def test_digits_True(self):
# string.digits contains digits 0-9
for c in string.digits:
self.assertTrue(BetfairOrder.is_valid_customer_order_ref_character(c)) | liampauling/flumine | [
110,
46,
110,
30,
1479407630
] |
def __init__(
self,
indent=DEFAULT_INDENT,
preserve=[],
blanks=DEFAULT_BLANKS,
compress=DEFAULT_COMPRESS,
selfclose=DEFAULT_SELFCLOSE,
indent_char=DEFAULT_INDENT_CHAR,
encoding_input=DEFAULT_ENCODING_INPUT,
encoding_output=DEFAULT_ENCODING_OUTPUT,
inline=DEFAULT_INLINE,
correct=DEFAULT_CORRECT,
eof_newline=DEFAULT_EOF_NEWLINE, | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def encoding_effective(self, enc=None):
if self.encoding_output:
return self.encoding_output
elif self.encoding_internal:
return self.encoding_internal
elif self.encoding_input:
return self.encoding_input
else:
return "UTF-8" | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def enc_encode(self, strg):
""" Encode a formatted XML document in target"""
if sys.version_info > (3, 0):
return strg.encode(self.encoding_effective) # v3
return strg.decode("utf-8").encode(self.encoding_effective) # v2 | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def format_string(self, xmldoc=""):
""" Format a XML document given by xmldoc """
token_list = Formatter.TokenList(self)
token_list.parser.Parse(xmldoc)
return self.enc_encode(str(token_list)) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __init__(self, formatter):
# Keep tokens in a list:
self._list = []
self.formatter = formatter
self.parser = xml.parsers.expat.ParserCreate(
encoding=self.formatter.encoding_input
)
self.parser.specified_attributes = 1
self.parser.buffer_text = True
# Push tokens to buffer:
for pattern in [
"XmlDecl%s",
"ElementDecl%s",
"AttlistDecl%s",
"EntityDecl%s",
"StartElement%s",
"EndElement%s",
"ProcessingInstruction%s",
"CharacterData%s",
"Comment%s",
"Default%s",
"StartDoctypeDecl%s",
"EndDoctypeDecl%s",
"StartCdataSection%s",
"EndCdataSection%s",
"NotationDecl%s",
]:
setattr(
self.parser, pattern % "Handler", self.xml_handler(pattern % "")
) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __len__(self):
return len(self._list) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __setitem__(self, pos, value):
if 0 <= pos < len(self._list):
self._list[pos] = value
else:
raise IndexError | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def append(self, tk):
""" Add token to tokenlist. """
tk.pos = len(self._list)
self._list.append(tk) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def level_decrement(self):
""" Decrement level counter. """
self.level_counter -= 1 | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def sequence(self, tk, scheme=None):
"""Returns sublist of token list.
None: next to last
EndElement: first to previous"""
if scheme == "EndElement" or (scheme is None and tk.end):
return reversed(self._list[: tk.pos])
return self._list[(tk.pos + 1) :] | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def token_indent_inline(self, tk):
""" Indent every element content - no matter enclosed by text or mixed content. """
for itk in iter(self.sequence(tk, "EndElement")):
if itk.level < tk.level and itk.name == "StartElement":
if itk.content_model == 1:
return True
return False
if (
itk.level == tk.level
and tk.name == "EndElement"
and itk.name == "StartElement"
):
if itk.content_model == 1:
return True
return False
return True | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def token_preserve(self, tk):
"""Preseve eyery descendant of an preserved element.
0: not locked
1: just (un)locked
2: locked"""
# Lock perserving for StartElements:
if tk.name == "StartElement":
if self.preserve_level is not None:
return 2
if tk.arg[0] in self.formatter.preserve:
self.preserve_level = tk.level
return 1
return 0
# Unlock preserving for EndElements:
elif tk.name == "EndElement":
if (
tk.arg[0] in self.formatter.preserve
and tk.level == self.preserve_level
):
self.preserve_level = None
return 1
elif self.preserve_level is None:
return 0
return 2
return self.preserve_level is not None | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def whitespace_append_leading(self, tk):
""" Add a leading whitespace to previous character data. """
if self.formatter.correct and tk.trailing and tk.not_empty:
self.whitespace_append(tk) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def whitespace_delete_leading(self, tk):
""" Returns True, if no next token or all empty (up to next end element)"""
if (
self.formatter.correct
and tk.leading
and not tk.preserve
and not tk.cdata_section
):
for itk in self.sequence(tk, "EndElement"):
if itk.trailing:
return True
elif itk.name in ["EndElement", "CharacterData", "EndCdataSection"]:
return False
return True
return False | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def insert_empty(self, tk, before=True):
""" Insert an Empty Token into token list - before or after tk. """
if not (0 < tk.pos < (len(self) - 1)):
return False
ptk = self[tk.pos - 1]
ntk = self.formatter.CharacterData(self, [" "])
ntk.level = max(ptk.level, tk.level)
ntk.descendant_mixed = tk.descendant_mixed
ntk.preserve = ptk.preserve * tk.preserve
ntk.cdata_section = ptk.cdata_section or tk.cdata_section
if before:
self._list.insert(tk.pos + 1, ntk)
else:
self._list.insert(tk.pos, ntk)
for i in range((tk.pos - 1), len(self._list)):
self._list[i].pos = i | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __init__(self, tklist, arg):
# Reference Token List:
self.list = tklist
# Token datas:
self.arg = list(arg)
# Token is placed in an CDATA section:
self.cdata_section = False
# Token has content model:
self.content_model = None
# Remove trailing wihtespaces:
self.delete_trailing = False
# Remove leading whitespaces:
self.delete_leading = False
# Token is descendant of text or mixed content element:
self.descendant_mixed = False
# Reference to formatter:
self.formatter = tklist.formatter
# Insert indenting white spaces:
self.indent = False
# N-th generation of roots descendants:
self.level = self.list.level_counter
# Token class:
self.name = self.__class__.__name__
# Preserve white spaces within enclosed tokens:
self.preserve = False
# Position in token list:
self.pos = None | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
return "" | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def end(self):
return self.name == "EndElement" | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def empty(self):
return self.name == "CharacterData" and re.match(
r"^[\t\s\n]*$", self.arg[0]
) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def leading(self):
return self.name == "CharacterData" and re.search(
r"^[\t\s\n]+", self.arg[0]
) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def not_empty(self):
return (
self.name == "CharacterData"
and not self.cdata_section
and not re.match(r"^[\t\s\n]+$", self.arg[0])
) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def trailing(self):
return self.name == "CharacterData" and re.search(
r"[\t\s\n]+$", self.arg[0]
) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def start(self):
return self.name == "StartElement" | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def correct(self):
return self.formatter.correct | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def indent_insert(self):
""" Indent token. """
# Child of root and no empty node
if (
self.level > 0 and not (self.end and self.list[self.pos - 1].start)
) or ( # not empty node:
self.end and not self.list[self.pos - 1].start
):
return self.indent_create(self.level)
return "" | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def identifier(self, systemid, publicid):
# TODO add base parameter:
if publicid and systemid:
return ' PUBLIC "%s" "%s"' % (publicid, systemid)
elif publicid:
return ' PUBLIC "%s"' % publicid
elif systemid:
return ' SYSTEM "%s"' % systemid
return "" | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def pre_operate(self):
pass | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
str = self.indent_create()
str += "<!ATTLIST %s %s" % (self.arg[0], self.arg[1])
if self.arg[2] is not None:
str += " %s" % self.arg[2]
if self.arg[4] and not self.arg[3]:
str += " #REQUIRED"
elif self.arg[3] and self.arg[4]:
str += " #FIXED"
elif not self.arg[4] and not self.arg[3]:
str += " #IMPLIED"
if self.arg[3]:
str += ' "%s"' % self.arg[3]
str += ">"
return str | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
str = self.arg[0]
if not self.preserve and not self.cdata_section:
# remove empty tokens always in element content!
if self.empty and not self.descendant_mixed:
if self.formatter.blanks and not self.formatter.compress and re.match(r"\s*\n\s*\n\s*", str):
str = "\n"
else:
str = ""
else:
if self.correct:
str = re.sub(r"\r\n", "\n", str)
str = re.sub(r"\r|\n|\t", " ", str)
str = re.sub(r"\s+", " ", str)
if self.delete_leading:
str = re.sub(r"^\s", "", str)
if self.delete_trailing:
str = re.sub(r"\s$", "", str)
if not self.cdata_section:
str = re.sub(r"&", "&", str)
str = re.sub(r"<", "<", str)
return str | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def post_operate(self):
self.delete_leading = self.list.whitespace_delete_leading(self)
self.delete_trailing = self.list.whitespace_delete_trailing(self) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
str = ""
if self.preserve in [0, 1] and self.indent:
str += self.indent_insert()
str += "<!--%s-->" % re.sub(
r"^[\r\n]+$", "\n", re.sub(r"^[\r\n]+", "\n", self.arg[0])
)
return str | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
return "]]>" | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
str = self.indent_create()
str += "<!ELEMENT %s%s>" % (self.arg[0], self.evaluate_model(self.arg[1]))
return str | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
str = ""
if self.list[self.pos - 1].name != "StartDoctypeDecl":
str += self.indent_create(0)
str += "]"
str += ">"
str += self.indent_create(0)
return str | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __init__(self, list, arg):
list.level_decrement()
super(Formatter.EndElement, self).__init__(list, arg) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def configure(self):
self.descendant_mixed = self.list.token_descendant_mixed(self)
self.preserve = self.list.token_preserve(self)
self.indent = self.list.token_indent(self) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
str = self.indent_create()
str += "<!ENTITY "
if self.arg[1]:
str += "% "
str += "%s " % self.arg[0]
if self.arg[2]:
str += '"%s"' % self.arg[2]
else:
str += "%s " % self.identifier(self.arg[4], self.arg[5])
if self.arg[6]:
str += "NDATA %s" % self.arg[6]
str += ">"
return str | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
str = self.indent_create()
str += "<!NOTATION %s%s>" % (
self.arg[0],
self.identifier(self.arg[2], self.arg[3]),
)
return str | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
str = ""
if self.preserve in [0, 1] and self.indent:
str += self.indent_insert()
str += "<?%s %s?>" % (self.arg[0], self.arg[1])
return str | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
return "<![CDATA[" | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __unicode__(self):
str = "<!DOCTYPE %s" % (self.arg[0])
if self.arg[1]:
str += self.identifier(self.arg[1], self.arg[2])
if self.arg[3]:
str += " ["
return str | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __init__(self, list, arg):
super(Formatter.StartElement, self).__init__(list, arg)
self.list.level_increment() | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def configure(self):
self.content_model = self.list.token_model(self)
self.descendant_mixed = self.list.token_descendant_mixed(self)
self.preserve = self.list.token_preserve(self)
self.indent = self.list.token_indent(self) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def __init__(self, list, arg):
super(Formatter.XmlDecl, self).__init__(list, arg)
if len(self.arg) > 1:
self.formatter.encoding_internal = self.arg[1] | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def cli_usage(msg=""):
""" Output usage for command line tool. """
sys.stderr.write(msg + "\n")
sys.stderr.write(
'Usage: xmlformat [--preserve "pre,literal"] [--blanks]\
[--compress] [--selfclose] [--indent num] [--indent-char char]\
[--outfile file] [--encoding enc] [--outencoding enc]\
[--disable-inlineformatting] [--overwrite] [--disable-correction]\
[--eof-newline]\
[--help] <--infile file | file | - >\n'
)
sys.exit(2) | pamoller/xmlformatter | [
16,
6,
16,
3,
1390927940
] |
def main():
"""
Standalone django model test with a 'memory-only-django-installation'.
You can play with a django model without a complete django app installation.
http://www.djangosnippets.org/snippets/1044/
"""
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
os.environ["DJANGO_SETTINGS_MODULE"] = "django.conf.global_settings"
from django.conf import global_settings
global_settings.INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.sites',
'django.contrib.contenttypes',
'websettings',
)
global_settings.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
global_settings.MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
global_settings.SECRET_KEY = "secret_key_for_testing"
global_settings.ROOT_URLCONF = "websettings.urls"
global_settings.WEBSETTINGS_MODULE = 'websettings.tests.settingstore'
from django.test.utils import get_runner
test_runner = get_runner(global_settings)
test_runner = test_runner()
failures = test_runner.run_tests(['websettings'])
sys.exit(failures) | hirokiky/django-websettings | [
7,
2,
7,
1,
1373117552
] |
def get_long_description():
readme_md = os.path.join(base_path, "README.md")
with open(readme_md) as f:
return f.read() | Anorov/cloudflare-scrape | [
3023,
444,
3023,
123,
1362095093
] |
def rand7():
return 0 | algorhythms/LeetCode | [
823,
267,
823,
3,
1403872362
] |
def createController():
"""Initialize controller."""
config = ctrlr.Config("deltaelektronika", "SM-700")
if not config.nodes:
config.nodes, config.names = ([1], ["SM700"])
if config.virtual:
driver = virtual.VirtualInstrument()
iface = ctrlr.virtualInstrumentController(config, driver)
else:
driver = delta.Sm700Series(drv.Serial(config.port))
iface = ctrlr.Controller(config, driver)
iface.addCommand(driver.source.voltage, "Voltage", poll=True, log=True)
iface.addCommand(driver.source.current, "Current", poll=True, log=True)
iface.populate()
return iface | Synss/pyhard2 | [
1,
2,
1,
4,
1379162937
] |
def __init__(self, network_interface: str):
self._your: Dict[str, Union[None, str]] = \
self._base.get_interface_settings(interface_name=network_interface,
required_parameters=['mac-address', 'ipv4-address',
'first-ipv4-address', 'last-ipv4-address'])
self.local_network: str = \
self._your['first-ipv4-address'] + '-' + \
self._your['last-ipv4-address'].split('.')[3]
if self._base.get_platform().startswith('Darwin'):
self._nmap_scan_result: str = '/tmp/nmap_scan.xml'
else:
self._nmap_scan_result: str = join(gettempdir(), 'nmap_scan.xml') | Vladimir-Ivanov-Git/raw-packet | [
201,
44,
201,
10,
1495112728
] |
def scan(self,
exit_on_failure: bool = True,
quiet: bool = False) -> Union[None, List[NamedTuple]]:
try:
# region Variables
network_devices: List[NamedTuple] = list()
ipv4_address: str = ''
mac_address: str = ''
vendor: str = ''
os: str = ''
ports: List[int] = list()
# endregion
nmap_command: str = 'nmap ' + self.local_network + \
' --open -n -O --osscan-guess -T5 -oX ' + self._nmap_scan_result
if not quiet:
self._base.print_info('Start nmap scan: ', nmap_command)
if self._base.get_platform().startswith('Windows'):
nmap_process = sub.Popen(nmap_command, shell=True, stdout=sub.PIPE, stderr=sub.STDOUT)
else:
nmap_process = sub.Popen([nmap_command], shell=True, stdout=sub.PIPE, stderr=sub.STDOUT)
nmap_process.wait()
assert isfile(self._nmap_scan_result), \
'Not found nmap scan result file: ' + self._base.error_text(self._nmap_scan_result)
nmap_report = ET.parse(self._nmap_scan_result)
root_tree = nmap_report.getroot()
for element in root_tree:
try:
assert element.tag == 'host'
state = element.find('status').attrib['state']
assert state == 'up'
# region Address
for address in element.findall('address'):
if address.attrib['addrtype'] == 'ipv4':
ipv4_address = address.attrib['addr']
if address.attrib['addrtype'] == 'mac':
mac_address = address.attrib['addr'].lower()
try:
vendor = address.attrib['vendor']
except KeyError:
pass
# endregion
# region Open TCP ports
for ports_info in element.find('ports'):
if ports_info.tag == 'port':
ports.append(ports_info.attrib['portid'])
# endregion
# region OS
for os_info in element.find('os'):
if os_info.tag == 'osmatch':
try:
os = os_info.attrib['name']
except TypeError:
pass
break
# endregion
network_devices.append(self.Info(vendor=vendor, os=os, mac_address=mac_address,
ipv4_address=ipv4_address, ports=ports))
except AssertionError:
pass
remove(self._nmap_scan_result)
assert len(network_devices) != 0, \
'Could not find any devices on interface: ' + self._base.error_text(self._your['network-interface'])
return network_devices
except OSError:
self._base.print_error('Something went wrong while trying to run ', 'nmap')
if exit_on_failure:
exit(2)
except KeyboardInterrupt:
self._base.print_info('Exit')
exit(0)
except AssertionError as Error:
self._base.print_error(Error.args[0])
if exit_on_failure:
exit(1)
return None | Vladimir-Ivanov-Git/raw-packet | [
201,
44,
201,
10,
1495112728
] |
def __init__(self, _object):
# the object
self._object = auxiliary.get_valid_dag_node(_object)
assert isinstance(self._object, pm.nodetypes.Transform)
# the data
self._futurePivot = pm.nodetypes.Transform
self._isSetup = False
# read the settings
self._read_settings() | eoyilmaz/anima | [
119,
27,
119,
3,
1392807749
] |
def _save_settings(self):
"""save settings inside objects pivotData attribute"""
# data to be save :
# -----------------
# futurePivot node
# create attributes
self._create_data_attribute()
# connect futurePivot node
pm.connectAttr(
"%s%s" % (self._futurePivot.name(), ".message"),
self._object.attr("pivotData.futurePivot"),
f=True,
) | eoyilmaz/anima | [
119,
27,
119,
3,
1392807749
] |
def _create_future_pivot(self):
"""creates the futurePivot locator"""
if self._isSetup:
return
# create a locator and move it to the current pivot
# parent the locator under the object
locator_name = self._object.name() + "_futurePivotLocator#"
self._futurePivot = auxiliary.get_valid_dag_node(
pm.spaceLocator(n=locator_name)
)
pm.parent(self._futurePivot, self._object)
current_pivot_pos = pm.xform(self._object, q=True, ws=True, piv=True)
pm.xform(self._futurePivot, ws=True, t=current_pivot_pos[0:3])
# change the color
self._futurePivot.setAttr("overrideEnabled", 1)
self._futurePivot.setAttr("overrideColor", 13)
# set translate and visibility to non-keyable
self._futurePivot.setAttr("tx", k=False, channelBox=True)
self._futurePivot.setAttr("ty", k=False, channelBox=True)
self._futurePivot.setAttr("tz", k=False, channelBox=True)
self._futurePivot.setAttr("v", k=False, channelBox=True)
# lock scale and rotate
self._futurePivot.setAttr("rx", lock=True, k=False, channelBox=False)
self._futurePivot.setAttr("ry", lock=True, k=False, channelBox=False)
self._futurePivot.setAttr("rz", lock=True, k=False, channelBox=False)
self._futurePivot.setAttr("sx", lock=True, k=False, channelBox=False)
self._futurePivot.setAttr("sy", lock=True, k=False, channelBox=False)
self._futurePivot.setAttr("sz", lock=True, k=False, channelBox=False)
# hide it
self._futurePivot.setAttr("v", 0) | eoyilmaz/anima | [
119,
27,
119,
3,
1392807749
] |
def toggle(self):
"""toggles pivot visibility"""
if not self._isSetup:
return
# toggle the pivot visibility
current_vis = self._futurePivot.getAttr("v")
current_vis = (current_vis + 1) % 2
self._futurePivot.setAttr("v", current_vis) | eoyilmaz/anima | [
119,
27,
119,
3,
1392807749
] |
def _set_dg_dirty(self):
"""sets the DG to dirty for _object, currentPivot and futurePivot"""
pm.dgdirty(self._object, self._futurePivot) | eoyilmaz/anima | [
119,
27,
119,
3,
1392807749
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.