repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tchellomello/python-amcrest | src/amcrest/http.py | Http._set_name | def _set_name(self):
"""Set device name."""
try:
self._name = pretty(self.machine_name)
self._serial = self.serial_number
except AttributeError:
self._name = None
self._serial = None | python | def _set_name(self):
"""Set device name."""
try:
self._name = pretty(self.machine_name)
self._serial = self.serial_number
except AttributeError:
self._name = None
self._serial = None | [
"def",
"_set_name",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_name",
"=",
"pretty",
"(",
"self",
".",
"machine_name",
")",
"self",
".",
"_serial",
"=",
"self",
".",
"serial_number",
"except",
"AttributeError",
":",
"self",
".",
"_name",
"=",
"N... | Set device name. | [
"Set",
"device",
"name",
"."
] | ed842139e234de2eaf6ee8fb480214711cde1249 | https://github.com/tchellomello/python-amcrest/blob/ed842139e234de2eaf6ee8fb480214711cde1249/src/amcrest/http.py#L101-L108 | train |
tchellomello/python-amcrest | src/amcrest/utils.py | to_unit | def to_unit(value, unit='B'):
"""Convert bytes to give unit."""
byte_array = ['B', 'KB', 'MB', 'GB', 'TB']
if not isinstance(value, (int, float)):
value = float(value)
if unit in byte_array:
result = value / 1024**byte_array.index(unit)
return round(result, PRECISION), unit
... | python | def to_unit(value, unit='B'):
"""Convert bytes to give unit."""
byte_array = ['B', 'KB', 'MB', 'GB', 'TB']
if not isinstance(value, (int, float)):
value = float(value)
if unit in byte_array:
result = value / 1024**byte_array.index(unit)
return round(result, PRECISION), unit
... | [
"def",
"to_unit",
"(",
"value",
",",
"unit",
"=",
"'B'",
")",
":",
"byte_array",
"=",
"[",
"'B'",
",",
"'KB'",
",",
"'MB'",
",",
"'GB'",
",",
"'TB'",
"]",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"v... | Convert bytes to give unit. | [
"Convert",
"bytes",
"to",
"give",
"unit",
"."
] | ed842139e234de2eaf6ee8fb480214711cde1249 | https://github.com/tchellomello/python-amcrest/blob/ed842139e234de2eaf6ee8fb480214711cde1249/src/amcrest/utils.py#L57-L68 | train |
tchellomello/python-amcrest | src/amcrest/special.py | Special.realtime_stream | def realtime_stream(self, channel=1, typeno=0, path_file=None):
"""
If the stream is redirect to a file, use mplayer tool to
visualize the video record
camera.realtime_stream(path_file="/home/user/Desktop/myvideo)
$ mplayer /home/user/Desktop/myvideo
"""
ret = se... | python | def realtime_stream(self, channel=1, typeno=0, path_file=None):
"""
If the stream is redirect to a file, use mplayer tool to
visualize the video record
camera.realtime_stream(path_file="/home/user/Desktop/myvideo)
$ mplayer /home/user/Desktop/myvideo
"""
ret = se... | [
"def",
"realtime_stream",
"(",
"self",
",",
"channel",
"=",
"1",
",",
"typeno",
"=",
"0",
",",
"path_file",
"=",
"None",
")",
":",
"ret",
"=",
"self",
".",
"command",
"(",
"'realmonitor.cgi?action=getStream&channel={0}&subtype={1}'",
".",
"format",
"(",
"chann... | If the stream is redirect to a file, use mplayer tool to
visualize the video record
camera.realtime_stream(path_file="/home/user/Desktop/myvideo)
$ mplayer /home/user/Desktop/myvideo | [
"If",
"the",
"stream",
"is",
"redirect",
"to",
"a",
"file",
"use",
"mplayer",
"tool",
"to",
"visualize",
"the",
"video",
"record"
] | ed842139e234de2eaf6ee8fb480214711cde1249 | https://github.com/tchellomello/python-amcrest/blob/ed842139e234de2eaf6ee8fb480214711cde1249/src/amcrest/special.py#L20-L37 | train |
tchellomello/python-amcrest | src/amcrest/special.py | Special.rtsp_url | def rtsp_url(self, channelno=None, typeno=None):
"""
Return RTSP streaming url
Params:
channelno: integer, the video channel index which starts from 1,
default 1 if not specified.
typeno: the stream type, default 0 if not specified. It can be
... | python | def rtsp_url(self, channelno=None, typeno=None):
"""
Return RTSP streaming url
Params:
channelno: integer, the video channel index which starts from 1,
default 1 if not specified.
typeno: the stream type, default 0 if not specified. It can be
... | [
"def",
"rtsp_url",
"(",
"self",
",",
"channelno",
"=",
"None",
",",
"typeno",
"=",
"None",
")",
":",
"if",
"channelno",
"is",
"None",
":",
"channelno",
"=",
"1",
"if",
"typeno",
"is",
"None",
":",
"typeno",
"=",
"0",
"cmd",
"=",
"'cam/realmonitor?chann... | Return RTSP streaming url
Params:
channelno: integer, the video channel index which starts from 1,
default 1 if not specified.
typeno: the stream type, default 0 if not specified. It can be
the following value:
0-Main Stre... | [
"Return",
"RTSP",
"streaming",
"url"
] | ed842139e234de2eaf6ee8fb480214711cde1249 | https://github.com/tchellomello/python-amcrest/blob/ed842139e234de2eaf6ee8fb480214711cde1249/src/amcrest/special.py#L39-L69 | train |
tchellomello/python-amcrest | src/amcrest/special.py | Special.mjpeg_url | def mjpeg_url(self, channelno=None, typeno=None):
"""
Return MJPEG streaming url
Params:
channelno: integer, the video channel index which starts from 1,
default 1 if not specified.
typeno: the stream type, default 0 if not specified. It can be
... | python | def mjpeg_url(self, channelno=None, typeno=None):
"""
Return MJPEG streaming url
Params:
channelno: integer, the video channel index which starts from 1,
default 1 if not specified.
typeno: the stream type, default 0 if not specified. It can be
... | [
"def",
"mjpeg_url",
"(",
"self",
",",
"channelno",
"=",
"None",
",",
"typeno",
"=",
"None",
")",
":",
"if",
"channelno",
"is",
"None",
":",
"channelno",
"=",
"0",
"if",
"typeno",
"is",
"None",
":",
"typeno",
"=",
"1",
"cmd",
"=",
"\"mjpg/video.cgi?chan... | Return MJPEG streaming url
Params:
channelno: integer, the video channel index which starts from 1,
default 1 if not specified.
typeno: the stream type, default 0 if not specified. It can be
the following value:
0-Main Str... | [
"Return",
"MJPEG",
"streaming",
"url"
] | ed842139e234de2eaf6ee8fb480214711cde1249 | https://github.com/tchellomello/python-amcrest/blob/ed842139e234de2eaf6ee8fb480214711cde1249/src/amcrest/special.py#L95-L118 | train |
tchellomello/python-amcrest | src/amcrest/network.py | Network.scan_devices | def scan_devices(self, subnet, timeout=None):
"""
Scan cameras in a range of ips
Params:
subnet - subnet, i.e: 192.168.1.0/24
if mask not used, assuming mask 24
timeout_sec - timeout in sec
Returns:
"""
# Maximum range from mask
... | python | def scan_devices(self, subnet, timeout=None):
"""
Scan cameras in a range of ips
Params:
subnet - subnet, i.e: 192.168.1.0/24
if mask not used, assuming mask 24
timeout_sec - timeout in sec
Returns:
"""
# Maximum range from mask
... | [
"def",
"scan_devices",
"(",
"self",
",",
"subnet",
",",
"timeout",
"=",
"None",
")",
":",
"# Maximum range from mask",
"# Format is mask: max_range",
"max_range",
"=",
"{",
"16",
":",
"256",
",",
"24",
":",
"256",
",",
"25",
":",
"128",
",",
"27",
":",
"... | Scan cameras in a range of ips
Params:
subnet - subnet, i.e: 192.168.1.0/24
if mask not used, assuming mask 24
timeout_sec - timeout in sec
Returns: | [
"Scan",
"cameras",
"in",
"a",
"range",
"of",
"ips"
] | ed842139e234de2eaf6ee8fb480214711cde1249 | https://github.com/tchellomello/python-amcrest/blob/ed842139e234de2eaf6ee8fb480214711cde1249/src/amcrest/network.py#L41-L109 | train |
peerplays-network/python-peerplays | peerplays/peerplays.py | PeerPlays.disallow | def disallow(
self, foreign, permission="active", account=None, threshold=None, **kwargs
):
""" Remove additional access to an account by some other public
key or account.
:param str foreign: The foreign account that will obtain access
:param str permission: (opt... | python | def disallow(
self, foreign, permission="active", account=None, threshold=None, **kwargs
):
""" Remove additional access to an account by some other public
key or account.
:param str foreign: The foreign account that will obtain access
:param str permission: (opt... | [
"def",
"disallow",
"(",
"self",
",",
"foreign",
",",
"permission",
"=",
"\"active\"",
",",
"account",
"=",
"None",
",",
"threshold",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"account",
":",
"if",
"\"default_account\"",
"in",
"self",
... | Remove additional access to an account by some other public
key or account.
:param str foreign: The foreign account that will obtain access
:param str permission: (optional) The actual permission to
modify (defaults to ``active``)
:param str account: (opt... | [
"Remove",
"additional",
"access",
"to",
"an",
"account",
"by",
"some",
"other",
"public",
"key",
"or",
"account",
"."
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/peerplays.py#L439-L520 | train |
peerplays-network/python-peerplays | peerplays/peerplays.py | PeerPlays.approvewitness | def approvewitness(self, witnesses, account=None, **kwargs):
""" Approve a witness
:param list witnesses: list of Witness name or id
:param str account: (optional) the account to allow access
to (defaults to ``default_account``)
"""
if not account:
... | python | def approvewitness(self, witnesses, account=None, **kwargs):
""" Approve a witness
:param list witnesses: list of Witness name or id
:param str account: (optional) the account to allow access
to (defaults to ``default_account``)
"""
if not account:
... | [
"def",
"approvewitness",
"(",
"self",
",",
"witnesses",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"account",
":",
"if",
"\"default_account\"",
"in",
"self",
".",
"config",
":",
"account",
"=",
"self",
".",
"config",
"... | Approve a witness
:param list witnesses: list of Witness name or id
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | [
"Approve",
"a",
"witness"
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/peerplays.py#L556-L592 | train |
peerplays-network/python-peerplays | peerplays/peerplays.py | PeerPlays.approvecommittee | def approvecommittee(self, committees, account=None, **kwargs):
""" Approve a committee
:param list committees: list of committee member name or id
:param str account: (optional) the account to allow access
to (defaults to ``default_account``)
"""
if not ... | python | def approvecommittee(self, committees, account=None, **kwargs):
""" Approve a committee
:param list committees: list of committee member name or id
:param str account: (optional) the account to allow access
to (defaults to ``default_account``)
"""
if not ... | [
"def",
"approvecommittee",
"(",
"self",
",",
"committees",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"account",
":",
"if",
"\"default_account\"",
"in",
"self",
".",
"config",
":",
"account",
"=",
"self",
".",
"config",
... | Approve a committee
:param list committees: list of committee member name or id
:param str account: (optional) the account to allow access
to (defaults to ``default_account``) | [
"Approve",
"a",
"committee"
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/peerplays.py#L633-L669 | train |
peerplays-network/python-peerplays | peerplays/peerplays.py | PeerPlays.betting_market_rules_create | def betting_market_rules_create(self, names, descriptions, account=None, **kwargs):
""" Create betting market rules
:param list names: Internationalized names, e.g. ``[['de', 'Foo'],
['en', 'bar']]``
:param list descriptions: Internationalized descriptions, e.g.
... | python | def betting_market_rules_create(self, names, descriptions, account=None, **kwargs):
""" Create betting market rules
:param list names: Internationalized names, e.g. ``[['de', 'Foo'],
['en', 'bar']]``
:param list descriptions: Internationalized descriptions, e.g.
... | [
"def",
"betting_market_rules_create",
"(",
"self",
",",
"names",
",",
"descriptions",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"names",
",",
"list",
")",
"assert",
"isinstance",
"(",
"descriptions",
",",
... | Create betting market rules
:param list names: Internationalized names, e.g. ``[['de', 'Foo'],
['en', 'bar']]``
:param list descriptions: Internationalized descriptions, e.g.
``[['de', 'Foo'], ['en', 'bar']]``
:param str account: (optional) the accoun... | [
"Create",
"betting",
"market",
"rules"
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/peerplays.py#L1149-L1176 | train |
peerplays-network/python-peerplays | peerplays/peerplays.py | PeerPlays.betting_market_rules_update | def betting_market_rules_update(
self, rules_id, names, descriptions, account=None, **kwargs
):
""" Update betting market rules
:param str rules_id: Id of the betting market rules to update
:param list names: Internationalized names, e.g. ``[['de', 'Foo'],
['... | python | def betting_market_rules_update(
self, rules_id, names, descriptions, account=None, **kwargs
):
""" Update betting market rules
:param str rules_id: Id of the betting market rules to update
:param list names: Internationalized names, e.g. ``[['de', 'Foo'],
['... | [
"def",
"betting_market_rules_update",
"(",
"self",
",",
"rules_id",
",",
"names",
",",
"descriptions",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"names",
",",
"list",
")",
"assert",
"isinstance",
"(",
"des... | Update betting market rules
:param str rules_id: Id of the betting market rules to update
:param list names: Internationalized names, e.g. ``[['de', 'Foo'],
['en', 'bar']]``
:param list descriptions: Internationalized descriptions, e.g.
``[['de', 'Foo... | [
"Update",
"betting",
"market",
"rules"
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/peerplays.py#L1178-L1210 | train |
peerplays-network/python-peerplays | peerplays/peerplays.py | PeerPlays.bet_place | def bet_place(
self,
betting_market_id,
amount_to_bet,
backer_multiplier,
back_or_lay,
account=None,
**kwargs
):
""" Place a bet
:param str betting_market_id: The identifier for the market to bet
in
:param peerp... | python | def bet_place(
self,
betting_market_id,
amount_to_bet,
backer_multiplier,
back_or_lay,
account=None,
**kwargs
):
""" Place a bet
:param str betting_market_id: The identifier for the market to bet
in
:param peerp... | [
"def",
"bet_place",
"(",
"self",
",",
"betting_market_id",
",",
"amount_to_bet",
",",
"backer_multiplier",
",",
"back_or_lay",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"import",
"GRAPHENE_BETTING_ODDS_PRECISION",
"assert",
"is... | Place a bet
:param str betting_market_id: The identifier for the market to bet
in
:param peerplays.amount.Amount amount_to_bet: Amount to bet with
:param int backer_multiplier: Multipler for backer
:param str back_or_lay: "back" or "lay" the bet
... | [
"Place",
"a",
"bet"
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/peerplays.py#L1488-L1531 | train |
peerplays-network/python-peerplays | peerplays/peerplays.py | PeerPlays.bet_cancel | def bet_cancel(self, bet_to_cancel, account=None, **kwargs):
""" Cancel a bet
:param str bet_to_cancel: The identifier that identifies the bet to
cancel
:param str account: (optional) the account that owns the bet
(defaults to ``default_account``)
... | python | def bet_cancel(self, bet_to_cancel, account=None, **kwargs):
""" Cancel a bet
:param str bet_to_cancel: The identifier that identifies the bet to
cancel
:param str account: (optional) the account that owns the bet
(defaults to ``default_account``)
... | [
"def",
"bet_cancel",
"(",
"self",
",",
"bet_to_cancel",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"account",
":",
"if",
"\"default_account\"",
"in",
"self",
".",
"config",
":",
"account",
"=",
"self",
".",
"config",
"... | Cancel a bet
:param str bet_to_cancel: The identifier that identifies the bet to
cancel
:param str account: (optional) the account that owns the bet
(defaults to ``default_account``) | [
"Cancel",
"a",
"bet"
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/peerplays.py#L1533-L1556 | train |
peerplays-network/python-peerplays | peerplays/cli/decorators.py | verbose | def verbose(f):
""" Add verbose flags and add logging handlers
"""
@click.pass_context
def new_func(ctx, *args, **kwargs):
global log
verbosity = ["critical", "error", "warn", "info", "debug"][
int(min(ctx.obj.get("verbose", 0), 4))
]
log.setLevel(getattr(log... | python | def verbose(f):
""" Add verbose flags and add logging handlers
"""
@click.pass_context
def new_func(ctx, *args, **kwargs):
global log
verbosity = ["critical", "error", "warn", "info", "debug"][
int(min(ctx.obj.get("verbose", 0), 4))
]
log.setLevel(getattr(log... | [
"def",
"verbose",
"(",
"f",
")",
":",
"@",
"click",
".",
"pass_context",
"def",
"new_func",
"(",
"ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"log",
"verbosity",
"=",
"[",
"\"critical\"",
",",
"\"error\"",
",",
"\"warn\"",
",... | Add verbose flags and add logging handlers | [
"Add",
"verbose",
"flags",
"and",
"add",
"logging",
"handlers"
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/cli/decorators.py#L13-L51 | train |
peerplays-network/python-peerplays | peerplays/cli/decorators.py | offline | def offline(f):
""" This decorator allows you to access ``ctx.peerplays`` which is
an instance of PeerPlays with ``offline=True``.
"""
@click.pass_context
@verbose
def new_func(ctx, *args, **kwargs):
ctx.obj["offline"] = True
ctx.peerplays = PeerPlays(**ctx.obj)
ctx.... | python | def offline(f):
""" This decorator allows you to access ``ctx.peerplays`` which is
an instance of PeerPlays with ``offline=True``.
"""
@click.pass_context
@verbose
def new_func(ctx, *args, **kwargs):
ctx.obj["offline"] = True
ctx.peerplays = PeerPlays(**ctx.obj)
ctx.... | [
"def",
"offline",
"(",
"f",
")",
":",
"@",
"click",
".",
"pass_context",
"@",
"verbose",
"def",
"new_func",
"(",
"ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
".",
"obj",
"[",
"\"offline\"",
"]",
"=",
"True",
"ctx",
".",
"pee... | This decorator allows you to access ``ctx.peerplays`` which is
an instance of PeerPlays with ``offline=True``. | [
"This",
"decorator",
"allows",
"you",
"to",
"access",
"ctx",
".",
"peerplays",
"which",
"is",
"an",
"instance",
"of",
"PeerPlays",
"with",
"offline",
"=",
"True",
"."
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/cli/decorators.py#L54-L68 | train |
peerplays-network/python-peerplays | peerplays/cli/decorators.py | configfile | def configfile(f):
""" This decorator will parse a configuration file in YAML format
and store the dictionary in ``ctx.blockchain.config``
"""
@click.pass_context
def new_func(ctx, *args, **kwargs):
ctx.config = yaml.load(open(ctx.obj["configfile"]))
return ctx.invoke(f, *args, ... | python | def configfile(f):
""" This decorator will parse a configuration file in YAML format
and store the dictionary in ``ctx.blockchain.config``
"""
@click.pass_context
def new_func(ctx, *args, **kwargs):
ctx.config = yaml.load(open(ctx.obj["configfile"]))
return ctx.invoke(f, *args, ... | [
"def",
"configfile",
"(",
"f",
")",
":",
"@",
"click",
".",
"pass_context",
"def",
"new_func",
"(",
"ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
".",
"config",
"=",
"yaml",
".",
"load",
"(",
"open",
"(",
"ctx",
".",
"obj",
... | This decorator will parse a configuration file in YAML format
and store the dictionary in ``ctx.blockchain.config`` | [
"This",
"decorator",
"will",
"parse",
"a",
"configuration",
"file",
"in",
"YAML",
"format",
"and",
"store",
"the",
"dictionary",
"in",
"ctx",
".",
"blockchain",
".",
"config"
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/cli/decorators.py#L154-L164 | train |
peerplays-network/python-peerplays | peerplaysapi/websocket.py | PeerPlaysWebsocket.on_message | def on_message(self, ws, reply, *args):
""" This method is called by the websocket connection on every
message that is received. If we receive a ``notice``, we
hand over post-processing and signalling of events to
``process_notice``.
"""
log.debug("Received me... | python | def on_message(self, ws, reply, *args):
""" This method is called by the websocket connection on every
message that is received. If we receive a ``notice``, we
hand over post-processing and signalling of events to
``process_notice``.
"""
log.debug("Received me... | [
"def",
"on_message",
"(",
"self",
",",
"ws",
",",
"reply",
",",
"*",
"args",
")",
":",
"log",
".",
"debug",
"(",
"\"Received message: %s\"",
"%",
"str",
"(",
"reply",
")",
")",
"data",
"=",
"{",
"}",
"try",
":",
"data",
"=",
"json",
".",
"loads",
... | This method is called by the websocket connection on every
message that is received. If we receive a ``notice``, we
hand over post-processing and signalling of events to
``process_notice``. | [
"This",
"method",
"is",
"called",
"by",
"the",
"websocket",
"connection",
"on",
"every",
"message",
"that",
"is",
"received",
".",
"If",
"we",
"receive",
"a",
"notice",
"we",
"hand",
"over",
"post",
"-",
"processing",
"and",
"signalling",
"of",
"events",
"... | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplaysapi/websocket.py#L216-L263 | train |
peerplays-network/python-peerplays | peerplaysapi/websocket.py | PeerPlaysWebsocket.on_close | def on_close(self, ws):
""" Called when websocket connection is closed
"""
log.debug("Closing WebSocket connection with {}".format(self.url))
if self.keepalive and self.keepalive.is_alive():
self.keepalive.do_run = False
self.keepalive.join() | python | def on_close(self, ws):
""" Called when websocket connection is closed
"""
log.debug("Closing WebSocket connection with {}".format(self.url))
if self.keepalive and self.keepalive.is_alive():
self.keepalive.do_run = False
self.keepalive.join() | [
"def",
"on_close",
"(",
"self",
",",
"ws",
")",
":",
"log",
".",
"debug",
"(",
"\"Closing WebSocket connection with {}\"",
".",
"format",
"(",
"self",
".",
"url",
")",
")",
"if",
"self",
".",
"keepalive",
"and",
"self",
".",
"keepalive",
".",
"is_alive",
... | Called when websocket connection is closed | [
"Called",
"when",
"websocket",
"connection",
"is",
"closed"
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplaysapi/websocket.py#L270-L276 | train |
peerplays-network/python-peerplays | peerplaysapi/websocket.py | PeerPlaysWebsocket.run_forever | def run_forever(self):
""" This method is used to run the websocket app continuously.
It will execute callbacks as defined and try to stay
connected with the provided APIs
"""
cnt = 0
while True:
cnt += 1
self.url = next(self.urls)
... | python | def run_forever(self):
""" This method is used to run the websocket app continuously.
It will execute callbacks as defined and try to stay
connected with the provided APIs
"""
cnt = 0
while True:
cnt += 1
self.url = next(self.urls)
... | [
"def",
"run_forever",
"(",
"self",
")",
":",
"cnt",
"=",
"0",
"while",
"True",
":",
"cnt",
"+=",
"1",
"self",
".",
"url",
"=",
"next",
"(",
"self",
".",
"urls",
")",
"log",
".",
"debug",
"(",
"\"Trying to connect to node %s\"",
"%",
"self",
".",
"url... | This method is used to run the websocket app continuously.
It will execute callbacks as defined and try to stay
connected with the provided APIs | [
"This",
"method",
"is",
"used",
"to",
"run",
"the",
"websocket",
"app",
"continuously",
".",
"It",
"will",
"execute",
"callbacks",
"as",
"defined",
"and",
"try",
"to",
"stay",
"connected",
"with",
"the",
"provided",
"APIs"
] | 188f04238e7e21d5f73e9b01099eea44289ef6b7 | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplaysapi/websocket.py#L278-L317 | train |
Zsailer/pandas_flavor | pandas_flavor/register.py | register_dataframe_method | def register_dataframe_method(method):
"""Register a function as a method attached to the Pandas DataFrame.
Example
-------
.. code-block:: python
@register_dataframe_method
def print_column(df, col):
'''Print the dataframe column given'''
print(df[col])
""... | python | def register_dataframe_method(method):
"""Register a function as a method attached to the Pandas DataFrame.
Example
-------
.. code-block:: python
@register_dataframe_method
def print_column(df, col):
'''Print the dataframe column given'''
print(df[col])
""... | [
"def",
"register_dataframe_method",
"(",
"method",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"AccessorMethod",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"pandas_obj",
")",
":",
"self",
"... | Register a function as a method attached to the Pandas DataFrame.
Example
-------
.. code-block:: python
@register_dataframe_method
def print_column(df, col):
'''Print the dataframe column given'''
print(df[col]) | [
"Register",
"a",
"function",
"as",
"a",
"method",
"attached",
"to",
"the",
"Pandas",
"DataFrame",
"."
] | 1953aeee09424300d69a11dd2ffd3460a806fb65 | https://github.com/Zsailer/pandas_flavor/blob/1953aeee09424300d69a11dd2ffd3460a806fb65/pandas_flavor/register.py#L6-L35 | train |
Zsailer/pandas_flavor | pandas_flavor/register.py | register_series_method | def register_series_method(method):
"""Register a function as a method attached to the Pandas Series.
"""
def inner(*args, **kwargs):
class AccessorMethod(object):
__doc__ = method.__doc__
def __init__(self, pandas_obj):
self._obj = pandas_obj
@... | python | def register_series_method(method):
"""Register a function as a method attached to the Pandas Series.
"""
def inner(*args, **kwargs):
class AccessorMethod(object):
__doc__ = method.__doc__
def __init__(self, pandas_obj):
self._obj = pandas_obj
@... | [
"def",
"register_series_method",
"(",
"method",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"AccessorMethod",
"(",
"object",
")",
":",
"__doc__",
"=",
"method",
".",
"__doc__",
"def",
"__init__",
"(",
"self",
... | Register a function as a method attached to the Pandas Series. | [
"Register",
"a",
"function",
"as",
"a",
"method",
"attached",
"to",
"the",
"Pandas",
"Series",
"."
] | 1953aeee09424300d69a11dd2ffd3460a806fb65 | https://github.com/Zsailer/pandas_flavor/blob/1953aeee09424300d69a11dd2ffd3460a806fb65/pandas_flavor/register.py#L38-L57 | train |
pinax/pinax-invitations | pinax/invitations/models.py | InvitationStat.add_invites_to_user | def add_invites_to_user(cls, user, amount):
"""
Add the specified number of invites to current allocated total.
"""
stat, _ = InvitationStat.objects.get_or_create(user=user)
if stat.invites_allocated != -1:
stat.invites_allocated += amount
stat.save() | python | def add_invites_to_user(cls, user, amount):
"""
Add the specified number of invites to current allocated total.
"""
stat, _ = InvitationStat.objects.get_or_create(user=user)
if stat.invites_allocated != -1:
stat.invites_allocated += amount
stat.save() | [
"def",
"add_invites_to_user",
"(",
"cls",
",",
"user",
",",
"amount",
")",
":",
"stat",
",",
"_",
"=",
"InvitationStat",
".",
"objects",
".",
"get_or_create",
"(",
"user",
"=",
"user",
")",
"if",
"stat",
".",
"invites_allocated",
"!=",
"-",
"1",
":",
"... | Add the specified number of invites to current allocated total. | [
"Add",
"the",
"specified",
"number",
"of",
"invites",
"to",
"current",
"allocated",
"total",
"."
] | 6c6e863da179a1c620074efe5b5728cd1e6eff1b | https://github.com/pinax/pinax-invitations/blob/6c6e863da179a1c620074efe5b5728cd1e6eff1b/pinax/invitations/models.py#L111-L118 | train |
pinax/pinax-invitations | pinax/invitations/models.py | InvitationStat.add_invites | def add_invites(cls, amount):
"""
Add invites for all users.
"""
for user in get_user_model().objects.all():
cls.add_invites_to_user(user, amount) | python | def add_invites(cls, amount):
"""
Add invites for all users.
"""
for user in get_user_model().objects.all():
cls.add_invites_to_user(user, amount) | [
"def",
"add_invites",
"(",
"cls",
",",
"amount",
")",
":",
"for",
"user",
"in",
"get_user_model",
"(",
")",
".",
"objects",
".",
"all",
"(",
")",
":",
"cls",
".",
"add_invites_to_user",
"(",
"user",
",",
"amount",
")"
] | Add invites for all users. | [
"Add",
"invites",
"for",
"all",
"users",
"."
] | 6c6e863da179a1c620074efe5b5728cd1e6eff1b | https://github.com/pinax/pinax-invitations/blob/6c6e863da179a1c620074efe5b5728cd1e6eff1b/pinax/invitations/models.py#L121-L126 | train |
pinax/pinax-invitations | pinax/invitations/models.py | InvitationStat.topoff_user | def topoff_user(cls, user, amount):
"""
Ensure user has a minimum number of invites.
"""
stat, _ = cls.objects.get_or_create(user=user)
remaining = stat.invites_remaining()
if remaining != -1 and remaining < amount:
stat.invites_allocated += (amount - remainin... | python | def topoff_user(cls, user, amount):
"""
Ensure user has a minimum number of invites.
"""
stat, _ = cls.objects.get_or_create(user=user)
remaining = stat.invites_remaining()
if remaining != -1 and remaining < amount:
stat.invites_allocated += (amount - remainin... | [
"def",
"topoff_user",
"(",
"cls",
",",
"user",
",",
"amount",
")",
":",
"stat",
",",
"_",
"=",
"cls",
".",
"objects",
".",
"get_or_create",
"(",
"user",
"=",
"user",
")",
"remaining",
"=",
"stat",
".",
"invites_remaining",
"(",
")",
"if",
"remaining",
... | Ensure user has a minimum number of invites. | [
"Ensure",
"user",
"has",
"a",
"minimum",
"number",
"of",
"invites",
"."
] | 6c6e863da179a1c620074efe5b5728cd1e6eff1b | https://github.com/pinax/pinax-invitations/blob/6c6e863da179a1c620074efe5b5728cd1e6eff1b/pinax/invitations/models.py#L129-L137 | train |
pinax/pinax-invitations | pinax/invitations/models.py | InvitationStat.topoff | def topoff(cls, amount):
"""
Ensure all users have a minimum number of invites.
"""
for user in get_user_model().objects.all():
cls.topoff_user(user, amount) | python | def topoff(cls, amount):
"""
Ensure all users have a minimum number of invites.
"""
for user in get_user_model().objects.all():
cls.topoff_user(user, amount) | [
"def",
"topoff",
"(",
"cls",
",",
"amount",
")",
":",
"for",
"user",
"in",
"get_user_model",
"(",
")",
".",
"objects",
".",
"all",
"(",
")",
":",
"cls",
".",
"topoff_user",
"(",
"user",
",",
"amount",
")"
] | Ensure all users have a minimum number of invites. | [
"Ensure",
"all",
"users",
"have",
"a",
"minimum",
"number",
"of",
"invites",
"."
] | 6c6e863da179a1c620074efe5b5728cd1e6eff1b | https://github.com/pinax/pinax-invitations/blob/6c6e863da179a1c620074efe5b5728cd1e6eff1b/pinax/invitations/models.py#L140-L145 | train |
skelsec/minidump | minidump/minidumpreader.py | MinidumpBufferedReader.align | def align(self, alignment = None):
"""
Repositions the current reader to match architecture alignment
"""
if alignment is None:
if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64:
alignment = 8
else:
alignment = 4
offset = self.current_position % alignment
if offset =... | python | def align(self, alignment = None):
"""
Repositions the current reader to match architecture alignment
"""
if alignment is None:
if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64:
alignment = 8
else:
alignment = 4
offset = self.current_position % alignment
if offset =... | [
"def",
"align",
"(",
"self",
",",
"alignment",
"=",
"None",
")",
":",
"if",
"alignment",
"is",
"None",
":",
"if",
"self",
".",
"reader",
".",
"sysinfo",
".",
"ProcessorArchitecture",
"==",
"PROCESSOR_ARCHITECTURE",
".",
"AMD64",
":",
"alignment",
"=",
"8",... | Repositions the current reader to match architecture alignment | [
"Repositions",
"the",
"current",
"reader",
"to",
"match",
"architecture",
"alignment"
] | 0c4dcabe6f11d7a403440919ffa9e3c9889c5212 | https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/minidumpreader.py#L87-L101 | train |
skelsec/minidump | minidump/minidumpreader.py | MinidumpBufferedReader.peek | def peek(self, length):
"""
Returns up to length bytes from the current memory segment
"""
t = self.current_position + length
if not self.current_segment.inrange(t):
raise Exception('Would read over segment boundaries!')
return self.current_segment.data[self.current_position - self.current_segment.start_... | python | def peek(self, length):
"""
Returns up to length bytes from the current memory segment
"""
t = self.current_position + length
if not self.current_segment.inrange(t):
raise Exception('Would read over segment boundaries!')
return self.current_segment.data[self.current_position - self.current_segment.start_... | [
"def",
"peek",
"(",
"self",
",",
"length",
")",
":",
"t",
"=",
"self",
".",
"current_position",
"+",
"length",
"if",
"not",
"self",
".",
"current_segment",
".",
"inrange",
"(",
"t",
")",
":",
"raise",
"Exception",
"(",
"'Would read over segment boundaries!'"... | Returns up to length bytes from the current memory segment | [
"Returns",
"up",
"to",
"length",
"bytes",
"from",
"the",
"current",
"memory",
"segment"
] | 0c4dcabe6f11d7a403440919ffa9e3c9889c5212 | https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/minidumpreader.py#L109-L116 | train |
skelsec/minidump | minidump/minidumpreader.py | MinidumpBufferedReader.read | def read(self, size = -1):
"""
Returns data bytes of size size from the current segment. If size is -1 it returns all the remaining data bytes from memory segment
"""
if size < -1:
raise Exception('You shouldnt be doing this')
if size == -1:
t = self.current_segment.remaining_len(self.current_position)
... | python | def read(self, size = -1):
"""
Returns data bytes of size size from the current segment. If size is -1 it returns all the remaining data bytes from memory segment
"""
if size < -1:
raise Exception('You shouldnt be doing this')
if size == -1:
t = self.current_segment.remaining_len(self.current_position)
... | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"size",
"<",
"-",
"1",
":",
"raise",
"Exception",
"(",
"'You shouldnt be doing this'",
")",
"if",
"size",
"==",
"-",
"1",
":",
"t",
"=",
"self",
".",
"current_segment",
".",
"r... | Returns data bytes of size size from the current segment. If size is -1 it returns all the remaining data bytes from memory segment | [
"Returns",
"data",
"bytes",
"of",
"size",
"size",
"from",
"the",
"current",
"segment",
".",
"If",
"size",
"is",
"-",
"1",
"it",
"returns",
"all",
"the",
"remaining",
"data",
"bytes",
"from",
"memory",
"segment"
] | 0c4dcabe6f11d7a403440919ffa9e3c9889c5212 | https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/minidumpreader.py#L118-L139 | train |
skelsec/minidump | minidump/minidumpreader.py | MinidumpBufferedReader.read_int | def read_int(self):
"""
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian singed int on 32 bit arch
Reads an 8 byte small-endian singed int on 64 bit arch
"""
if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64:
return int.from_bytes(self.read(8... | python | def read_int(self):
"""
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian singed int on 32 bit arch
Reads an 8 byte small-endian singed int on 64 bit arch
"""
if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64:
return int.from_bytes(self.read(8... | [
"def",
"read_int",
"(",
"self",
")",
":",
"if",
"self",
".",
"reader",
".",
"sysinfo",
".",
"ProcessorArchitecture",
"==",
"PROCESSOR_ARCHITECTURE",
".",
"AMD64",
":",
"return",
"int",
".",
"from_bytes",
"(",
"self",
".",
"read",
"(",
"8",
")",
",",
"byt... | Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian singed int on 32 bit arch
Reads an 8 byte small-endian singed int on 64 bit arch | [
"Reads",
"an",
"integer",
".",
"The",
"size",
"depends",
"on",
"the",
"architecture",
".",
"Reads",
"a",
"4",
"byte",
"small",
"-",
"endian",
"singed",
"int",
"on",
"32",
"bit",
"arch",
"Reads",
"an",
"8",
"byte",
"small",
"-",
"endian",
"singed",
"int... | 0c4dcabe6f11d7a403440919ffa9e3c9889c5212 | https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/minidumpreader.py#L141-L150 | train |
skelsec/minidump | minidump/minidumpreader.py | MinidumpBufferedReader.read_uint | def read_uint(self):
"""
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian unsinged int on 32 bit arch
Reads an 8 byte small-endian unsinged int on 64 bit arch
"""
if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64:
return int.from_bytes(self.r... | python | def read_uint(self):
"""
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian unsinged int on 32 bit arch
Reads an 8 byte small-endian unsinged int on 64 bit arch
"""
if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64:
return int.from_bytes(self.r... | [
"def",
"read_uint",
"(",
"self",
")",
":",
"if",
"self",
".",
"reader",
".",
"sysinfo",
".",
"ProcessorArchitecture",
"==",
"PROCESSOR_ARCHITECTURE",
".",
"AMD64",
":",
"return",
"int",
".",
"from_bytes",
"(",
"self",
".",
"read",
"(",
"8",
")",
",",
"by... | Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian unsinged int on 32 bit arch
Reads an 8 byte small-endian unsinged int on 64 bit arch | [
"Reads",
"an",
"integer",
".",
"The",
"size",
"depends",
"on",
"the",
"architecture",
".",
"Reads",
"a",
"4",
"byte",
"small",
"-",
"endian",
"unsinged",
"int",
"on",
"32",
"bit",
"arch",
"Reads",
"an",
"8",
"byte",
"small",
"-",
"endian",
"unsinged",
... | 0c4dcabe6f11d7a403440919ffa9e3c9889c5212 | https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/minidumpreader.py#L152-L161 | train |
skelsec/minidump | minidump/minidumpreader.py | MinidumpBufferedReader.find | def find(self, pattern):
"""
Searches for a pattern in the current memory segment
"""
pos = self.current_segment.data.find(pattern)
if pos == -1:
return -1
return pos + self.current_position | python | def find(self, pattern):
"""
Searches for a pattern in the current memory segment
"""
pos = self.current_segment.data.find(pattern)
if pos == -1:
return -1
return pos + self.current_position | [
"def",
"find",
"(",
"self",
",",
"pattern",
")",
":",
"pos",
"=",
"self",
".",
"current_segment",
".",
"data",
".",
"find",
"(",
"pattern",
")",
"if",
"pos",
"==",
"-",
"1",
":",
"return",
"-",
"1",
"return",
"pos",
"+",
"self",
".",
"current_posit... | Searches for a pattern in the current memory segment | [
"Searches",
"for",
"a",
"pattern",
"in",
"the",
"current",
"memory",
"segment"
] | 0c4dcabe6f11d7a403440919ffa9e3c9889c5212 | https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/minidumpreader.py#L163-L170 | train |
skelsec/minidump | minidump/minidumpreader.py | MinidumpBufferedReader.find_all | def find_all(self, pattern):
"""
Searches for all occurrences of a pattern in the current memory segment, returns all occurrences as a list
"""
pos = []
last_found = -1
while True:
last_found = self.current_segment.data.find(pattern, last_found + 1)
if last_found == -1:
break
pos.append(last_fo... | python | def find_all(self, pattern):
"""
Searches for all occurrences of a pattern in the current memory segment, returns all occurrences as a list
"""
pos = []
last_found = -1
while True:
last_found = self.current_segment.data.find(pattern, last_found + 1)
if last_found == -1:
break
pos.append(last_fo... | [
"def",
"find_all",
"(",
"self",
",",
"pattern",
")",
":",
"pos",
"=",
"[",
"]",
"last_found",
"=",
"-",
"1",
"while",
"True",
":",
"last_found",
"=",
"self",
".",
"current_segment",
".",
"data",
".",
"find",
"(",
"pattern",
",",
"last_found",
"+",
"1... | Searches for all occurrences of a pattern in the current memory segment, returns all occurrences as a list | [
"Searches",
"for",
"all",
"occurrences",
"of",
"a",
"pattern",
"in",
"the",
"current",
"memory",
"segment",
"returns",
"all",
"occurrences",
"as",
"a",
"list"
] | 0c4dcabe6f11d7a403440919ffa9e3c9889c5212 | https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/minidumpreader.py#L172-L184 | train |
skelsec/minidump | minidump/minidumpreader.py | MinidumpBufferedReader.find_global | def find_global(self, pattern):
"""
Searches for the pattern in the whole process memory space and returns the first occurrence.
This is exhaustive!
"""
pos_s = self.reader.search(pattern)
if len(pos_s) == 0:
return -1
return pos_s[0] | python | def find_global(self, pattern):
"""
Searches for the pattern in the whole process memory space and returns the first occurrence.
This is exhaustive!
"""
pos_s = self.reader.search(pattern)
if len(pos_s) == 0:
return -1
return pos_s[0] | [
"def",
"find_global",
"(",
"self",
",",
"pattern",
")",
":",
"pos_s",
"=",
"self",
".",
"reader",
".",
"search",
"(",
"pattern",
")",
"if",
"len",
"(",
"pos_s",
")",
"==",
"0",
":",
"return",
"-",
"1",
"return",
"pos_s",
"[",
"0",
"]"
] | Searches for the pattern in the whole process memory space and returns the first occurrence.
This is exhaustive! | [
"Searches",
"for",
"the",
"pattern",
"in",
"the",
"whole",
"process",
"memory",
"space",
"and",
"returns",
"the",
"first",
"occurrence",
".",
"This",
"is",
"exhaustive!"
] | 0c4dcabe6f11d7a403440919ffa9e3c9889c5212 | https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/minidumpreader.py#L186-L195 | train |
skelsec/minidump | minidump/utils/privileges.py | report_privilege_information | def report_privilege_information():
"Report all privilege information assigned to the current process."
privileges = get_privilege_information()
print("found {0} privileges".format(privileges.count))
tuple(map(print, privileges)) | python | def report_privilege_information():
"Report all privilege information assigned to the current process."
privileges = get_privilege_information()
print("found {0} privileges".format(privileges.count))
tuple(map(print, privileges)) | [
"def",
"report_privilege_information",
"(",
")",
":",
"privileges",
"=",
"get_privilege_information",
"(",
")",
"print",
"(",
"\"found {0} privileges\"",
".",
"format",
"(",
"privileges",
".",
"count",
")",
")",
"tuple",
"(",
"map",
"(",
"print",
",",
"privilege... | Report all privilege information assigned to the current process. | [
"Report",
"all",
"privilege",
"information",
"assigned",
"to",
"the",
"current",
"process",
"."
] | 0c4dcabe6f11d7a403440919ffa9e3c9889c5212 | https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/utils/privileges.py#L171-L175 | train |
rajasimon/beatserver | beatserver/server.py | BeatServer.handle | async def handle(self):
"""
Listens on all the provided channels and handles the messages.
"""
# For each channel, launch its own listening coroutine
listeners = []
for key, value in self.beat_config.items():
listeners.append(asyncio.ensure_future(
... | python | async def handle(self):
"""
Listens on all the provided channels and handles the messages.
"""
# For each channel, launch its own listening coroutine
listeners = []
for key, value in self.beat_config.items():
listeners.append(asyncio.ensure_future(
... | [
"async",
"def",
"handle",
"(",
"self",
")",
":",
"# For each channel, launch its own listening coroutine",
"listeners",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"self",
".",
"beat_config",
".",
"items",
"(",
")",
":",
"listeners",
".",
"append",
"(",
... | Listens on all the provided channels and handles the messages. | [
"Listens",
"on",
"all",
"the",
"provided",
"channels",
"and",
"handles",
"the",
"messages",
"."
] | 8c653c46cdcf98398ca9d0bc6d3e47e5d621bb6a | https://github.com/rajasimon/beatserver/blob/8c653c46cdcf98398ca9d0bc6d3e47e5d621bb6a/beatserver/server.py#L16-L37 | train |
rajasimon/beatserver | beatserver/server.py | BeatServer.emitters | async def emitters(self, key, value):
"""
Single-channel emitter
"""
while True:
await asyncio.sleep(value['schedule'].total_seconds())
await self.channel_layer.send(key, {
"type": value['type'],
"message": value['message']
... | python | async def emitters(self, key, value):
"""
Single-channel emitter
"""
while True:
await asyncio.sleep(value['schedule'].total_seconds())
await self.channel_layer.send(key, {
"type": value['type'],
"message": value['message']
... | [
"async",
"def",
"emitters",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"while",
"True",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"value",
"[",
"'schedule'",
"]",
".",
"total_seconds",
"(",
")",
")",
"await",
"self",
".",
"channel_layer",
".",
... | Single-channel emitter | [
"Single",
"-",
"channel",
"emitter"
] | 8c653c46cdcf98398ca9d0bc6d3e47e5d621bb6a | https://github.com/rajasimon/beatserver/blob/8c653c46cdcf98398ca9d0bc6d3e47e5d621bb6a/beatserver/server.py#L40-L50 | train |
rajasimon/beatserver | beatserver/server.py | BeatServer.listener | async def listener(self, channel):
"""
Single-channel listener
"""
while True:
message = await self.channel_layer.receive(channel)
if not message.get("type", None):
raise ValueError("Worker received message with no type.")
# Make a scop... | python | async def listener(self, channel):
"""
Single-channel listener
"""
while True:
message = await self.channel_layer.receive(channel)
if not message.get("type", None):
raise ValueError("Worker received message with no type.")
# Make a scop... | [
"async",
"def",
"listener",
"(",
"self",
",",
"channel",
")",
":",
"while",
"True",
":",
"message",
"=",
"await",
"self",
".",
"channel_layer",
".",
"receive",
"(",
"channel",
")",
"if",
"not",
"message",
".",
"get",
"(",
"\"type\"",
",",
"None",
")",
... | Single-channel listener | [
"Single",
"-",
"channel",
"listener"
] | 8c653c46cdcf98398ca9d0bc6d3e47e5d621bb6a | https://github.com/rajasimon/beatserver/blob/8c653c46cdcf98398ca9d0bc6d3e47e5d621bb6a/beatserver/server.py#L54-L66 | train |
pinax/pinax-ratings | pinax/ratings/templatetags/pinax_ratings_tags.py | rating_count | def rating_count(obj):
"""
Total amount of users who have submitted a positive rating for this object.
Usage:
{% rating_count obj %}
"""
count = Rating.objects.filter(
object_id=obj.pk,
content_type=ContentType.objects.get_for_model(obj),
).exclude(rating=0).count()
... | python | def rating_count(obj):
"""
Total amount of users who have submitted a positive rating for this object.
Usage:
{% rating_count obj %}
"""
count = Rating.objects.filter(
object_id=obj.pk,
content_type=ContentType.objects.get_for_model(obj),
).exclude(rating=0).count()
... | [
"def",
"rating_count",
"(",
"obj",
")",
":",
"count",
"=",
"Rating",
".",
"objects",
".",
"filter",
"(",
"object_id",
"=",
"obj",
".",
"pk",
",",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
",",
")",
".",
... | Total amount of users who have submitted a positive rating for this object.
Usage:
{% rating_count obj %} | [
"Total",
"amount",
"of",
"users",
"who",
"have",
"submitted",
"a",
"positive",
"rating",
"for",
"this",
"object",
"."
] | eca388fea1ccd09ba844ac29a7489e41b64267f5 | https://github.com/pinax/pinax-ratings/blob/eca388fea1ccd09ba844ac29a7489e41b64267f5/pinax/ratings/templatetags/pinax_ratings_tags.py#L115-L126 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/BicolorMatrix8x8.py | BicolorMatrix8x8.set_pixel | def set_pixel(self, x, y, value):
"""Set pixel at position x, y to the given value. X and Y should be values
of 0 to 8. Value should be OFF, GREEN, RED, or YELLOW.
"""
if x < 0 or x > 7 or y < 0 or y > 7:
# Ignore out of bounds pixels.
return
# Set green... | python | def set_pixel(self, x, y, value):
"""Set pixel at position x, y to the given value. X and Y should be values
of 0 to 8. Value should be OFF, GREEN, RED, or YELLOW.
"""
if x < 0 or x > 7 or y < 0 or y > 7:
# Ignore out of bounds pixels.
return
# Set green... | [
"def",
"set_pixel",
"(",
"self",
",",
"x",
",",
"y",
",",
"value",
")",
":",
"if",
"x",
"<",
"0",
"or",
"x",
">",
"7",
"or",
"y",
"<",
"0",
"or",
"y",
">",
"7",
":",
"# Ignore out of bounds pixels.",
"return",
"# Set green LED based on 1st bit in value."... | Set pixel at position x, y to the given value. X and Y should be values
of 0 to 8. Value should be OFF, GREEN, RED, or YELLOW. | [
"Set",
"pixel",
"at",
"position",
"x",
"y",
"to",
"the",
"given",
"value",
".",
"X",
"and",
"Y",
"should",
"be",
"values",
"of",
"0",
"to",
"8",
".",
"Value",
"should",
"be",
"OFF",
"GREEN",
"RED",
"or",
"YELLOW",
"."
] | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/BicolorMatrix8x8.py#L41-L51 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/BicolorBargraph24.py | BicolorBargraph24.set_bar | def set_bar(self, bar, value):
"""Set bar to desired color. Bar should be a value of 0 to 23, and value
should be OFF, GREEN, RED, or YELLOW.
"""
if bar < 0 or bar > 23:
# Ignore out of bounds bars.
return
# Compute cathode and anode value.
c = (b... | python | def set_bar(self, bar, value):
"""Set bar to desired color. Bar should be a value of 0 to 23, and value
should be OFF, GREEN, RED, or YELLOW.
"""
if bar < 0 or bar > 23:
# Ignore out of bounds bars.
return
# Compute cathode and anode value.
c = (b... | [
"def",
"set_bar",
"(",
"self",
",",
"bar",
",",
"value",
")",
":",
"if",
"bar",
"<",
"0",
"or",
"bar",
">",
"23",
":",
"# Ignore out of bounds bars.",
"return",
"# Compute cathode and anode value.",
"c",
"=",
"(",
"bar",
"if",
"bar",
"<",
"12",
"else",
"... | Set bar to desired color. Bar should be a value of 0 to 23, and value
should be OFF, GREEN, RED, or YELLOW. | [
"Set",
"bar",
"to",
"desired",
"color",
".",
"Bar",
"should",
"be",
"a",
"value",
"of",
"0",
"to",
"23",
"and",
"value",
"should",
"be",
"OFF",
"GREEN",
"RED",
"or",
"YELLOW",
"."
] | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/BicolorBargraph24.py#L44-L59 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/Matrix8x8.py | Matrix8x8.animate | def animate(self, images, delay=.25):
"""Displays each of the input images in order, pausing for "delay"
seconds after each image.
Keyword arguments:
image -- An iterable collection of Image objects.
delay -- How many seconds to wait after displaying an image before
... | python | def animate(self, images, delay=.25):
"""Displays each of the input images in order, pausing for "delay"
seconds after each image.
Keyword arguments:
image -- An iterable collection of Image objects.
delay -- How many seconds to wait after displaying an image before
... | [
"def",
"animate",
"(",
"self",
",",
"images",
",",
"delay",
"=",
".25",
")",
":",
"for",
"image",
"in",
"images",
":",
"# Draw the image on the display buffer.",
"self",
".",
"set_image",
"(",
"image",
")",
"# Draw the buffer to the display hardware.",
"self",
"."... | Displays each of the input images in order, pausing for "delay"
seconds after each image.
Keyword arguments:
image -- An iterable collection of Image objects.
delay -- How many seconds to wait after displaying an image before
displaying the next one. (Default = .25) | [
"Displays",
"each",
"of",
"the",
"input",
"images",
"in",
"order",
"pausing",
"for",
"delay",
"seconds",
"after",
"each",
"image",
"."
] | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/Matrix8x8.py#L160-L175 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/Matrix8x16.py | Matrix8x16.set_pixel | def set_pixel(self, x, y, value):
"""Set pixel at position x, y to the given value. X and Y should be values
of 0 to 7 and 0 to 15, resp. Value should be 0 for off and non-zero for on.
"""
if x < 0 or x > 7 or y < 0 or y > 15:
# Ignore out of bounds pixels.
retu... | python | def set_pixel(self, x, y, value):
"""Set pixel at position x, y to the given value. X and Y should be values
of 0 to 7 and 0 to 15, resp. Value should be 0 for off and non-zero for on.
"""
if x < 0 or x > 7 or y < 0 or y > 15:
# Ignore out of bounds pixels.
retu... | [
"def",
"set_pixel",
"(",
"self",
",",
"x",
",",
"y",
",",
"value",
")",
":",
"if",
"x",
"<",
"0",
"or",
"x",
">",
"7",
"or",
"y",
"<",
"0",
"or",
"y",
">",
"15",
":",
"# Ignore out of bounds pixels.",
"return",
"self",
".",
"set_led",
"(",
"(",
... | Set pixel at position x, y to the given value. X and Y should be values
of 0 to 7 and 0 to 15, resp. Value should be 0 for off and non-zero for on. | [
"Set",
"pixel",
"at",
"position",
"x",
"y",
"to",
"the",
"given",
"value",
".",
"X",
"and",
"Y",
"should",
"be",
"values",
"of",
"0",
"to",
"7",
"and",
"0",
"to",
"15",
"resp",
".",
"Value",
"should",
"be",
"0",
"for",
"off",
"and",
"non",
"-",
... | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/Matrix8x16.py#L35-L42 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/Matrix8x16.py | Matrix8x16.set_image | def set_image(self, image):
"""Set display buffer to Python Image Library image. Image will be converted
to 1 bit color and non-zero color values will light the LEDs.
"""
imwidth, imheight = image.size
if imwidth != 8 or imheight != 16:
raise ValueError('Image must b... | python | def set_image(self, image):
"""Set display buffer to Python Image Library image. Image will be converted
to 1 bit color and non-zero color values will light the LEDs.
"""
imwidth, imheight = image.size
if imwidth != 8 or imheight != 16:
raise ValueError('Image must b... | [
"def",
"set_image",
"(",
"self",
",",
"image",
")",
":",
"imwidth",
",",
"imheight",
"=",
"image",
".",
"size",
"if",
"imwidth",
"!=",
"8",
"or",
"imheight",
"!=",
"16",
":",
"raise",
"ValueError",
"(",
"'Image must be an 8x16 pixels in size.'",
")",
"# Conv... | Set display buffer to Python Image Library image. Image will be converted
to 1 bit color and non-zero color values will light the LEDs. | [
"Set",
"display",
"buffer",
"to",
"Python",
"Image",
"Library",
"image",
".",
"Image",
"will",
"be",
"converted",
"to",
"1",
"bit",
"color",
"and",
"non",
"-",
"zero",
"color",
"values",
"will",
"light",
"the",
"LEDs",
"."
] | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/Matrix8x16.py#L44-L61 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/Matrix8x16.py | Matrix8x16.horizontal_scroll | def horizontal_scroll(self, image, padding=True):
"""Returns a list of images which appear to scroll from left to right
across the input image when displayed on the LED matrix in order.
The input image is not limited to being 8x16. If the input image is
larger than this, then all column... | python | def horizontal_scroll(self, image, padding=True):
"""Returns a list of images which appear to scroll from left to right
across the input image when displayed on the LED matrix in order.
The input image is not limited to being 8x16. If the input image is
larger than this, then all column... | [
"def",
"horizontal_scroll",
"(",
"self",
",",
"image",
",",
"padding",
"=",
"True",
")",
":",
"image_list",
"=",
"list",
"(",
")",
"width",
"=",
"image",
".",
"size",
"[",
"0",
"]",
"# Scroll into the blank image.",
"if",
"padding",
":",
"for",
"x",
"in"... | Returns a list of images which appear to scroll from left to right
across the input image when displayed on the LED matrix in order.
The input image is not limited to being 8x16. If the input image is
larger than this, then all columns will be scrolled through but only
the top 16 rows o... | [
"Returns",
"a",
"list",
"of",
"images",
"which",
"appear",
"to",
"scroll",
"from",
"left",
"to",
"right",
"across",
"the",
"input",
"image",
"when",
"displayed",
"on",
"the",
"LED",
"matrix",
"in",
"order",
"."
] | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/Matrix8x16.py#L67-L112 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/Matrix8x16.py | Matrix8x16.vertical_scroll | def vertical_scroll(self, image, padding=True):
"""Returns a list of images which appear to scroll from top to bottom
down the input image when displayed on the LED matrix in order.
The input image is not limited to being 8x16. If the input image is
largerthan this, then all rows will b... | python | def vertical_scroll(self, image, padding=True):
"""Returns a list of images which appear to scroll from top to bottom
down the input image when displayed on the LED matrix in order.
The input image is not limited to being 8x16. If the input image is
largerthan this, then all rows will b... | [
"def",
"vertical_scroll",
"(",
"self",
",",
"image",
",",
"padding",
"=",
"True",
")",
":",
"image_list",
"=",
"list",
"(",
")",
"height",
"=",
"image",
".",
"size",
"[",
"1",
"]",
"# Scroll into the blank image.",
"if",
"padding",
":",
"for",
"y",
"in",... | Returns a list of images which appear to scroll from top to bottom
down the input image when displayed on the LED matrix in order.
The input image is not limited to being 8x16. If the input image is
largerthan this, then all rows will be scrolled through but only the
left-most 8 columns... | [
"Returns",
"a",
"list",
"of",
"images",
"which",
"appear",
"to",
"scroll",
"from",
"top",
"to",
"bottom",
"down",
"the",
"input",
"image",
"when",
"displayed",
"on",
"the",
"LED",
"matrix",
"in",
"order",
"."
] | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/Matrix8x16.py#L114-L158 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/AlphaNum4.py | AlphaNum4.print_number_str | def print_number_str(self, value, justify_right=True):
"""Print a 4 character long string of numeric values to the display. This
function is similar to print_str but will interpret periods not as
characters but as decimal points associated with the previous character.
"""
# Calcu... | python | def print_number_str(self, value, justify_right=True):
"""Print a 4 character long string of numeric values to the display. This
function is similar to print_str but will interpret periods not as
characters but as decimal points associated with the previous character.
"""
# Calcu... | [
"def",
"print_number_str",
"(",
"self",
",",
"value",
",",
"justify_right",
"=",
"True",
")",
":",
"# Calculate length of value without decimals.",
"length",
"=",
"len",
"(",
"value",
".",
"translate",
"(",
"None",
",",
"'.'",
")",
")",
"# Error if value without d... | Print a 4 character long string of numeric values to the display. This
function is similar to print_str but will interpret periods not as
characters but as decimal points associated with the previous character. | [
"Print",
"a",
"4",
"character",
"long",
"string",
"of",
"numeric",
"values",
"to",
"the",
"display",
".",
"This",
"function",
"is",
"similar",
"to",
"print_str",
"but",
"will",
"interpret",
"periods",
"not",
"as",
"characters",
"but",
"as",
"decimal",
"point... | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/AlphaNum4.py#L177-L197 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/AlphaNum4.py | AlphaNum4.print_float | def print_float(self, value, decimal_digits=2, justify_right=True):
"""Print a numeric value to the display. If value is negative
it will be printed with a leading minus sign. Decimal digits is the
desired number of digits after the decimal point.
"""
format_string = '{{0:0.{0}... | python | def print_float(self, value, decimal_digits=2, justify_right=True):
"""Print a numeric value to the display. If value is negative
it will be printed with a leading minus sign. Decimal digits is the
desired number of digits after the decimal point.
"""
format_string = '{{0:0.{0}... | [
"def",
"print_float",
"(",
"self",
",",
"value",
",",
"decimal_digits",
"=",
"2",
",",
"justify_right",
"=",
"True",
")",
":",
"format_string",
"=",
"'{{0:0.{0}F}}'",
".",
"format",
"(",
"decimal_digits",
")",
"self",
".",
"print_number_str",
"(",
"format_stri... | Print a numeric value to the display. If value is negative
it will be printed with a leading minus sign. Decimal digits is the
desired number of digits after the decimal point. | [
"Print",
"a",
"numeric",
"value",
"to",
"the",
"display",
".",
"If",
"value",
"is",
"negative",
"it",
"will",
"be",
"printed",
"with",
"a",
"leading",
"minus",
"sign",
".",
"Decimal",
"digits",
"is",
"the",
"desired",
"number",
"of",
"digits",
"after",
"... | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/AlphaNum4.py#L199-L205 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/SevenSegment.py | SevenSegment.set_left_colon | def set_left_colon(self, show_colon):
"""Turn the left colon on with show color True, or off with show colon
False. Only the large 1.2" 7-segment display has a left colon.
"""
if show_colon:
self.buffer[4] |= 0x04
self.buffer[4] |= 0x08
else:
... | python | def set_left_colon(self, show_colon):
"""Turn the left colon on with show color True, or off with show colon
False. Only the large 1.2" 7-segment display has a left colon.
"""
if show_colon:
self.buffer[4] |= 0x04
self.buffer[4] |= 0x08
else:
... | [
"def",
"set_left_colon",
"(",
"self",
",",
"show_colon",
")",
":",
"if",
"show_colon",
":",
"self",
".",
"buffer",
"[",
"4",
"]",
"|=",
"0x04",
"self",
".",
"buffer",
"[",
"4",
"]",
"|=",
"0x08",
"else",
":",
"self",
".",
"buffer",
"[",
"4",
"]",
... | Turn the left colon on with show color True, or off with show colon
False. Only the large 1.2" 7-segment display has a left colon. | [
"Turn",
"the",
"left",
"colon",
"on",
"with",
"show",
"color",
"True",
"or",
"off",
"with",
"show",
"colon",
"False",
".",
"Only",
"the",
"large",
"1",
".",
"2",
"7",
"-",
"segment",
"display",
"has",
"a",
"left",
"colon",
"."
] | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/SevenSegment.py#L145-L154 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/SevenSegment.py | SevenSegment.print_number_str | def print_number_str(self, value, justify_right=True):
"""Print a 4 character long string of numeric values to the display.
Characters in the string should be any supported character by set_digit,
or a decimal point. Decimal point characters will be associated with
the previous characte... | python | def print_number_str(self, value, justify_right=True):
"""Print a 4 character long string of numeric values to the display.
Characters in the string should be any supported character by set_digit,
or a decimal point. Decimal point characters will be associated with
the previous characte... | [
"def",
"print_number_str",
"(",
"self",
",",
"value",
",",
"justify_right",
"=",
"True",
")",
":",
"# Calculate length of value without decimals.",
"length",
"=",
"sum",
"(",
"map",
"(",
"lambda",
"x",
":",
"1",
"if",
"x",
"!=",
"'.'",
"else",
"0",
",",
"v... | Print a 4 character long string of numeric values to the display.
Characters in the string should be any supported character by set_digit,
or a decimal point. Decimal point characters will be associated with
the previous character. | [
"Print",
"a",
"4",
"character",
"long",
"string",
"of",
"numeric",
"values",
"to",
"the",
"display",
".",
"Characters",
"in",
"the",
"string",
"should",
"be",
"any",
"supported",
"character",
"by",
"set_digit",
"or",
"a",
"decimal",
"point",
".",
"Decimal",
... | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/SevenSegment.py#L167-L188 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/HT16K33.py | HT16K33.begin | def begin(self):
"""Initialize driver with LEDs enabled and all turned off."""
# Turn on the oscillator.
self._device.writeList(HT16K33_SYSTEM_SETUP | HT16K33_OSCILLATOR, [])
# Turn display on with no blinking.
self.set_blink(HT16K33_BLINK_OFF)
# Set display to full brigh... | python | def begin(self):
"""Initialize driver with LEDs enabled and all turned off."""
# Turn on the oscillator.
self._device.writeList(HT16K33_SYSTEM_SETUP | HT16K33_OSCILLATOR, [])
# Turn display on with no blinking.
self.set_blink(HT16K33_BLINK_OFF)
# Set display to full brigh... | [
"def",
"begin",
"(",
"self",
")",
":",
"# Turn on the oscillator.",
"self",
".",
"_device",
".",
"writeList",
"(",
"HT16K33_SYSTEM_SETUP",
"|",
"HT16K33_OSCILLATOR",
",",
"[",
"]",
")",
"# Turn display on with no blinking.",
"self",
".",
"set_blink",
"(",
"HT16K33_B... | Initialize driver with LEDs enabled and all turned off. | [
"Initialize",
"driver",
"with",
"LEDs",
"enabled",
"and",
"all",
"turned",
"off",
"."
] | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/HT16K33.py#L50-L57 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/HT16K33.py | HT16K33.write_display | def write_display(self):
"""Write display buffer to display hardware."""
for i, value in enumerate(self.buffer):
self._device.write8(i, value) | python | def write_display(self):
"""Write display buffer to display hardware."""
for i, value in enumerate(self.buffer):
self._device.write8(i, value) | [
"def",
"write_display",
"(",
"self",
")",
":",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"self",
".",
"buffer",
")",
":",
"self",
".",
"_device",
".",
"write8",
"(",
"i",
",",
"value",
")"
] | Write display buffer to display hardware. | [
"Write",
"display",
"buffer",
"to",
"display",
"hardware",
"."
] | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/HT16K33.py#L93-L96 | train |
adafruit/Adafruit_Python_LED_Backpack | Adafruit_LED_Backpack/HT16K33.py | HT16K33.clear | def clear(self):
"""Clear contents of display buffer."""
for i, value in enumerate(self.buffer):
self.buffer[i] = 0 | python | def clear(self):
"""Clear contents of display buffer."""
for i, value in enumerate(self.buffer):
self.buffer[i] = 0 | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"self",
".",
"buffer",
")",
":",
"self",
".",
"buffer",
"[",
"i",
"]",
"=",
"0"
] | Clear contents of display buffer. | [
"Clear",
"contents",
"of",
"display",
"buffer",
"."
] | 7356b4dd8b4bb162d60987878c2cb752fdd017d5 | https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/HT16K33.py#L98-L101 | train |
swisscom/cleanerversion | versions/admin.py | VersionedAdmin.get_readonly_fields | def get_readonly_fields(self, request, obj=None):
"""
This is required a subclass of VersionedAdmin has readonly_fields
ours won't be undone
"""
if obj:
return list(self.readonly_fields) + ['id', 'identity',
'is_current... | python | def get_readonly_fields(self, request, obj=None):
"""
This is required a subclass of VersionedAdmin has readonly_fields
ours won't be undone
"""
if obj:
return list(self.readonly_fields) + ['id', 'identity',
'is_current... | [
"def",
"get_readonly_fields",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
":",
"return",
"list",
"(",
"self",
".",
"readonly_fields",
")",
"+",
"[",
"'id'",
",",
"'identity'",
",",
"'is_current'",
"]",
"return",
"self",
... | This is required a subclass of VersionedAdmin has readonly_fields
ours won't be undone | [
"This",
"is",
"required",
"a",
"subclass",
"of",
"VersionedAdmin",
"has",
"readonly_fields",
"ours",
"won",
"t",
"be",
"undone"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L144-L152 | train |
swisscom/cleanerversion | versions/admin.py | VersionedAdmin.get_list_display | def get_list_display(self, request):
"""
This method determines which fields go in the changelist
"""
# Force cast to list as super get_list_display could return a tuple
list_display = list(
super(VersionedAdmin, self).get_list_display(request))
# Preprend t... | python | def get_list_display(self, request):
"""
This method determines which fields go in the changelist
"""
# Force cast to list as super get_list_display could return a tuple
list_display = list(
super(VersionedAdmin, self).get_list_display(request))
# Preprend t... | [
"def",
"get_list_display",
"(",
"self",
",",
"request",
")",
":",
"# Force cast to list as super get_list_display could return a tuple",
"list_display",
"=",
"list",
"(",
"super",
"(",
"VersionedAdmin",
",",
"self",
")",
".",
"get_list_display",
"(",
"request",
")",
"... | This method determines which fields go in the changelist | [
"This",
"method",
"determines",
"which",
"fields",
"go",
"in",
"the",
"changelist"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L157-L176 | train |
swisscom/cleanerversion | versions/admin.py | VersionedAdmin.get_list_filter | def get_list_filter(self, request):
"""
Adds versionable custom filtering ability to changelist
"""
list_filter = super(VersionedAdmin, self).get_list_filter(request)
return list(list_filter) + [('version_start_date', DateTimeFilter),
IsCurrent... | python | def get_list_filter(self, request):
"""
Adds versionable custom filtering ability to changelist
"""
list_filter = super(VersionedAdmin, self).get_list_filter(request)
return list(list_filter) + [('version_start_date', DateTimeFilter),
IsCurrent... | [
"def",
"get_list_filter",
"(",
"self",
",",
"request",
")",
":",
"list_filter",
"=",
"super",
"(",
"VersionedAdmin",
",",
"self",
")",
".",
"get_list_filter",
"(",
"request",
")",
"return",
"list",
"(",
"list_filter",
")",
"+",
"[",
"(",
"'version_start_date... | Adds versionable custom filtering ability to changelist | [
"Adds",
"versionable",
"custom",
"filtering",
"ability",
"to",
"changelist"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L178-L184 | train |
swisscom/cleanerversion | versions/admin.py | VersionedAdmin.restore | def restore(self, request, *args, **kwargs):
"""
View for restoring object from change view
"""
paths = request.path_info.split('/')
object_id_index = paths.index("restore") - 2
object_id = paths[object_id_index]
obj = super(VersionedAdmin, self).get_object(reque... | python | def restore(self, request, *args, **kwargs):
"""
View for restoring object from change view
"""
paths = request.path_info.split('/')
object_id_index = paths.index("restore") - 2
object_id = paths[object_id_index]
obj = super(VersionedAdmin, self).get_object(reque... | [
"def",
"restore",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"paths",
"=",
"request",
".",
"path_info",
".",
"split",
"(",
"'/'",
")",
"object_id_index",
"=",
"paths",
".",
"index",
"(",
"\"restore\"",
")",
"-",... | View for restoring object from change view | [
"View",
"for",
"restoring",
"object",
"from",
"change",
"view"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L186-L209 | train |
swisscom/cleanerversion | versions/admin.py | VersionedAdmin.will_not_clone | def will_not_clone(self, request, *args, **kwargs):
"""
Add save but not clone capability in the changeview
"""
paths = request.path_info.split('/')
index_of_object_id = paths.index("will_not_clone") - 1
object_id = paths[index_of_object_id]
self.change_view(reque... | python | def will_not_clone(self, request, *args, **kwargs):
"""
Add save but not clone capability in the changeview
"""
paths = request.path_info.split('/')
index_of_object_id = paths.index("will_not_clone") - 1
object_id = paths[index_of_object_id]
self.change_view(reque... | [
"def",
"will_not_clone",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"paths",
"=",
"request",
".",
"path_info",
".",
"split",
"(",
"'/'",
")",
"index_of_object_id",
"=",
"paths",
".",
"index",
"(",
"\"will_not_clone\... | Add save but not clone capability in the changeview | [
"Add",
"save",
"but",
"not",
"clone",
"capability",
"in",
"the",
"changeview"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L211-L224 | train |
swisscom/cleanerversion | versions/admin.py | VersionedAdmin.exclude | def exclude(self):
"""
Custom descriptor for exclude since there is no get_exclude method to
be overridden
"""
exclude = self.VERSIONED_EXCLUDE
if super(VersionedAdmin, self).exclude is not None:
# Force cast to list as super exclude could return a tuple
... | python | def exclude(self):
"""
Custom descriptor for exclude since there is no get_exclude method to
be overridden
"""
exclude = self.VERSIONED_EXCLUDE
if super(VersionedAdmin, self).exclude is not None:
# Force cast to list as super exclude could return a tuple
... | [
"def",
"exclude",
"(",
"self",
")",
":",
"exclude",
"=",
"self",
".",
"VERSIONED_EXCLUDE",
"if",
"super",
"(",
"VersionedAdmin",
",",
"self",
")",
".",
"exclude",
"is",
"not",
"None",
":",
"# Force cast to list as super exclude could return a tuple",
"exclude",
"=... | Custom descriptor for exclude since there is no get_exclude method to
be overridden | [
"Custom",
"descriptor",
"for",
"exclude",
"since",
"there",
"is",
"no",
"get_exclude",
"method",
"to",
"be",
"overridden"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L227-L238 | train |
swisscom/cleanerversion | versions/admin.py | VersionedAdmin.get_object | def get_object(self, request, object_id, from_field=None):
"""
our implementation of get_object allows for cloning when updating an
object, not cloning when the button 'save but not clone' is pushed
and at no other time will clone be called
"""
# from_field breaks in 1.7.... | python | def get_object(self, request, object_id, from_field=None):
"""
our implementation of get_object allows for cloning when updating an
object, not cloning when the button 'save but not clone' is pushed
and at no other time will clone be called
"""
# from_field breaks in 1.7.... | [
"def",
"get_object",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"from_field",
"=",
"None",
")",
":",
"# from_field breaks in 1.7.8",
"obj",
"=",
"super",
"(",
"VersionedAdmin",
",",
"self",
")",
".",
"get_object",
"(",
"request",
",",
"object_id",
"... | our implementation of get_object allows for cloning when updating an
object, not cloning when the button 'save but not clone' is pushed
and at no other time will clone be called | [
"our",
"implementation",
"of",
"get_object",
"allows",
"for",
"cloning",
"when",
"updating",
"an",
"object",
"not",
"cloning",
"when",
"the",
"button",
"save",
"but",
"not",
"clone",
"is",
"pushed",
"and",
"at",
"no",
"other",
"time",
"will",
"clone",
"be",
... | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L240-L259 | train |
swisscom/cleanerversion | versions/admin.py | VersionedAdmin.get_urls | def get_urls(self):
"""
Appends the custom will_not_clone url to the admin site
"""
not_clone_url = [url(r'^(.+)/will_not_clone/$',
admin.site.admin_view(self.will_not_clone))]
restore_url = [
url(r'^(.+)/restore/$', admin.site.admin_view(... | python | def get_urls(self):
"""
Appends the custom will_not_clone url to the admin site
"""
not_clone_url = [url(r'^(.+)/will_not_clone/$',
admin.site.admin_view(self.will_not_clone))]
restore_url = [
url(r'^(.+)/restore/$', admin.site.admin_view(... | [
"def",
"get_urls",
"(",
"self",
")",
":",
"not_clone_url",
"=",
"[",
"url",
"(",
"r'^(.+)/will_not_clone/$'",
",",
"admin",
".",
"site",
".",
"admin_view",
"(",
"self",
".",
"will_not_clone",
")",
")",
"]",
"restore_url",
"=",
"[",
"url",
"(",
"r'^(.+)/res... | Appends the custom will_not_clone url to the admin site | [
"Appends",
"the",
"custom",
"will_not_clone",
"url",
"to",
"the",
"admin",
"site"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L297-L306 | train |
swisscom/cleanerversion | versions/util/postgresql.py | create_current_version_unique_identity_indexes | def create_current_version_unique_identity_indexes(app_name, database=None):
"""
Add partial unique indexes for the the identity column of versionable
models.
This enforces that no two *current* versions can have the same identity.
This will only try to create indexes if they do not exist in the d... | python | def create_current_version_unique_identity_indexes(app_name, database=None):
"""
Add partial unique indexes for the the identity column of versionable
models.
This enforces that no two *current* versions can have the same identity.
This will only try to create indexes if they do not exist in the d... | [
"def",
"create_current_version_unique_identity_indexes",
"(",
"app_name",
",",
"database",
"=",
"None",
")",
":",
"indexes_created",
"=",
"0",
"connection",
"=",
"database_connection",
"(",
"database",
")",
"with",
"connection",
".",
"cursor",
"(",
")",
"as",
"cur... | Add partial unique indexes for the the identity column of versionable
models.
This enforces that no two *current* versions can have the same identity.
This will only try to create indexes if they do not exist in the database,
so it should be safe to run in a post_migrate signal handler. Running it
... | [
"Add",
"partial",
"unique",
"indexes",
"for",
"the",
"the",
"identity",
"column",
"of",
"versionable",
"models",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/util/postgresql.py#L148-L182 | train |
swisscom/cleanerversion | versions/models.py | VersionManager.get_queryset | def get_queryset(self):
"""
Returns a VersionedQuerySet capable of handling version time
restrictions.
:return: VersionedQuerySet
"""
qs = VersionedQuerySet(self.model, using=self._db)
if hasattr(self, 'instance') and hasattr(self.instance, '_querytime'):
... | python | def get_queryset(self):
"""
Returns a VersionedQuerySet capable of handling version time
restrictions.
:return: VersionedQuerySet
"""
qs = VersionedQuerySet(self.model, using=self._db)
if hasattr(self, 'instance') and hasattr(self.instance, '_querytime'):
... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"VersionedQuerySet",
"(",
"self",
".",
"model",
",",
"using",
"=",
"self",
".",
"_db",
")",
"if",
"hasattr",
"(",
"self",
",",
"'instance'",
")",
"and",
"hasattr",
"(",
"self",
".",
"instance",
... | Returns a VersionedQuerySet capable of handling version time
restrictions.
:return: VersionedQuerySet | [
"Returns",
"a",
"VersionedQuerySet",
"capable",
"of",
"handling",
"version",
"time",
"restrictions",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L62-L72 | train |
swisscom/cleanerversion | versions/models.py | VersionManager.next_version | def next_version(self, object, relations_as_of='end'):
"""
Return the next version of the given object.
In case there is no next object existing, meaning the given
object is the current version, the function returns this version.
Note that if object's version_end_date is None, ... | python | def next_version(self, object, relations_as_of='end'):
"""
Return the next version of the given object.
In case there is no next object existing, meaning the given
object is the current version, the function returns this version.
Note that if object's version_end_date is None, ... | [
"def",
"next_version",
"(",
"self",
",",
"object",
",",
"relations_as_of",
"=",
"'end'",
")",
":",
"if",
"object",
".",
"version_end_date",
"is",
"None",
":",
"next",
"=",
"object",
"else",
":",
"next",
"=",
"self",
".",
"filter",
"(",
"Q",
"(",
"ident... | Return the next version of the given object.
In case there is no next object existing, meaning the given
object is the current version, the function returns this version.
Note that if object's version_end_date is None, this does not check
the database to see if there is a newer version... | [
"Return",
"the",
"next",
"version",
"of",
"the",
"given",
"object",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L83-L117 | train |
swisscom/cleanerversion | versions/models.py | VersionManager.previous_version | def previous_version(self, object, relations_as_of='end'):
"""
Return the previous version of the given object.
In case there is no previous object existing, meaning the given object
is the first version of the object, then the function returns this
version.
``relations... | python | def previous_version(self, object, relations_as_of='end'):
"""
Return the previous version of the given object.
In case there is no previous object existing, meaning the given object
is the first version of the object, then the function returns this
version.
``relations... | [
"def",
"previous_version",
"(",
"self",
",",
"object",
",",
"relations_as_of",
"=",
"'end'",
")",
":",
"if",
"object",
".",
"version_birth_date",
"==",
"object",
".",
"version_start_date",
":",
"previous",
"=",
"object",
"else",
":",
"previous",
"=",
"self",
... | Return the previous version of the given object.
In case there is no previous object existing, meaning the given object
is the first version of the object, then the function returns this
version.
``relations_as_of`` is used to fix the point in time for the version;
this affects... | [
"Return",
"the",
"previous",
"version",
"of",
"the",
"given",
"object",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L119-L151 | train |
swisscom/cleanerversion | versions/models.py | VersionManager.current_version | def current_version(self, object, relations_as_of=None, check_db=False):
"""
Return the current version of the given object.
The current version is the one having its version_end_date set to NULL.
If there is not such a version then it means the object has been
'deleted' and so ... | python | def current_version(self, object, relations_as_of=None, check_db=False):
"""
Return the current version of the given object.
The current version is the one having its version_end_date set to NULL.
If there is not such a version then it means the object has been
'deleted' and so ... | [
"def",
"current_version",
"(",
"self",
",",
"object",
",",
"relations_as_of",
"=",
"None",
",",
"check_db",
"=",
"False",
")",
":",
"if",
"object",
".",
"version_end_date",
"is",
"None",
"and",
"not",
"check_db",
":",
"current",
"=",
"object",
"else",
":",... | Return the current version of the given object.
The current version is the one having its version_end_date set to NULL.
If there is not such a version then it means the object has been
'deleted' and so there is no current version available. In this case
the function returns None.
... | [
"Return",
"the",
"current",
"version",
"of",
"the",
"given",
"object",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L153-L185 | train |
swisscom/cleanerversion | versions/models.py | VersionManager.adjust_version_as_of | def adjust_version_as_of(version, relations_as_of):
"""
Adjusts the passed version's as_of time to an appropriate value, and
returns it.
``relations_as_of`` is used to fix the point in time for the version;
this affects which related objects are returned when querying for
... | python | def adjust_version_as_of(version, relations_as_of):
"""
Adjusts the passed version's as_of time to an appropriate value, and
returns it.
``relations_as_of`` is used to fix the point in time for the version;
this affects which related objects are returned when querying for
... | [
"def",
"adjust_version_as_of",
"(",
"version",
",",
"relations_as_of",
")",
":",
"if",
"not",
"version",
":",
"return",
"version",
"if",
"relations_as_of",
"==",
"'end'",
":",
"if",
"version",
".",
"is_current",
":",
"# Ensure that version._querytime is active, in cas... | Adjusts the passed version's as_of time to an appropriate value, and
returns it.
``relations_as_of`` is used to fix the point in time for the version;
this affects which related objects are returned when querying for
object relations.
Valid ``relations_as_of`` values and how thi... | [
"Adjusts",
"the",
"passed",
"version",
"s",
"as_of",
"time",
"to",
"an",
"appropriate",
"value",
"and",
"returns",
"it",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L188-L252 | train |
swisscom/cleanerversion | versions/models.py | VersionedQuerySet._fetch_all | def _fetch_all(self):
"""
Completely overrides the QuerySet._fetch_all method by adding the
timestamp to all objects
:return: See django.db.models.query.QuerySet._fetch_all for return
values
"""
if self._result_cache is None:
self._result_cache = ... | python | def _fetch_all(self):
"""
Completely overrides the QuerySet._fetch_all method by adding the
timestamp to all objects
:return: See django.db.models.query.QuerySet._fetch_all for return
values
"""
if self._result_cache is None:
self._result_cache = ... | [
"def",
"_fetch_all",
"(",
"self",
")",
":",
"if",
"self",
".",
"_result_cache",
"is",
"None",
":",
"self",
".",
"_result_cache",
"=",
"list",
"(",
"self",
".",
"iterator",
"(",
")",
")",
"# TODO: Do we have to test for ValuesListIterable, ValuesIterable,",
"# and ... | Completely overrides the QuerySet._fetch_all method by adding the
timestamp to all objects
:return: See django.db.models.query.QuerySet._fetch_all for return
values | [
"Completely",
"overrides",
"the",
"QuerySet",
".",
"_fetch_all",
"method",
"by",
"adding",
"the",
"timestamp",
"to",
"all",
"objects"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L500-L516 | train |
swisscom/cleanerversion | versions/models.py | VersionedQuerySet._clone | def _clone(self, *args, **kwargs):
"""
Overrides the QuerySet._clone method by adding the cloning of the
VersionedQuerySet's query_time parameter
:param kwargs: Same as the original QuerySet._clone params
:return: Just as QuerySet._clone, this method returns a clone of the
... | python | def _clone(self, *args, **kwargs):
"""
Overrides the QuerySet._clone method by adding the cloning of the
VersionedQuerySet's query_time parameter
:param kwargs: Same as the original QuerySet._clone params
:return: Just as QuerySet._clone, this method returns a clone of the
... | [
"def",
"_clone",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"clone",
"=",
"super",
"(",
"VersionedQuerySet",
",",
"self",
")",
".",
"_clone",
"(",
"*",
"*",
"kwargs",
")",
"clone",
".",
"querytime",
"=",
"self",
".",
"queryti... | Overrides the QuerySet._clone method by adding the cloning of the
VersionedQuerySet's query_time parameter
:param kwargs: Same as the original QuerySet._clone params
:return: Just as QuerySet._clone, this method returns a clone of the
original object | [
"Overrides",
"the",
"QuerySet",
".",
"_clone",
"method",
"by",
"adding",
"the",
"cloning",
"of",
"the",
"VersionedQuerySet",
"s",
"query_time",
"parameter"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L518-L529 | train |
swisscom/cleanerversion | versions/models.py | VersionedQuerySet._set_item_querytime | def _set_item_querytime(self, item, type_check=True):
"""
Sets the time for which the query was made on the resulting item
:param item: an item of type Versionable
:param type_check: Check the item to be a Versionable
:return: Returns the item itself with the time set
""... | python | def _set_item_querytime(self, item, type_check=True):
"""
Sets the time for which the query was made on the resulting item
:param item: an item of type Versionable
:param type_check: Check the item to be a Versionable
:return: Returns the item itself with the time set
""... | [
"def",
"_set_item_querytime",
"(",
"self",
",",
"item",
",",
"type_check",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"Versionable",
")",
":",
"item",
".",
"_querytime",
"=",
"self",
".",
"querytime",
"elif",
"isinstance",
"(",
"item",
... | Sets the time for which the query was made on the resulting item
:param item: an item of type Versionable
:param type_check: Check the item to be a Versionable
:return: Returns the item itself with the time set | [
"Sets",
"the",
"time",
"for",
"which",
"the",
"query",
"was",
"made",
"on",
"the",
"resulting",
"item"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L531-L548 | train |
swisscom/cleanerversion | versions/models.py | VersionedQuerySet.as_of | def as_of(self, qtime=None):
"""
Sets the time for which we want to retrieve an object.
:param qtime: The UTC date and time; if None then use the current
state (where version_end_date = NULL)
:return: A VersionedQuerySet
"""
clone = self._clone()
clon... | python | def as_of(self, qtime=None):
"""
Sets the time for which we want to retrieve an object.
:param qtime: The UTC date and time; if None then use the current
state (where version_end_date = NULL)
:return: A VersionedQuerySet
"""
clone = self._clone()
clon... | [
"def",
"as_of",
"(",
"self",
",",
"qtime",
"=",
"None",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"clone",
".",
"querytime",
"=",
"QueryTime",
"(",
"time",
"=",
"qtime",
",",
"active",
"=",
"True",
")",
"return",
"clone"
] | Sets the time for which we want to retrieve an object.
:param qtime: The UTC date and time; if None then use the current
state (where version_end_date = NULL)
:return: A VersionedQuerySet | [
"Sets",
"the",
"time",
"for",
"which",
"we",
"want",
"to",
"retrieve",
"an",
"object",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L550-L560 | train |
swisscom/cleanerversion | versions/models.py | VersionedQuerySet.delete | def delete(self):
"""
Deletes the records in the QuerySet.
"""
assert self.query.can_filter(), \
"Cannot use 'limit' or 'offset' with delete."
# Ensure that only current objects are selected.
del_query = self.filter(version_end_date__isnull=True)
# T... | python | def delete(self):
"""
Deletes the records in the QuerySet.
"""
assert self.query.can_filter(), \
"Cannot use 'limit' or 'offset' with delete."
# Ensure that only current objects are selected.
del_query = self.filter(version_end_date__isnull=True)
# T... | [
"def",
"delete",
"(",
"self",
")",
":",
"assert",
"self",
".",
"query",
".",
"can_filter",
"(",
")",
",",
"\"Cannot use 'limit' or 'offset' with delete.\"",
"# Ensure that only current objects are selected.",
"del_query",
"=",
"self",
".",
"filter",
"(",
"version_end_da... | Deletes the records in the QuerySet. | [
"Deletes",
"the",
"records",
"in",
"the",
"QuerySet",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L562-L588 | train |
swisscom/cleanerversion | versions/models.py | Versionable.uuid | def uuid(uuid_value=None):
"""
Returns a uuid value that is valid to use for id and identity fields.
:return: unicode uuid object if using UUIDFields, uuid unicode string
otherwise.
"""
if uuid_value:
if not validate_uuid(uuid_value):
rais... | python | def uuid(uuid_value=None):
"""
Returns a uuid value that is valid to use for id and identity fields.
:return: unicode uuid object if using UUIDFields, uuid unicode string
otherwise.
"""
if uuid_value:
if not validate_uuid(uuid_value):
rais... | [
"def",
"uuid",
"(",
"uuid_value",
"=",
"None",
")",
":",
"if",
"uuid_value",
":",
"if",
"not",
"validate_uuid",
"(",
"uuid_value",
")",
":",
"raise",
"ValueError",
"(",
"\"uuid_value must be a valid UUID version 4 object\"",
")",
"else",
":",
"uuid_value",
"=",
... | Returns a uuid value that is valid to use for id and identity fields.
:return: unicode uuid object if using UUIDFields, uuid unicode string
otherwise. | [
"Returns",
"a",
"uuid",
"value",
"that",
"is",
"valid",
"to",
"use",
"for",
"id",
"and",
"identity",
"fields",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L737-L754 | train |
swisscom/cleanerversion | versions/models.py | Versionable.restore | def restore(self, **kwargs):
"""
Restores this version as a new version, and returns this new version.
If a current version already exists, it will be terminated before
restoring this version.
Relations (foreign key, reverse foreign key, many-to-many) are not
restored w... | python | def restore(self, **kwargs):
"""
Restores this version as a new version, and returns this new version.
If a current version already exists, it will be terminated before
restoring this version.
Relations (foreign key, reverse foreign key, many-to-many) are not
restored w... | [
"def",
"restore",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"pk",
":",
"raise",
"ValueError",
"(",
"'Instance must be saved and terminated before it can be '",
"'restored.'",
")",
"if",
"self",
".",
"is_current",
":",
"raise",
"... | Restores this version as a new version, and returns this new version.
If a current version already exists, it will be terminated before
restoring this version.
Relations (foreign key, reverse foreign key, many-to-many) are not
restored with the old version. If provided in kwargs,
... | [
"Restores",
"this",
"version",
"as",
"a",
"new",
"version",
"and",
"returns",
"this",
"new",
"version",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L908-L1002 | train |
swisscom/cleanerversion | versions/models.py | Versionable.detach | def detach(self):
"""
Detaches the instance from its history.
Similar to creating a new object with the same field values. The id and
identity fields are set to a new value. The returned object has not
been saved, call save() afterwards when you are ready to persist the
... | python | def detach(self):
"""
Detaches the instance from its history.
Similar to creating a new object with the same field values. The id and
identity fields are set to a new value. The returned object has not
been saved, call save() afterwards when you are ready to persist the
... | [
"def",
"detach",
"(",
"self",
")",
":",
"self",
".",
"id",
"=",
"self",
".",
"identity",
"=",
"self",
".",
"uuid",
"(",
")",
"self",
".",
"version_start_date",
"=",
"self",
".",
"version_birth_date",
"=",
"get_utc_now",
"(",
")",
"self",
".",
"version_... | Detaches the instance from its history.
Similar to creating a new object with the same field values. The id and
identity fields are set to a new value. The returned object has not
been saved, call save() afterwards when you are ready to persist the
object.
ManyToMany and revers... | [
"Detaches",
"the",
"instance",
"from",
"its",
"history",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L1013-L1030 | train |
swisscom/cleanerversion | versions/models.py | Versionable.matches_querytime | def matches_querytime(instance, querytime):
"""
Checks whether the given instance satisfies the given QueryTime object.
:param instance: an instance of Versionable
:param querytime: QueryTime value to check against
"""
if not querytime.active:
return True
... | python | def matches_querytime(instance, querytime):
"""
Checks whether the given instance satisfies the given QueryTime object.
:param instance: an instance of Versionable
:param querytime: QueryTime value to check against
"""
if not querytime.active:
return True
... | [
"def",
"matches_querytime",
"(",
"instance",
",",
"querytime",
")",
":",
"if",
"not",
"querytime",
".",
"active",
":",
"return",
"True",
"if",
"not",
"querytime",
".",
"time",
":",
"return",
"instance",
".",
"version_end_date",
"is",
"None",
"return",
"(",
... | Checks whether the given instance satisfies the given QueryTime object.
:param instance: an instance of Versionable
:param querytime: QueryTime value to check against | [
"Checks",
"whether",
"the",
"given",
"instance",
"satisfies",
"the",
"given",
"QueryTime",
"object",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L1033-L1048 | train |
swisscom/cleanerversion | versions/fields.py | VersionedForeignKey.contribute_to_related_class | def contribute_to_related_class(self, cls, related):
"""
Override ForeignKey's methods, and replace the descriptor, if set by
the parent's methods
"""
# Internal FK's - i.e., those with a related name ending with '+' -
# and swapped models don't get a related descriptor.
... | python | def contribute_to_related_class(self, cls, related):
"""
Override ForeignKey's methods, and replace the descriptor, if set by
the parent's methods
"""
# Internal FK's - i.e., those with a related name ending with '+' -
# and swapped models don't get a related descriptor.
... | [
"def",
"contribute_to_related_class",
"(",
"self",
",",
"cls",
",",
"related",
")",
":",
"# Internal FK's - i.e., those with a related name ending with '+' -",
"# and swapped models don't get a related descriptor.",
"super",
"(",
"VersionedForeignKey",
",",
"self",
")",
".",
"c... | Override ForeignKey's methods, and replace the descriptor, if set by
the parent's methods | [
"Override",
"ForeignKey",
"s",
"methods",
"and",
"replace",
"the",
"descriptor",
"if",
"set",
"by",
"the",
"parent",
"s",
"methods"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/fields.py#L32-L44 | train |
swisscom/cleanerversion | versions/fields.py | VersionedForeignKey.get_joining_columns | def get_joining_columns(self, reverse_join=False):
"""
Get and return joining columns defined by this foreign key relationship
:return: A tuple containing the column names of the tables to be
joined (<local_col_name>, <remote_col_name>)
:rtype: tuple
"""
sour... | python | def get_joining_columns(self, reverse_join=False):
"""
Get and return joining columns defined by this foreign key relationship
:return: A tuple containing the column names of the tables to be
joined (<local_col_name>, <remote_col_name>)
:rtype: tuple
"""
sour... | [
"def",
"get_joining_columns",
"(",
"self",
",",
"reverse_join",
"=",
"False",
")",
":",
"source",
"=",
"self",
".",
"reverse_related_fields",
"if",
"reverse_join",
"else",
"self",
".",
"related_fields",
"joining_columns",
"=",
"tuple",
"(",
")",
"for",
"lhs_fiel... | Get and return joining columns defined by this foreign key relationship
:return: A tuple containing the column names of the tables to be
joined (<local_col_name>, <remote_col_name>)
:rtype: tuple | [
"Get",
"and",
"return",
"joining",
"columns",
"defined",
"by",
"this",
"foreign",
"key",
"relationship"
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/fields.py#L65-L90 | train |
swisscom/cleanerversion | versions/settings.py | get_versioned_delete_collector_class | def get_versioned_delete_collector_class():
"""
Gets the class to use for deletion collection.
:return: class
"""
key = 'VERSIONED_DELETE_COLLECTOR'
try:
cls = _cache[key]
except KeyError:
collector_class_string = getattr(settings, key)
cls = import_from_string(colle... | python | def get_versioned_delete_collector_class():
"""
Gets the class to use for deletion collection.
:return: class
"""
key = 'VERSIONED_DELETE_COLLECTOR'
try:
cls = _cache[key]
except KeyError:
collector_class_string = getattr(settings, key)
cls = import_from_string(colle... | [
"def",
"get_versioned_delete_collector_class",
"(",
")",
":",
"key",
"=",
"'VERSIONED_DELETE_COLLECTOR'",
"try",
":",
"cls",
"=",
"_cache",
"[",
"key",
"]",
"except",
"KeyError",
":",
"collector_class_string",
"=",
"getattr",
"(",
"settings",
",",
"key",
")",
"c... | Gets the class to use for deletion collection.
:return: class | [
"Gets",
"the",
"class",
"to",
"use",
"for",
"deletion",
"collection",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/settings.py#L57-L70 | train |
swisscom/cleanerversion | versions/deletion.py | VersionedCollector.related_objects | def related_objects(self, related, objs):
"""
Gets a QuerySet of current objects related to ``objs`` via the
relation ``related``.
"""
from versions.models import Versionable
related_model = related.related_model
if issubclass(related_model, Versionable):
... | python | def related_objects(self, related, objs):
"""
Gets a QuerySet of current objects related to ``objs`` via the
relation ``related``.
"""
from versions.models import Versionable
related_model = related.related_model
if issubclass(related_model, Versionable):
... | [
"def",
"related_objects",
"(",
"self",
",",
"related",
",",
"objs",
")",
":",
"from",
"versions",
".",
"models",
"import",
"Versionable",
"related_model",
"=",
"related",
".",
"related_model",
"if",
"issubclass",
"(",
"related_model",
",",
"Versionable",
")",
... | Gets a QuerySet of current objects related to ``objs`` via the
relation ``related``. | [
"Gets",
"a",
"QuerySet",
"of",
"current",
"objects",
"related",
"to",
"objs",
"via",
"the",
"relation",
"related",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/deletion.py#L149-L163 | train |
swisscom/cleanerversion | versions/deletion.py | VersionedCollector.versionable_delete | def versionable_delete(self, instance, timestamp):
"""
Soft-deletes the instance, setting it's version_end_date to timestamp.
Override this method to implement custom behaviour.
:param Versionable instance:
:param datetime timestamp:
"""
instance._delete_at(time... | python | def versionable_delete(self, instance, timestamp):
"""
Soft-deletes the instance, setting it's version_end_date to timestamp.
Override this method to implement custom behaviour.
:param Versionable instance:
:param datetime timestamp:
"""
instance._delete_at(time... | [
"def",
"versionable_delete",
"(",
"self",
",",
"instance",
",",
"timestamp",
")",
":",
"instance",
".",
"_delete_at",
"(",
"timestamp",
",",
"using",
"=",
"self",
".",
"using",
")"
] | Soft-deletes the instance, setting it's version_end_date to timestamp.
Override this method to implement custom behaviour.
:param Versionable instance:
:param datetime timestamp: | [
"Soft",
"-",
"deletes",
"the",
"instance",
"setting",
"it",
"s",
"version_end_date",
"to",
"timestamp",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/deletion.py#L185-L194 | train |
swisscom/cleanerversion | versions/descriptors.py | VersionedManyToManyDescriptor.pks_from_objects | def pks_from_objects(self, objects):
"""
Extract all the primary key strings from the given objects.
Objects may be Versionables, or bare primary keys.
:rtype : set
"""
return {o.pk if isinstance(o, Model) else o for o in objects} | python | def pks_from_objects(self, objects):
"""
Extract all the primary key strings from the given objects.
Objects may be Versionables, or bare primary keys.
:rtype : set
"""
return {o.pk if isinstance(o, Model) else o for o in objects} | [
"def",
"pks_from_objects",
"(",
"self",
",",
"objects",
")",
":",
"return",
"{",
"o",
".",
"pk",
"if",
"isinstance",
"(",
"o",
",",
"Model",
")",
"else",
"o",
"for",
"o",
"in",
"objects",
"}"
] | Extract all the primary key strings from the given objects.
Objects may be Versionables, or bare primary keys.
:rtype : set | [
"Extract",
"all",
"the",
"primary",
"key",
"strings",
"from",
"the",
"given",
"objects",
".",
"Objects",
"may",
"be",
"Versionables",
"or",
"bare",
"primary",
"keys",
"."
] | becadbab5d7b474a0e9a596b99e97682402d2f2c | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/descriptors.py#L395-L402 | train |
matsui528/nanopq | nanopq/pq.py | PQ.fit | def fit(self, vecs, iter=20, seed=123):
"""Given training vectors, run k-means for each sub-space and create
codewords for each sub-space.
This function should be run once first of all.
Args:
vecs (np.ndarray): Training vectors with shape=(N, D) and dtype=np.float32.
... | python | def fit(self, vecs, iter=20, seed=123):
"""Given training vectors, run k-means for each sub-space and create
codewords for each sub-space.
This function should be run once first of all.
Args:
vecs (np.ndarray): Training vectors with shape=(N, D) and dtype=np.float32.
... | [
"def",
"fit",
"(",
"self",
",",
"vecs",
",",
"iter",
"=",
"20",
",",
"seed",
"=",
"123",
")",
":",
"assert",
"vecs",
".",
"dtype",
"==",
"np",
".",
"float32",
"assert",
"vecs",
".",
"ndim",
"==",
"2",
"N",
",",
"D",
"=",
"vecs",
".",
"shape",
... | Given training vectors, run k-means for each sub-space and create
codewords for each sub-space.
This function should be run once first of all.
Args:
vecs (np.ndarray): Training vectors with shape=(N, D) and dtype=np.float32.
iter (int): The number of iteration for k-mea... | [
"Given",
"training",
"vectors",
"run",
"k",
"-",
"means",
"for",
"each",
"sub",
"-",
"space",
"and",
"create",
"codewords",
"for",
"each",
"sub",
"-",
"space",
"."
] | 1ce68cad2e3cab62b409e6dd63f676ed7b443ee9 | https://github.com/matsui528/nanopq/blob/1ce68cad2e3cab62b409e6dd63f676ed7b443ee9/nanopq/pq.py#L53-L87 | train |
matsui528/nanopq | nanopq/pq.py | PQ.encode | def encode(self, vecs):
"""Encode input vectors into PQ-codes.
Args:
vecs (np.ndarray): Input vectors with shape=(N, D) and dtype=np.float32.
Returns:
np.ndarray: PQ codes with shape=(N, M) and dtype=self.code_dtype
"""
assert vecs.dtype == np.float32
... | python | def encode(self, vecs):
"""Encode input vectors into PQ-codes.
Args:
vecs (np.ndarray): Input vectors with shape=(N, D) and dtype=np.float32.
Returns:
np.ndarray: PQ codes with shape=(N, M) and dtype=self.code_dtype
"""
assert vecs.dtype == np.float32
... | [
"def",
"encode",
"(",
"self",
",",
"vecs",
")",
":",
"assert",
"vecs",
".",
"dtype",
"==",
"np",
".",
"float32",
"assert",
"vecs",
".",
"ndim",
"==",
"2",
"N",
",",
"D",
"=",
"vecs",
".",
"shape",
"assert",
"D",
"==",
"self",
".",
"Ds",
"*",
"s... | Encode input vectors into PQ-codes.
Args:
vecs (np.ndarray): Input vectors with shape=(N, D) and dtype=np.float32.
Returns:
np.ndarray: PQ codes with shape=(N, M) and dtype=self.code_dtype | [
"Encode",
"input",
"vectors",
"into",
"PQ",
"-",
"codes",
"."
] | 1ce68cad2e3cab62b409e6dd63f676ed7b443ee9 | https://github.com/matsui528/nanopq/blob/1ce68cad2e3cab62b409e6dd63f676ed7b443ee9/nanopq/pq.py#L89-L112 | train |
matsui528/nanopq | nanopq/pq.py | PQ.decode | def decode(self, codes):
"""Given PQ-codes, reconstruct original D-dimensional vectors
approximately by fetching the codewords.
Args:
codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype.
Each row is a PQ-code
Returns:
np.ndar... | python | def decode(self, codes):
"""Given PQ-codes, reconstruct original D-dimensional vectors
approximately by fetching the codewords.
Args:
codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype.
Each row is a PQ-code
Returns:
np.ndar... | [
"def",
"decode",
"(",
"self",
",",
"codes",
")",
":",
"assert",
"codes",
".",
"ndim",
"==",
"2",
"N",
",",
"M",
"=",
"codes",
".",
"shape",
"assert",
"M",
"==",
"self",
".",
"M",
"assert",
"codes",
".",
"dtype",
"==",
"self",
".",
"code_dtype",
"... | Given PQ-codes, reconstruct original D-dimensional vectors
approximately by fetching the codewords.
Args:
codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype.
Each row is a PQ-code
Returns:
np.ndarray: Reconstructed vectors with shap... | [
"Given",
"PQ",
"-",
"codes",
"reconstruct",
"original",
"D",
"-",
"dimensional",
"vectors",
"approximately",
"by",
"fetching",
"the",
"codewords",
"."
] | 1ce68cad2e3cab62b409e6dd63f676ed7b443ee9 | https://github.com/matsui528/nanopq/blob/1ce68cad2e3cab62b409e6dd63f676ed7b443ee9/nanopq/pq.py#L114-L135 | train |
stephenmcd/hot-redis | hot_redis/client.py | transaction | def transaction():
"""
Swaps out the current client with a pipeline instance,
so that each Redis method call inside the context will be
pipelined. Once the context is exited, we execute the pipeline.
"""
client = default_client()
_thread.client = client.pipeline()
try:
yield
... | python | def transaction():
"""
Swaps out the current client with a pipeline instance,
so that each Redis method call inside the context will be
pipelined. Once the context is exited, we execute the pipeline.
"""
client = default_client()
_thread.client = client.pipeline()
try:
yield
... | [
"def",
"transaction",
"(",
")",
":",
"client",
"=",
"default_client",
"(",
")",
"_thread",
".",
"client",
"=",
"client",
".",
"pipeline",
"(",
")",
"try",
":",
"yield",
"_thread",
".",
"client",
".",
"execute",
"(",
")",
"finally",
":",
"_thread",
".",... | Swaps out the current client with a pipeline instance,
so that each Redis method call inside the context will be
pipelined. Once the context is exited, we execute the pipeline. | [
"Swaps",
"out",
"the",
"current",
"client",
"with",
"a",
"pipeline",
"instance",
"so",
"that",
"each",
"Redis",
"method",
"call",
"inside",
"the",
"context",
"will",
"be",
"pipelined",
".",
"Once",
"the",
"context",
"is",
"exited",
"we",
"execute",
"the",
... | 6b0cf260c775fd98c44b6703030d33004dabf67d | https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/client.py#L78-L90 | train |
stephenmcd/hot-redis | hot_redis/client.py | HotClient._get_lua_path | def _get_lua_path(self, name):
"""
Joins the given name with the relative path of the module.
"""
parts = (os.path.dirname(os.path.abspath(__file__)), "lua", name)
return os.path.join(*parts) | python | def _get_lua_path(self, name):
"""
Joins the given name with the relative path of the module.
"""
parts = (os.path.dirname(os.path.abspath(__file__)), "lua", name)
return os.path.join(*parts) | [
"def",
"_get_lua_path",
"(",
"self",
",",
"name",
")",
":",
"parts",
"=",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
",",
"\"lua\"",
",",
"name",
")",
"return",
"os",
".",
"path",
".... | Joins the given name with the relative path of the module. | [
"Joins",
"the",
"given",
"name",
"with",
"the",
"relative",
"path",
"of",
"the",
"module",
"."
] | 6b0cf260c775fd98c44b6703030d33004dabf67d | https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/client.py#L27-L32 | train |
stephenmcd/hot-redis | hot_redis/client.py | HotClient._create_lua_method | def _create_lua_method(self, name, code):
"""
Registers the code snippet as a Lua script, and binds the
script to the client as a method that can be called with
the same signature as regular client methods, eg with a
single key arg.
"""
script = self.register_scri... | python | def _create_lua_method(self, name, code):
"""
Registers the code snippet as a Lua script, and binds the
script to the client as a method that can be called with
the same signature as regular client methods, eg with a
single key arg.
"""
script = self.register_scri... | [
"def",
"_create_lua_method",
"(",
"self",
",",
"name",
",",
"code",
")",
":",
"script",
"=",
"self",
".",
"register_script",
"(",
"code",
")",
"setattr",
"(",
"script",
",",
"\"name\"",
",",
"name",
")",
"# Helps debugging redis lib.",
"method",
"=",
"lambda... | Registers the code snippet as a Lua script, and binds the
script to the client as a method that can be called with
the same signature as regular client methods, eg with a
single key arg. | [
"Registers",
"the",
"code",
"snippet",
"as",
"a",
"Lua",
"script",
"and",
"binds",
"the",
"script",
"to",
"the",
"client",
"as",
"a",
"method",
"that",
"can",
"be",
"called",
"with",
"the",
"same",
"signature",
"as",
"regular",
"client",
"methods",
"eg",
... | 6b0cf260c775fd98c44b6703030d33004dabf67d | https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/client.py#L47-L57 | train |
stephenmcd/hot-redis | hot_redis/types.py | value_left | def value_left(self, other):
"""
Returns the value of the other type instance to use in an
operator method, namely when the method's instance is on the
left side of the expression.
"""
return other.value if isinstance(other, self.__class__) else other | python | def value_left(self, other):
"""
Returns the value of the other type instance to use in an
operator method, namely when the method's instance is on the
left side of the expression.
"""
return other.value if isinstance(other, self.__class__) else other | [
"def",
"value_left",
"(",
"self",
",",
"other",
")",
":",
"return",
"other",
".",
"value",
"if",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
"else",
"other"
] | Returns the value of the other type instance to use in an
operator method, namely when the method's instance is on the
left side of the expression. | [
"Returns",
"the",
"value",
"of",
"the",
"other",
"type",
"instance",
"to",
"use",
"in",
"an",
"operator",
"method",
"namely",
"when",
"the",
"method",
"s",
"instance",
"is",
"on",
"the",
"left",
"side",
"of",
"the",
"expression",
"."
] | 6b0cf260c775fd98c44b6703030d33004dabf67d | https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/types.py#L28-L34 | train |
stephenmcd/hot-redis | hot_redis/types.py | value_right | def value_right(self, other):
"""
Returns the value of the type instance calling an to use in an
operator method, namely when the method's instance is on the
right side of the expression.
"""
return self if isinstance(other, self.__class__) else self.value | python | def value_right(self, other):
"""
Returns the value of the type instance calling an to use in an
operator method, namely when the method's instance is on the
right side of the expression.
"""
return self if isinstance(other, self.__class__) else self.value | [
"def",
"value_right",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
"if",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
"else",
"self",
".",
"value"
] | Returns the value of the type instance calling an to use in an
operator method, namely when the method's instance is on the
right side of the expression. | [
"Returns",
"the",
"value",
"of",
"the",
"type",
"instance",
"calling",
"an",
"to",
"use",
"in",
"an",
"operator",
"method",
"namely",
"when",
"the",
"method",
"s",
"instance",
"is",
"on",
"the",
"right",
"side",
"of",
"the",
"expression",
"."
] | 6b0cf260c775fd98c44b6703030d33004dabf67d | https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/types.py#L37-L43 | train |
stephenmcd/hot-redis | hot_redis/types.py | op_left | def op_left(op):
"""
Returns a type instance method for the given operator, applied
when the instance appears on the left side of the expression.
"""
def method(self, other):
return op(self.value, value_left(self, other))
return method | python | def op_left(op):
"""
Returns a type instance method for the given operator, applied
when the instance appears on the left side of the expression.
"""
def method(self, other):
return op(self.value, value_left(self, other))
return method | [
"def",
"op_left",
"(",
"op",
")",
":",
"def",
"method",
"(",
"self",
",",
"other",
")",
":",
"return",
"op",
"(",
"self",
".",
"value",
",",
"value_left",
"(",
"self",
",",
"other",
")",
")",
"return",
"method"
] | Returns a type instance method for the given operator, applied
when the instance appears on the left side of the expression. | [
"Returns",
"a",
"type",
"instance",
"method",
"for",
"the",
"given",
"operator",
"applied",
"when",
"the",
"instance",
"appears",
"on",
"the",
"left",
"side",
"of",
"the",
"expression",
"."
] | 6b0cf260c775fd98c44b6703030d33004dabf67d | https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/types.py#L46-L53 | train |
stephenmcd/hot-redis | hot_redis/types.py | op_right | def op_right(op):
"""
Returns a type instance method for the given operator, applied
when the instance appears on the right side of the expression.
"""
def method(self, other):
return op(value_left(self, other), value_right(self, other))
return method | python | def op_right(op):
"""
Returns a type instance method for the given operator, applied
when the instance appears on the right side of the expression.
"""
def method(self, other):
return op(value_left(self, other), value_right(self, other))
return method | [
"def",
"op_right",
"(",
"op",
")",
":",
"def",
"method",
"(",
"self",
",",
"other",
")",
":",
"return",
"op",
"(",
"value_left",
"(",
"self",
",",
"other",
")",
",",
"value_right",
"(",
"self",
",",
"other",
")",
")",
"return",
"method"
] | Returns a type instance method for the given operator, applied
when the instance appears on the right side of the expression. | [
"Returns",
"a",
"type",
"instance",
"method",
"for",
"the",
"given",
"operator",
"applied",
"when",
"the",
"instance",
"appears",
"on",
"the",
"right",
"side",
"of",
"the",
"expression",
"."
] | 6b0cf260c775fd98c44b6703030d33004dabf67d | https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/types.py#L56-L63 | train |
jfhbrook/pyee | pyee/_base.py | BaseEventEmitter.on | def on(self, event, f=None):
"""Registers the function ``f`` to the event name ``event``.
If ``f`` isn't provided, this method returns a function that
takes ``f`` as a callback; in other words, you can use this method
as a decorator, like so::
@ee.on('data')
def... | python | def on(self, event, f=None):
"""Registers the function ``f`` to the event name ``event``.
If ``f`` isn't provided, this method returns a function that
takes ``f`` as a callback; in other words, you can use this method
as a decorator, like so::
@ee.on('data')
def... | [
"def",
"on",
"(",
"self",
",",
"event",
",",
"f",
"=",
"None",
")",
":",
"def",
"_on",
"(",
"f",
")",
":",
"self",
".",
"_add_event_handler",
"(",
"event",
",",
"f",
",",
"f",
")",
"return",
"f",
"if",
"f",
"is",
"None",
":",
"return",
"_on",
... | Registers the function ``f`` to the event name ``event``.
If ``f`` isn't provided, this method returns a function that
takes ``f`` as a callback; in other words, you can use this method
as a decorator, like so::
@ee.on('data')
def data_handler(data):
pri... | [
"Registers",
"the",
"function",
"f",
"to",
"the",
"event",
"name",
"event",
"."
] | f5896239f421381e8b787c61c6185e33defb0292 | https://github.com/jfhbrook/pyee/blob/f5896239f421381e8b787c61c6185e33defb0292/pyee/_base.py#L42-L65 | train |
jfhbrook/pyee | pyee/_base.py | BaseEventEmitter.once | def once(self, event, f=None):
"""The same as ``ee.on``, except that the listener is automatically
removed after being called.
"""
def _wrapper(f):
def g(*args, **kwargs):
self.remove_listener(event, f)
# f may return a coroutine, so we need to... | python | def once(self, event, f=None):
"""The same as ``ee.on``, except that the listener is automatically
removed after being called.
"""
def _wrapper(f):
def g(*args, **kwargs):
self.remove_listener(event, f)
# f may return a coroutine, so we need to... | [
"def",
"once",
"(",
"self",
",",
"event",
",",
"f",
"=",
"None",
")",
":",
"def",
"_wrapper",
"(",
"f",
")",
":",
"def",
"g",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"remove_listener",
"(",
"event",
",",
"f",
")",
"#... | The same as ``ee.on``, except that the listener is automatically
removed after being called. | [
"The",
"same",
"as",
"ee",
".",
"on",
"except",
"that",
"the",
"listener",
"is",
"automatically",
"removed",
"after",
"being",
"called",
"."
] | f5896239f421381e8b787c61c6185e33defb0292 | https://github.com/jfhbrook/pyee/blob/f5896239f421381e8b787c61c6185e33defb0292/pyee/_base.py#L110-L127 | train |
jfhbrook/pyee | pyee/_base.py | BaseEventEmitter.remove_all_listeners | def remove_all_listeners(self, event=None):
"""Remove all listeners attached to ``event``.
If ``event`` is ``None``, remove all listeners on all events.
"""
if event is not None:
self._events[event] = OrderedDict()
else:
self._events = defaultdict(OrderedD... | python | def remove_all_listeners(self, event=None):
"""Remove all listeners attached to ``event``.
If ``event`` is ``None``, remove all listeners on all events.
"""
if event is not None:
self._events[event] = OrderedDict()
else:
self._events = defaultdict(OrderedD... | [
"def",
"remove_all_listeners",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"if",
"event",
"is",
"not",
"None",
":",
"self",
".",
"_events",
"[",
"event",
"]",
"=",
"OrderedDict",
"(",
")",
"else",
":",
"self",
".",
"_events",
"=",
"defaultdict",
... | Remove all listeners attached to ``event``.
If ``event`` is ``None``, remove all listeners on all events. | [
"Remove",
"all",
"listeners",
"attached",
"to",
"event",
".",
"If",
"event",
"is",
"None",
"remove",
"all",
"listeners",
"on",
"all",
"events",
"."
] | f5896239f421381e8b787c61c6185e33defb0292 | https://github.com/jfhbrook/pyee/blob/f5896239f421381e8b787c61c6185e33defb0292/pyee/_base.py#L133-L140 | train |
scott-griffiths/bitstring | bitstring.py | offsetcopy | def offsetcopy(s, newoffset):
"""Return a copy of a ByteStore with the newoffset.
Not part of public interface.
"""
assert 0 <= newoffset < 8
if not s.bitlength:
return copy.copy(s)
else:
if newoffset == s.offset % 8:
return ByteStore(s.getbyteslice(s.byteoffset, s.b... | python | def offsetcopy(s, newoffset):
"""Return a copy of a ByteStore with the newoffset.
Not part of public interface.
"""
assert 0 <= newoffset < 8
if not s.bitlength:
return copy.copy(s)
else:
if newoffset == s.offset % 8:
return ByteStore(s.getbyteslice(s.byteoffset, s.b... | [
"def",
"offsetcopy",
"(",
"s",
",",
"newoffset",
")",
":",
"assert",
"0",
"<=",
"newoffset",
"<",
"8",
"if",
"not",
"s",
".",
"bitlength",
":",
"return",
"copy",
".",
"copy",
"(",
"s",
")",
"else",
":",
"if",
"newoffset",
"==",
"s",
".",
"offset",
... | Return a copy of a ByteStore with the newoffset.
Not part of public interface. | [
"Return",
"a",
"copy",
"of",
"a",
"ByteStore",
"with",
"the",
"newoffset",
"."
] | ab40ae7f0b43fe223a39b63cbc0529b09f3ef653 | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L248-L287 | train |
scott-griffiths/bitstring | bitstring.py | structparser | def structparser(token):
"""Parse struct-like format string token into sub-token list."""
m = STRUCT_PACK_RE.match(token)
if not m:
return [token]
else:
endian = m.group('endian')
if endian is None:
return [token]
# Split the format string into a list of 'q', ... | python | def structparser(token):
"""Parse struct-like format string token into sub-token list."""
m = STRUCT_PACK_RE.match(token)
if not m:
return [token]
else:
endian = m.group('endian')
if endian is None:
return [token]
# Split the format string into a list of 'q', ... | [
"def",
"structparser",
"(",
"token",
")",
":",
"m",
"=",
"STRUCT_PACK_RE",
".",
"match",
"(",
"token",
")",
"if",
"not",
"m",
":",
"return",
"[",
"token",
"]",
"else",
":",
"endian",
"=",
"m",
".",
"group",
"(",
"'endian'",
")",
"if",
"endian",
"is... | Parse struct-like format string token into sub-token list. | [
"Parse",
"struct",
"-",
"like",
"format",
"string",
"token",
"into",
"sub",
"-",
"token",
"list",
"."
] | ab40ae7f0b43fe223a39b63cbc0529b09f3ef653 | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L506-L532 | train |
scott-griffiths/bitstring | bitstring.py | tokenparser | def tokenparser(fmt, keys=None, token_cache={}):
"""Divide the format string into tokens and parse them.
Return stretchy token and list of [initialiser, length, value]
initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc.
length is None if not known, as is value.
If the token is... | python | def tokenparser(fmt, keys=None, token_cache={}):
"""Divide the format string into tokens and parse them.
Return stretchy token and list of [initialiser, length, value]
initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc.
length is None if not known, as is value.
If the token is... | [
"def",
"tokenparser",
"(",
"fmt",
",",
"keys",
"=",
"None",
",",
"token_cache",
"=",
"{",
"}",
")",
":",
"try",
":",
"return",
"token_cache",
"[",
"(",
"fmt",
",",
"keys",
")",
"]",
"except",
"KeyError",
":",
"token_key",
"=",
"(",
"fmt",
",",
"key... | Divide the format string into tokens and parse them.
Return stretchy token and list of [initialiser, length, value]
initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc.
length is None if not known, as is value.
If the token is in the keyword dictionary (keys) then it counts as a
... | [
"Divide",
"the",
"format",
"string",
"into",
"tokens",
"and",
"parse",
"them",
"."
] | ab40ae7f0b43fe223a39b63cbc0529b09f3ef653 | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L534-L633 | train |
scott-griffiths/bitstring | bitstring.py | expand_brackets | def expand_brackets(s):
"""Remove whitespace and expand all brackets."""
s = ''.join(s.split())
while True:
start = s.find('(')
if start == -1:
break
count = 1 # Number of hanging open brackets
p = start + 1
while p < len(s):
if s[p] == '(':
... | python | def expand_brackets(s):
"""Remove whitespace and expand all brackets."""
s = ''.join(s.split())
while True:
start = s.find('(')
if start == -1:
break
count = 1 # Number of hanging open brackets
p = start + 1
while p < len(s):
if s[p] == '(':
... | [
"def",
"expand_brackets",
"(",
"s",
")",
":",
"s",
"=",
"''",
".",
"join",
"(",
"s",
".",
"split",
"(",
")",
")",
"while",
"True",
":",
"start",
"=",
"s",
".",
"find",
"(",
"'('",
")",
"if",
"start",
"==",
"-",
"1",
":",
"break",
"count",
"="... | Remove whitespace and expand all brackets. | [
"Remove",
"whitespace",
"and",
"expand",
"all",
"brackets",
"."
] | ab40ae7f0b43fe223a39b63cbc0529b09f3ef653 | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L638-L667 | train |
scott-griffiths/bitstring | bitstring.py | pack | def pack(fmt, *values, **kwargs):
"""Pack the values according to the format string and return a new BitStream.
fmt -- A single string or a list of strings with comma separated tokens
describing how to create the BitStream.
values -- Zero or more values to pack according to the format.
kwarg... | python | def pack(fmt, *values, **kwargs):
"""Pack the values according to the format string and return a new BitStream.
fmt -- A single string or a list of strings with comma separated tokens
describing how to create the BitStream.
values -- Zero or more values to pack according to the format.
kwarg... | [
"def",
"pack",
"(",
"fmt",
",",
"*",
"values",
",",
"*",
"*",
"kwargs",
")",
":",
"tokens",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"fmt",
",",
"basestring",
")",
":",
"fmt",
"=",
"[",
"fmt",
"]",
"try",
":",
"for",
"f_item",
"in",
"fmt",
":",
... | Pack the values according to the format string and return a new BitStream.
fmt -- A single string or a list of strings with comma separated tokens
describing how to create the BitStream.
values -- Zero or more values to pack according to the format.
kwargs -- A dictionary or keyword-value pairs ... | [
"Pack",
"the",
"values",
"according",
"to",
"the",
"format",
"string",
"and",
"return",
"a",
"new",
"BitStream",
"."
] | ab40ae7f0b43fe223a39b63cbc0529b09f3ef653 | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L4161-L4233 | train |
scott-griffiths/bitstring | bitstring.py | ConstByteStore.getbyteslice | def getbyteslice(self, start, end):
"""Direct access to byte data."""
c = self._rawarray[start:end]
return c | python | def getbyteslice(self, start, end):
"""Direct access to byte data."""
c = self._rawarray[start:end]
return c | [
"def",
"getbyteslice",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"c",
"=",
"self",
".",
"_rawarray",
"[",
"start",
":",
"end",
"]",
"return",
"c"
] | Direct access to byte data. | [
"Direct",
"access",
"to",
"byte",
"data",
"."
] | ab40ae7f0b43fe223a39b63cbc0529b09f3ef653 | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L157-L160 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.