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 |
---|---|---|---|---|---|---|---|---|---|---|---|
sprockets/sprockets-influxdb | sprockets_influxdb.py | _write_measurements | def _write_measurements():
"""Write out all of the metrics in each of the databases,
returning a future that will indicate all metrics have been written
when that future is done.
:rtype: tornado.concurrent.Future
"""
global _timeout, _writing
future = concurrent.Future()
if _writing:
LOGGER.warning('Currently writing measurements, skipping write')
future.set_result(False)
elif not _pending_measurements():
future.set_result(True)
elif not _sample_batch():
LOGGER.debug('Skipping batch submission due to sampling')
future.set_result(True)
# Exit early if there's an error condition
if future.done():
return future
if not _http_client or _dirty:
_create_http_client()
# Keep track of the futures for each batch submission
futures = []
# Submit a batch for each database
for database in _measurements:
url = '{}?db={}&precision=ms'.format(_base_url, database)
# Get the measurements to submit
measurements = _measurements[database][:_max_batch_size]
# Pop them off the stack of pending measurements
_measurements[database] = _measurements[database][_max_batch_size:]
# Create the request future
LOGGER.debug('Submitting %r measurements to %r',
len(measurements), url)
request = _http_client.fetch(
url, method='POST', body='\n'.join(measurements).encode('utf-8'))
# Keep track of each request in our future stack
futures.append((request, str(uuid.uuid4()), database, measurements))
# Start the wait cycle for all the requests to complete
_writing = True
_futures_wait(future, futures)
return future | python | def _write_measurements():
"""Write out all of the metrics in each of the databases,
returning a future that will indicate all metrics have been written
when that future is done.
:rtype: tornado.concurrent.Future
"""
global _timeout, _writing
future = concurrent.Future()
if _writing:
LOGGER.warning('Currently writing measurements, skipping write')
future.set_result(False)
elif not _pending_measurements():
future.set_result(True)
elif not _sample_batch():
LOGGER.debug('Skipping batch submission due to sampling')
future.set_result(True)
# Exit early if there's an error condition
if future.done():
return future
if not _http_client or _dirty:
_create_http_client()
# Keep track of the futures for each batch submission
futures = []
# Submit a batch for each database
for database in _measurements:
url = '{}?db={}&precision=ms'.format(_base_url, database)
# Get the measurements to submit
measurements = _measurements[database][:_max_batch_size]
# Pop them off the stack of pending measurements
_measurements[database] = _measurements[database][_max_batch_size:]
# Create the request future
LOGGER.debug('Submitting %r measurements to %r',
len(measurements), url)
request = _http_client.fetch(
url, method='POST', body='\n'.join(measurements).encode('utf-8'))
# Keep track of each request in our future stack
futures.append((request, str(uuid.uuid4()), database, measurements))
# Start the wait cycle for all the requests to complete
_writing = True
_futures_wait(future, futures)
return future | [
"def",
"_write_measurements",
"(",
")",
":",
"global",
"_timeout",
",",
"_writing",
"future",
"=",
"concurrent",
".",
"Future",
"(",
")",
"if",
"_writing",
":",
"LOGGER",
".",
"warning",
"(",
"'Currently writing measurements, skipping write'",
")",
"future",
".",
"set_result",
"(",
"False",
")",
"elif",
"not",
"_pending_measurements",
"(",
")",
":",
"future",
".",
"set_result",
"(",
"True",
")",
"elif",
"not",
"_sample_batch",
"(",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Skipping batch submission due to sampling'",
")",
"future",
".",
"set_result",
"(",
"True",
")",
"# Exit early if there's an error condition",
"if",
"future",
".",
"done",
"(",
")",
":",
"return",
"future",
"if",
"not",
"_http_client",
"or",
"_dirty",
":",
"_create_http_client",
"(",
")",
"# Keep track of the futures for each batch submission",
"futures",
"=",
"[",
"]",
"# Submit a batch for each database",
"for",
"database",
"in",
"_measurements",
":",
"url",
"=",
"'{}?db={}&precision=ms'",
".",
"format",
"(",
"_base_url",
",",
"database",
")",
"# Get the measurements to submit",
"measurements",
"=",
"_measurements",
"[",
"database",
"]",
"[",
":",
"_max_batch_size",
"]",
"# Pop them off the stack of pending measurements",
"_measurements",
"[",
"database",
"]",
"=",
"_measurements",
"[",
"database",
"]",
"[",
"_max_batch_size",
":",
"]",
"# Create the request future",
"LOGGER",
".",
"debug",
"(",
"'Submitting %r measurements to %r'",
",",
"len",
"(",
"measurements",
")",
",",
"url",
")",
"request",
"=",
"_http_client",
".",
"fetch",
"(",
"url",
",",
"method",
"=",
"'POST'",
",",
"body",
"=",
"'\\n'",
".",
"join",
"(",
"measurements",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"# Keep track of each request in our future stack",
"futures",
".",
"append",
"(",
"(",
"request",
",",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
",",
"database",
",",
"measurements",
")",
")",
"# Start the wait cycle for all the requests to complete",
"_writing",
"=",
"True",
"_futures_wait",
"(",
"future",
",",
"futures",
")",
"return",
"future"
] | Write out all of the metrics in each of the databases,
returning a future that will indicate all metrics have been written
when that future is done.
:rtype: tornado.concurrent.Future | [
"Write",
"out",
"all",
"of",
"the",
"metrics",
"in",
"each",
"of",
"the",
"databases",
"returning",
"a",
"future",
"that",
"will",
"indicate",
"all",
"metrics",
"have",
"been",
"written",
"when",
"that",
"future",
"is",
"done",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L670-L724 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | Measurement.duration | def duration(self, name):
"""Record the time it takes to run an arbitrary code block.
:param str name: The field name to record the timing in
This method returns a context manager that records the amount
of time spent inside of the context, adding the timing to the
measurement.
"""
start = time.time()
try:
yield
finally:
self.set_field(name, max(time.time(), start) - start) | python | def duration(self, name):
"""Record the time it takes to run an arbitrary code block.
:param str name: The field name to record the timing in
This method returns a context manager that records the amount
of time spent inside of the context, adding the timing to the
measurement.
"""
start = time.time()
try:
yield
finally:
self.set_field(name, max(time.time(), start) - start) | [
"def",
"duration",
"(",
"self",
",",
"name",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
"yield",
"finally",
":",
"self",
".",
"set_field",
"(",
"name",
",",
"max",
"(",
"time",
".",
"time",
"(",
")",
",",
"start",
")",
"-",
"start",
")"
] | Record the time it takes to run an arbitrary code block.
:param str name: The field name to record the timing in
This method returns a context manager that records the amount
of time spent inside of the context, adding the timing to the
measurement. | [
"Record",
"the",
"time",
"it",
"takes",
"to",
"run",
"an",
"arbitrary",
"code",
"block",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L842-L856 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | Measurement.marshall | def marshall(self):
"""Return the measurement in the line protocol format.
:rtype: str
"""
return '{},{} {} {}'.format(
self._escape(self.name),
','.join(['{}={}'.format(self._escape(k), self._escape(v))
for k, v in self.tags.items()]),
self._marshall_fields(),
int(self.timestamp * 1000)) | python | def marshall(self):
"""Return the measurement in the line protocol format.
:rtype: str
"""
return '{},{} {} {}'.format(
self._escape(self.name),
','.join(['{}={}'.format(self._escape(k), self._escape(v))
for k, v in self.tags.items()]),
self._marshall_fields(),
int(self.timestamp * 1000)) | [
"def",
"marshall",
"(",
"self",
")",
":",
"return",
"'{},{} {} {}'",
".",
"format",
"(",
"self",
".",
"_escape",
"(",
"self",
".",
"name",
")",
",",
"','",
".",
"join",
"(",
"[",
"'{}={}'",
".",
"format",
"(",
"self",
".",
"_escape",
"(",
"k",
")",
",",
"self",
".",
"_escape",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"tags",
".",
"items",
"(",
")",
"]",
")",
",",
"self",
".",
"_marshall_fields",
"(",
")",
",",
"int",
"(",
"self",
".",
"timestamp",
"*",
"1000",
")",
")"
] | Return the measurement in the line protocol format.
:rtype: str | [
"Return",
"the",
"measurement",
"in",
"the",
"line",
"protocol",
"format",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L858-L869 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | Measurement.set_field | def set_field(self, name, value):
"""Set the value of a field in the measurement.
:param str name: The name of the field to set the value for
:param int|float|bool|str value: The value of the field
:raises: ValueError
"""
if not any([isinstance(value, t) for t in {int, float, bool, str}]):
LOGGER.debug('Invalid field value: %r', value)
raise ValueError('Value must be a str, bool, integer, or float')
self.fields[name] = value | python | def set_field(self, name, value):
"""Set the value of a field in the measurement.
:param str name: The name of the field to set the value for
:param int|float|bool|str value: The value of the field
:raises: ValueError
"""
if not any([isinstance(value, t) for t in {int, float, bool, str}]):
LOGGER.debug('Invalid field value: %r', value)
raise ValueError('Value must be a str, bool, integer, or float')
self.fields[name] = value | [
"def",
"set_field",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"any",
"(",
"[",
"isinstance",
"(",
"value",
",",
"t",
")",
"for",
"t",
"in",
"{",
"int",
",",
"float",
",",
"bool",
",",
"str",
"}",
"]",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Invalid field value: %r'",
",",
"value",
")",
"raise",
"ValueError",
"(",
"'Value must be a str, bool, integer, or float'",
")",
"self",
".",
"fields",
"[",
"name",
"]",
"=",
"value"
] | Set the value of a field in the measurement.
:param str name: The name of the field to set the value for
:param int|float|bool|str value: The value of the field
:raises: ValueError | [
"Set",
"the",
"value",
"of",
"a",
"field",
"in",
"the",
"measurement",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L871-L882 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | Measurement.set_tags | def set_tags(self, tags):
"""Set multiple tags for the measurement.
:param dict tags: Tag key/value pairs to assign
This will overwrite the current value assigned to a tag
if one exists with the same name.
"""
for key, value in tags.items():
self.set_tag(key, value) | python | def set_tags(self, tags):
"""Set multiple tags for the measurement.
:param dict tags: Tag key/value pairs to assign
This will overwrite the current value assigned to a tag
if one exists with the same name.
"""
for key, value in tags.items():
self.set_tag(key, value) | [
"def",
"set_tags",
"(",
"self",
",",
"tags",
")",
":",
"for",
"key",
",",
"value",
"in",
"tags",
".",
"items",
"(",
")",
":",
"self",
".",
"set_tag",
"(",
"key",
",",
"value",
")"
] | Set multiple tags for the measurement.
:param dict tags: Tag key/value pairs to assign
This will overwrite the current value assigned to a tag
if one exists with the same name. | [
"Set",
"multiple",
"tags",
"for",
"the",
"measurement",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L896-L906 | train |
bearyinnovative/bearychat.py | bearychat/rtm_message.py | RTMMessage.reply | def reply(self, text):
"""Replys a text message
Args:
text(str): message content
Returns:
RTMMessage
"""
data = {'text': text, 'vchannel_id': self['vchannel_id']}
if self.is_p2p():
data['type'] = RTMMessageType.P2PMessage
data['to_uid'] = self['uid']
else:
data['type'] = RTMMessageType.ChannelMessage
data['channel_id'] = self['channel_id']
return RTMMessage(data) | python | def reply(self, text):
"""Replys a text message
Args:
text(str): message content
Returns:
RTMMessage
"""
data = {'text': text, 'vchannel_id': self['vchannel_id']}
if self.is_p2p():
data['type'] = RTMMessageType.P2PMessage
data['to_uid'] = self['uid']
else:
data['type'] = RTMMessageType.ChannelMessage
data['channel_id'] = self['channel_id']
return RTMMessage(data) | [
"def",
"reply",
"(",
"self",
",",
"text",
")",
":",
"data",
"=",
"{",
"'text'",
":",
"text",
",",
"'vchannel_id'",
":",
"self",
"[",
"'vchannel_id'",
"]",
"}",
"if",
"self",
".",
"is_p2p",
"(",
")",
":",
"data",
"[",
"'type'",
"]",
"=",
"RTMMessageType",
".",
"P2PMessage",
"data",
"[",
"'to_uid'",
"]",
"=",
"self",
"[",
"'uid'",
"]",
"else",
":",
"data",
"[",
"'type'",
"]",
"=",
"RTMMessageType",
".",
"ChannelMessage",
"data",
"[",
"'channel_id'",
"]",
"=",
"self",
"[",
"'channel_id'",
"]",
"return",
"RTMMessage",
"(",
"data",
")"
] | Replys a text message
Args:
text(str): message content
Returns:
RTMMessage | [
"Replys",
"a",
"text",
"message"
] | 6c7af2d215c2ff7135bb5af66ca333d0ea1089fd | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_message.py#L53-L69 | train |
bearyinnovative/bearychat.py | bearychat/rtm_message.py | RTMMessage.refer | def refer(self, text):
"""Refers current message and replys a new message
Args:
text(str): message content
Returns:
RTMMessage
"""
data = self.reply(text)
data['refer_key'] = self['key']
return data | python | def refer(self, text):
"""Refers current message and replys a new message
Args:
text(str): message content
Returns:
RTMMessage
"""
data = self.reply(text)
data['refer_key'] = self['key']
return data | [
"def",
"refer",
"(",
"self",
",",
"text",
")",
":",
"data",
"=",
"self",
".",
"reply",
"(",
"text",
")",
"data",
"[",
"'refer_key'",
"]",
"=",
"self",
"[",
"'key'",
"]",
"return",
"data"
] | Refers current message and replys a new message
Args:
text(str): message content
Returns:
RTMMessage | [
"Refers",
"current",
"message",
"and",
"replys",
"a",
"new",
"message"
] | 6c7af2d215c2ff7135bb5af66ca333d0ea1089fd | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_message.py#L71-L82 | train |
bitesofcode/projexui | projexui/widgets/xtimerlabel.py | XTimerLabel.increment | def increment(self):
"""
Increments the delta information and refreshes the interface.
"""
if self._starttime is not None:
self._delta = datetime.datetime.now() - self._starttime
else:
self._delta = datetime.timedelta()
self.refresh()
self.ticked.emit() | python | def increment(self):
"""
Increments the delta information and refreshes the interface.
"""
if self._starttime is not None:
self._delta = datetime.datetime.now() - self._starttime
else:
self._delta = datetime.timedelta()
self.refresh()
self.ticked.emit() | [
"def",
"increment",
"(",
"self",
")",
":",
"if",
"self",
".",
"_starttime",
"is",
"not",
"None",
":",
"self",
".",
"_delta",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_starttime",
"else",
":",
"self",
".",
"_delta",
"=",
"datetime",
".",
"timedelta",
"(",
")",
"self",
".",
"refresh",
"(",
")",
"self",
".",
"ticked",
".",
"emit",
"(",
")"
] | Increments the delta information and refreshes the interface. | [
"Increments",
"the",
"delta",
"information",
"and",
"refreshes",
"the",
"interface",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtimerlabel.py#L87-L97 | train |
bitesofcode/projexui | projexui/widgets/xtimerlabel.py | XTimerLabel.refresh | def refresh(self):
"""
Updates the label display with the current timer information.
"""
delta = self.elapsed()
seconds = delta.seconds
limit = self.limit()
options = {}
options['hours'] = self.hours()
options['minutes'] = self.minutes()
options['seconds'] = self.seconds()
try:
text = self.format() % options
except ValueError:
text = '#ERROR'
self.setText(text)
if limit and limit <= seconds:
self.stop()
self.timeout.emit() | python | def refresh(self):
"""
Updates the label display with the current timer information.
"""
delta = self.elapsed()
seconds = delta.seconds
limit = self.limit()
options = {}
options['hours'] = self.hours()
options['minutes'] = self.minutes()
options['seconds'] = self.seconds()
try:
text = self.format() % options
except ValueError:
text = '#ERROR'
self.setText(text)
if limit and limit <= seconds:
self.stop()
self.timeout.emit() | [
"def",
"refresh",
"(",
"self",
")",
":",
"delta",
"=",
"self",
".",
"elapsed",
"(",
")",
"seconds",
"=",
"delta",
".",
"seconds",
"limit",
"=",
"self",
".",
"limit",
"(",
")",
"options",
"=",
"{",
"}",
"options",
"[",
"'hours'",
"]",
"=",
"self",
".",
"hours",
"(",
")",
"options",
"[",
"'minutes'",
"]",
"=",
"self",
".",
"minutes",
"(",
")",
"options",
"[",
"'seconds'",
"]",
"=",
"self",
".",
"seconds",
"(",
")",
"try",
":",
"text",
"=",
"self",
".",
"format",
"(",
")",
"%",
"options",
"except",
"ValueError",
":",
"text",
"=",
"'#ERROR'",
"self",
".",
"setText",
"(",
"text",
")",
"if",
"limit",
"and",
"limit",
"<=",
"seconds",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"timeout",
".",
"emit",
"(",
")"
] | Updates the label display with the current timer information. | [
"Updates",
"the",
"label",
"display",
"with",
"the",
"current",
"timer",
"information",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtimerlabel.py#L132-L154 | train |
bitesofcode/projexui | projexui/widgets/xtimerlabel.py | XTimerLabel.reset | def reset(self):
"""
Stops the timer and resets its values to 0.
"""
self._elapsed = datetime.timedelta()
self._delta = datetime.timedelta()
self._starttime = datetime.datetime.now()
self.refresh() | python | def reset(self):
"""
Stops the timer and resets its values to 0.
"""
self._elapsed = datetime.timedelta()
self._delta = datetime.timedelta()
self._starttime = datetime.datetime.now()
self.refresh() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_elapsed",
"=",
"datetime",
".",
"timedelta",
"(",
")",
"self",
".",
"_delta",
"=",
"datetime",
".",
"timedelta",
"(",
")",
"self",
".",
"_starttime",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"refresh",
"(",
")"
] | Stops the timer and resets its values to 0. | [
"Stops",
"the",
"timer",
"and",
"resets",
"its",
"values",
"to",
"0",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtimerlabel.py#L157-L165 | train |
bitesofcode/projexui | projexui/widgets/xtimerlabel.py | XTimerLabel.stop | def stop(self):
"""
Stops the timer. If the timer is not currently running, then
this method will do nothing.
"""
if not self._timer.isActive():
return
self._elapsed += self._delta
self._timer.stop() | python | def stop(self):
"""
Stops the timer. If the timer is not currently running, then
this method will do nothing.
"""
if not self._timer.isActive():
return
self._elapsed += self._delta
self._timer.stop() | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_timer",
".",
"isActive",
"(",
")",
":",
"return",
"self",
".",
"_elapsed",
"+=",
"self",
".",
"_delta",
"self",
".",
"_timer",
".",
"stop",
"(",
")"
] | Stops the timer. If the timer is not currently running, then
this method will do nothing. | [
"Stops",
"the",
"timer",
".",
"If",
"the",
"timer",
"is",
"not",
"currently",
"running",
"then",
"this",
"method",
"will",
"do",
"nothing",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtimerlabel.py#L237-L246 | train |
bitesofcode/projexui | projexui/xthread.py | XThread.start | def start( self ):
"""
Starts the thread in its own event loop if the local and global thread
options are true, otherwise runs the thread logic in the main event
loop.
"""
if ( self.localThreadingEnabled() and self.globalThreadingEnabled() ):
super(XThread, self).start()
else:
self.run()
self.finished.emit() | python | def start( self ):
"""
Starts the thread in its own event loop if the local and global thread
options are true, otherwise runs the thread logic in the main event
loop.
"""
if ( self.localThreadingEnabled() and self.globalThreadingEnabled() ):
super(XThread, self).start()
else:
self.run()
self.finished.emit() | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"localThreadingEnabled",
"(",
")",
"and",
"self",
".",
"globalThreadingEnabled",
"(",
")",
")",
":",
"super",
"(",
"XThread",
",",
"self",
")",
".",
"start",
"(",
")",
"else",
":",
"self",
".",
"run",
"(",
")",
"self",
".",
"finished",
".",
"emit",
"(",
")"
] | Starts the thread in its own event loop if the local and global thread
options are true, otherwise runs the thread logic in the main event
loop. | [
"Starts",
"the",
"thread",
"in",
"its",
"own",
"event",
"loop",
"if",
"the",
"local",
"and",
"global",
"thread",
"options",
"are",
"true",
"otherwise",
"runs",
"the",
"thread",
"logic",
"in",
"the",
"main",
"event",
"loop",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xthread.py#L57-L67 | train |
bitesofcode/projexui | projexui/widgets/xorbtreewidget/xorbtreewidget.py | XBatchItem.startLoading | def startLoading(self):
"""
Starts loading this item for the batch.
"""
if super(XBatchItem, self).startLoading():
tree = self.treeWidget()
if not isinstance(tree, XOrbTreeWidget):
self.takeFromTree()
return
next_batch = self.batch()
tree._loadBatch(self, next_batch) | python | def startLoading(self):
"""
Starts loading this item for the batch.
"""
if super(XBatchItem, self).startLoading():
tree = self.treeWidget()
if not isinstance(tree, XOrbTreeWidget):
self.takeFromTree()
return
next_batch = self.batch()
tree._loadBatch(self, next_batch) | [
"def",
"startLoading",
"(",
"self",
")",
":",
"if",
"super",
"(",
"XBatchItem",
",",
"self",
")",
".",
"startLoading",
"(",
")",
":",
"tree",
"=",
"self",
".",
"treeWidget",
"(",
")",
"if",
"not",
"isinstance",
"(",
"tree",
",",
"XOrbTreeWidget",
")",
":",
"self",
".",
"takeFromTree",
"(",
")",
"return",
"next_batch",
"=",
"self",
".",
"batch",
"(",
")",
"tree",
".",
"_loadBatch",
"(",
"self",
",",
"next_batch",
")"
] | Starts loading this item for the batch. | [
"Starts",
"loading",
"this",
"item",
"for",
"the",
"batch",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L307-L318 | train |
bitesofcode/projexui | projexui/widgets/xorbtreewidget/xorbtreewidget.py | XOrbTreeWidget.assignOrderNames | def assignOrderNames(self):
"""
Assigns the order names for this tree based on the name of the
columns.
"""
try:
schema = self.tableType().schema()
except AttributeError:
return
for colname in self.columns():
column = schema.column(colname)
if column:
self.setColumnOrderName(colname, column.name()) | python | def assignOrderNames(self):
"""
Assigns the order names for this tree based on the name of the
columns.
"""
try:
schema = self.tableType().schema()
except AttributeError:
return
for colname in self.columns():
column = schema.column(colname)
if column:
self.setColumnOrderName(colname, column.name()) | [
"def",
"assignOrderNames",
"(",
"self",
")",
":",
"try",
":",
"schema",
"=",
"self",
".",
"tableType",
"(",
")",
".",
"schema",
"(",
")",
"except",
"AttributeError",
":",
"return",
"for",
"colname",
"in",
"self",
".",
"columns",
"(",
")",
":",
"column",
"=",
"schema",
".",
"column",
"(",
"colname",
")",
"if",
"column",
":",
"self",
".",
"setColumnOrderName",
"(",
"colname",
",",
"column",
".",
"name",
"(",
")",
")"
] | Assigns the order names for this tree based on the name of the
columns. | [
"Assigns",
"the",
"order",
"names",
"for",
"this",
"tree",
"based",
"on",
"the",
"name",
"of",
"the",
"columns",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L601-L614 | train |
bitesofcode/projexui | projexui/widgets/xorbtreewidget/xorbtreewidget.py | XOrbTreeWidget.clearAll | def clearAll(self):
"""
Clears the tree and record information.
"""
# clear the tree information
self.clear()
# clear table information
self._tableTypeName = ''
self._tableType = None
# clear the records information
self._recordSet = None
self._currentRecordSet = None
# clear lookup information
self._query = None
self._order = None
self._groupBy = None
# clear paging information
if not self.signalsBlocked():
self.recordsChanged.emit() | python | def clearAll(self):
"""
Clears the tree and record information.
"""
# clear the tree information
self.clear()
# clear table information
self._tableTypeName = ''
self._tableType = None
# clear the records information
self._recordSet = None
self._currentRecordSet = None
# clear lookup information
self._query = None
self._order = None
self._groupBy = None
# clear paging information
if not self.signalsBlocked():
self.recordsChanged.emit() | [
"def",
"clearAll",
"(",
"self",
")",
":",
"# clear the tree information\r",
"self",
".",
"clear",
"(",
")",
"# clear table information\r",
"self",
".",
"_tableTypeName",
"=",
"''",
"self",
".",
"_tableType",
"=",
"None",
"# clear the records information\r",
"self",
".",
"_recordSet",
"=",
"None",
"self",
".",
"_currentRecordSet",
"=",
"None",
"# clear lookup information\r",
"self",
".",
"_query",
"=",
"None",
"self",
".",
"_order",
"=",
"None",
"self",
".",
"_groupBy",
"=",
"None",
"# clear paging information\r",
"if",
"not",
"self",
".",
"signalsBlocked",
"(",
")",
":",
"self",
".",
"recordsChanged",
".",
"emit",
"(",
")"
] | Clears the tree and record information. | [
"Clears",
"the",
"tree",
"and",
"record",
"information",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L634-L657 | train |
bitesofcode/projexui | projexui/widgets/xorbtreewidget/xorbtreewidget.py | XOrbTreeWidget.groupByHeaderIndex | def groupByHeaderIndex(self):
"""
Assigns the grouping to the current header index.
"""
index = self.headerMenuColumn()
columnTitle = self.columnOf(index)
tableType = self.tableType()
if not tableType:
return
column = tableType.schema().column(columnTitle)
if not column:
return
self.setGroupBy(column.name())
self.setGroupingActive(True) | python | def groupByHeaderIndex(self):
"""
Assigns the grouping to the current header index.
"""
index = self.headerMenuColumn()
columnTitle = self.columnOf(index)
tableType = self.tableType()
if not tableType:
return
column = tableType.schema().column(columnTitle)
if not column:
return
self.setGroupBy(column.name())
self.setGroupingActive(True) | [
"def",
"groupByHeaderIndex",
"(",
"self",
")",
":",
"index",
"=",
"self",
".",
"headerMenuColumn",
"(",
")",
"columnTitle",
"=",
"self",
".",
"columnOf",
"(",
"index",
")",
"tableType",
"=",
"self",
".",
"tableType",
"(",
")",
"if",
"not",
"tableType",
":",
"return",
"column",
"=",
"tableType",
".",
"schema",
"(",
")",
".",
"column",
"(",
"columnTitle",
")",
"if",
"not",
"column",
":",
"return",
"self",
".",
"setGroupBy",
"(",
"column",
".",
"name",
"(",
")",
")",
"self",
".",
"setGroupingActive",
"(",
"True",
")"
] | Assigns the grouping to the current header index. | [
"Assigns",
"the",
"grouping",
"to",
"the",
"current",
"header",
"index",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L1012-L1028 | train |
bitesofcode/projexui | projexui/widgets/xorbtreewidget/xorbtreewidget.py | XOrbTreeWidget.initializeColumns | def initializeColumns(self):
"""
Initializes the columns that will be used for this tree widget based \
on the table type linked to it.
"""
tableType = self.tableType()
if not tableType:
return
elif self._columnsInitialized or self.columnOf(0) != '1':
self.assignOrderNames()
return
# set the table header information
tschema = tableType.schema()
columns = tschema.columns()
names = [col.displayName() for col in columns if not col.isPrivate()]
self.setColumns(sorted(names))
self.assignOrderNames()
self.resizeToContents() | python | def initializeColumns(self):
"""
Initializes the columns that will be used for this tree widget based \
on the table type linked to it.
"""
tableType = self.tableType()
if not tableType:
return
elif self._columnsInitialized or self.columnOf(0) != '1':
self.assignOrderNames()
return
# set the table header information
tschema = tableType.schema()
columns = tschema.columns()
names = [col.displayName() for col in columns if not col.isPrivate()]
self.setColumns(sorted(names))
self.assignOrderNames()
self.resizeToContents() | [
"def",
"initializeColumns",
"(",
"self",
")",
":",
"tableType",
"=",
"self",
".",
"tableType",
"(",
")",
"if",
"not",
"tableType",
":",
"return",
"elif",
"self",
".",
"_columnsInitialized",
"or",
"self",
".",
"columnOf",
"(",
"0",
")",
"!=",
"'1'",
":",
"self",
".",
"assignOrderNames",
"(",
")",
"return",
"# set the table header information\r",
"tschema",
"=",
"tableType",
".",
"schema",
"(",
")",
"columns",
"=",
"tschema",
".",
"columns",
"(",
")",
"names",
"=",
"[",
"col",
".",
"displayName",
"(",
")",
"for",
"col",
"in",
"columns",
"if",
"not",
"col",
".",
"isPrivate",
"(",
")",
"]",
"self",
".",
"setColumns",
"(",
"sorted",
"(",
"names",
")",
")",
"self",
".",
"assignOrderNames",
"(",
")",
"self",
".",
"resizeToContents",
"(",
")"
] | Initializes the columns that will be used for this tree widget based \
on the table type linked to it. | [
"Initializes",
"the",
"columns",
"that",
"will",
"be",
"used",
"for",
"this",
"tree",
"widget",
"based",
"\\",
"on",
"the",
"table",
"type",
"linked",
"to",
"it",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L1213-L1232 | train |
bitesofcode/projexui | projexui/widgets/xorbtreewidget/xorbtreewidget.py | XOrbTreeWidget.refresh | def refresh(self, reloadData=False, force=False):
"""
Refreshes the record list for the tree.
"""
if not (self.isVisible() or force):
self._refreshTimer.start()
return
if self.isLoading():
return
if reloadData:
self.refreshQueryRecords()
# cancel current work
self._refreshTimer.stop()
self.worker().cancel()
if self._popup:
self._popup.close()
# grab the record set
currset = self.currentRecordSet()
self.worker().setBatched(self.isPaged())
self.worker().setBatchSize(self.pageSize())
# group the information
if self._searchTerms:
currset.setGroupBy(None)
pageSize = 0
# work with groups
elif self.groupBy() and self.isGroupingActive():
currset.setGroupBy(self.groupBy())
# work with batching
else:
currset.setGroupBy(None)
# order the information
if self.order():
currset.setOrdered(True)
currset.setOrder(self.order())
# for larger queries, run it through the thread
if self.useLoader():
loader = XLoaderWidget.start(self)
# specify the columns to load
if self.specifiedColumnsOnly():
currset.setColumns(map(lambda x: x.name(),
self.specifiedColumns()))
self._loadedColumns = set(self.visibleColumns())
if self.isThreadEnabled() and currset.isThreadEnabled():
self.worker().setPreloadColumns(self._preloadColumns)
self.loadRequested.emit(currset)
else:
QApplication.setOverrideCursor(Qt.WaitCursor)
self.worker().loadRecords(currset)
QApplication.restoreOverrideCursor() | python | def refresh(self, reloadData=False, force=False):
"""
Refreshes the record list for the tree.
"""
if not (self.isVisible() or force):
self._refreshTimer.start()
return
if self.isLoading():
return
if reloadData:
self.refreshQueryRecords()
# cancel current work
self._refreshTimer.stop()
self.worker().cancel()
if self._popup:
self._popup.close()
# grab the record set
currset = self.currentRecordSet()
self.worker().setBatched(self.isPaged())
self.worker().setBatchSize(self.pageSize())
# group the information
if self._searchTerms:
currset.setGroupBy(None)
pageSize = 0
# work with groups
elif self.groupBy() and self.isGroupingActive():
currset.setGroupBy(self.groupBy())
# work with batching
else:
currset.setGroupBy(None)
# order the information
if self.order():
currset.setOrdered(True)
currset.setOrder(self.order())
# for larger queries, run it through the thread
if self.useLoader():
loader = XLoaderWidget.start(self)
# specify the columns to load
if self.specifiedColumnsOnly():
currset.setColumns(map(lambda x: x.name(),
self.specifiedColumns()))
self._loadedColumns = set(self.visibleColumns())
if self.isThreadEnabled() and currset.isThreadEnabled():
self.worker().setPreloadColumns(self._preloadColumns)
self.loadRequested.emit(currset)
else:
QApplication.setOverrideCursor(Qt.WaitCursor)
self.worker().loadRecords(currset)
QApplication.restoreOverrideCursor() | [
"def",
"refresh",
"(",
"self",
",",
"reloadData",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"(",
"self",
".",
"isVisible",
"(",
")",
"or",
"force",
")",
":",
"self",
".",
"_refreshTimer",
".",
"start",
"(",
")",
"return",
"if",
"self",
".",
"isLoading",
"(",
")",
":",
"return",
"if",
"reloadData",
":",
"self",
".",
"refreshQueryRecords",
"(",
")",
"# cancel current work\r",
"self",
".",
"_refreshTimer",
".",
"stop",
"(",
")",
"self",
".",
"worker",
"(",
")",
".",
"cancel",
"(",
")",
"if",
"self",
".",
"_popup",
":",
"self",
".",
"_popup",
".",
"close",
"(",
")",
"# grab the record set\r",
"currset",
"=",
"self",
".",
"currentRecordSet",
"(",
")",
"self",
".",
"worker",
"(",
")",
".",
"setBatched",
"(",
"self",
".",
"isPaged",
"(",
")",
")",
"self",
".",
"worker",
"(",
")",
".",
"setBatchSize",
"(",
"self",
".",
"pageSize",
"(",
")",
")",
"# group the information\r",
"if",
"self",
".",
"_searchTerms",
":",
"currset",
".",
"setGroupBy",
"(",
"None",
")",
"pageSize",
"=",
"0",
"# work with groups\r",
"elif",
"self",
".",
"groupBy",
"(",
")",
"and",
"self",
".",
"isGroupingActive",
"(",
")",
":",
"currset",
".",
"setGroupBy",
"(",
"self",
".",
"groupBy",
"(",
")",
")",
"# work with batching\r",
"else",
":",
"currset",
".",
"setGroupBy",
"(",
"None",
")",
"# order the information\r",
"if",
"self",
".",
"order",
"(",
")",
":",
"currset",
".",
"setOrdered",
"(",
"True",
")",
"currset",
".",
"setOrder",
"(",
"self",
".",
"order",
"(",
")",
")",
"# for larger queries, run it through the thread\r",
"if",
"self",
".",
"useLoader",
"(",
")",
":",
"loader",
"=",
"XLoaderWidget",
".",
"start",
"(",
"self",
")",
"# specify the columns to load\r",
"if",
"self",
".",
"specifiedColumnsOnly",
"(",
")",
":",
"currset",
".",
"setColumns",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"name",
"(",
")",
",",
"self",
".",
"specifiedColumns",
"(",
")",
")",
")",
"self",
".",
"_loadedColumns",
"=",
"set",
"(",
"self",
".",
"visibleColumns",
"(",
")",
")",
"if",
"self",
".",
"isThreadEnabled",
"(",
")",
"and",
"currset",
".",
"isThreadEnabled",
"(",
")",
":",
"self",
".",
"worker",
"(",
")",
".",
"setPreloadColumns",
"(",
"self",
".",
"_preloadColumns",
")",
"self",
".",
"loadRequested",
".",
"emit",
"(",
"currset",
")",
"else",
":",
"QApplication",
".",
"setOverrideCursor",
"(",
"Qt",
".",
"WaitCursor",
")",
"self",
".",
"worker",
"(",
")",
".",
"loadRecords",
"(",
"currset",
")",
"QApplication",
".",
"restoreOverrideCursor",
"(",
")"
] | Refreshes the record list for the tree. | [
"Refreshes",
"the",
"record",
"list",
"for",
"the",
"tree",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L1577-L1639 | train |
bitesofcode/projexui | projexui/widgets/xorbtreewidget/xorbtreewidget.py | XOrbTreeWidget.refreshQueryRecords | def refreshQueryRecords(self):
"""
Refreshes the query results based on the tree's query.
"""
if self._recordSet is not None:
records = RecordSet(self._recordSet)
elif self.tableType():
records = self.tableType().select()
else:
return
records.setDatabase(self.database())
# replace the base query with this widget
if self.queryAction() == XOrbTreeWidget.QueryAction.Replace:
if self.query():
records.setQuery(self.query())
else:
records.setQuery(None)
# join together the query for this widget
elif self.queryAction() == XOrbTreeWidget.QueryAction.Join:
if records.query():
records.setQuery(self.query() & self.query())
elif self.query():
records.setQuery(self.query())
else:
records.setQuery(None)
self._recordSet = records
if not self.signalsBlocked():
self.queryChanged.emit()
self.recordsChanged.emit() | python | def refreshQueryRecords(self):
"""
Refreshes the query results based on the tree's query.
"""
if self._recordSet is not None:
records = RecordSet(self._recordSet)
elif self.tableType():
records = self.tableType().select()
else:
return
records.setDatabase(self.database())
# replace the base query with this widget
if self.queryAction() == XOrbTreeWidget.QueryAction.Replace:
if self.query():
records.setQuery(self.query())
else:
records.setQuery(None)
# join together the query for this widget
elif self.queryAction() == XOrbTreeWidget.QueryAction.Join:
if records.query():
records.setQuery(self.query() & self.query())
elif self.query():
records.setQuery(self.query())
else:
records.setQuery(None)
self._recordSet = records
if not self.signalsBlocked():
self.queryChanged.emit()
self.recordsChanged.emit() | [
"def",
"refreshQueryRecords",
"(",
"self",
")",
":",
"if",
"self",
".",
"_recordSet",
"is",
"not",
"None",
":",
"records",
"=",
"RecordSet",
"(",
"self",
".",
"_recordSet",
")",
"elif",
"self",
".",
"tableType",
"(",
")",
":",
"records",
"=",
"self",
".",
"tableType",
"(",
")",
".",
"select",
"(",
")",
"else",
":",
"return",
"records",
".",
"setDatabase",
"(",
"self",
".",
"database",
"(",
")",
")",
"# replace the base query with this widget\r",
"if",
"self",
".",
"queryAction",
"(",
")",
"==",
"XOrbTreeWidget",
".",
"QueryAction",
".",
"Replace",
":",
"if",
"self",
".",
"query",
"(",
")",
":",
"records",
".",
"setQuery",
"(",
"self",
".",
"query",
"(",
")",
")",
"else",
":",
"records",
".",
"setQuery",
"(",
"None",
")",
"# join together the query for this widget\r",
"elif",
"self",
".",
"queryAction",
"(",
")",
"==",
"XOrbTreeWidget",
".",
"QueryAction",
".",
"Join",
":",
"if",
"records",
".",
"query",
"(",
")",
":",
"records",
".",
"setQuery",
"(",
"self",
".",
"query",
"(",
")",
"&",
"self",
".",
"query",
"(",
")",
")",
"elif",
"self",
".",
"query",
"(",
")",
":",
"records",
".",
"setQuery",
"(",
"self",
".",
"query",
"(",
")",
")",
"else",
":",
"records",
".",
"setQuery",
"(",
"None",
")",
"self",
".",
"_recordSet",
"=",
"records",
"if",
"not",
"self",
".",
"signalsBlocked",
"(",
")",
":",
"self",
".",
"queryChanged",
".",
"emit",
"(",
")",
"self",
".",
"recordsChanged",
".",
"emit",
"(",
")"
] | Refreshes the query results based on the tree's query. | [
"Refreshes",
"the",
"query",
"results",
"based",
"on",
"the",
"tree",
"s",
"query",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L1641-L1674 | train |
bitesofcode/projexui | projexui/widgets/xlockbutton.py | XLockButton.updateState | def updateState(self):
"""
Updates the icon for this lock button based on its check state.
"""
if self.isChecked():
self.setIcon(self.lockIcon())
self.setToolTip('Click to unlock')
else:
self.setIcon(self.unlockIcon())
self.setToolTip('Click to lock') | python | def updateState(self):
"""
Updates the icon for this lock button based on its check state.
"""
if self.isChecked():
self.setIcon(self.lockIcon())
self.setToolTip('Click to unlock')
else:
self.setIcon(self.unlockIcon())
self.setToolTip('Click to lock') | [
"def",
"updateState",
"(",
"self",
")",
":",
"if",
"self",
".",
"isChecked",
"(",
")",
":",
"self",
".",
"setIcon",
"(",
"self",
".",
"lockIcon",
"(",
")",
")",
"self",
".",
"setToolTip",
"(",
"'Click to unlock'",
")",
"else",
":",
"self",
".",
"setIcon",
"(",
"self",
".",
"unlockIcon",
"(",
")",
")",
"self",
".",
"setToolTip",
"(",
"'Click to lock'",
")"
] | Updates the icon for this lock button based on its check state. | [
"Updates",
"the",
"icon",
"for",
"this",
"lock",
"button",
"based",
"on",
"its",
"check",
"state",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlockbutton.py#L78-L87 | train |
neithere/eav-django | eav/admin.py | BaseEntityAdmin.render_change_form | def render_change_form(self, request, context, **kwargs):
"""
Wrapper for ModelAdmin.render_change_form. Replaces standard static
AdminForm with an EAV-friendly one. The point is that our form generates
fields dynamically and fieldsets must be inferred from a prepared and
validated form instance, not just the form class. Django does not seem
to provide hooks for this purpose, so we simply wrap the view and
substitute some data.
"""
form = context['adminform'].form
# infer correct data from the form
fieldsets = [(None, {'fields': form.fields.keys()})]
adminform = helpers.AdminForm(form, fieldsets,
self.prepopulated_fields)
media = mark_safe(self.media + adminform.media)
context.update(adminform=adminform, media=media)
super_meth = super(BaseEntityAdmin, self).render_change_form
return super_meth(request, context, **kwargs) | python | def render_change_form(self, request, context, **kwargs):
"""
Wrapper for ModelAdmin.render_change_form. Replaces standard static
AdminForm with an EAV-friendly one. The point is that our form generates
fields dynamically and fieldsets must be inferred from a prepared and
validated form instance, not just the form class. Django does not seem
to provide hooks for this purpose, so we simply wrap the view and
substitute some data.
"""
form = context['adminform'].form
# infer correct data from the form
fieldsets = [(None, {'fields': form.fields.keys()})]
adminform = helpers.AdminForm(form, fieldsets,
self.prepopulated_fields)
media = mark_safe(self.media + adminform.media)
context.update(adminform=adminform, media=media)
super_meth = super(BaseEntityAdmin, self).render_change_form
return super_meth(request, context, **kwargs) | [
"def",
"render_change_form",
"(",
"self",
",",
"request",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"form",
"=",
"context",
"[",
"'adminform'",
"]",
".",
"form",
"# infer correct data from the form",
"fieldsets",
"=",
"[",
"(",
"None",
",",
"{",
"'fields'",
":",
"form",
".",
"fields",
".",
"keys",
"(",
")",
"}",
")",
"]",
"adminform",
"=",
"helpers",
".",
"AdminForm",
"(",
"form",
",",
"fieldsets",
",",
"self",
".",
"prepopulated_fields",
")",
"media",
"=",
"mark_safe",
"(",
"self",
".",
"media",
"+",
"adminform",
".",
"media",
")",
"context",
".",
"update",
"(",
"adminform",
"=",
"adminform",
",",
"media",
"=",
"media",
")",
"super_meth",
"=",
"super",
"(",
"BaseEntityAdmin",
",",
"self",
")",
".",
"render_change_form",
"return",
"super_meth",
"(",
"request",
",",
"context",
",",
"*",
"*",
"kwargs",
")"
] | Wrapper for ModelAdmin.render_change_form. Replaces standard static
AdminForm with an EAV-friendly one. The point is that our form generates
fields dynamically and fieldsets must be inferred from a prepared and
validated form instance, not just the form class. Django does not seem
to provide hooks for this purpose, so we simply wrap the view and
substitute some data. | [
"Wrapper",
"for",
"ModelAdmin",
".",
"render_change_form",
".",
"Replaces",
"standard",
"static",
"AdminForm",
"with",
"an",
"EAV",
"-",
"friendly",
"one",
".",
"The",
"point",
"is",
"that",
"our",
"form",
"generates",
"fields",
"dynamically",
"and",
"fieldsets",
"must",
"be",
"inferred",
"from",
"a",
"prepared",
"and",
"validated",
"form",
"instance",
"not",
"just",
"the",
"form",
"class",
".",
"Django",
"does",
"not",
"seem",
"to",
"provide",
"hooks",
"for",
"this",
"purpose",
"so",
"we",
"simply",
"wrap",
"the",
"view",
"and",
"substitute",
"some",
"data",
"."
] | 7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/admin.py#L35-L55 | train |
viatoriche/microservices | microservices/http/runners.py | gevent_run | def gevent_run(app, port=5000, log=None, error_log=None, address='',
monkey_patch=True, start=True, **kwargs): # pragma: no cover
"""Run your app in gevent.wsgi.WSGIServer
:param app: wsgi application, ex. Microservice instance
:param port: int, listen port, default 5000
:param address: str, listen address, default: ""
:param log: logger instance, default app.logger
:param error_log: logger instance, default app.logger
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: True
:param start: boolean, if True, server will be start (server.serve_forever())
:param kwargs: other params for WSGIServer(**kwargs)
:return: server
"""
if log is None:
log = app.logger
if error_log is None:
error_log = app.logger
if monkey_patch:
from gevent import monkey
monkey.patch_all()
from gevent.wsgi import WSGIServer
http_server = WSGIServer((address, port), app, log=log, error_log=error_log,
**kwargs)
if start:
http_server.serve_forever()
return http_server | python | def gevent_run(app, port=5000, log=None, error_log=None, address='',
monkey_patch=True, start=True, **kwargs): # pragma: no cover
"""Run your app in gevent.wsgi.WSGIServer
:param app: wsgi application, ex. Microservice instance
:param port: int, listen port, default 5000
:param address: str, listen address, default: ""
:param log: logger instance, default app.logger
:param error_log: logger instance, default app.logger
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: True
:param start: boolean, if True, server will be start (server.serve_forever())
:param kwargs: other params for WSGIServer(**kwargs)
:return: server
"""
if log is None:
log = app.logger
if error_log is None:
error_log = app.logger
if monkey_patch:
from gevent import monkey
monkey.patch_all()
from gevent.wsgi import WSGIServer
http_server = WSGIServer((address, port), app, log=log, error_log=error_log,
**kwargs)
if start:
http_server.serve_forever()
return http_server | [
"def",
"gevent_run",
"(",
"app",
",",
"port",
"=",
"5000",
",",
"log",
"=",
"None",
",",
"error_log",
"=",
"None",
",",
"address",
"=",
"''",
",",
"monkey_patch",
"=",
"True",
",",
"start",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"if",
"log",
"is",
"None",
":",
"log",
"=",
"app",
".",
"logger",
"if",
"error_log",
"is",
"None",
":",
"error_log",
"=",
"app",
".",
"logger",
"if",
"monkey_patch",
":",
"from",
"gevent",
"import",
"monkey",
"monkey",
".",
"patch_all",
"(",
")",
"from",
"gevent",
".",
"wsgi",
"import",
"WSGIServer",
"http_server",
"=",
"WSGIServer",
"(",
"(",
"address",
",",
"port",
")",
",",
"app",
",",
"log",
"=",
"log",
",",
"error_log",
"=",
"error_log",
",",
"*",
"*",
"kwargs",
")",
"if",
"start",
":",
"http_server",
".",
"serve_forever",
"(",
")",
"return",
"http_server"
] | Run your app in gevent.wsgi.WSGIServer
:param app: wsgi application, ex. Microservice instance
:param port: int, listen port, default 5000
:param address: str, listen address, default: ""
:param log: logger instance, default app.logger
:param error_log: logger instance, default app.logger
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: True
:param start: boolean, if True, server will be start (server.serve_forever())
:param kwargs: other params for WSGIServer(**kwargs)
:return: server | [
"Run",
"your",
"app",
"in",
"gevent",
".",
"wsgi",
".",
"WSGIServer"
] | 3510563edd15dc6131b8a948d6062856cd904ac7 | https://github.com/viatoriche/microservices/blob/3510563edd15dc6131b8a948d6062856cd904ac7/microservices/http/runners.py#L12-L40 | train |
viatoriche/microservices | microservices/http/runners.py | tornado_run | def tornado_run(app, port=5000, address="", use_gevent=False, start=True,
monkey_patch=None, Container=None,
Server=None, threadpool=None): # pragma: no cover
"""Run your app in one tornado event loop process
:param app: wsgi application, Microservice instance
:param port: port for listen, int, default: 5000
:param address: address for listen, str, default: ""
:param use_gevent: if True, app.wsgi will be run in gevent.spawn
:param start: if True, will be call utils.tornado_start()
:param Container: your class, bases on tornado.wsgi.WSGIContainer, default: tornado.wsgi.WSGIContainer
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: use_gevent
:param Server: your class, bases on tornado.httpserver.HTTPServer, default: tornado.httpserver.HTTPServer
:return: tornado server
"""
if Container is None:
from tornado.wsgi import WSGIContainer
Container = WSGIContainer
if Server is None:
from tornado.httpserver import HTTPServer
Server = HTTPServer
if monkey_patch is None:
monkey_patch = use_gevent
CustomWSGIContainer = Container
if use_gevent:
if monkey_patch:
from gevent import monkey
monkey.patch_all()
import gevent
class GeventWSGIContainer(Container):
def __call__(self, *args, **kwargs):
def async_task():
super(GeventWSGIContainer, self).__call__(*args, **kwargs)
gevent.spawn(async_task)
CustomWSGIContainer = GeventWSGIContainer
if threadpool is not None:
from multiprocessing.pool import ThreadPool
if not isinstance(threadpool, ThreadPool):
threadpool = ThreadPool(threadpool)
class ThreadPoolWSGIContainer(Container):
def __call__(self, *args, **kwargs):
def async_task():
super(ThreadPoolWSGIContainer, self).__call__(*args, **kwargs)
threadpool.apply_async(async_task)
CustomWSGIContainer = ThreadPoolWSGIContainer
http_server = Server(CustomWSGIContainer(app))
http_server.listen(port, address)
if start:
tornado_start()
return http_server | python | def tornado_run(app, port=5000, address="", use_gevent=False, start=True,
monkey_patch=None, Container=None,
Server=None, threadpool=None): # pragma: no cover
"""Run your app in one tornado event loop process
:param app: wsgi application, Microservice instance
:param port: port for listen, int, default: 5000
:param address: address for listen, str, default: ""
:param use_gevent: if True, app.wsgi will be run in gevent.spawn
:param start: if True, will be call utils.tornado_start()
:param Container: your class, bases on tornado.wsgi.WSGIContainer, default: tornado.wsgi.WSGIContainer
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: use_gevent
:param Server: your class, bases on tornado.httpserver.HTTPServer, default: tornado.httpserver.HTTPServer
:return: tornado server
"""
if Container is None:
from tornado.wsgi import WSGIContainer
Container = WSGIContainer
if Server is None:
from tornado.httpserver import HTTPServer
Server = HTTPServer
if monkey_patch is None:
monkey_patch = use_gevent
CustomWSGIContainer = Container
if use_gevent:
if monkey_patch:
from gevent import monkey
monkey.patch_all()
import gevent
class GeventWSGIContainer(Container):
def __call__(self, *args, **kwargs):
def async_task():
super(GeventWSGIContainer, self).__call__(*args, **kwargs)
gevent.spawn(async_task)
CustomWSGIContainer = GeventWSGIContainer
if threadpool is not None:
from multiprocessing.pool import ThreadPool
if not isinstance(threadpool, ThreadPool):
threadpool = ThreadPool(threadpool)
class ThreadPoolWSGIContainer(Container):
def __call__(self, *args, **kwargs):
def async_task():
super(ThreadPoolWSGIContainer, self).__call__(*args, **kwargs)
threadpool.apply_async(async_task)
CustomWSGIContainer = ThreadPoolWSGIContainer
http_server = Server(CustomWSGIContainer(app))
http_server.listen(port, address)
if start:
tornado_start()
return http_server | [
"def",
"tornado_run",
"(",
"app",
",",
"port",
"=",
"5000",
",",
"address",
"=",
"\"\"",
",",
"use_gevent",
"=",
"False",
",",
"start",
"=",
"True",
",",
"monkey_patch",
"=",
"None",
",",
"Container",
"=",
"None",
",",
"Server",
"=",
"None",
",",
"threadpool",
"=",
"None",
")",
":",
"# pragma: no cover",
"if",
"Container",
"is",
"None",
":",
"from",
"tornado",
".",
"wsgi",
"import",
"WSGIContainer",
"Container",
"=",
"WSGIContainer",
"if",
"Server",
"is",
"None",
":",
"from",
"tornado",
".",
"httpserver",
"import",
"HTTPServer",
"Server",
"=",
"HTTPServer",
"if",
"monkey_patch",
"is",
"None",
":",
"monkey_patch",
"=",
"use_gevent",
"CustomWSGIContainer",
"=",
"Container",
"if",
"use_gevent",
":",
"if",
"monkey_patch",
":",
"from",
"gevent",
"import",
"monkey",
"monkey",
".",
"patch_all",
"(",
")",
"import",
"gevent",
"class",
"GeventWSGIContainer",
"(",
"Container",
")",
":",
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"async_task",
"(",
")",
":",
"super",
"(",
"GeventWSGIContainer",
",",
"self",
")",
".",
"__call__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"gevent",
".",
"spawn",
"(",
"async_task",
")",
"CustomWSGIContainer",
"=",
"GeventWSGIContainer",
"if",
"threadpool",
"is",
"not",
"None",
":",
"from",
"multiprocessing",
".",
"pool",
"import",
"ThreadPool",
"if",
"not",
"isinstance",
"(",
"threadpool",
",",
"ThreadPool",
")",
":",
"threadpool",
"=",
"ThreadPool",
"(",
"threadpool",
")",
"class",
"ThreadPoolWSGIContainer",
"(",
"Container",
")",
":",
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"async_task",
"(",
")",
":",
"super",
"(",
"ThreadPoolWSGIContainer",
",",
"self",
")",
".",
"__call__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"threadpool",
".",
"apply_async",
"(",
"async_task",
")",
"CustomWSGIContainer",
"=",
"ThreadPoolWSGIContainer",
"http_server",
"=",
"Server",
"(",
"CustomWSGIContainer",
"(",
"app",
")",
")",
"http_server",
".",
"listen",
"(",
"port",
",",
"address",
")",
"if",
"start",
":",
"tornado_start",
"(",
")",
"return",
"http_server"
] | Run your app in one tornado event loop process
:param app: wsgi application, Microservice instance
:param port: port for listen, int, default: 5000
:param address: address for listen, str, default: ""
:param use_gevent: if True, app.wsgi will be run in gevent.spawn
:param start: if True, will be call utils.tornado_start()
:param Container: your class, bases on tornado.wsgi.WSGIContainer, default: tornado.wsgi.WSGIContainer
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: use_gevent
:param Server: your class, bases on tornado.httpserver.HTTPServer, default: tornado.httpserver.HTTPServer
:return: tornado server | [
"Run",
"your",
"app",
"in",
"one",
"tornado",
"event",
"loop",
"process"
] | 3510563edd15dc6131b8a948d6062856cd904ac7 | https://github.com/viatoriche/microservices/blob/3510563edd15dc6131b8a948d6062856cd904ac7/microservices/http/runners.py#L58-L121 | train |
viatoriche/microservices | microservices/http/runners.py | tornado_combiner | def tornado_combiner(configs, use_gevent=False, start=True, monkey_patch=None,
Container=None, Server=None, threadpool=None): # pragma: no cover
"""Combine servers in one tornado event loop process
:param configs: [
{
'app': Microservice Application or another wsgi application, required
'port': int, default: 5000
'address': str, default: ""
},
{ ... }
]
:param use_gevent: if True, app.wsgi will be run in gevent.spawn
:param start: if True, will be call utils.tornado_start()
:param Container: your class, bases on tornado.wsgi.WSGIContainer, default: tornado.wsgi.WSGIContainer
:param Server: your class, bases on tornado.httpserver.HTTPServer, default: tornado.httpserver.HTTPServer
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: use_gevent
:return: list of tornado servers
"""
servers = []
if monkey_patch is None:
monkey_patch = use_gevent
if use_gevent:
if monkey_patch:
from gevent import monkey
monkey.patch_all()
if threadpool is not None:
from multiprocessing.pool import ThreadPool
if not isinstance(threadpool, ThreadPool):
threadpool = ThreadPool(threadpool)
for config in configs:
app = config['app']
port = config.get('port', 5000)
address = config.get('address', '')
server = tornado_run(app, use_gevent=use_gevent, port=port,
monkey_patch=False, address=address, start=False,
Container=Container,
Server=Server, threadpool=threadpool)
servers.append(server)
if start:
tornado_start()
return servers | python | def tornado_combiner(configs, use_gevent=False, start=True, monkey_patch=None,
Container=None, Server=None, threadpool=None): # pragma: no cover
"""Combine servers in one tornado event loop process
:param configs: [
{
'app': Microservice Application or another wsgi application, required
'port': int, default: 5000
'address': str, default: ""
},
{ ... }
]
:param use_gevent: if True, app.wsgi will be run in gevent.spawn
:param start: if True, will be call utils.tornado_start()
:param Container: your class, bases on tornado.wsgi.WSGIContainer, default: tornado.wsgi.WSGIContainer
:param Server: your class, bases on tornado.httpserver.HTTPServer, default: tornado.httpserver.HTTPServer
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: use_gevent
:return: list of tornado servers
"""
servers = []
if monkey_patch is None:
monkey_patch = use_gevent
if use_gevent:
if monkey_patch:
from gevent import monkey
monkey.patch_all()
if threadpool is not None:
from multiprocessing.pool import ThreadPool
if not isinstance(threadpool, ThreadPool):
threadpool = ThreadPool(threadpool)
for config in configs:
app = config['app']
port = config.get('port', 5000)
address = config.get('address', '')
server = tornado_run(app, use_gevent=use_gevent, port=port,
monkey_patch=False, address=address, start=False,
Container=Container,
Server=Server, threadpool=threadpool)
servers.append(server)
if start:
tornado_start()
return servers | [
"def",
"tornado_combiner",
"(",
"configs",
",",
"use_gevent",
"=",
"False",
",",
"start",
"=",
"True",
",",
"monkey_patch",
"=",
"None",
",",
"Container",
"=",
"None",
",",
"Server",
"=",
"None",
",",
"threadpool",
"=",
"None",
")",
":",
"# pragma: no cover",
"servers",
"=",
"[",
"]",
"if",
"monkey_patch",
"is",
"None",
":",
"monkey_patch",
"=",
"use_gevent",
"if",
"use_gevent",
":",
"if",
"monkey_patch",
":",
"from",
"gevent",
"import",
"monkey",
"monkey",
".",
"patch_all",
"(",
")",
"if",
"threadpool",
"is",
"not",
"None",
":",
"from",
"multiprocessing",
".",
"pool",
"import",
"ThreadPool",
"if",
"not",
"isinstance",
"(",
"threadpool",
",",
"ThreadPool",
")",
":",
"threadpool",
"=",
"ThreadPool",
"(",
"threadpool",
")",
"for",
"config",
"in",
"configs",
":",
"app",
"=",
"config",
"[",
"'app'",
"]",
"port",
"=",
"config",
".",
"get",
"(",
"'port'",
",",
"5000",
")",
"address",
"=",
"config",
".",
"get",
"(",
"'address'",
",",
"''",
")",
"server",
"=",
"tornado_run",
"(",
"app",
",",
"use_gevent",
"=",
"use_gevent",
",",
"port",
"=",
"port",
",",
"monkey_patch",
"=",
"False",
",",
"address",
"=",
"address",
",",
"start",
"=",
"False",
",",
"Container",
"=",
"Container",
",",
"Server",
"=",
"Server",
",",
"threadpool",
"=",
"threadpool",
")",
"servers",
".",
"append",
"(",
"server",
")",
"if",
"start",
":",
"tornado_start",
"(",
")",
"return",
"servers"
] | Combine servers in one tornado event loop process
:param configs: [
{
'app': Microservice Application or another wsgi application, required
'port': int, default: 5000
'address': str, default: ""
},
{ ... }
]
:param use_gevent: if True, app.wsgi will be run in gevent.spawn
:param start: if True, will be call utils.tornado_start()
:param Container: your class, bases on tornado.wsgi.WSGIContainer, default: tornado.wsgi.WSGIContainer
:param Server: your class, bases on tornado.httpserver.HTTPServer, default: tornado.httpserver.HTTPServer
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: use_gevent
:return: list of tornado servers | [
"Combine",
"servers",
"in",
"one",
"tornado",
"event",
"loop",
"process"
] | 3510563edd15dc6131b8a948d6062856cd904ac7 | https://github.com/viatoriche/microservices/blob/3510563edd15dc6131b8a948d6062856cd904ac7/microservices/http/runners.py#L124-L169 | train |
talkincode/txradius | txradius/radius/dictionary.py | Dictionary.ReadDictionary | def ReadDictionary(self, file):
"""Parse a dictionary file.
Reads a RADIUS dictionary file and merges its contents into the
class instance.
:param file: Name of dictionary file to parse or a file-like object
:type file: string or file-like object
"""
fil = dictfile.DictFile(file)
state = {}
state['vendor'] = ''
self.defer_parse = []
for line in fil:
state['file'] = fil.File()
state['line'] = fil.Line()
line = line.split('#', 1)[0].strip()
tokens = line.split()
if not tokens:
continue
key = tokens[0].upper()
if key == 'ATTRIBUTE':
self.__ParseAttribute(state, tokens)
elif key == 'VALUE':
self.__ParseValue(state, tokens, True)
elif key == 'VENDOR':
self.__ParseVendor(state, tokens)
elif key == 'BEGIN-VENDOR':
self.__ParseBeginVendor(state, tokens)
elif key == 'END-VENDOR':
self.__ParseEndVendor(state, tokens)
for state, tokens in self.defer_parse:
key = tokens[0].upper()
if key == 'VALUE':
self.__ParseValue(state, tokens, False)
self.defer_parse = [] | python | def ReadDictionary(self, file):
"""Parse a dictionary file.
Reads a RADIUS dictionary file and merges its contents into the
class instance.
:param file: Name of dictionary file to parse or a file-like object
:type file: string or file-like object
"""
fil = dictfile.DictFile(file)
state = {}
state['vendor'] = ''
self.defer_parse = []
for line in fil:
state['file'] = fil.File()
state['line'] = fil.Line()
line = line.split('#', 1)[0].strip()
tokens = line.split()
if not tokens:
continue
key = tokens[0].upper()
if key == 'ATTRIBUTE':
self.__ParseAttribute(state, tokens)
elif key == 'VALUE':
self.__ParseValue(state, tokens, True)
elif key == 'VENDOR':
self.__ParseVendor(state, tokens)
elif key == 'BEGIN-VENDOR':
self.__ParseBeginVendor(state, tokens)
elif key == 'END-VENDOR':
self.__ParseEndVendor(state, tokens)
for state, tokens in self.defer_parse:
key = tokens[0].upper()
if key == 'VALUE':
self.__ParseValue(state, tokens, False)
self.defer_parse = [] | [
"def",
"ReadDictionary",
"(",
"self",
",",
"file",
")",
":",
"fil",
"=",
"dictfile",
".",
"DictFile",
"(",
"file",
")",
"state",
"=",
"{",
"}",
"state",
"[",
"'vendor'",
"]",
"=",
"''",
"self",
".",
"defer_parse",
"=",
"[",
"]",
"for",
"line",
"in",
"fil",
":",
"state",
"[",
"'file'",
"]",
"=",
"fil",
".",
"File",
"(",
")",
"state",
"[",
"'line'",
"]",
"=",
"fil",
".",
"Line",
"(",
")",
"line",
"=",
"line",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"tokens",
"=",
"line",
".",
"split",
"(",
")",
"if",
"not",
"tokens",
":",
"continue",
"key",
"=",
"tokens",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"if",
"key",
"==",
"'ATTRIBUTE'",
":",
"self",
".",
"__ParseAttribute",
"(",
"state",
",",
"tokens",
")",
"elif",
"key",
"==",
"'VALUE'",
":",
"self",
".",
"__ParseValue",
"(",
"state",
",",
"tokens",
",",
"True",
")",
"elif",
"key",
"==",
"'VENDOR'",
":",
"self",
".",
"__ParseVendor",
"(",
"state",
",",
"tokens",
")",
"elif",
"key",
"==",
"'BEGIN-VENDOR'",
":",
"self",
".",
"__ParseBeginVendor",
"(",
"state",
",",
"tokens",
")",
"elif",
"key",
"==",
"'END-VENDOR'",
":",
"self",
".",
"__ParseEndVendor",
"(",
"state",
",",
"tokens",
")",
"for",
"state",
",",
"tokens",
"in",
"self",
".",
"defer_parse",
":",
"key",
"=",
"tokens",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"if",
"key",
"==",
"'VALUE'",
":",
"self",
".",
"__ParseValue",
"(",
"state",
",",
"tokens",
",",
"False",
")",
"self",
".",
"defer_parse",
"=",
"[",
"]"
] | Parse a dictionary file.
Reads a RADIUS dictionary file and merges its contents into the
class instance.
:param file: Name of dictionary file to parse or a file-like object
:type file: string or file-like object | [
"Parse",
"a",
"dictionary",
"file",
".",
"Reads",
"a",
"RADIUS",
"dictionary",
"file",
"and",
"merges",
"its",
"contents",
"into",
"the",
"class",
"instance",
"."
] | b86fdbc9be41183680b82b07d3a8e8ea10926e01 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/dictionary.py#L303-L343 | train |
bitesofcode/projexui | projexui/widgets/xchartwidget/xchartscene.py | XChartScene.drawAxis | def drawAxis( self, painter ):
"""
Draws the axis for this system.
"""
# draw the axis lines
pen = QPen(self.axisColor())
pen.setWidth(4)
painter.setPen(pen)
painter.drawLines(self._buildData['axis_lines'])
# draw the notches
for rect, text in self._buildData['grid_h_notches']:
painter.drawText(rect, Qt.AlignTop | Qt.AlignRight, text)
for rect, text in self._buildData['grid_v_notches']:
painter.drawText(rect, Qt.AlignCenter, text) | python | def drawAxis( self, painter ):
"""
Draws the axis for this system.
"""
# draw the axis lines
pen = QPen(self.axisColor())
pen.setWidth(4)
painter.setPen(pen)
painter.drawLines(self._buildData['axis_lines'])
# draw the notches
for rect, text in self._buildData['grid_h_notches']:
painter.drawText(rect, Qt.AlignTop | Qt.AlignRight, text)
for rect, text in self._buildData['grid_v_notches']:
painter.drawText(rect, Qt.AlignCenter, text) | [
"def",
"drawAxis",
"(",
"self",
",",
"painter",
")",
":",
"# draw the axis lines\r",
"pen",
"=",
"QPen",
"(",
"self",
".",
"axisColor",
"(",
")",
")",
"pen",
".",
"setWidth",
"(",
"4",
")",
"painter",
".",
"setPen",
"(",
"pen",
")",
"painter",
".",
"drawLines",
"(",
"self",
".",
"_buildData",
"[",
"'axis_lines'",
"]",
")",
"# draw the notches\r",
"for",
"rect",
",",
"text",
"in",
"self",
".",
"_buildData",
"[",
"'grid_h_notches'",
"]",
":",
"painter",
".",
"drawText",
"(",
"rect",
",",
"Qt",
".",
"AlignTop",
"|",
"Qt",
".",
"AlignRight",
",",
"text",
")",
"for",
"rect",
",",
"text",
"in",
"self",
".",
"_buildData",
"[",
"'grid_v_notches'",
"]",
":",
"painter",
".",
"drawText",
"(",
"rect",
",",
"Qt",
".",
"AlignCenter",
",",
"text",
")"
] | Draws the axis for this system. | [
"Draws",
"the",
"axis",
"for",
"this",
"system",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchartwidget/xchartscene.py#L223-L238 | train |
bitesofcode/projexui | projexui/widgets/xchartwidget/xchartscene.py | XChartScene.rebuild | def rebuild( self ):
"""
Rebuilds the data for this scene to draw with.
"""
global XChartWidgetItem
if ( XChartWidgetItem is None ):
from projexui.widgets.xchartwidget.xchartwidgetitem \
import XChartWidgetItem
self._buildData = {}
# build the grid location
x = 8
y = 8
w = self.sceneRect().width()
h = self.sceneRect().height()
hpad = self.horizontalPadding()
vpad = self.verticalPadding()
hmax = self.horizontalRuler().maxNotchSize(Qt.Horizontal)
left_offset = hpad + self.verticalRuler().maxNotchSize(Qt.Vertical)
right_offset = left_offset + hpad
top_offset = vpad
bottom_offset = top_offset + vpad + hmax
left = x + left_offset
right = w - right_offset
top = y + top_offset
bottom = h - bottom_offset
rect = QRectF()
rect.setLeft(left)
rect.setRight(right)
rect.setBottom(bottom)
rect.setTop(top)
self._buildData['grid_rect'] = rect
# rebuild the ruler data
self.rebuildGrid()
self._dirty = False
# rebuild all the items
padding = self.horizontalPadding() + self.verticalPadding()
grid = self.sceneRect()
filt = lambda x: isinstance(x, XChartWidgetItem)
items = filter(filt, self.items())
height = float(grid.height())
if height == 0:
ratio = 1
else:
ratio = grid.width() / height
count = len(items)
if ( not count ):
return
if ( ratio >= 1 ):
radius = (grid.height() - padding * 2) / 2.0
x = rect.center().x()
y = rect.center().y()
dx = radius * 2.5
dy = 0
else:
radius = (grid.width() - padding * 2) / 2.0
x = rect.center().x()
y = rect.center().y()
dx = 0
dy = radius * 2.5
for item in items:
item.setPieCenter(QPointF(x, y))
item.setRadius(radius)
item.rebuild()
x += dx
y += dy
if ( self._trackerItem and self._trackerItem() ):
self._trackerItem().rebuild(self._buildData['grid_rect']) | python | def rebuild( self ):
"""
Rebuilds the data for this scene to draw with.
"""
global XChartWidgetItem
if ( XChartWidgetItem is None ):
from projexui.widgets.xchartwidget.xchartwidgetitem \
import XChartWidgetItem
self._buildData = {}
# build the grid location
x = 8
y = 8
w = self.sceneRect().width()
h = self.sceneRect().height()
hpad = self.horizontalPadding()
vpad = self.verticalPadding()
hmax = self.horizontalRuler().maxNotchSize(Qt.Horizontal)
left_offset = hpad + self.verticalRuler().maxNotchSize(Qt.Vertical)
right_offset = left_offset + hpad
top_offset = vpad
bottom_offset = top_offset + vpad + hmax
left = x + left_offset
right = w - right_offset
top = y + top_offset
bottom = h - bottom_offset
rect = QRectF()
rect.setLeft(left)
rect.setRight(right)
rect.setBottom(bottom)
rect.setTop(top)
self._buildData['grid_rect'] = rect
# rebuild the ruler data
self.rebuildGrid()
self._dirty = False
# rebuild all the items
padding = self.horizontalPadding() + self.verticalPadding()
grid = self.sceneRect()
filt = lambda x: isinstance(x, XChartWidgetItem)
items = filter(filt, self.items())
height = float(grid.height())
if height == 0:
ratio = 1
else:
ratio = grid.width() / height
count = len(items)
if ( not count ):
return
if ( ratio >= 1 ):
radius = (grid.height() - padding * 2) / 2.0
x = rect.center().x()
y = rect.center().y()
dx = radius * 2.5
dy = 0
else:
radius = (grid.width() - padding * 2) / 2.0
x = rect.center().x()
y = rect.center().y()
dx = 0
dy = radius * 2.5
for item in items:
item.setPieCenter(QPointF(x, y))
item.setRadius(radius)
item.rebuild()
x += dx
y += dy
if ( self._trackerItem and self._trackerItem() ):
self._trackerItem().rebuild(self._buildData['grid_rect']) | [
"def",
"rebuild",
"(",
"self",
")",
":",
"global",
"XChartWidgetItem",
"if",
"(",
"XChartWidgetItem",
"is",
"None",
")",
":",
"from",
"projexui",
".",
"widgets",
".",
"xchartwidget",
".",
"xchartwidgetitem",
"import",
"XChartWidgetItem",
"self",
".",
"_buildData",
"=",
"{",
"}",
"# build the grid location\r",
"x",
"=",
"8",
"y",
"=",
"8",
"w",
"=",
"self",
".",
"sceneRect",
"(",
")",
".",
"width",
"(",
")",
"h",
"=",
"self",
".",
"sceneRect",
"(",
")",
".",
"height",
"(",
")",
"hpad",
"=",
"self",
".",
"horizontalPadding",
"(",
")",
"vpad",
"=",
"self",
".",
"verticalPadding",
"(",
")",
"hmax",
"=",
"self",
".",
"horizontalRuler",
"(",
")",
".",
"maxNotchSize",
"(",
"Qt",
".",
"Horizontal",
")",
"left_offset",
"=",
"hpad",
"+",
"self",
".",
"verticalRuler",
"(",
")",
".",
"maxNotchSize",
"(",
"Qt",
".",
"Vertical",
")",
"right_offset",
"=",
"left_offset",
"+",
"hpad",
"top_offset",
"=",
"vpad",
"bottom_offset",
"=",
"top_offset",
"+",
"vpad",
"+",
"hmax",
"left",
"=",
"x",
"+",
"left_offset",
"right",
"=",
"w",
"-",
"right_offset",
"top",
"=",
"y",
"+",
"top_offset",
"bottom",
"=",
"h",
"-",
"bottom_offset",
"rect",
"=",
"QRectF",
"(",
")",
"rect",
".",
"setLeft",
"(",
"left",
")",
"rect",
".",
"setRight",
"(",
"right",
")",
"rect",
".",
"setBottom",
"(",
"bottom",
")",
"rect",
".",
"setTop",
"(",
"top",
")",
"self",
".",
"_buildData",
"[",
"'grid_rect'",
"]",
"=",
"rect",
"# rebuild the ruler data\r",
"self",
".",
"rebuildGrid",
"(",
")",
"self",
".",
"_dirty",
"=",
"False",
"# rebuild all the items\r",
"padding",
"=",
"self",
".",
"horizontalPadding",
"(",
")",
"+",
"self",
".",
"verticalPadding",
"(",
")",
"grid",
"=",
"self",
".",
"sceneRect",
"(",
")",
"filt",
"=",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"XChartWidgetItem",
")",
"items",
"=",
"filter",
"(",
"filt",
",",
"self",
".",
"items",
"(",
")",
")",
"height",
"=",
"float",
"(",
"grid",
".",
"height",
"(",
")",
")",
"if",
"height",
"==",
"0",
":",
"ratio",
"=",
"1",
"else",
":",
"ratio",
"=",
"grid",
".",
"width",
"(",
")",
"/",
"height",
"count",
"=",
"len",
"(",
"items",
")",
"if",
"(",
"not",
"count",
")",
":",
"return",
"if",
"(",
"ratio",
">=",
"1",
")",
":",
"radius",
"=",
"(",
"grid",
".",
"height",
"(",
")",
"-",
"padding",
"*",
"2",
")",
"/",
"2.0",
"x",
"=",
"rect",
".",
"center",
"(",
")",
".",
"x",
"(",
")",
"y",
"=",
"rect",
".",
"center",
"(",
")",
".",
"y",
"(",
")",
"dx",
"=",
"radius",
"*",
"2.5",
"dy",
"=",
"0",
"else",
":",
"radius",
"=",
"(",
"grid",
".",
"width",
"(",
")",
"-",
"padding",
"*",
"2",
")",
"/",
"2.0",
"x",
"=",
"rect",
".",
"center",
"(",
")",
".",
"x",
"(",
")",
"y",
"=",
"rect",
".",
"center",
"(",
")",
".",
"y",
"(",
")",
"dx",
"=",
"0",
"dy",
"=",
"radius",
"*",
"2.5",
"for",
"item",
"in",
"items",
":",
"item",
".",
"setPieCenter",
"(",
"QPointF",
"(",
"x",
",",
"y",
")",
")",
"item",
".",
"setRadius",
"(",
"radius",
")",
"item",
".",
"rebuild",
"(",
")",
"x",
"+=",
"dx",
"y",
"+=",
"dy",
"if",
"(",
"self",
".",
"_trackerItem",
"and",
"self",
".",
"_trackerItem",
"(",
")",
")",
":",
"self",
".",
"_trackerItem",
"(",
")",
".",
"rebuild",
"(",
"self",
".",
"_buildData",
"[",
"'grid_rect'",
"]",
")"
] | Rebuilds the data for this scene to draw with. | [
"Rebuilds",
"the",
"data",
"for",
"this",
"scene",
"to",
"draw",
"with",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchartwidget/xchartscene.py#L407-L486 | train |
bitesofcode/projexui | projexui/widgets/xchartwidget/xchartscene.py | XChartScene.setSceneRect | def setSceneRect( self, *args ):
"""
Overloads the set scene rect to handle rebuild information.
"""
super(XChartScene, self).setSceneRect(*args)
self._dirty = True | python | def setSceneRect( self, *args ):
"""
Overloads the set scene rect to handle rebuild information.
"""
super(XChartScene, self).setSceneRect(*args)
self._dirty = True | [
"def",
"setSceneRect",
"(",
"self",
",",
"*",
"args",
")",
":",
"super",
"(",
"XChartScene",
",",
"self",
")",
".",
"setSceneRect",
"(",
"*",
"args",
")",
"self",
".",
"_dirty",
"=",
"True"
] | Overloads the set scene rect to handle rebuild information. | [
"Overloads",
"the",
"set",
"scene",
"rect",
"to",
"handle",
"rebuild",
"information",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchartwidget/xchartscene.py#L676-L681 | train |
bitesofcode/projexui | projexui/widgets/xchartwidget/xchartscene.py | XChartScene.updateTrackerItem | def updateTrackerItem( self, point = None ):
"""
Updates the tracker item information.
"""
item = self.trackerItem()
if not item:
return
gridRect = self._buildData.get('grid_rect')
if ( not (gridRect and gridRect.isValid()) ):
item.setVisible(False)
return
if ( point is not None ):
item.setPos(point.x(), gridRect.top())
if ( not gridRect.contains(item.pos()) ):
item.setVisible(False)
return
if ( self.chartType() != self.Type.Line ):
item.setVisible(False)
return
if ( not self.isTrackingEnabled() ):
item.setVisible(False)
return
item.rebuild(gridRect) | python | def updateTrackerItem( self, point = None ):
"""
Updates the tracker item information.
"""
item = self.trackerItem()
if not item:
return
gridRect = self._buildData.get('grid_rect')
if ( not (gridRect and gridRect.isValid()) ):
item.setVisible(False)
return
if ( point is not None ):
item.setPos(point.x(), gridRect.top())
if ( not gridRect.contains(item.pos()) ):
item.setVisible(False)
return
if ( self.chartType() != self.Type.Line ):
item.setVisible(False)
return
if ( not self.isTrackingEnabled() ):
item.setVisible(False)
return
item.rebuild(gridRect) | [
"def",
"updateTrackerItem",
"(",
"self",
",",
"point",
"=",
"None",
")",
":",
"item",
"=",
"self",
".",
"trackerItem",
"(",
")",
"if",
"not",
"item",
":",
"return",
"gridRect",
"=",
"self",
".",
"_buildData",
".",
"get",
"(",
"'grid_rect'",
")",
"if",
"(",
"not",
"(",
"gridRect",
"and",
"gridRect",
".",
"isValid",
"(",
")",
")",
")",
":",
"item",
".",
"setVisible",
"(",
"False",
")",
"return",
"if",
"(",
"point",
"is",
"not",
"None",
")",
":",
"item",
".",
"setPos",
"(",
"point",
".",
"x",
"(",
")",
",",
"gridRect",
".",
"top",
"(",
")",
")",
"if",
"(",
"not",
"gridRect",
".",
"contains",
"(",
"item",
".",
"pos",
"(",
")",
")",
")",
":",
"item",
".",
"setVisible",
"(",
"False",
")",
"return",
"if",
"(",
"self",
".",
"chartType",
"(",
")",
"!=",
"self",
".",
"Type",
".",
"Line",
")",
":",
"item",
".",
"setVisible",
"(",
"False",
")",
"return",
"if",
"(",
"not",
"self",
".",
"isTrackingEnabled",
"(",
")",
")",
":",
"item",
".",
"setVisible",
"(",
"False",
")",
"return",
"item",
".",
"rebuild",
"(",
"gridRect",
")"
] | Updates the tracker item information. | [
"Updates",
"the",
"tracker",
"item",
"information",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchartwidget/xchartscene.py#L774-L803 | train |
bitesofcode/projexui | projexui/widgets/xnavigationedit.py | XNavigationEdit.acceptEdit | def acceptEdit( self ):
"""
Accepts the current text and rebuilds the parts widget.
"""
if ( self._partsWidget.isVisible() ):
return False
use_completion = self.completer().popup().isVisible()
completion = self.completer().currentCompletion()
self._completerTree.hide()
self.completer().popup().hide()
if ( use_completion ):
self.setText(completion)
else:
self.rebuild()
return True | python | def acceptEdit( self ):
"""
Accepts the current text and rebuilds the parts widget.
"""
if ( self._partsWidget.isVisible() ):
return False
use_completion = self.completer().popup().isVisible()
completion = self.completer().currentCompletion()
self._completerTree.hide()
self.completer().popup().hide()
if ( use_completion ):
self.setText(completion)
else:
self.rebuild()
return True | [
"def",
"acceptEdit",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_partsWidget",
".",
"isVisible",
"(",
")",
")",
":",
"return",
"False",
"use_completion",
"=",
"self",
".",
"completer",
"(",
")",
".",
"popup",
"(",
")",
".",
"isVisible",
"(",
")",
"completion",
"=",
"self",
".",
"completer",
"(",
")",
".",
"currentCompletion",
"(",
")",
"self",
".",
"_completerTree",
".",
"hide",
"(",
")",
"self",
".",
"completer",
"(",
")",
".",
"popup",
"(",
")",
".",
"hide",
"(",
")",
"if",
"(",
"use_completion",
")",
":",
"self",
".",
"setText",
"(",
"completion",
")",
"else",
":",
"self",
".",
"rebuild",
"(",
")",
"return",
"True"
] | Accepts the current text and rebuilds the parts widget. | [
"Accepts",
"the",
"current",
"text",
"and",
"rebuilds",
"the",
"parts",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnavigationedit.py#L298-L317 | train |
bitesofcode/projexui | projexui/widgets/xnavigationedit.py | XNavigationEdit.cancelEdit | def cancelEdit( self ):
"""
Rejects the current edit and shows the parts widget.
"""
if ( self._partsWidget.isVisible() ):
return False
self._completerTree.hide()
self.completer().popup().hide()
self.setText(self._originalText)
return True | python | def cancelEdit( self ):
"""
Rejects the current edit and shows the parts widget.
"""
if ( self._partsWidget.isVisible() ):
return False
self._completerTree.hide()
self.completer().popup().hide()
self.setText(self._originalText)
return True | [
"def",
"cancelEdit",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_partsWidget",
".",
"isVisible",
"(",
")",
")",
":",
"return",
"False",
"self",
".",
"_completerTree",
".",
"hide",
"(",
")",
"self",
".",
"completer",
"(",
")",
".",
"popup",
"(",
")",
".",
"hide",
"(",
")",
"self",
".",
"setText",
"(",
"self",
".",
"_originalText",
")",
"return",
"True"
] | Rejects the current edit and shows the parts widget. | [
"Rejects",
"the",
"current",
"edit",
"and",
"shows",
"the",
"parts",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnavigationedit.py#L319-L331 | train |
bitesofcode/projexui | projexui/widgets/xnavigationedit.py | XNavigationEdit.startEdit | def startEdit( self ):
"""
Rebuilds the pathing based on the parts.
"""
self._originalText = self.text()
self.scrollWidget().hide()
self.setFocus()
self.selectAll() | python | def startEdit( self ):
"""
Rebuilds the pathing based on the parts.
"""
self._originalText = self.text()
self.scrollWidget().hide()
self.setFocus()
self.selectAll() | [
"def",
"startEdit",
"(",
"self",
")",
":",
"self",
".",
"_originalText",
"=",
"self",
".",
"text",
"(",
")",
"self",
".",
"scrollWidget",
"(",
")",
".",
"hide",
"(",
")",
"self",
".",
"setFocus",
"(",
")",
"self",
".",
"selectAll",
"(",
")"
] | Rebuilds the pathing based on the parts. | [
"Rebuilds",
"the",
"pathing",
"based",
"on",
"the",
"parts",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnavigationedit.py#L515-L522 | train |
bitesofcode/projexui | projexui/widgets/xnavigationedit.py | XNavigationEdit.rebuild | def rebuild( self ):
"""
Rebuilds the parts widget with the latest text.
"""
navitem = self.currentItem()
if ( navitem ):
navitem.initialize()
self.setUpdatesEnabled(False)
self.scrollWidget().show()
self._originalText = ''
partsw = self.partsWidget()
for button in self._buttonGroup.buttons():
self._buttonGroup.removeButton(button)
button.close()
button.setParent(None)
button.deleteLater()
# create the root button
layout = partsw.layout()
parts = self.parts()
button = QToolButton(partsw)
button.setAutoRaise(True)
button.setMaximumWidth(12)
button.setArrowType(Qt.RightArrow)
button.setProperty('path', wrapVariant(''))
button.setProperty('is_completer', wrapVariant(True))
last_button = button
self._buttonGroup.addButton(button)
layout.insertWidget(0, button)
# check to see if we have a navigation model setup
if ( self._navigationModel ):
last_item = self._navigationModel.itemByPath(self.text())
show_last = last_item and last_item.rowCount() > 0
else:
show_last = False
# load the navigation system
count = len(parts)
for i, part in enumerate(parts):
path = self.separator().join(parts[:i+1])
button = QToolButton(partsw)
button.setAutoRaise(True)
button.setText(part)
if ( self._navigationModel ):
item = self._navigationModel.itemByPath(path)
if ( item ):
button.setIcon(item.icon())
button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
button.setProperty('path', wrapVariant(path))
button.setProperty('is_completer', wrapVariant(False))
self._buttonGroup.addButton(button)
layout.insertWidget((i * 2) + 1, button)
# determine if we should show the final button
if ( show_last or i < (count - 1) ):
button = QToolButton(partsw)
button.setAutoRaise(True)
button.setMaximumWidth(12)
button.setArrowType(Qt.RightArrow)
button.setProperty('path', wrapVariant(path))
button.setProperty('is_completer', wrapVariant(True))
self._buttonGroup.addButton(button)
layout.insertWidget((i * 2) + 2, button)
last_button = button
if ( self.scrollWidget().width() < partsw.width() ):
self.scrollParts(partsw.width() - self.scrollWidget().width())
self.setUpdatesEnabled(True)
self.navigationChanged.emit() | python | def rebuild( self ):
"""
Rebuilds the parts widget with the latest text.
"""
navitem = self.currentItem()
if ( navitem ):
navitem.initialize()
self.setUpdatesEnabled(False)
self.scrollWidget().show()
self._originalText = ''
partsw = self.partsWidget()
for button in self._buttonGroup.buttons():
self._buttonGroup.removeButton(button)
button.close()
button.setParent(None)
button.deleteLater()
# create the root button
layout = partsw.layout()
parts = self.parts()
button = QToolButton(partsw)
button.setAutoRaise(True)
button.setMaximumWidth(12)
button.setArrowType(Qt.RightArrow)
button.setProperty('path', wrapVariant(''))
button.setProperty('is_completer', wrapVariant(True))
last_button = button
self._buttonGroup.addButton(button)
layout.insertWidget(0, button)
# check to see if we have a navigation model setup
if ( self._navigationModel ):
last_item = self._navigationModel.itemByPath(self.text())
show_last = last_item and last_item.rowCount() > 0
else:
show_last = False
# load the navigation system
count = len(parts)
for i, part in enumerate(parts):
path = self.separator().join(parts[:i+1])
button = QToolButton(partsw)
button.setAutoRaise(True)
button.setText(part)
if ( self._navigationModel ):
item = self._navigationModel.itemByPath(path)
if ( item ):
button.setIcon(item.icon())
button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
button.setProperty('path', wrapVariant(path))
button.setProperty('is_completer', wrapVariant(False))
self._buttonGroup.addButton(button)
layout.insertWidget((i * 2) + 1, button)
# determine if we should show the final button
if ( show_last or i < (count - 1) ):
button = QToolButton(partsw)
button.setAutoRaise(True)
button.setMaximumWidth(12)
button.setArrowType(Qt.RightArrow)
button.setProperty('path', wrapVariant(path))
button.setProperty('is_completer', wrapVariant(True))
self._buttonGroup.addButton(button)
layout.insertWidget((i * 2) + 2, button)
last_button = button
if ( self.scrollWidget().width() < partsw.width() ):
self.scrollParts(partsw.width() - self.scrollWidget().width())
self.setUpdatesEnabled(True)
self.navigationChanged.emit() | [
"def",
"rebuild",
"(",
"self",
")",
":",
"navitem",
"=",
"self",
".",
"currentItem",
"(",
")",
"if",
"(",
"navitem",
")",
":",
"navitem",
".",
"initialize",
"(",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"self",
".",
"scrollWidget",
"(",
")",
".",
"show",
"(",
")",
"self",
".",
"_originalText",
"=",
"''",
"partsw",
"=",
"self",
".",
"partsWidget",
"(",
")",
"for",
"button",
"in",
"self",
".",
"_buttonGroup",
".",
"buttons",
"(",
")",
":",
"self",
".",
"_buttonGroup",
".",
"removeButton",
"(",
"button",
")",
"button",
".",
"close",
"(",
")",
"button",
".",
"setParent",
"(",
"None",
")",
"button",
".",
"deleteLater",
"(",
")",
"# create the root button",
"layout",
"=",
"partsw",
".",
"layout",
"(",
")",
"parts",
"=",
"self",
".",
"parts",
"(",
")",
"button",
"=",
"QToolButton",
"(",
"partsw",
")",
"button",
".",
"setAutoRaise",
"(",
"True",
")",
"button",
".",
"setMaximumWidth",
"(",
"12",
")",
"button",
".",
"setArrowType",
"(",
"Qt",
".",
"RightArrow",
")",
"button",
".",
"setProperty",
"(",
"'path'",
",",
"wrapVariant",
"(",
"''",
")",
")",
"button",
".",
"setProperty",
"(",
"'is_completer'",
",",
"wrapVariant",
"(",
"True",
")",
")",
"last_button",
"=",
"button",
"self",
".",
"_buttonGroup",
".",
"addButton",
"(",
"button",
")",
"layout",
".",
"insertWidget",
"(",
"0",
",",
"button",
")",
"# check to see if we have a navigation model setup",
"if",
"(",
"self",
".",
"_navigationModel",
")",
":",
"last_item",
"=",
"self",
".",
"_navigationModel",
".",
"itemByPath",
"(",
"self",
".",
"text",
"(",
")",
")",
"show_last",
"=",
"last_item",
"and",
"last_item",
".",
"rowCount",
"(",
")",
">",
"0",
"else",
":",
"show_last",
"=",
"False",
"# load the navigation system",
"count",
"=",
"len",
"(",
"parts",
")",
"for",
"i",
",",
"part",
"in",
"enumerate",
"(",
"parts",
")",
":",
"path",
"=",
"self",
".",
"separator",
"(",
")",
".",
"join",
"(",
"parts",
"[",
":",
"i",
"+",
"1",
"]",
")",
"button",
"=",
"QToolButton",
"(",
"partsw",
")",
"button",
".",
"setAutoRaise",
"(",
"True",
")",
"button",
".",
"setText",
"(",
"part",
")",
"if",
"(",
"self",
".",
"_navigationModel",
")",
":",
"item",
"=",
"self",
".",
"_navigationModel",
".",
"itemByPath",
"(",
"path",
")",
"if",
"(",
"item",
")",
":",
"button",
".",
"setIcon",
"(",
"item",
".",
"icon",
"(",
")",
")",
"button",
".",
"setToolButtonStyle",
"(",
"Qt",
".",
"ToolButtonTextBesideIcon",
")",
"button",
".",
"setProperty",
"(",
"'path'",
",",
"wrapVariant",
"(",
"path",
")",
")",
"button",
".",
"setProperty",
"(",
"'is_completer'",
",",
"wrapVariant",
"(",
"False",
")",
")",
"self",
".",
"_buttonGroup",
".",
"addButton",
"(",
"button",
")",
"layout",
".",
"insertWidget",
"(",
"(",
"i",
"*",
"2",
")",
"+",
"1",
",",
"button",
")",
"# determine if we should show the final button",
"if",
"(",
"show_last",
"or",
"i",
"<",
"(",
"count",
"-",
"1",
")",
")",
":",
"button",
"=",
"QToolButton",
"(",
"partsw",
")",
"button",
".",
"setAutoRaise",
"(",
"True",
")",
"button",
".",
"setMaximumWidth",
"(",
"12",
")",
"button",
".",
"setArrowType",
"(",
"Qt",
".",
"RightArrow",
")",
"button",
".",
"setProperty",
"(",
"'path'",
",",
"wrapVariant",
"(",
"path",
")",
")",
"button",
".",
"setProperty",
"(",
"'is_completer'",
",",
"wrapVariant",
"(",
"True",
")",
")",
"self",
".",
"_buttonGroup",
".",
"addButton",
"(",
"button",
")",
"layout",
".",
"insertWidget",
"(",
"(",
"i",
"*",
"2",
")",
"+",
"2",
",",
"button",
")",
"last_button",
"=",
"button",
"if",
"(",
"self",
".",
"scrollWidget",
"(",
")",
".",
"width",
"(",
")",
"<",
"partsw",
".",
"width",
"(",
")",
")",
":",
"self",
".",
"scrollParts",
"(",
"partsw",
".",
"width",
"(",
")",
"-",
"self",
".",
"scrollWidget",
"(",
")",
".",
"width",
"(",
")",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"True",
")",
"self",
".",
"navigationChanged",
".",
"emit",
"(",
")"
] | Rebuilds the parts widget with the latest text. | [
"Rebuilds",
"the",
"parts",
"widget",
"with",
"the",
"latest",
"text",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnavigationedit.py#L524-L606 | train |
core/uricore | uricore/core.py | ResourceIdentifier.query | def query(self):
"""Return a new instance of query_cls."""
if not hasattr(self, '_decoded_query'):
self._decoded_query = list(urls._url_decode_impl(
self.querystr.split('&'), 'utf-8', False, True, 'strict'))
return self.query_cls(self._decoded_query) | python | def query(self):
"""Return a new instance of query_cls."""
if not hasattr(self, '_decoded_query'):
self._decoded_query = list(urls._url_decode_impl(
self.querystr.split('&'), 'utf-8', False, True, 'strict'))
return self.query_cls(self._decoded_query) | [
"def",
"query",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_decoded_query'",
")",
":",
"self",
".",
"_decoded_query",
"=",
"list",
"(",
"urls",
".",
"_url_decode_impl",
"(",
"self",
".",
"querystr",
".",
"split",
"(",
"'&'",
")",
",",
"'utf-8'",
",",
"False",
",",
"True",
",",
"'strict'",
")",
")",
"return",
"self",
".",
"query_cls",
"(",
"self",
".",
"_decoded_query",
")"
] | Return a new instance of query_cls. | [
"Return",
"a",
"new",
"instance",
"of",
"query_cls",
"."
] | dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a | https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/core.py#L110-L116 | train |
bitesofcode/projexui | projexui/dialogs/xconfigdialog/xconfigwidget.py | XConfigWidget.refreshUi | def refreshUi( self ):
"""
Load the plugin information to the interface.
"""
dataSet = self.dataSet()
if not dataSet:
return False
# lookup widgets based on the data set information
for widget in self.findChildren(QWidget):
prop = unwrapVariant(widget.property('dataName'))
if prop is None:
continue
# update the data for the widget
prop_name = nativestring(prop)
if prop_name in dataSet:
value = dataSet.value(prop_name)
projexui.setWidgetValue(widget, value)
return True | python | def refreshUi( self ):
"""
Load the plugin information to the interface.
"""
dataSet = self.dataSet()
if not dataSet:
return False
# lookup widgets based on the data set information
for widget in self.findChildren(QWidget):
prop = unwrapVariant(widget.property('dataName'))
if prop is None:
continue
# update the data for the widget
prop_name = nativestring(prop)
if prop_name in dataSet:
value = dataSet.value(prop_name)
projexui.setWidgetValue(widget, value)
return True | [
"def",
"refreshUi",
"(",
"self",
")",
":",
"dataSet",
"=",
"self",
".",
"dataSet",
"(",
")",
"if",
"not",
"dataSet",
":",
"return",
"False",
"# lookup widgets based on the data set information",
"for",
"widget",
"in",
"self",
".",
"findChildren",
"(",
"QWidget",
")",
":",
"prop",
"=",
"unwrapVariant",
"(",
"widget",
".",
"property",
"(",
"'dataName'",
")",
")",
"if",
"prop",
"is",
"None",
":",
"continue",
"# update the data for the widget",
"prop_name",
"=",
"nativestring",
"(",
"prop",
")",
"if",
"prop_name",
"in",
"dataSet",
":",
"value",
"=",
"dataSet",
".",
"value",
"(",
"prop_name",
")",
"projexui",
".",
"setWidgetValue",
"(",
"widget",
",",
"value",
")",
"return",
"True"
] | Load the plugin information to the interface. | [
"Load",
"the",
"plugin",
"information",
"to",
"the",
"interface",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xconfigdialog/xconfigwidget.py#L57-L77 | train |
bitesofcode/projexui | projexui/dialogs/xconfigdialog/xconfigwidget.py | XConfigWidget.reset | def reset( self ):
"""
Resets the ui information to the default data for the widget.
"""
if not self.plugin():
return False
self.plugin().reset()
self.refreshUi()
return True | python | def reset( self ):
"""
Resets the ui information to the default data for the widget.
"""
if not self.plugin():
return False
self.plugin().reset()
self.refreshUi()
return True | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"plugin",
"(",
")",
":",
"return",
"False",
"self",
".",
"plugin",
"(",
")",
".",
"reset",
"(",
")",
"self",
".",
"refreshUi",
"(",
")",
"return",
"True"
] | Resets the ui information to the default data for the widget. | [
"Resets",
"the",
"ui",
"information",
"to",
"the",
"default",
"data",
"for",
"the",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xconfigdialog/xconfigwidget.py#L79-L89 | train |
talkincode/txradius | txradius/mschap/des_c.py | n2l | def n2l(c, l):
"network to host long"
l = U32(c[0] << 24)
l = l | (U32(c[1]) << 16)
l = l | (U32(c[2]) << 8)
l = l | (U32(c[3]))
return l | python | def n2l(c, l):
"network to host long"
l = U32(c[0] << 24)
l = l | (U32(c[1]) << 16)
l = l | (U32(c[2]) << 8)
l = l | (U32(c[3]))
return l | [
"def",
"n2l",
"(",
"c",
",",
"l",
")",
":",
"l",
"=",
"U32",
"(",
"c",
"[",
"0",
"]",
"<<",
"24",
")",
"l",
"=",
"l",
"|",
"(",
"U32",
"(",
"c",
"[",
"1",
"]",
")",
"<<",
"16",
")",
"l",
"=",
"l",
"|",
"(",
"U32",
"(",
"c",
"[",
"2",
"]",
")",
"<<",
"8",
")",
"l",
"=",
"l",
"|",
"(",
"U32",
"(",
"c",
"[",
"3",
"]",
")",
")",
"return",
"l"
] | network to host long | [
"network",
"to",
"host",
"long"
] | b86fdbc9be41183680b82b07d3a8e8ea10926e01 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/mschap/des_c.py#L75-L81 | train |
talkincode/txradius | txradius/mschap/des_c.py | l2n | def l2n(l, c):
"host to network long"
c = []
c.append(int((l >> 24) & U32(0xFF)))
c.append(int((l >> 16) & U32(0xFF)))
c.append(int((l >> 8) & U32(0xFF)))
c.append(int((l ) & U32(0xFF)))
return c | python | def l2n(l, c):
"host to network long"
c = []
c.append(int((l >> 24) & U32(0xFF)))
c.append(int((l >> 16) & U32(0xFF)))
c.append(int((l >> 8) & U32(0xFF)))
c.append(int((l ) & U32(0xFF)))
return c | [
"def",
"l2n",
"(",
"l",
",",
"c",
")",
":",
"c",
"=",
"[",
"]",
"c",
".",
"append",
"(",
"int",
"(",
"(",
"l",
">>",
"24",
")",
"&",
"U32",
"(",
"0xFF",
")",
")",
")",
"c",
".",
"append",
"(",
"int",
"(",
"(",
"l",
">>",
"16",
")",
"&",
"U32",
"(",
"0xFF",
")",
")",
")",
"c",
".",
"append",
"(",
"int",
"(",
"(",
"l",
">>",
"8",
")",
"&",
"U32",
"(",
"0xFF",
")",
")",
")",
"c",
".",
"append",
"(",
"int",
"(",
"(",
"l",
")",
"&",
"U32",
"(",
"0xFF",
")",
")",
")",
"return",
"c"
] | host to network long | [
"host",
"to",
"network",
"long"
] | b86fdbc9be41183680b82b07d3a8e8ea10926e01 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/mschap/des_c.py#L83-L90 | train |
bearyinnovative/bearychat.py | bearychat/rtm_client.py | RTMClient.start | def start(self):
"""Gets the rtm ws_host and user information
Returns:
None if request failed,
else a dict containing "user"(User) and "ws_host"
"""
resp = self.post('start')
if resp.is_fail():
return None
if 'result' not in resp.data:
return None
result = resp.data['result']
return {
'user': result['user'],
'ws_host': result['ws_host'],
} | python | def start(self):
"""Gets the rtm ws_host and user information
Returns:
None if request failed,
else a dict containing "user"(User) and "ws_host"
"""
resp = self.post('start')
if resp.is_fail():
return None
if 'result' not in resp.data:
return None
result = resp.data['result']
return {
'user': result['user'],
'ws_host': result['ws_host'],
} | [
"def",
"start",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"post",
"(",
"'start'",
")",
"if",
"resp",
".",
"is_fail",
"(",
")",
":",
"return",
"None",
"if",
"'result'",
"not",
"in",
"resp",
".",
"data",
":",
"return",
"None",
"result",
"=",
"resp",
".",
"data",
"[",
"'result'",
"]",
"return",
"{",
"'user'",
":",
"result",
"[",
"'user'",
"]",
",",
"'ws_host'",
":",
"result",
"[",
"'ws_host'",
"]",
",",
"}"
] | Gets the rtm ws_host and user information
Returns:
None if request failed,
else a dict containing "user"(User) and "ws_host" | [
"Gets",
"the",
"rtm",
"ws_host",
"and",
"user",
"information"
] | 6c7af2d215c2ff7135bb5af66ca333d0ea1089fd | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client.py#L52-L70 | train |
bearyinnovative/bearychat.py | bearychat/rtm_client.py | RTMClient.do | def do(self,
resource,
method,
params=None,
data=None,
json=None,
headers=None):
"""Does the request job
Args:
resource(str): resource uri(relative path)
method(str): HTTP method
params(dict): uri queries
data(dict): HTTP body(form)
json(dict): HTTP body(json)
headers(dict): HTTP headers
Returns:
RTMResponse
"""
uri = "{0}/{1}".format(self._api_base, resource)
if not params:
params = {}
params.update({'token': self._token})
req = Request(
method=method,
url=uri,
params=params,
headers=headers,
data=data,
json=json)
s = Session()
prepped = s.prepare_request(req)
resp = s.send(prepped)
return RTMResponse(resp) | python | def do(self,
resource,
method,
params=None,
data=None,
json=None,
headers=None):
"""Does the request job
Args:
resource(str): resource uri(relative path)
method(str): HTTP method
params(dict): uri queries
data(dict): HTTP body(form)
json(dict): HTTP body(json)
headers(dict): HTTP headers
Returns:
RTMResponse
"""
uri = "{0}/{1}".format(self._api_base, resource)
if not params:
params = {}
params.update({'token': self._token})
req = Request(
method=method,
url=uri,
params=params,
headers=headers,
data=data,
json=json)
s = Session()
prepped = s.prepare_request(req)
resp = s.send(prepped)
return RTMResponse(resp) | [
"def",
"do",
"(",
"self",
",",
"resource",
",",
"method",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"uri",
"=",
"\"{0}/{1}\"",
".",
"format",
"(",
"self",
".",
"_api_base",
",",
"resource",
")",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"params",
".",
"update",
"(",
"{",
"'token'",
":",
"self",
".",
"_token",
"}",
")",
"req",
"=",
"Request",
"(",
"method",
"=",
"method",
",",
"url",
"=",
"uri",
",",
"params",
"=",
"params",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"data",
",",
"json",
"=",
"json",
")",
"s",
"=",
"Session",
"(",
")",
"prepped",
"=",
"s",
".",
"prepare_request",
"(",
"req",
")",
"resp",
"=",
"s",
".",
"send",
"(",
"prepped",
")",
"return",
"RTMResponse",
"(",
"resp",
")"
] | Does the request job
Args:
resource(str): resource uri(relative path)
method(str): HTTP method
params(dict): uri queries
data(dict): HTTP body(form)
json(dict): HTTP body(json)
headers(dict): HTTP headers
Returns:
RTMResponse | [
"Does",
"the",
"request",
"job"
] | 6c7af2d215c2ff7135bb5af66ca333d0ea1089fd | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client.py#L72-L108 | train |
bearyinnovative/bearychat.py | bearychat/rtm_client.py | RTMClient.get | def get(self, resource, params=None, headers=None):
"""Sends a GET request
Returns:
RTMResponse
"""
return self.do(resource, 'GET', params=params, headers=headers) | python | def get(self, resource, params=None, headers=None):
"""Sends a GET request
Returns:
RTMResponse
"""
return self.do(resource, 'GET', params=params, headers=headers) | [
"def",
"get",
"(",
"self",
",",
"resource",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"return",
"self",
".",
"do",
"(",
"resource",
",",
"'GET'",
",",
"params",
"=",
"params",
",",
"headers",
"=",
"headers",
")"
] | Sends a GET request
Returns:
RTMResponse | [
"Sends",
"a",
"GET",
"request"
] | 6c7af2d215c2ff7135bb5af66ca333d0ea1089fd | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client.py#L110-L116 | train |
bearyinnovative/bearychat.py | bearychat/rtm_client.py | RTMClient.post | def post(self, resource, data=None, json=None):
"""Sends a POST request
Returns:
RTMResponse
"""
return self.do(resource, 'POST', data=data, json=json) | python | def post(self, resource, data=None, json=None):
"""Sends a POST request
Returns:
RTMResponse
"""
return self.do(resource, 'POST', data=data, json=json) | [
"def",
"post",
"(",
"self",
",",
"resource",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
")",
":",
"return",
"self",
".",
"do",
"(",
"resource",
",",
"'POST'",
",",
"data",
"=",
"data",
",",
"json",
"=",
"json",
")"
] | Sends a POST request
Returns:
RTMResponse | [
"Sends",
"a",
"POST",
"request"
] | 6c7af2d215c2ff7135bb5af66ca333d0ea1089fd | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client.py#L118-L124 | train |
intelsdi-x/snap-plugin-lib-py | snap_plugin/v1/collector_proxy.py | _CollectorProxy.CollectMetrics | def CollectMetrics(self, request, context):
"""Dispatches the request to the plugins collect method"""
LOG.debug("CollectMetrics called")
try:
metrics_to_collect = []
for metric in request.metrics:
metrics_to_collect.append(Metric(pb=metric))
metrics_collected = self.plugin.collect(metrics_to_collect)
return MetricsReply(metrics=[m.pb for m in metrics_collected])
except Exception as err:
msg = "message: {}\n\nstack trace: {}".format(
err, traceback.format_exc())
return MetricsReply(metrics=[], error=msg) | python | def CollectMetrics(self, request, context):
"""Dispatches the request to the plugins collect method"""
LOG.debug("CollectMetrics called")
try:
metrics_to_collect = []
for metric in request.metrics:
metrics_to_collect.append(Metric(pb=metric))
metrics_collected = self.plugin.collect(metrics_to_collect)
return MetricsReply(metrics=[m.pb for m in metrics_collected])
except Exception as err:
msg = "message: {}\n\nstack trace: {}".format(
err, traceback.format_exc())
return MetricsReply(metrics=[], error=msg) | [
"def",
"CollectMetrics",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"LOG",
".",
"debug",
"(",
"\"CollectMetrics called\"",
")",
"try",
":",
"metrics_to_collect",
"=",
"[",
"]",
"for",
"metric",
"in",
"request",
".",
"metrics",
":",
"metrics_to_collect",
".",
"append",
"(",
"Metric",
"(",
"pb",
"=",
"metric",
")",
")",
"metrics_collected",
"=",
"self",
".",
"plugin",
".",
"collect",
"(",
"metrics_to_collect",
")",
"return",
"MetricsReply",
"(",
"metrics",
"=",
"[",
"m",
".",
"pb",
"for",
"m",
"in",
"metrics_collected",
"]",
")",
"except",
"Exception",
"as",
"err",
":",
"msg",
"=",
"\"message: {}\\n\\nstack trace: {}\"",
".",
"format",
"(",
"err",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"return",
"MetricsReply",
"(",
"metrics",
"=",
"[",
"]",
",",
"error",
"=",
"msg",
")"
] | Dispatches the request to the plugins collect method | [
"Dispatches",
"the",
"request",
"to",
"the",
"plugins",
"collect",
"method"
] | 8da5d00ac5f9d2b48a7239563ac7788209891ca4 | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/collector_proxy.py#L36-L48 | train |
intelsdi-x/snap-plugin-lib-py | snap_plugin/v1/plugin_proxy.py | PluginProxy.GetConfigPolicy | def GetConfigPolicy(self, request, context):
"""Dispatches the request to the plugins get_config_policy method"""
try:
policy = self.plugin.get_config_policy()
return policy._pb
except Exception as err:
msg = "message: {}\n\nstack trace: {}".format(
err.message, traceback.format_exc())
return GetConfigPolicyReply(error=msg) | python | def GetConfigPolicy(self, request, context):
"""Dispatches the request to the plugins get_config_policy method"""
try:
policy = self.plugin.get_config_policy()
return policy._pb
except Exception as err:
msg = "message: {}\n\nstack trace: {}".format(
err.message, traceback.format_exc())
return GetConfigPolicyReply(error=msg) | [
"def",
"GetConfigPolicy",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"try",
":",
"policy",
"=",
"self",
".",
"plugin",
".",
"get_config_policy",
"(",
")",
"return",
"policy",
".",
"_pb",
"except",
"Exception",
"as",
"err",
":",
"msg",
"=",
"\"message: {}\\n\\nstack trace: {}\"",
".",
"format",
"(",
"err",
".",
"message",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"return",
"GetConfigPolicyReply",
"(",
"error",
"=",
"msg",
")"
] | Dispatches the request to the plugins get_config_policy method | [
"Dispatches",
"the",
"request",
"to",
"the",
"plugins",
"get_config_policy",
"method"
] | 8da5d00ac5f9d2b48a7239563ac7788209891ca4 | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/plugin_proxy.py#L43-L51 | train |
wrboyce/telegrambot | telegrambot/api/__init__.py | TelegramAPIMixin.send_message | def send_message(self, text, chat_id, reply_to_message_id=None, disable_web_page_preview=False, reply_markup=None):
"""
Use this method to send text messages. On success, the sent Message is returned.
"""
self.logger.info('sending message "%s"', format(text.replace('\n', '\\n')))
payload = dict(text=text,
chat_id=chat_id,
reply_to_message_id=reply_to_message_id,
disable_web_page_preview=disable_web_page_preview,
reply_markup=reply_markup)
return Message.from_api(self, **self._get('sendMessage', payload)) | python | def send_message(self, text, chat_id, reply_to_message_id=None, disable_web_page_preview=False, reply_markup=None):
"""
Use this method to send text messages. On success, the sent Message is returned.
"""
self.logger.info('sending message "%s"', format(text.replace('\n', '\\n')))
payload = dict(text=text,
chat_id=chat_id,
reply_to_message_id=reply_to_message_id,
disable_web_page_preview=disable_web_page_preview,
reply_markup=reply_markup)
return Message.from_api(self, **self._get('sendMessage', payload)) | [
"def",
"send_message",
"(",
"self",
",",
"text",
",",
"chat_id",
",",
"reply_to_message_id",
"=",
"None",
",",
"disable_web_page_preview",
"=",
"False",
",",
"reply_markup",
"=",
"None",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'sending message \"%s\"'",
",",
"format",
"(",
"text",
".",
"replace",
"(",
"'\\n'",
",",
"'\\\\n'",
")",
")",
")",
"payload",
"=",
"dict",
"(",
"text",
"=",
"text",
",",
"chat_id",
"=",
"chat_id",
",",
"reply_to_message_id",
"=",
"reply_to_message_id",
",",
"disable_web_page_preview",
"=",
"disable_web_page_preview",
",",
"reply_markup",
"=",
"reply_markup",
")",
"return",
"Message",
".",
"from_api",
"(",
"self",
",",
"*",
"*",
"self",
".",
"_get",
"(",
"'sendMessage'",
",",
"payload",
")",
")"
] | Use this method to send text messages. On success, the sent Message is returned. | [
"Use",
"this",
"method",
"to",
"send",
"text",
"messages",
".",
"On",
"success",
"the",
"sent",
"Message",
"is",
"returned",
"."
] | c35ce19886df4c306a2a19851cc1f63e3066d70d | https://github.com/wrboyce/telegrambot/blob/c35ce19886df4c306a2a19851cc1f63e3066d70d/telegrambot/api/__init__.py#L63-L73 | train |
wrboyce/telegrambot | telegrambot/api/__init__.py | TelegramAPIMixin.send_audio | def send_audio(self, chat_id, audio, duration=None, performer=None, title=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send audio files, if you want Telegram clients to display them in the music player.
Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send
audio files of up to 50 MB in size, this limit may be changed in the future.
For backward compatibility, when the fields title and performer are both empty and the mime-type of the
file to be sent is not audio/mpeg, the file will be sent as a playable voice message. For this to work,
the audio must be in an .ogg file encoded with OPUS.
This behavior will be phased out in the future.
For sending voice messages, use the send_voice method instead.
"""
self.logger.info('sending audio payload %s', audio)
payload = dict(chat_id=chat_id,
duration=duration,
performer=performer,
title=title,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup)
files = dict(audio=open(audio, 'rb'))
return Message.from_api(self, **self._post('sendAudio', payload, files)) | python | def send_audio(self, chat_id, audio, duration=None, performer=None, title=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send audio files, if you want Telegram clients to display them in the music player.
Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send
audio files of up to 50 MB in size, this limit may be changed in the future.
For backward compatibility, when the fields title and performer are both empty and the mime-type of the
file to be sent is not audio/mpeg, the file will be sent as a playable voice message. For this to work,
the audio must be in an .ogg file encoded with OPUS.
This behavior will be phased out in the future.
For sending voice messages, use the send_voice method instead.
"""
self.logger.info('sending audio payload %s', audio)
payload = dict(chat_id=chat_id,
duration=duration,
performer=performer,
title=title,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup)
files = dict(audio=open(audio, 'rb'))
return Message.from_api(self, **self._post('sendAudio', payload, files)) | [
"def",
"send_audio",
"(",
"self",
",",
"chat_id",
",",
"audio",
",",
"duration",
"=",
"None",
",",
"performer",
"=",
"None",
",",
"title",
"=",
"None",
",",
"reply_to_message_id",
"=",
"None",
",",
"reply_markup",
"=",
"None",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'sending audio payload %s'",
",",
"audio",
")",
"payload",
"=",
"dict",
"(",
"chat_id",
"=",
"chat_id",
",",
"duration",
"=",
"duration",
",",
"performer",
"=",
"performer",
",",
"title",
"=",
"title",
",",
"reply_to_message_id",
"=",
"reply_to_message_id",
",",
"reply_markup",
"=",
"reply_markup",
")",
"files",
"=",
"dict",
"(",
"audio",
"=",
"open",
"(",
"audio",
",",
"'rb'",
")",
")",
"return",
"Message",
".",
"from_api",
"(",
"self",
",",
"*",
"*",
"self",
".",
"_post",
"(",
"'sendAudio'",
",",
"payload",
",",
"files",
")",
")"
] | Use this method to send audio files, if you want Telegram clients to display them in the music player.
Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send
audio files of up to 50 MB in size, this limit may be changed in the future.
For backward compatibility, when the fields title and performer are both empty and the mime-type of the
file to be sent is not audio/mpeg, the file will be sent as a playable voice message. For this to work,
the audio must be in an .ogg file encoded with OPUS.
This behavior will be phased out in the future.
For sending voice messages, use the send_voice method instead. | [
"Use",
"this",
"method",
"to",
"send",
"audio",
"files",
"if",
"you",
"want",
"Telegram",
"clients",
"to",
"display",
"them",
"in",
"the",
"music",
"player",
".",
"Your",
"audio",
"must",
"be",
"in",
"the",
".",
"mp3",
"format",
".",
"On",
"success",
"the",
"sent",
"Message",
"is",
"returned",
".",
"Bots",
"can",
"currently",
"send",
"audio",
"files",
"of",
"up",
"to",
"50",
"MB",
"in",
"size",
"this",
"limit",
"may",
"be",
"changed",
"in",
"the",
"future",
"."
] | c35ce19886df4c306a2a19851cc1f63e3066d70d | https://github.com/wrboyce/telegrambot/blob/c35ce19886df4c306a2a19851cc1f63e3066d70d/telegrambot/api/__init__.py#L97-L118 | train |
wrboyce/telegrambot | telegrambot/api/__init__.py | TelegramAPIMixin.send_document | def send_document(self, chat_id=None, document=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send general files. On success, the sent Message is returned.
Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
"""
payload = dict(chat_id=chat_id,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup)
files = dict(video=open(document, 'rb'))
return Message.from_api(api, **self._post('sendDocument', payload, files)) | python | def send_document(self, chat_id=None, document=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send general files. On success, the sent Message is returned.
Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
"""
payload = dict(chat_id=chat_id,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup)
files = dict(video=open(document, 'rb'))
return Message.from_api(api, **self._post('sendDocument', payload, files)) | [
"def",
"send_document",
"(",
"self",
",",
"chat_id",
"=",
"None",
",",
"document",
"=",
"None",
",",
"reply_to_message_id",
"=",
"None",
",",
"reply_markup",
"=",
"None",
")",
":",
"payload",
"=",
"dict",
"(",
"chat_id",
"=",
"chat_id",
",",
"reply_to_message_id",
"=",
"reply_to_message_id",
",",
"reply_markup",
"=",
"reply_markup",
")",
"files",
"=",
"dict",
"(",
"video",
"=",
"open",
"(",
"document",
",",
"'rb'",
")",
")",
"return",
"Message",
".",
"from_api",
"(",
"api",
",",
"*",
"*",
"self",
".",
"_post",
"(",
"'sendDocument'",
",",
"payload",
",",
"files",
")",
")"
] | Use this method to send general files. On success, the sent Message is returned.
Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. | [
"Use",
"this",
"method",
"to",
"send",
"general",
"files",
".",
"On",
"success",
"the",
"sent",
"Message",
"is",
"returned",
".",
"Bots",
"can",
"currently",
"send",
"files",
"of",
"any",
"type",
"of",
"up",
"to",
"50",
"MB",
"in",
"size",
"this",
"limit",
"may",
"be",
"changed",
"in",
"the",
"future",
"."
] | c35ce19886df4c306a2a19851cc1f63e3066d70d | https://github.com/wrboyce/telegrambot/blob/c35ce19886df4c306a2a19851cc1f63e3066d70d/telegrambot/api/__init__.py#L120-L129 | train |
wrboyce/telegrambot | telegrambot/api/__init__.py | TelegramAPIMixin.send_sticker | def send_sticker(self, chat_id=None, sticker=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send .webp stickers. On success, the sent Message is returned.
"""
payload = dict(chat_id=chat_id,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup)
files = dict(sticker=open(sticker, 'rb'))
return Message.from_api(api, **self._post('sendSticker', payload, files)) | python | def send_sticker(self, chat_id=None, sticker=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send .webp stickers. On success, the sent Message is returned.
"""
payload = dict(chat_id=chat_id,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup)
files = dict(sticker=open(sticker, 'rb'))
return Message.from_api(api, **self._post('sendSticker', payload, files)) | [
"def",
"send_sticker",
"(",
"self",
",",
"chat_id",
"=",
"None",
",",
"sticker",
"=",
"None",
",",
"reply_to_message_id",
"=",
"None",
",",
"reply_markup",
"=",
"None",
")",
":",
"payload",
"=",
"dict",
"(",
"chat_id",
"=",
"chat_id",
",",
"reply_to_message_id",
"=",
"reply_to_message_id",
",",
"reply_markup",
"=",
"reply_markup",
")",
"files",
"=",
"dict",
"(",
"sticker",
"=",
"open",
"(",
"sticker",
",",
"'rb'",
")",
")",
"return",
"Message",
".",
"from_api",
"(",
"api",
",",
"*",
"*",
"self",
".",
"_post",
"(",
"'sendSticker'",
",",
"payload",
",",
"files",
")",
")"
] | Use this method to send .webp stickers. On success, the sent Message is returned. | [
"Use",
"this",
"method",
"to",
"send",
".",
"webp",
"stickers",
".",
"On",
"success",
"the",
"sent",
"Message",
"is",
"returned",
"."
] | c35ce19886df4c306a2a19851cc1f63e3066d70d | https://github.com/wrboyce/telegrambot/blob/c35ce19886df4c306a2a19851cc1f63e3066d70d/telegrambot/api/__init__.py#L131-L139 | train |
bitesofcode/projexui | projexui/widgets/xganttwidget/xganttwidgetitem.py | XGanttWidgetItem.removeFromScene | def removeFromScene(self):
"""
Removes this item from the view scene.
"""
gantt = self.ganttWidget()
if not gantt:
return
scene = gantt.viewWidget().scene()
scene.removeItem(self.viewItem())
for target, viewItem in self._dependencies.items():
target._reverseDependencies.pop(self)
scene.removeItem(viewItem) | python | def removeFromScene(self):
"""
Removes this item from the view scene.
"""
gantt = self.ganttWidget()
if not gantt:
return
scene = gantt.viewWidget().scene()
scene.removeItem(self.viewItem())
for target, viewItem in self._dependencies.items():
target._reverseDependencies.pop(self)
scene.removeItem(viewItem) | [
"def",
"removeFromScene",
"(",
"self",
")",
":",
"gantt",
"=",
"self",
".",
"ganttWidget",
"(",
")",
"if",
"not",
"gantt",
":",
"return",
"scene",
"=",
"gantt",
".",
"viewWidget",
"(",
")",
".",
"scene",
"(",
")",
"scene",
".",
"removeItem",
"(",
"self",
".",
"viewItem",
"(",
")",
")",
"for",
"target",
",",
"viewItem",
"in",
"self",
".",
"_dependencies",
".",
"items",
"(",
")",
":",
"target",
".",
"_reverseDependencies",
".",
"pop",
"(",
"self",
")",
"scene",
".",
"removeItem",
"(",
"viewItem",
")"
] | Removes this item from the view scene. | [
"Removes",
"this",
"item",
"from",
"the",
"view",
"scene",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidgetitem.py#L331-L344 | train |
bitesofcode/projexui | projexui/widgets/xganttwidget/xganttwidgetitem.py | XGanttWidgetItem.sync | def sync(self, recursive=False):
"""
Syncs the information from this item to the tree and view.
"""
self.syncTree(recursive=recursive)
self.syncView(recursive=recursive) | python | def sync(self, recursive=False):
"""
Syncs the information from this item to the tree and view.
"""
self.syncTree(recursive=recursive)
self.syncView(recursive=recursive) | [
"def",
"sync",
"(",
"self",
",",
"recursive",
"=",
"False",
")",
":",
"self",
".",
"syncTree",
"(",
"recursive",
"=",
"recursive",
")",
"self",
".",
"syncView",
"(",
"recursive",
"=",
"recursive",
")"
] | Syncs the information from this item to the tree and view. | [
"Syncs",
"the",
"information",
"from",
"this",
"item",
"to",
"the",
"tree",
"and",
"view",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidgetitem.py#L503-L508 | train |
bitesofcode/projexui | projexui/widgets/xganttwidget/xganttwidgetitem.py | XGanttWidgetItem.syncTree | def syncTree(self, recursive=False, blockSignals=True):
"""
Syncs the information from this item to the tree.
"""
tree = self.treeWidget()
# sync the tree information
if not tree:
return
items = [self]
if recursive:
items += list(self.children(recursive=True))
if blockSignals and not tree.signalsBlocked():
blocked = True
tree.blockSignals(True)
else:
blocked = False
date_format = self.ganttWidget().dateFormat()
for item in items:
for c, col in enumerate(tree.columns()):
value = item.property(col, '')
item.setData(c, Qt.EditRole, wrapVariant(value))
if blocked:
tree.blockSignals(False) | python | def syncTree(self, recursive=False, blockSignals=True):
"""
Syncs the information from this item to the tree.
"""
tree = self.treeWidget()
# sync the tree information
if not tree:
return
items = [self]
if recursive:
items += list(self.children(recursive=True))
if blockSignals and not tree.signalsBlocked():
blocked = True
tree.blockSignals(True)
else:
blocked = False
date_format = self.ganttWidget().dateFormat()
for item in items:
for c, col in enumerate(tree.columns()):
value = item.property(col, '')
item.setData(c, Qt.EditRole, wrapVariant(value))
if blocked:
tree.blockSignals(False) | [
"def",
"syncTree",
"(",
"self",
",",
"recursive",
"=",
"False",
",",
"blockSignals",
"=",
"True",
")",
":",
"tree",
"=",
"self",
".",
"treeWidget",
"(",
")",
"# sync the tree information\r",
"if",
"not",
"tree",
":",
"return",
"items",
"=",
"[",
"self",
"]",
"if",
"recursive",
":",
"items",
"+=",
"list",
"(",
"self",
".",
"children",
"(",
"recursive",
"=",
"True",
")",
")",
"if",
"blockSignals",
"and",
"not",
"tree",
".",
"signalsBlocked",
"(",
")",
":",
"blocked",
"=",
"True",
"tree",
".",
"blockSignals",
"(",
"True",
")",
"else",
":",
"blocked",
"=",
"False",
"date_format",
"=",
"self",
".",
"ganttWidget",
"(",
")",
".",
"dateFormat",
"(",
")",
"for",
"item",
"in",
"items",
":",
"for",
"c",
",",
"col",
"in",
"enumerate",
"(",
"tree",
".",
"columns",
"(",
")",
")",
":",
"value",
"=",
"item",
".",
"property",
"(",
"col",
",",
"''",
")",
"item",
".",
"setData",
"(",
"c",
",",
"Qt",
".",
"EditRole",
",",
"wrapVariant",
"(",
"value",
")",
")",
"if",
"blocked",
":",
"tree",
".",
"blockSignals",
"(",
"False",
")"
] | Syncs the information from this item to the tree. | [
"Syncs",
"the",
"information",
"from",
"this",
"item",
"to",
"the",
"tree",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidgetitem.py#L535-L563 | train |
bitesofcode/projexui | projexui/widgets/xganttwidget/xganttwidgetitem.py | XGanttWidgetItem.syncView | def syncView(self, recursive=False):
"""
Syncs the information from this item to the view.
"""
# update the view widget
gantt = self.ganttWidget()
tree = self.treeWidget()
if not gantt:
return
vwidget = gantt.viewWidget()
scene = vwidget.scene()
cell_w = gantt.cellWidth()
tree_offset_y = tree.header().height() + 1
tree_offset_y += tree.verticalScrollBar().value()
# collect the items to work on
items = [self]
if recursive:
items += list(self.children(recursive=True))
for item in items:
# grab the view item from the gantt item
vitem = item.viewItem()
if not vitem.scene():
scene.addItem(vitem)
# make sure the item should be visible
if item.isHidden() or not tree:
vitem.hide()
continue
vitem.show()
tree_rect = tree.visualItemRect(item)
tree_y = tree_rect.y() + tree_offset_y
tree_h = tree_rect.height()
# check to see if this item is hidden
if tree_rect.height() == 0:
vitem.hide()
continue
if gantt.timescale() in (gantt.Timescale.Minute,
gantt.Timescale.Hour,
gantt.Timescale.Day):
dstart = item.dateTimeStart()
dend = item.dateTimeEnd()
view_x = scene.datetimeXPos(dstart)
view_r = scene.datetimeXPos(dend)
view_w = view_r - view_x
else:
view_x = scene.dateXPos(item.dateStart())
view_w = item.duration() * cell_w
# determine the % off from the length based on this items time
if not item.isAllDay():
full_day = 24 * 60 * 60 # full days worth of seconds
# determine the start offset
start = item.timeStart()
start_day = (start.hour() * 60 * 60)
start_day += (start.minute() * 60)
start_day += (start.second())
offset_start = (start_day / float(full_day)) * cell_w
# determine the end offset
end = item.timeEnd()
end_day = (end.hour() * 60 * 60)
end_day += (start.minute() * 60)
end_day += (start.second() + 1) # forces at least 1 sec
offset_end = ((full_day - end_day) / float(full_day))
offset_end *= cell_w
# update the xpos and widths
view_x += offset_start
view_w -= (offset_start + offset_end)
view_w = max(view_w, 5)
vitem.setSyncing(True)
vitem.setPos(view_x, tree_y)
vitem.setRect(0, 0, view_w, tree_h)
vitem.setSyncing(False)
# setup standard properties
flags = vitem.ItemIsSelectable
flags |= vitem.ItemIsFocusable
if item.flags() & Qt.ItemIsEditable:
flags |= vitem.ItemIsMovable
vitem.setFlags(flags)
item.syncDependencies() | python | def syncView(self, recursive=False):
"""
Syncs the information from this item to the view.
"""
# update the view widget
gantt = self.ganttWidget()
tree = self.treeWidget()
if not gantt:
return
vwidget = gantt.viewWidget()
scene = vwidget.scene()
cell_w = gantt.cellWidth()
tree_offset_y = tree.header().height() + 1
tree_offset_y += tree.verticalScrollBar().value()
# collect the items to work on
items = [self]
if recursive:
items += list(self.children(recursive=True))
for item in items:
# grab the view item from the gantt item
vitem = item.viewItem()
if not vitem.scene():
scene.addItem(vitem)
# make sure the item should be visible
if item.isHidden() or not tree:
vitem.hide()
continue
vitem.show()
tree_rect = tree.visualItemRect(item)
tree_y = tree_rect.y() + tree_offset_y
tree_h = tree_rect.height()
# check to see if this item is hidden
if tree_rect.height() == 0:
vitem.hide()
continue
if gantt.timescale() in (gantt.Timescale.Minute,
gantt.Timescale.Hour,
gantt.Timescale.Day):
dstart = item.dateTimeStart()
dend = item.dateTimeEnd()
view_x = scene.datetimeXPos(dstart)
view_r = scene.datetimeXPos(dend)
view_w = view_r - view_x
else:
view_x = scene.dateXPos(item.dateStart())
view_w = item.duration() * cell_w
# determine the % off from the length based on this items time
if not item.isAllDay():
full_day = 24 * 60 * 60 # full days worth of seconds
# determine the start offset
start = item.timeStart()
start_day = (start.hour() * 60 * 60)
start_day += (start.minute() * 60)
start_day += (start.second())
offset_start = (start_day / float(full_day)) * cell_w
# determine the end offset
end = item.timeEnd()
end_day = (end.hour() * 60 * 60)
end_day += (start.minute() * 60)
end_day += (start.second() + 1) # forces at least 1 sec
offset_end = ((full_day - end_day) / float(full_day))
offset_end *= cell_w
# update the xpos and widths
view_x += offset_start
view_w -= (offset_start + offset_end)
view_w = max(view_w, 5)
vitem.setSyncing(True)
vitem.setPos(view_x, tree_y)
vitem.setRect(0, 0, view_w, tree_h)
vitem.setSyncing(False)
# setup standard properties
flags = vitem.ItemIsSelectable
flags |= vitem.ItemIsFocusable
if item.flags() & Qt.ItemIsEditable:
flags |= vitem.ItemIsMovable
vitem.setFlags(flags)
item.syncDependencies() | [
"def",
"syncView",
"(",
"self",
",",
"recursive",
"=",
"False",
")",
":",
"# update the view widget\r",
"gantt",
"=",
"self",
".",
"ganttWidget",
"(",
")",
"tree",
"=",
"self",
".",
"treeWidget",
"(",
")",
"if",
"not",
"gantt",
":",
"return",
"vwidget",
"=",
"gantt",
".",
"viewWidget",
"(",
")",
"scene",
"=",
"vwidget",
".",
"scene",
"(",
")",
"cell_w",
"=",
"gantt",
".",
"cellWidth",
"(",
")",
"tree_offset_y",
"=",
"tree",
".",
"header",
"(",
")",
".",
"height",
"(",
")",
"+",
"1",
"tree_offset_y",
"+=",
"tree",
".",
"verticalScrollBar",
"(",
")",
".",
"value",
"(",
")",
"# collect the items to work on\r",
"items",
"=",
"[",
"self",
"]",
"if",
"recursive",
":",
"items",
"+=",
"list",
"(",
"self",
".",
"children",
"(",
"recursive",
"=",
"True",
")",
")",
"for",
"item",
"in",
"items",
":",
"# grab the view item from the gantt item\r",
"vitem",
"=",
"item",
".",
"viewItem",
"(",
")",
"if",
"not",
"vitem",
".",
"scene",
"(",
")",
":",
"scene",
".",
"addItem",
"(",
"vitem",
")",
"# make sure the item should be visible\r",
"if",
"item",
".",
"isHidden",
"(",
")",
"or",
"not",
"tree",
":",
"vitem",
".",
"hide",
"(",
")",
"continue",
"vitem",
".",
"show",
"(",
")",
"tree_rect",
"=",
"tree",
".",
"visualItemRect",
"(",
"item",
")",
"tree_y",
"=",
"tree_rect",
".",
"y",
"(",
")",
"+",
"tree_offset_y",
"tree_h",
"=",
"tree_rect",
".",
"height",
"(",
")",
"# check to see if this item is hidden\r",
"if",
"tree_rect",
".",
"height",
"(",
")",
"==",
"0",
":",
"vitem",
".",
"hide",
"(",
")",
"continue",
"if",
"gantt",
".",
"timescale",
"(",
")",
"in",
"(",
"gantt",
".",
"Timescale",
".",
"Minute",
",",
"gantt",
".",
"Timescale",
".",
"Hour",
",",
"gantt",
".",
"Timescale",
".",
"Day",
")",
":",
"dstart",
"=",
"item",
".",
"dateTimeStart",
"(",
")",
"dend",
"=",
"item",
".",
"dateTimeEnd",
"(",
")",
"view_x",
"=",
"scene",
".",
"datetimeXPos",
"(",
"dstart",
")",
"view_r",
"=",
"scene",
".",
"datetimeXPos",
"(",
"dend",
")",
"view_w",
"=",
"view_r",
"-",
"view_x",
"else",
":",
"view_x",
"=",
"scene",
".",
"dateXPos",
"(",
"item",
".",
"dateStart",
"(",
")",
")",
"view_w",
"=",
"item",
".",
"duration",
"(",
")",
"*",
"cell_w",
"# determine the % off from the length based on this items time\r",
"if",
"not",
"item",
".",
"isAllDay",
"(",
")",
":",
"full_day",
"=",
"24",
"*",
"60",
"*",
"60",
"# full days worth of seconds\r",
"# determine the start offset\r",
"start",
"=",
"item",
".",
"timeStart",
"(",
")",
"start_day",
"=",
"(",
"start",
".",
"hour",
"(",
")",
"*",
"60",
"*",
"60",
")",
"start_day",
"+=",
"(",
"start",
".",
"minute",
"(",
")",
"*",
"60",
")",
"start_day",
"+=",
"(",
"start",
".",
"second",
"(",
")",
")",
"offset_start",
"=",
"(",
"start_day",
"/",
"float",
"(",
"full_day",
")",
")",
"*",
"cell_w",
"# determine the end offset\r",
"end",
"=",
"item",
".",
"timeEnd",
"(",
")",
"end_day",
"=",
"(",
"end",
".",
"hour",
"(",
")",
"*",
"60",
"*",
"60",
")",
"end_day",
"+=",
"(",
"start",
".",
"minute",
"(",
")",
"*",
"60",
")",
"end_day",
"+=",
"(",
"start",
".",
"second",
"(",
")",
"+",
"1",
")",
"# forces at least 1 sec\r",
"offset_end",
"=",
"(",
"(",
"full_day",
"-",
"end_day",
")",
"/",
"float",
"(",
"full_day",
")",
")",
"offset_end",
"*=",
"cell_w",
"# update the xpos and widths\r",
"view_x",
"+=",
"offset_start",
"view_w",
"-=",
"(",
"offset_start",
"+",
"offset_end",
")",
"view_w",
"=",
"max",
"(",
"view_w",
",",
"5",
")",
"vitem",
".",
"setSyncing",
"(",
"True",
")",
"vitem",
".",
"setPos",
"(",
"view_x",
",",
"tree_y",
")",
"vitem",
".",
"setRect",
"(",
"0",
",",
"0",
",",
"view_w",
",",
"tree_h",
")",
"vitem",
".",
"setSyncing",
"(",
"False",
")",
"# setup standard properties\r",
"flags",
"=",
"vitem",
".",
"ItemIsSelectable",
"flags",
"|=",
"vitem",
".",
"ItemIsFocusable",
"if",
"item",
".",
"flags",
"(",
")",
"&",
"Qt",
".",
"ItemIsEditable",
":",
"flags",
"|=",
"vitem",
".",
"ItemIsMovable",
"vitem",
".",
"setFlags",
"(",
"flags",
")",
"item",
".",
"syncDependencies",
"(",
")"
] | Syncs the information from this item to the view. | [
"Syncs",
"the",
"information",
"from",
"this",
"item",
"to",
"the",
"view",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidgetitem.py#L565-L662 | train |
pmuller/versions | versions/requirements.py | Requirement.match | def match(self, package):
"""Match ``package`` with the requirement.
:param package: Package to test with the requirement.
:type package: package expression string or :class:`Package`
:returns: ``True`` if ``package`` satisfies the requirement.
:rtype: bool
"""
if isinstance(package, basestring):
from .packages import Package
package = Package.parse(package)
if self.name != package.name:
return False
if self.version_constraints and \
package.version not in self.version_constraints:
return False
if self.build_options:
if package.build_options:
if self.build_options - package.build_options:
return False
else:
return True
else:
return False
else:
return True | python | def match(self, package):
"""Match ``package`` with the requirement.
:param package: Package to test with the requirement.
:type package: package expression string or :class:`Package`
:returns: ``True`` if ``package`` satisfies the requirement.
:rtype: bool
"""
if isinstance(package, basestring):
from .packages import Package
package = Package.parse(package)
if self.name != package.name:
return False
if self.version_constraints and \
package.version not in self.version_constraints:
return False
if self.build_options:
if package.build_options:
if self.build_options - package.build_options:
return False
else:
return True
else:
return False
else:
return True | [
"def",
"match",
"(",
"self",
",",
"package",
")",
":",
"if",
"isinstance",
"(",
"package",
",",
"basestring",
")",
":",
"from",
".",
"packages",
"import",
"Package",
"package",
"=",
"Package",
".",
"parse",
"(",
"package",
")",
"if",
"self",
".",
"name",
"!=",
"package",
".",
"name",
":",
"return",
"False",
"if",
"self",
".",
"version_constraints",
"and",
"package",
".",
"version",
"not",
"in",
"self",
".",
"version_constraints",
":",
"return",
"False",
"if",
"self",
".",
"build_options",
":",
"if",
"package",
".",
"build_options",
":",
"if",
"self",
".",
"build_options",
"-",
"package",
".",
"build_options",
":",
"return",
"False",
"else",
":",
"return",
"True",
"else",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | Match ``package`` with the requirement.
:param package: Package to test with the requirement.
:type package: package expression string or :class:`Package`
:returns: ``True`` if ``package`` satisfies the requirement.
:rtype: bool | [
"Match",
"package",
"with",
"the",
"requirement",
"."
] | 951bc3fd99b6a675190f11ee0752af1d7ff5b440 | https://github.com/pmuller/versions/blob/951bc3fd99b6a675190f11ee0752af1d7ff5b440/versions/requirements.py#L117-L146 | train |
johnnoone/aioconsul | aioconsul/client/status_endpoint.py | StatusEndpoint.leader | async def leader(self):
"""Returns the current Raft leader
Returns:
str: address of leader such as ``10.1.10.12:8300``
"""
response = await self._api.get("/v1/status/leader")
if response.status == 200:
return response.body | python | async def leader(self):
"""Returns the current Raft leader
Returns:
str: address of leader such as ``10.1.10.12:8300``
"""
response = await self._api.get("/v1/status/leader")
if response.status == 200:
return response.body | [
"async",
"def",
"leader",
"(",
"self",
")",
":",
"response",
"=",
"await",
"self",
".",
"_api",
".",
"get",
"(",
"\"/v1/status/leader\"",
")",
"if",
"response",
".",
"status",
"==",
"200",
":",
"return",
"response",
".",
"body"
] | Returns the current Raft leader
Returns:
str: address of leader such as ``10.1.10.12:8300`` | [
"Returns",
"the",
"current",
"Raft",
"leader"
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/status_endpoint.py#L11-L19 | train |
johnnoone/aioconsul | aioconsul/client/status_endpoint.py | StatusEndpoint.peers | async def peers(self):
"""Returns the current Raft peer set
Returns:
Collection: addresses of peers
This endpoint retrieves the Raft peers for the datacenter in which
the agent is running. It returns a collection of addresses, such as::
[
"10.1.10.12:8300",
"10.1.10.11:8300",
"10.1.10.10:8300"
]
This list of peers is strongly consistent and can be useful in
determining when a given server has successfully joined the cluster.
"""
response = await self._api.get("/v1/status/peers")
if response.status == 200:
return set(response.body) | python | async def peers(self):
"""Returns the current Raft peer set
Returns:
Collection: addresses of peers
This endpoint retrieves the Raft peers for the datacenter in which
the agent is running. It returns a collection of addresses, such as::
[
"10.1.10.12:8300",
"10.1.10.11:8300",
"10.1.10.10:8300"
]
This list of peers is strongly consistent and can be useful in
determining when a given server has successfully joined the cluster.
"""
response = await self._api.get("/v1/status/peers")
if response.status == 200:
return set(response.body) | [
"async",
"def",
"peers",
"(",
"self",
")",
":",
"response",
"=",
"await",
"self",
".",
"_api",
".",
"get",
"(",
"\"/v1/status/peers\"",
")",
"if",
"response",
".",
"status",
"==",
"200",
":",
"return",
"set",
"(",
"response",
".",
"body",
")"
] | Returns the current Raft peer set
Returns:
Collection: addresses of peers
This endpoint retrieves the Raft peers for the datacenter in which
the agent is running. It returns a collection of addresses, such as::
[
"10.1.10.12:8300",
"10.1.10.11:8300",
"10.1.10.10:8300"
]
This list of peers is strongly consistent and can be useful in
determining when a given server has successfully joined the cluster. | [
"Returns",
"the",
"current",
"Raft",
"peer",
"set"
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/status_endpoint.py#L21-L41 | train |
bitesofcode/projexui | projexui/widgets/xsplitter.py | XSplitterHandle.unmarkCollapsed | def unmarkCollapsed( self ):
"""
Unmarks this splitter as being in a collapsed state, clearing any \
collapsed information.
"""
if ( not self.isCollapsed() ):
return
self._collapsed = False
self._storedSizes = None
if ( self.orientation() == Qt.Vertical ):
self._collapseBefore.setArrowType( Qt.UpArrow )
self._collapseAfter.setArrowType( Qt.DownArrow )
else:
self._collapseBefore.setArrowType( Qt.LeftArrow )
self._collapseAfter.setArrowType( Qt.RightArrow ) | python | def unmarkCollapsed( self ):
"""
Unmarks this splitter as being in a collapsed state, clearing any \
collapsed information.
"""
if ( not self.isCollapsed() ):
return
self._collapsed = False
self._storedSizes = None
if ( self.orientation() == Qt.Vertical ):
self._collapseBefore.setArrowType( Qt.UpArrow )
self._collapseAfter.setArrowType( Qt.DownArrow )
else:
self._collapseBefore.setArrowType( Qt.LeftArrow )
self._collapseAfter.setArrowType( Qt.RightArrow ) | [
"def",
"unmarkCollapsed",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"isCollapsed",
"(",
")",
")",
":",
"return",
"self",
".",
"_collapsed",
"=",
"False",
"self",
".",
"_storedSizes",
"=",
"None",
"if",
"(",
"self",
".",
"orientation",
"(",
")",
"==",
"Qt",
".",
"Vertical",
")",
":",
"self",
".",
"_collapseBefore",
".",
"setArrowType",
"(",
"Qt",
".",
"UpArrow",
")",
"self",
".",
"_collapseAfter",
".",
"setArrowType",
"(",
"Qt",
".",
"DownArrow",
")",
"else",
":",
"self",
".",
"_collapseBefore",
".",
"setArrowType",
"(",
"Qt",
".",
"LeftArrow",
")",
"self",
".",
"_collapseAfter",
".",
"setArrowType",
"(",
"Qt",
".",
"RightArrow",
")"
] | Unmarks this splitter as being in a collapsed state, clearing any \
collapsed information. | [
"Unmarks",
"this",
"splitter",
"as",
"being",
"in",
"a",
"collapsed",
"state",
"clearing",
"any",
"\\",
"collapsed",
"information",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsplitter.py#L269-L285 | train |
bitesofcode/projexui | projexui/widgets/xsplitter.py | XSplitterHandle.toggleCollapseAfter | def toggleCollapseAfter( self ):
"""
Collapses the splitter after this handle.
"""
if ( self.isCollapsed() ):
self.uncollapse()
else:
self.collapse( XSplitterHandle.CollapseDirection.After ) | python | def toggleCollapseAfter( self ):
"""
Collapses the splitter after this handle.
"""
if ( self.isCollapsed() ):
self.uncollapse()
else:
self.collapse( XSplitterHandle.CollapseDirection.After ) | [
"def",
"toggleCollapseAfter",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"isCollapsed",
"(",
")",
")",
":",
"self",
".",
"uncollapse",
"(",
")",
"else",
":",
"self",
".",
"collapse",
"(",
"XSplitterHandle",
".",
"CollapseDirection",
".",
"After",
")"
] | Collapses the splitter after this handle. | [
"Collapses",
"the",
"splitter",
"after",
"this",
"handle",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsplitter.py#L287-L294 | train |
bitesofcode/projexui | projexui/widgets/xsplitter.py | XSplitterHandle.toggleCollapseBefore | def toggleCollapseBefore( self ):
"""
Collapses the splitter before this handle.
"""
if ( self.isCollapsed() ):
self.uncollapse()
else:
self.collapse( XSplitterHandle.CollapseDirection.Before ) | python | def toggleCollapseBefore( self ):
"""
Collapses the splitter before this handle.
"""
if ( self.isCollapsed() ):
self.uncollapse()
else:
self.collapse( XSplitterHandle.CollapseDirection.Before ) | [
"def",
"toggleCollapseBefore",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"isCollapsed",
"(",
")",
")",
":",
"self",
".",
"uncollapse",
"(",
")",
"else",
":",
"self",
".",
"collapse",
"(",
"XSplitterHandle",
".",
"CollapseDirection",
".",
"Before",
")"
] | Collapses the splitter before this handle. | [
"Collapses",
"the",
"splitter",
"before",
"this",
"handle",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsplitter.py#L296-L303 | train |
bitesofcode/projexui | projexui/configs/xschemeconfig.py | XSchemeConfig.reset | def reset( self ):
"""
Resets the colors to the default settings.
"""
dataSet = self.dataSet()
if ( not dataSet ):
dataSet = XScheme()
dataSet.reset() | python | def reset( self ):
"""
Resets the colors to the default settings.
"""
dataSet = self.dataSet()
if ( not dataSet ):
dataSet = XScheme()
dataSet.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"dataSet",
"=",
"self",
".",
"dataSet",
"(",
")",
"if",
"(",
"not",
"dataSet",
")",
":",
"dataSet",
"=",
"XScheme",
"(",
")",
"dataSet",
".",
"reset",
"(",
")"
] | Resets the colors to the default settings. | [
"Resets",
"the",
"colors",
"to",
"the",
"default",
"settings",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/configs/xschemeconfig.py#L113-L121 | train |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnodelayer.py | XNodeLayer.ensureVisible | def ensureVisible(self):
"""
Ensures that this layer is visible by turning on all parent layers \
that it needs to based on its inheritance value.
"""
# make sure all parents are visible
if self._parent and self._inheritVisibility:
self._parent.ensureVisible()
self._visible = True
self.sync() | python | def ensureVisible(self):
"""
Ensures that this layer is visible by turning on all parent layers \
that it needs to based on its inheritance value.
"""
# make sure all parents are visible
if self._parent and self._inheritVisibility:
self._parent.ensureVisible()
self._visible = True
self.sync() | [
"def",
"ensureVisible",
"(",
"self",
")",
":",
"# make sure all parents are visible",
"if",
"self",
".",
"_parent",
"and",
"self",
".",
"_inheritVisibility",
":",
"self",
".",
"_parent",
".",
"ensureVisible",
"(",
")",
"self",
".",
"_visible",
"=",
"True",
"self",
".",
"sync",
"(",
")"
] | Ensures that this layer is visible by turning on all parent layers \
that it needs to based on its inheritance value. | [
"Ensures",
"that",
"this",
"layer",
"is",
"visible",
"by",
"turning",
"on",
"all",
"parent",
"layers",
"\\",
"that",
"it",
"needs",
"to",
"based",
"on",
"its",
"inheritance",
"value",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodelayer.py#L97-L107 | train |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnodelayer.py | XNodeLayer.sync | def sync(self):
"""
Syncs the items on this layer with the current layer settings.
"""
layerData = self.layerData()
for item in self.scene().items():
try:
if item._layer == self:
item.syncLayerData(layerData)
except AttributeError:
continue | python | def sync(self):
"""
Syncs the items on this layer with the current layer settings.
"""
layerData = self.layerData()
for item in self.scene().items():
try:
if item._layer == self:
item.syncLayerData(layerData)
except AttributeError:
continue | [
"def",
"sync",
"(",
"self",
")",
":",
"layerData",
"=",
"self",
".",
"layerData",
"(",
")",
"for",
"item",
"in",
"self",
".",
"scene",
"(",
")",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"item",
".",
"_layer",
"==",
"self",
":",
"item",
".",
"syncLayerData",
"(",
"layerData",
")",
"except",
"AttributeError",
":",
"continue"
] | Syncs the items on this layer with the current layer settings. | [
"Syncs",
"the",
"items",
"on",
"this",
"layer",
"with",
"the",
"current",
"layer",
"settings",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodelayer.py#L391-L401 | train |
core/uricore | uricore/wkz_urls.py | _safe_urlsplit | def _safe_urlsplit(s):
"""the urlparse.urlsplit cache breaks if it contains unicode and
we cannot control that. So we force type cast that thing back
to what we think it is.
"""
rv = urlparse.urlsplit(s)
# we have to check rv[2] here and not rv[1] as rv[1] will be
# an empty bytestring in case no domain was given.
if type(rv[2]) is not type(s):
assert hasattr(urlparse, 'clear_cache')
urlparse.clear_cache()
rv = urlparse.urlsplit(s)
assert type(rv[2]) is type(s)
return rv | python | def _safe_urlsplit(s):
"""the urlparse.urlsplit cache breaks if it contains unicode and
we cannot control that. So we force type cast that thing back
to what we think it is.
"""
rv = urlparse.urlsplit(s)
# we have to check rv[2] here and not rv[1] as rv[1] will be
# an empty bytestring in case no domain was given.
if type(rv[2]) is not type(s):
assert hasattr(urlparse, 'clear_cache')
urlparse.clear_cache()
rv = urlparse.urlsplit(s)
assert type(rv[2]) is type(s)
return rv | [
"def",
"_safe_urlsplit",
"(",
"s",
")",
":",
"rv",
"=",
"urlparse",
".",
"urlsplit",
"(",
"s",
")",
"# we have to check rv[2] here and not rv[1] as rv[1] will be",
"# an empty bytestring in case no domain was given.",
"if",
"type",
"(",
"rv",
"[",
"2",
"]",
")",
"is",
"not",
"type",
"(",
"s",
")",
":",
"assert",
"hasattr",
"(",
"urlparse",
",",
"'clear_cache'",
")",
"urlparse",
".",
"clear_cache",
"(",
")",
"rv",
"=",
"urlparse",
".",
"urlsplit",
"(",
"s",
")",
"assert",
"type",
"(",
"rv",
"[",
"2",
"]",
")",
"is",
"type",
"(",
"s",
")",
"return",
"rv"
] | the urlparse.urlsplit cache breaks if it contains unicode and
we cannot control that. So we force type cast that thing back
to what we think it is. | [
"the",
"urlparse",
".",
"urlsplit",
"cache",
"breaks",
"if",
"it",
"contains",
"unicode",
"and",
"we",
"cannot",
"control",
"that",
".",
"So",
"we",
"force",
"type",
"cast",
"that",
"thing",
"back",
"to",
"what",
"we",
"think",
"it",
"is",
"."
] | dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a | https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L58-L71 | train |
core/uricore | uricore/wkz_urls.py | _uri_split | def _uri_split(uri):
"""Splits up an URI or IRI."""
scheme, netloc, path, query, fragment = _safe_urlsplit(uri)
auth = None
port = None
if '@' in netloc:
auth, netloc = netloc.split('@', 1)
if netloc.startswith('['):
host, port_part = netloc[1:].split(']', 1)
if port_part.startswith(':'):
port = port_part[1:]
elif ':' in netloc:
host, port = netloc.split(':', 1)
else:
host = netloc
return scheme, auth, host, port, path, query, fragment | python | def _uri_split(uri):
"""Splits up an URI or IRI."""
scheme, netloc, path, query, fragment = _safe_urlsplit(uri)
auth = None
port = None
if '@' in netloc:
auth, netloc = netloc.split('@', 1)
if netloc.startswith('['):
host, port_part = netloc[1:].split(']', 1)
if port_part.startswith(':'):
port = port_part[1:]
elif ':' in netloc:
host, port = netloc.split(':', 1)
else:
host = netloc
return scheme, auth, host, port, path, query, fragment | [
"def",
"_uri_split",
"(",
"uri",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
"=",
"_safe_urlsplit",
"(",
"uri",
")",
"auth",
"=",
"None",
"port",
"=",
"None",
"if",
"'@'",
"in",
"netloc",
":",
"auth",
",",
"netloc",
"=",
"netloc",
".",
"split",
"(",
"'@'",
",",
"1",
")",
"if",
"netloc",
".",
"startswith",
"(",
"'['",
")",
":",
"host",
",",
"port_part",
"=",
"netloc",
"[",
"1",
":",
"]",
".",
"split",
"(",
"']'",
",",
"1",
")",
"if",
"port_part",
".",
"startswith",
"(",
"':'",
")",
":",
"port",
"=",
"port_part",
"[",
"1",
":",
"]",
"elif",
"':'",
"in",
"netloc",
":",
"host",
",",
"port",
"=",
"netloc",
".",
"split",
"(",
"':'",
",",
"1",
")",
"else",
":",
"host",
"=",
"netloc",
"return",
"scheme",
",",
"auth",
",",
"host",
",",
"port",
",",
"path",
",",
"query",
",",
"fragment"
] | Splits up an URI or IRI. | [
"Splits",
"up",
"an",
"URI",
"or",
"IRI",
"."
] | dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a | https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L95-L113 | train |
core/uricore | uricore/wkz_urls.py | url_unquote | def url_unquote(s, charset='utf-8', errors='replace'):
"""URL decode a single string with a given decoding.
Per default encoding errors are ignored. If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
`HTTPUnicodeError` is raised.
:param s: the string to unquote.
:param charset: the charset to be used.
:param errors: the error handling for the charset decoding.
"""
if isinstance(s, unicode):
s = s.encode(charset)
return _decode_unicode(_unquote(s), charset, errors) | python | def url_unquote(s, charset='utf-8', errors='replace'):
"""URL decode a single string with a given decoding.
Per default encoding errors are ignored. If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
`HTTPUnicodeError` is raised.
:param s: the string to unquote.
:param charset: the charset to be used.
:param errors: the error handling for the charset decoding.
"""
if isinstance(s, unicode):
s = s.encode(charset)
return _decode_unicode(_unquote(s), charset, errors) | [
"def",
"url_unquote",
"(",
"s",
",",
"charset",
"=",
"'utf-8'",
",",
"errors",
"=",
"'replace'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"charset",
")",
"return",
"_decode_unicode",
"(",
"_unquote",
"(",
"s",
")",
",",
"charset",
",",
"errors",
")"
] | URL decode a single string with a given decoding.
Per default encoding errors are ignored. If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
`HTTPUnicodeError` is raised.
:param s: the string to unquote.
:param charset: the charset to be used.
:param errors: the error handling for the charset decoding. | [
"URL",
"decode",
"a",
"single",
"string",
"with",
"a",
"given",
"decoding",
"."
] | dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a | https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L412-L425 | train |
core/uricore | uricore/wkz_urls.py | url_unquote_plus | def url_unquote_plus(s, charset='utf-8', errors='replace'):
"""URL decode a single string with the given decoding and decode
a "+" to whitespace.
Per default encoding errors are ignored. If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
`HTTPUnicodeError` is raised.
:param s: the string to unquote.
:param charset: the charset to be used.
:param errors: the error handling for the charset decoding.
"""
if isinstance(s, unicode):
s = s.encode(charset)
return _decode_unicode(_unquote_plus(s), charset, errors) | python | def url_unquote_plus(s, charset='utf-8', errors='replace'):
"""URL decode a single string with the given decoding and decode
a "+" to whitespace.
Per default encoding errors are ignored. If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
`HTTPUnicodeError` is raised.
:param s: the string to unquote.
:param charset: the charset to be used.
:param errors: the error handling for the charset decoding.
"""
if isinstance(s, unicode):
s = s.encode(charset)
return _decode_unicode(_unquote_plus(s), charset, errors) | [
"def",
"url_unquote_plus",
"(",
"s",
",",
"charset",
"=",
"'utf-8'",
",",
"errors",
"=",
"'replace'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"charset",
")",
"return",
"_decode_unicode",
"(",
"_unquote_plus",
"(",
"s",
")",
",",
"charset",
",",
"errors",
")"
] | URL decode a single string with the given decoding and decode
a "+" to whitespace.
Per default encoding errors are ignored. If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
`HTTPUnicodeError` is raised.
:param s: the string to unquote.
:param charset: the charset to be used.
:param errors: the error handling for the charset decoding. | [
"URL",
"decode",
"a",
"single",
"string",
"with",
"the",
"given",
"decoding",
"and",
"decode",
"a",
"+",
"to",
"whitespace",
"."
] | dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a | https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L428-L442 | train |
Gbps/fastlog | fastlog/log.py | FastLogger.addHandler | def addHandler(self, handler):
"""
Setups a new internal logging handler. For fastlog loggers,
handlers are kept track of in the self._handlers list
"""
self._handlers.append(handler)
self.inner.addHandler(handler) | python | def addHandler(self, handler):
"""
Setups a new internal logging handler. For fastlog loggers,
handlers are kept track of in the self._handlers list
"""
self._handlers.append(handler)
self.inner.addHandler(handler) | [
"def",
"addHandler",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"_handlers",
".",
"append",
"(",
"handler",
")",
"self",
".",
"inner",
".",
"addHandler",
"(",
"handler",
")"
] | Setups a new internal logging handler. For fastlog loggers,
handlers are kept track of in the self._handlers list | [
"Setups",
"a",
"new",
"internal",
"logging",
"handler",
".",
"For",
"fastlog",
"loggers",
"handlers",
"are",
"kept",
"track",
"of",
"in",
"the",
"self",
".",
"_handlers",
"list"
] | 8edb2327d72191510302c4654ffaa1691fe31277 | https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/log.py#L38-L44 | train |
Gbps/fastlog | fastlog/log.py | FastLogger.setStyle | def setStyle(self, stylename):
"""
Adjusts the output format of messages based on the style name provided
Styles are loaded like python modules, so you can import styles from your own modules or use the ones in fastlog.styles
Available styles can be found under /fastlog/styles/
The default style is 'fastlog.styles.pwntools'
"""
self.style = importlib.import_module(stylename)
newHandler = Handler()
newHandler.setFormatter(Formatter(self.style))
self.addHandler(newHandler) | python | def setStyle(self, stylename):
"""
Adjusts the output format of messages based on the style name provided
Styles are loaded like python modules, so you can import styles from your own modules or use the ones in fastlog.styles
Available styles can be found under /fastlog/styles/
The default style is 'fastlog.styles.pwntools'
"""
self.style = importlib.import_module(stylename)
newHandler = Handler()
newHandler.setFormatter(Formatter(self.style))
self.addHandler(newHandler) | [
"def",
"setStyle",
"(",
"self",
",",
"stylename",
")",
":",
"self",
".",
"style",
"=",
"importlib",
".",
"import_module",
"(",
"stylename",
")",
"newHandler",
"=",
"Handler",
"(",
")",
"newHandler",
".",
"setFormatter",
"(",
"Formatter",
"(",
"self",
".",
"style",
")",
")",
"self",
".",
"addHandler",
"(",
"newHandler",
")"
] | Adjusts the output format of messages based on the style name provided
Styles are loaded like python modules, so you can import styles from your own modules or use the ones in fastlog.styles
Available styles can be found under /fastlog/styles/
The default style is 'fastlog.styles.pwntools' | [
"Adjusts",
"the",
"output",
"format",
"of",
"messages",
"based",
"on",
"the",
"style",
"name",
"provided"
] | 8edb2327d72191510302c4654ffaa1691fe31277 | https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/log.py#L46-L59 | train |
Gbps/fastlog | fastlog/log.py | FastLogger._log | def _log(self, lvl, msg, type, args, kwargs):
"""
Internal method to filter into the formatter before being passed to the main Python logger
"""
extra = kwargs.get('extra', {})
extra.setdefault("fastlog-type", type)
extra.setdefault("fastlog-indent", self._indent)
kwargs['extra'] = extra
self._lastlevel = lvl
self.inner.log(lvl, msg, *args, **kwargs) | python | def _log(self, lvl, msg, type, args, kwargs):
"""
Internal method to filter into the formatter before being passed to the main Python logger
"""
extra = kwargs.get('extra', {})
extra.setdefault("fastlog-type", type)
extra.setdefault("fastlog-indent", self._indent)
kwargs['extra'] = extra
self._lastlevel = lvl
self.inner.log(lvl, msg, *args, **kwargs) | [
"def",
"_log",
"(",
"self",
",",
"lvl",
",",
"msg",
",",
"type",
",",
"args",
",",
"kwargs",
")",
":",
"extra",
"=",
"kwargs",
".",
"get",
"(",
"'extra'",
",",
"{",
"}",
")",
"extra",
".",
"setdefault",
"(",
"\"fastlog-type\"",
",",
"type",
")",
"extra",
".",
"setdefault",
"(",
"\"fastlog-indent\"",
",",
"self",
".",
"_indent",
")",
"kwargs",
"[",
"'extra'",
"]",
"=",
"extra",
"self",
".",
"_lastlevel",
"=",
"lvl",
"self",
".",
"inner",
".",
"log",
"(",
"lvl",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Internal method to filter into the formatter before being passed to the main Python logger | [
"Internal",
"method",
"to",
"filter",
"into",
"the",
"formatter",
"before",
"being",
"passed",
"to",
"the",
"main",
"Python",
"logger"
] | 8edb2327d72191510302c4654ffaa1691fe31277 | https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/log.py#L67-L78 | train |
Gbps/fastlog | fastlog/log.py | FastLogger.separator | def separator(self, *args, **kwargs):
"""
Prints a separator to the log. This can be used to separate blocks of log messages.
The separator will default its log level to the level of the last message printed unless
specified with the level= kwarg.
The length and type of the separator string is determined
by the current style. See ``setStyle``
"""
levelOverride = kwargs.get('level') or self._lastlevel
self._log(levelOverride, '', 'separator', args, kwargs) | python | def separator(self, *args, **kwargs):
"""
Prints a separator to the log. This can be used to separate blocks of log messages.
The separator will default its log level to the level of the last message printed unless
specified with the level= kwarg.
The length and type of the separator string is determined
by the current style. See ``setStyle``
"""
levelOverride = kwargs.get('level') or self._lastlevel
self._log(levelOverride, '', 'separator', args, kwargs) | [
"def",
"separator",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"levelOverride",
"=",
"kwargs",
".",
"get",
"(",
"'level'",
")",
"or",
"self",
".",
"_lastlevel",
"self",
".",
"_log",
"(",
"levelOverride",
",",
"''",
",",
"'separator'",
",",
"args",
",",
"kwargs",
")"
] | Prints a separator to the log. This can be used to separate blocks of log messages.
The separator will default its log level to the level of the last message printed unless
specified with the level= kwarg.
The length and type of the separator string is determined
by the current style. See ``setStyle`` | [
"Prints",
"a",
"separator",
"to",
"the",
"log",
".",
"This",
"can",
"be",
"used",
"to",
"separate",
"blocks",
"of",
"log",
"messages",
"."
] | 8edb2327d72191510302c4654ffaa1691fe31277 | https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/log.py#L106-L117 | train |
Gbps/fastlog | fastlog/log.py | FastLogger.indent | def indent(self):
"""
Begins an indented block. Must be used in a 'with' code block.
All calls to the logger inside of the block will be indented.
"""
blk = IndentBlock(self, self._indent)
self._indent += 1
return blk | python | def indent(self):
"""
Begins an indented block. Must be used in a 'with' code block.
All calls to the logger inside of the block will be indented.
"""
blk = IndentBlock(self, self._indent)
self._indent += 1
return blk | [
"def",
"indent",
"(",
"self",
")",
":",
"blk",
"=",
"IndentBlock",
"(",
"self",
",",
"self",
".",
"_indent",
")",
"self",
".",
"_indent",
"+=",
"1",
"return",
"blk"
] | Begins an indented block. Must be used in a 'with' code block.
All calls to the logger inside of the block will be indented. | [
"Begins",
"an",
"indented",
"block",
".",
"Must",
"be",
"used",
"in",
"a",
"with",
"code",
"block",
".",
"All",
"calls",
"to",
"the",
"logger",
"inside",
"of",
"the",
"block",
"will",
"be",
"indented",
"."
] | 8edb2327d72191510302c4654ffaa1691fe31277 | https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/log.py#L119-L126 | train |
Gbps/fastlog | fastlog/log.py | FastLogger.newline | def newline(self, *args, **kwargs):
"""
Prints an empty line to the log. Uses the level of the last message
printed unless specified otherwise with the level= kwarg.
"""
levelOverride = kwargs.get('level') or self._lastlevel
self._log(levelOverride, '', 'newline', args, kwargs) | python | def newline(self, *args, **kwargs):
"""
Prints an empty line to the log. Uses the level of the last message
printed unless specified otherwise with the level= kwarg.
"""
levelOverride = kwargs.get('level') or self._lastlevel
self._log(levelOverride, '', 'newline', args, kwargs) | [
"def",
"newline",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"levelOverride",
"=",
"kwargs",
".",
"get",
"(",
"'level'",
")",
"or",
"self",
".",
"_lastlevel",
"self",
".",
"_log",
"(",
"levelOverride",
",",
"''",
",",
"'newline'",
",",
"args",
",",
"kwargs",
")"
] | Prints an empty line to the log. Uses the level of the last message
printed unless specified otherwise with the level= kwarg. | [
"Prints",
"an",
"empty",
"line",
"to",
"the",
"log",
".",
"Uses",
"the",
"level",
"of",
"the",
"last",
"message",
"printed",
"unless",
"specified",
"otherwise",
"with",
"the",
"level",
"=",
"kwarg",
"."
] | 8edb2327d72191510302c4654ffaa1691fe31277 | https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/log.py#L135-L141 | train |
Gbps/fastlog | fastlog/log.py | FastLogger.hexdump | def hexdump(self, s, *args, **kwargs):
"""
Outputs a colorful hexdump of the first argument.
This function will attempt to 'flatten' iterable data passed to it until all remaining elements
are binary representable.
In python2, objects should be of type 'str', in python3, 'bytes' or 'bytearray' will work.
The level of the last message printed is used unless specified otherwise with the level= kwarg
Arguments to pass to hexdump:
width(int): The number of characters per line
skip(bool): Set to True, if repeated lines should be replaced by a "*"
hexii(bool): Set to True, if a hexii-dump should be returned instead of a hexdump.
begin(int): Offset of the first byte to print in the left column
highlight(iterable): Byte values to highlight.
"""
levelOverride = kwargs.get('level') or self._lastlevel
hexdmp = hexdump.hexdump(self, s, **kwargs)
self._log(levelOverride, hexdmp, 'indented', args, kwargs) | python | def hexdump(self, s, *args, **kwargs):
"""
Outputs a colorful hexdump of the first argument.
This function will attempt to 'flatten' iterable data passed to it until all remaining elements
are binary representable.
In python2, objects should be of type 'str', in python3, 'bytes' or 'bytearray' will work.
The level of the last message printed is used unless specified otherwise with the level= kwarg
Arguments to pass to hexdump:
width(int): The number of characters per line
skip(bool): Set to True, if repeated lines should be replaced by a "*"
hexii(bool): Set to True, if a hexii-dump should be returned instead of a hexdump.
begin(int): Offset of the first byte to print in the left column
highlight(iterable): Byte values to highlight.
"""
levelOverride = kwargs.get('level') or self._lastlevel
hexdmp = hexdump.hexdump(self, s, **kwargs)
self._log(levelOverride, hexdmp, 'indented', args, kwargs) | [
"def",
"hexdump",
"(",
"self",
",",
"s",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"levelOverride",
"=",
"kwargs",
".",
"get",
"(",
"'level'",
")",
"or",
"self",
".",
"_lastlevel",
"hexdmp",
"=",
"hexdump",
".",
"hexdump",
"(",
"self",
",",
"s",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_log",
"(",
"levelOverride",
",",
"hexdmp",
",",
"'indented'",
",",
"args",
",",
"kwargs",
")"
] | Outputs a colorful hexdump of the first argument.
This function will attempt to 'flatten' iterable data passed to it until all remaining elements
are binary representable.
In python2, objects should be of type 'str', in python3, 'bytes' or 'bytearray' will work.
The level of the last message printed is used unless specified otherwise with the level= kwarg
Arguments to pass to hexdump:
width(int): The number of characters per line
skip(bool): Set to True, if repeated lines should be replaced by a "*"
hexii(bool): Set to True, if a hexii-dump should be returned instead of a hexdump.
begin(int): Offset of the first byte to print in the left column
highlight(iterable): Byte values to highlight. | [
"Outputs",
"a",
"colorful",
"hexdump",
"of",
"the",
"first",
"argument",
"."
] | 8edb2327d72191510302c4654ffaa1691fe31277 | https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/log.py#L143-L163 | train |
bitesofcode/projexui | projexui/widgets/xcombobox.py | XComboBox.currentText | def currentText(self):
"""
Returns the current text for this combobox, including the hint option \
if no text is set.
"""
lineEdit = self.lineEdit()
if lineEdit:
return lineEdit.currentText()
text = nativestring(super(XComboBox, self).currentText())
if not text:
return self._hint
return text | python | def currentText(self):
"""
Returns the current text for this combobox, including the hint option \
if no text is set.
"""
lineEdit = self.lineEdit()
if lineEdit:
return lineEdit.currentText()
text = nativestring(super(XComboBox, self).currentText())
if not text:
return self._hint
return text | [
"def",
"currentText",
"(",
"self",
")",
":",
"lineEdit",
"=",
"self",
".",
"lineEdit",
"(",
")",
"if",
"lineEdit",
":",
"return",
"lineEdit",
".",
"currentText",
"(",
")",
"text",
"=",
"nativestring",
"(",
"super",
"(",
"XComboBox",
",",
"self",
")",
".",
"currentText",
"(",
")",
")",
"if",
"not",
"text",
":",
"return",
"self",
".",
"_hint",
"return",
"text"
] | Returns the current text for this combobox, including the hint option \
if no text is set. | [
"Returns",
"the",
"current",
"text",
"for",
"this",
"combobox",
"including",
"the",
"hint",
"option",
"\\",
"if",
"no",
"text",
"is",
"set",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L142-L153 | train |
bitesofcode/projexui | projexui/widgets/xcombobox.py | XComboBox.showPopup | def showPopup( self ):
"""
Displays a custom popup widget for this system if a checkable state \
is setup.
"""
if not self.isCheckable():
return super(XComboBox, self).showPopup()
if not self.isVisible():
return
# update the checkable widget popup
point = self.mapToGlobal(QPoint(0, self.height() - 1))
popup = self.checkablePopup()
popup.setModel(self.model())
popup.move(point)
popup.setFixedWidth(self.width())
height = (self.count() * 19) + 2
if height > 400:
height = 400
popup.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
else:
popup.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
popup.setFixedHeight(height)
popup.show()
popup.raise_() | python | def showPopup( self ):
"""
Displays a custom popup widget for this system if a checkable state \
is setup.
"""
if not self.isCheckable():
return super(XComboBox, self).showPopup()
if not self.isVisible():
return
# update the checkable widget popup
point = self.mapToGlobal(QPoint(0, self.height() - 1))
popup = self.checkablePopup()
popup.setModel(self.model())
popup.move(point)
popup.setFixedWidth(self.width())
height = (self.count() * 19) + 2
if height > 400:
height = 400
popup.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
else:
popup.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
popup.setFixedHeight(height)
popup.show()
popup.raise_() | [
"def",
"showPopup",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"isCheckable",
"(",
")",
":",
"return",
"super",
"(",
"XComboBox",
",",
"self",
")",
".",
"showPopup",
"(",
")",
"if",
"not",
"self",
".",
"isVisible",
"(",
")",
":",
"return",
"# update the checkable widget popup",
"point",
"=",
"self",
".",
"mapToGlobal",
"(",
"QPoint",
"(",
"0",
",",
"self",
".",
"height",
"(",
")",
"-",
"1",
")",
")",
"popup",
"=",
"self",
".",
"checkablePopup",
"(",
")",
"popup",
".",
"setModel",
"(",
"self",
".",
"model",
"(",
")",
")",
"popup",
".",
"move",
"(",
"point",
")",
"popup",
".",
"setFixedWidth",
"(",
"self",
".",
"width",
"(",
")",
")",
"height",
"=",
"(",
"self",
".",
"count",
"(",
")",
"*",
"19",
")",
"+",
"2",
"if",
"height",
">",
"400",
":",
"height",
"=",
"400",
"popup",
".",
"setVerticalScrollBarPolicy",
"(",
"Qt",
".",
"ScrollBarAlwaysOn",
")",
"else",
":",
"popup",
".",
"setVerticalScrollBarPolicy",
"(",
"Qt",
".",
"ScrollBarAlwaysOff",
")",
"popup",
".",
"setFixedHeight",
"(",
"height",
")",
"popup",
".",
"show",
"(",
")",
"popup",
".",
"raise_",
"(",
")"
] | Displays a custom popup widget for this system if a checkable state \
is setup. | [
"Displays",
"a",
"custom",
"popup",
"widget",
"for",
"this",
"system",
"if",
"a",
"checkable",
"state",
"\\",
"is",
"setup",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L500-L527 | train |
bitesofcode/projexui | projexui/widgets/xcombobox.py | XComboBox.updateCheckState | def updateCheckState( self ):
"""
Updates the items to reflect the current check state system.
"""
checkable = self.isCheckable()
model = self.model()
flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled
for i in range(self.count()):
item = model.item(i)
if not (checkable and item.text()):
item.setCheckable(False)
item.setFlags(flags)
# only allow checking for items with text
else:
item.setCheckable(True)
item.setFlags(flags | Qt.ItemIsUserCheckable) | python | def updateCheckState( self ):
"""
Updates the items to reflect the current check state system.
"""
checkable = self.isCheckable()
model = self.model()
flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled
for i in range(self.count()):
item = model.item(i)
if not (checkable and item.text()):
item.setCheckable(False)
item.setFlags(flags)
# only allow checking for items with text
else:
item.setCheckable(True)
item.setFlags(flags | Qt.ItemIsUserCheckable) | [
"def",
"updateCheckState",
"(",
"self",
")",
":",
"checkable",
"=",
"self",
".",
"isCheckable",
"(",
")",
"model",
"=",
"self",
".",
"model",
"(",
")",
"flags",
"=",
"Qt",
".",
"ItemIsSelectable",
"|",
"Qt",
".",
"ItemIsEnabled",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"count",
"(",
")",
")",
":",
"item",
"=",
"model",
".",
"item",
"(",
"i",
")",
"if",
"not",
"(",
"checkable",
"and",
"item",
".",
"text",
"(",
")",
")",
":",
"item",
".",
"setCheckable",
"(",
"False",
")",
"item",
".",
"setFlags",
"(",
"flags",
")",
"# only allow checking for items with text",
"else",
":",
"item",
".",
"setCheckable",
"(",
"True",
")",
"item",
".",
"setFlags",
"(",
"flags",
"|",
"Qt",
".",
"ItemIsUserCheckable",
")"
] | Updates the items to reflect the current check state system. | [
"Updates",
"the",
"items",
"to",
"reflect",
"the",
"current",
"check",
"state",
"system",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L529-L547 | train |
bitesofcode/projexui | projexui/widgets/xcombobox.py | XComboBox.updateCheckedText | def updateCheckedText(self):
"""
Updates the text in the editor to reflect the latest state.
"""
if not self.isCheckable():
return
indexes = self.checkedIndexes()
items = self.checkedItems()
if len(items) < 2 or self.separator():
self.lineEdit().setText(self.separator().join(items))
else:
self.lineEdit().setText('{0} items selected'.format(len(items)))
if not self.signalsBlocked():
self.checkedItemsChanged.emit(items)
self.checkedIndexesChanged.emit(indexes) | python | def updateCheckedText(self):
"""
Updates the text in the editor to reflect the latest state.
"""
if not self.isCheckable():
return
indexes = self.checkedIndexes()
items = self.checkedItems()
if len(items) < 2 or self.separator():
self.lineEdit().setText(self.separator().join(items))
else:
self.lineEdit().setText('{0} items selected'.format(len(items)))
if not self.signalsBlocked():
self.checkedItemsChanged.emit(items)
self.checkedIndexesChanged.emit(indexes) | [
"def",
"updateCheckedText",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"isCheckable",
"(",
")",
":",
"return",
"indexes",
"=",
"self",
".",
"checkedIndexes",
"(",
")",
"items",
"=",
"self",
".",
"checkedItems",
"(",
")",
"if",
"len",
"(",
"items",
")",
"<",
"2",
"or",
"self",
".",
"separator",
"(",
")",
":",
"self",
".",
"lineEdit",
"(",
")",
".",
"setText",
"(",
"self",
".",
"separator",
"(",
")",
".",
"join",
"(",
"items",
")",
")",
"else",
":",
"self",
".",
"lineEdit",
"(",
")",
".",
"setText",
"(",
"'{0} items selected'",
".",
"format",
"(",
"len",
"(",
"items",
")",
")",
")",
"if",
"not",
"self",
".",
"signalsBlocked",
"(",
")",
":",
"self",
".",
"checkedItemsChanged",
".",
"emit",
"(",
"items",
")",
"self",
".",
"checkedIndexesChanged",
".",
"emit",
"(",
"indexes",
")"
] | Updates the text in the editor to reflect the latest state. | [
"Updates",
"the",
"text",
"in",
"the",
"editor",
"to",
"reflect",
"the",
"latest",
"state",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L549-L566 | train |
intelsdi-x/snap-plugin-lib-py | examples/processor/tag.py | Tag.process | def process(self, metrics, config):
"""Processes metrics.
This method is called by the Snap deamon during the process phase
of the execution of a Snap workflow. Examples of processing metrics
include applying filtering, max, min, average functions as well as
adding additional context to the metrics to name just a few.
In this example we are adding a tag called 'context' to every metric.
Args:
metrics (obj:`list` of `snap_plugin.v1.Metric`):
List of metrics to be processed.
Returns:
:obj:`list` of `snap_plugin.v1.Metric`:
List of processed metrics.
"""
LOG.debug("Process called")
for metric in metrics:
metric.tags["instance-id"] = config["instance-id"]
return metrics | python | def process(self, metrics, config):
"""Processes metrics.
This method is called by the Snap deamon during the process phase
of the execution of a Snap workflow. Examples of processing metrics
include applying filtering, max, min, average functions as well as
adding additional context to the metrics to name just a few.
In this example we are adding a tag called 'context' to every metric.
Args:
metrics (obj:`list` of `snap_plugin.v1.Metric`):
List of metrics to be processed.
Returns:
:obj:`list` of `snap_plugin.v1.Metric`:
List of processed metrics.
"""
LOG.debug("Process called")
for metric in metrics:
metric.tags["instance-id"] = config["instance-id"]
return metrics | [
"def",
"process",
"(",
"self",
",",
"metrics",
",",
"config",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Process called\"",
")",
"for",
"metric",
"in",
"metrics",
":",
"metric",
".",
"tags",
"[",
"\"instance-id\"",
"]",
"=",
"config",
"[",
"\"instance-id\"",
"]",
"return",
"metrics"
] | Processes metrics.
This method is called by the Snap deamon during the process phase
of the execution of a Snap workflow. Examples of processing metrics
include applying filtering, max, min, average functions as well as
adding additional context to the metrics to name just a few.
In this example we are adding a tag called 'context' to every metric.
Args:
metrics (obj:`list` of `snap_plugin.v1.Metric`):
List of metrics to be processed.
Returns:
:obj:`list` of `snap_plugin.v1.Metric`:
List of processed metrics. | [
"Processes",
"metrics",
"."
] | 8da5d00ac5f9d2b48a7239563ac7788209891ca4 | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/examples/processor/tag.py#L34-L55 | train |
bitesofcode/projexui | projexui/widgets/xtoolbutton.py | XToolButton.cleanup | def cleanup(self):
"""
Cleanup references to the movie when this button is destroyed.
"""
if self._movie is not None:
self._movie.frameChanged.disconnect(self._updateFrame)
self._movie = None | python | def cleanup(self):
"""
Cleanup references to the movie when this button is destroyed.
"""
if self._movie is not None:
self._movie.frameChanged.disconnect(self._updateFrame)
self._movie = None | [
"def",
"cleanup",
"(",
"self",
")",
":",
"if",
"self",
".",
"_movie",
"is",
"not",
"None",
":",
"self",
".",
"_movie",
".",
"frameChanged",
".",
"disconnect",
"(",
"self",
".",
"_updateFrame",
")",
"self",
".",
"_movie",
"=",
"None"
] | Cleanup references to the movie when this button is destroyed. | [
"Cleanup",
"references",
"to",
"the",
"movie",
"when",
"this",
"button",
"is",
"destroyed",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtoolbutton.py#L121-L127 | train |
bitesofcode/projexui | projexui/widgets/xtoolbutton.py | XToolButton.paintEvent | def paintEvent(self, event):
"""
Overloads the paint even to render this button.
"""
if self.isHoverable() and self.icon().isNull():
return
# initialize the painter
painter = QtGui.QStylePainter()
painter.begin(self)
try:
option = QtGui.QStyleOptionToolButton()
self.initStyleOption(option)
# generate the scaling and rotating factors
x_scale = 1
y_scale = 1
if self.flipHorizontal():
x_scale = -1
if self.flipVertical():
y_scale = -1
center = self.rect().center()
painter.translate(center.x(), center.y())
painter.rotate(self.angle())
painter.scale(x_scale, y_scale)
painter.translate(-center.x(), -center.y())
painter.drawComplexControl(QtGui.QStyle.CC_ToolButton, option)
finally:
painter.end() | python | def paintEvent(self, event):
"""
Overloads the paint even to render this button.
"""
if self.isHoverable() and self.icon().isNull():
return
# initialize the painter
painter = QtGui.QStylePainter()
painter.begin(self)
try:
option = QtGui.QStyleOptionToolButton()
self.initStyleOption(option)
# generate the scaling and rotating factors
x_scale = 1
y_scale = 1
if self.flipHorizontal():
x_scale = -1
if self.flipVertical():
y_scale = -1
center = self.rect().center()
painter.translate(center.x(), center.y())
painter.rotate(self.angle())
painter.scale(x_scale, y_scale)
painter.translate(-center.x(), -center.y())
painter.drawComplexControl(QtGui.QStyle.CC_ToolButton, option)
finally:
painter.end() | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"isHoverable",
"(",
")",
"and",
"self",
".",
"icon",
"(",
")",
".",
"isNull",
"(",
")",
":",
"return",
"# initialize the painter\r",
"painter",
"=",
"QtGui",
".",
"QStylePainter",
"(",
")",
"painter",
".",
"begin",
"(",
"self",
")",
"try",
":",
"option",
"=",
"QtGui",
".",
"QStyleOptionToolButton",
"(",
")",
"self",
".",
"initStyleOption",
"(",
"option",
")",
"# generate the scaling and rotating factors\r",
"x_scale",
"=",
"1",
"y_scale",
"=",
"1",
"if",
"self",
".",
"flipHorizontal",
"(",
")",
":",
"x_scale",
"=",
"-",
"1",
"if",
"self",
".",
"flipVertical",
"(",
")",
":",
"y_scale",
"=",
"-",
"1",
"center",
"=",
"self",
".",
"rect",
"(",
")",
".",
"center",
"(",
")",
"painter",
".",
"translate",
"(",
"center",
".",
"x",
"(",
")",
",",
"center",
".",
"y",
"(",
")",
")",
"painter",
".",
"rotate",
"(",
"self",
".",
"angle",
"(",
")",
")",
"painter",
".",
"scale",
"(",
"x_scale",
",",
"y_scale",
")",
"painter",
".",
"translate",
"(",
"-",
"center",
".",
"x",
"(",
")",
",",
"-",
"center",
".",
"y",
"(",
")",
")",
"painter",
".",
"drawComplexControl",
"(",
"QtGui",
".",
"QStyle",
".",
"CC_ToolButton",
",",
"option",
")",
"finally",
":",
"painter",
".",
"end",
"(",
")"
] | Overloads the paint even to render this button. | [
"Overloads",
"the",
"paint",
"even",
"to",
"render",
"this",
"button",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtoolbutton.py#L206-L237 | train |
starling-lab/rnlp | rnlp/__init__.py | converter | def converter(input_string, block_size=2):
"""
The cli tool as a built-in function.
:param input_string: A string that should be converted to a set of facts.
:type input_string: str.
:param blocks_size: Optional block size of sentences (Default: 2).
:type block_size: int.
"""
sentences = textprocessing.getSentences(input_string)
blocks = textprocessing.getBlocks(sentences, block_size)
parse.makeIdentifiers(blocks) | python | def converter(input_string, block_size=2):
"""
The cli tool as a built-in function.
:param input_string: A string that should be converted to a set of facts.
:type input_string: str.
:param blocks_size: Optional block size of sentences (Default: 2).
:type block_size: int.
"""
sentences = textprocessing.getSentences(input_string)
blocks = textprocessing.getBlocks(sentences, block_size)
parse.makeIdentifiers(blocks) | [
"def",
"converter",
"(",
"input_string",
",",
"block_size",
"=",
"2",
")",
":",
"sentences",
"=",
"textprocessing",
".",
"getSentences",
"(",
"input_string",
")",
"blocks",
"=",
"textprocessing",
".",
"getBlocks",
"(",
"sentences",
",",
"block_size",
")",
"parse",
".",
"makeIdentifiers",
"(",
"blocks",
")"
] | The cli tool as a built-in function.
:param input_string: A string that should be converted to a set of facts.
:type input_string: str.
:param blocks_size: Optional block size of sentences (Default: 2).
:type block_size: int. | [
"The",
"cli",
"tool",
"as",
"a",
"built",
"-",
"in",
"function",
"."
] | 72054cc2c0cbaea1d281bf3d56b271d4da29fc4a | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/__init__.py#L82-L94 | train |
bitesofcode/projexui | projexui/widgets/xmultitagedit.py | XMultiTagEdit.copy | def copy( self ):
"""
Copies the selected items to the clipboard.
"""
text = []
for item in self.selectedItems():
text.append(nativestring(item.text()))
QApplication.clipboard().setText(','.join(text)) | python | def copy( self ):
"""
Copies the selected items to the clipboard.
"""
text = []
for item in self.selectedItems():
text.append(nativestring(item.text()))
QApplication.clipboard().setText(','.join(text)) | [
"def",
"copy",
"(",
"self",
")",
":",
"text",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"selectedItems",
"(",
")",
":",
"text",
".",
"append",
"(",
"nativestring",
"(",
"item",
".",
"text",
"(",
")",
")",
")",
"QApplication",
".",
"clipboard",
"(",
")",
".",
"setText",
"(",
"','",
".",
"join",
"(",
"text",
")",
")"
] | Copies the selected items to the clipboard. | [
"Copies",
"the",
"selected",
"items",
"to",
"the",
"clipboard",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xmultitagedit.py#L254-L262 | train |
bitesofcode/projexui | projexui/widgets/xmultitagedit.py | XMultiTagEdit.finishEditing | def finishEditing(self, tag):
"""
Finishes editing the current item.
"""
curr_item = self.currentItem()
create_item = self.createItem()
self.closePersistentEditor(curr_item)
if curr_item == create_item:
self.addTag(tag)
elif self.isTagValid(tag):
curr_item.setText(tag) | python | def finishEditing(self, tag):
"""
Finishes editing the current item.
"""
curr_item = self.currentItem()
create_item = self.createItem()
self.closePersistentEditor(curr_item)
if curr_item == create_item:
self.addTag(tag)
elif self.isTagValid(tag):
curr_item.setText(tag) | [
"def",
"finishEditing",
"(",
"self",
",",
"tag",
")",
":",
"curr_item",
"=",
"self",
".",
"currentItem",
"(",
")",
"create_item",
"=",
"self",
".",
"createItem",
"(",
")",
"self",
".",
"closePersistentEditor",
"(",
"curr_item",
")",
"if",
"curr_item",
"==",
"create_item",
":",
"self",
".",
"addTag",
"(",
"tag",
")",
"elif",
"self",
".",
"isTagValid",
"(",
"tag",
")",
":",
"curr_item",
".",
"setText",
"(",
"tag",
")"
] | Finishes editing the current item. | [
"Finishes",
"editing",
"the",
"current",
"item",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xmultitagedit.py#L381-L393 | train |
bitesofcode/projexui | projexui/widgets/xmultitagedit.py | XMultiTagEdit.paste | def paste( self ):
"""
Pastes text from the clipboard.
"""
text = nativestring(QApplication.clipboard().text())
for tag in text.split(','):
tag = tag.strip()
if ( self.isTagValid(tag) ):
self.addTag(tag) | python | def paste( self ):
"""
Pastes text from the clipboard.
"""
text = nativestring(QApplication.clipboard().text())
for tag in text.split(','):
tag = tag.strip()
if ( self.isTagValid(tag) ):
self.addTag(tag) | [
"def",
"paste",
"(",
"self",
")",
":",
"text",
"=",
"nativestring",
"(",
"QApplication",
".",
"clipboard",
"(",
")",
".",
"text",
"(",
")",
")",
"for",
"tag",
"in",
"text",
".",
"split",
"(",
"','",
")",
":",
"tag",
"=",
"tag",
".",
"strip",
"(",
")",
"if",
"(",
"self",
".",
"isTagValid",
"(",
"tag",
")",
")",
":",
"self",
".",
"addTag",
"(",
"tag",
")"
] | Pastes text from the clipboard. | [
"Pastes",
"text",
"from",
"the",
"clipboard",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xmultitagedit.py#L585-L593 | train |
bitesofcode/projexui | projexui/widgets/xmultitagedit.py | XMultiTagEdit.resizeEvent | def resizeEvent(self, event):
"""
Overloads the resize event to control if we are still editing.
If we are resizing, then we are no longer editing.
"""
curr_item = self.currentItem()
self.closePersistentEditor(curr_item)
super(XMultiTagEdit, self).resizeEvent(event) | python | def resizeEvent(self, event):
"""
Overloads the resize event to control if we are still editing.
If we are resizing, then we are no longer editing.
"""
curr_item = self.currentItem()
self.closePersistentEditor(curr_item)
super(XMultiTagEdit, self).resizeEvent(event) | [
"def",
"resizeEvent",
"(",
"self",
",",
"event",
")",
":",
"curr_item",
"=",
"self",
".",
"currentItem",
"(",
")",
"self",
".",
"closePersistentEditor",
"(",
"curr_item",
")",
"super",
"(",
"XMultiTagEdit",
",",
"self",
")",
".",
"resizeEvent",
"(",
"event",
")"
] | Overloads the resize event to control if we are still editing.
If we are resizing, then we are no longer editing. | [
"Overloads",
"the",
"resize",
"event",
"to",
"control",
"if",
"we",
"are",
"still",
"editing",
".",
"If",
"we",
"are",
"resizing",
"then",
"we",
"are",
"no",
"longer",
"editing",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xmultitagedit.py#L595-L604 | train |
intelsdi-x/snap-plugin-lib-py | snap_plugin/v1/publisher_proxy.py | PublisherProxy.Publish | def Publish(self, request, context):
"""Dispatches the request to the plugins publish method"""
LOG.debug("Publish called")
try:
self.plugin.publish(
[Metric(pb=m) for m in request.Metrics],
ConfigMap(pb=request.Config)
)
return ErrReply()
except Exception as err:
msg = "message: {}\n\nstack trace: {}".format(
err, traceback.format_exc())
return ErrReply(error=msg) | python | def Publish(self, request, context):
"""Dispatches the request to the plugins publish method"""
LOG.debug("Publish called")
try:
self.plugin.publish(
[Metric(pb=m) for m in request.Metrics],
ConfigMap(pb=request.Config)
)
return ErrReply()
except Exception as err:
msg = "message: {}\n\nstack trace: {}".format(
err, traceback.format_exc())
return ErrReply(error=msg) | [
"def",
"Publish",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Publish called\"",
")",
"try",
":",
"self",
".",
"plugin",
".",
"publish",
"(",
"[",
"Metric",
"(",
"pb",
"=",
"m",
")",
"for",
"m",
"in",
"request",
".",
"Metrics",
"]",
",",
"ConfigMap",
"(",
"pb",
"=",
"request",
".",
"Config",
")",
")",
"return",
"ErrReply",
"(",
")",
"except",
"Exception",
"as",
"err",
":",
"msg",
"=",
"\"message: {}\\n\\nstack trace: {}\"",
".",
"format",
"(",
"err",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"return",
"ErrReply",
"(",
"error",
"=",
"msg",
")"
] | Dispatches the request to the plugins publish method | [
"Dispatches",
"the",
"request",
"to",
"the",
"plugins",
"publish",
"method"
] | 8da5d00ac5f9d2b48a7239563ac7788209891ca4 | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/publisher_proxy.py#L35-L47 | train |
deezer/template-remover | scripts/remove_template.py | main | def main():
"""Entry point for remove_template."""
# Wrap sys stdout for python 2, so print can understand unicode.
if sys.version_info[0] < 3:
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
options = docopt.docopt(__doc__,
help=True,
version='template_remover v%s' % __VERSION__)
print(template_remover.clean(io.open(options['FILENAME']).read()))
return 0 | python | def main():
"""Entry point for remove_template."""
# Wrap sys stdout for python 2, so print can understand unicode.
if sys.version_info[0] < 3:
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
options = docopt.docopt(__doc__,
help=True,
version='template_remover v%s' % __VERSION__)
print(template_remover.clean(io.open(options['FILENAME']).read()))
return 0 | [
"def",
"main",
"(",
")",
":",
"# Wrap sys stdout for python 2, so print can understand unicode.",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"sys",
".",
"stdout",
"=",
"codecs",
".",
"getwriter",
"(",
"\"utf-8\"",
")",
"(",
"sys",
".",
"stdout",
")",
"options",
"=",
"docopt",
".",
"docopt",
"(",
"__doc__",
",",
"help",
"=",
"True",
",",
"version",
"=",
"'template_remover v%s'",
"%",
"__VERSION__",
")",
"print",
"(",
"template_remover",
".",
"clean",
"(",
"io",
".",
"open",
"(",
"options",
"[",
"'FILENAME'",
"]",
")",
".",
"read",
"(",
")",
")",
")",
"return",
"0"
] | Entry point for remove_template. | [
"Entry",
"point",
"for",
"remove_template",
"."
] | de963f221612f57d4982fbc779acd21302c7b817 | https://github.com/deezer/template-remover/blob/de963f221612f57d4982fbc779acd21302c7b817/scripts/remove_template.py#L49-L62 | train |
neithere/eav-django | eav/models.py | validate_range_value | def validate_range_value(value):
"""
Validates given value against `Schema.TYPE_RANGE` data type. Raises
TypeError or ValueError if something is wrong. Returns None if everything
is OK.
"""
if value == (None, None):
return
if not hasattr(value, '__iter__'):
raise TypeError('Range value must be an iterable, got "%s".' % value)
if not 2 == len(value):
raise ValueError('Range value must consist of two elements, got %d.' %
len(value))
if not all(isinstance(x, (int,float)) for x in value):
raise TypeError('Range value must consist of two numbers, got "%s" '
'and "%s" instead.' % value)
if not value[0] <= value[1]:
raise ValueError('Range must consist of min and max values (min <= '
'max) but got "%s" and "%s" instead.' % value)
return | python | def validate_range_value(value):
"""
Validates given value against `Schema.TYPE_RANGE` data type. Raises
TypeError or ValueError if something is wrong. Returns None if everything
is OK.
"""
if value == (None, None):
return
if not hasattr(value, '__iter__'):
raise TypeError('Range value must be an iterable, got "%s".' % value)
if not 2 == len(value):
raise ValueError('Range value must consist of two elements, got %d.' %
len(value))
if not all(isinstance(x, (int,float)) for x in value):
raise TypeError('Range value must consist of two numbers, got "%s" '
'and "%s" instead.' % value)
if not value[0] <= value[1]:
raise ValueError('Range must consist of min and max values (min <= '
'max) but got "%s" and "%s" instead.' % value)
return | [
"def",
"validate_range_value",
"(",
"value",
")",
":",
"if",
"value",
"==",
"(",
"None",
",",
"None",
")",
":",
"return",
"if",
"not",
"hasattr",
"(",
"value",
",",
"'__iter__'",
")",
":",
"raise",
"TypeError",
"(",
"'Range value must be an iterable, got \"%s\".'",
"%",
"value",
")",
"if",
"not",
"2",
"==",
"len",
"(",
"value",
")",
":",
"raise",
"ValueError",
"(",
"'Range value must consist of two elements, got %d.'",
"%",
"len",
"(",
"value",
")",
")",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"x",
",",
"(",
"int",
",",
"float",
")",
")",
"for",
"x",
"in",
"value",
")",
":",
"raise",
"TypeError",
"(",
"'Range value must consist of two numbers, got \"%s\" '",
"'and \"%s\" instead.'",
"%",
"value",
")",
"if",
"not",
"value",
"[",
"0",
"]",
"<=",
"value",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'Range must consist of min and max values (min <= '",
"'max) but got \"%s\" and \"%s\" instead.'",
"%",
"value",
")",
"return"
] | Validates given value against `Schema.TYPE_RANGE` data type. Raises
TypeError or ValueError if something is wrong. Returns None if everything
is OK. | [
"Validates",
"given",
"value",
"against",
"Schema",
".",
"TYPE_RANGE",
"data",
"type",
".",
"Raises",
"TypeError",
"or",
"ValueError",
"if",
"something",
"is",
"wrong",
".",
"Returns",
"None",
"if",
"everything",
"is",
"OK",
"."
] | 7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/models.py#L357-L377 | train |
neithere/eav-django | eav/models.py | BaseSchema.save_attr | def save_attr(self, entity, value):
"""
Saves given EAV attribute with given value for given entity.
If schema is not many-to-one, the value is saved to the corresponding
Attr instance (which is created or updated).
If schema is many-to-one, the value is processed thusly:
* if value is iterable, all Attr instances for corresponding managed m2m
schemata are updated (those with names from the value list are set to
True, others to False). If a list item is not in available choices,
ValueError is raised;
* if the value is None, all corresponding Attr instances are reset to False;
* if the value is neither a list nor None, it is wrapped into a list and
processed as above (i.e. "foo" --> ["foo"]).
"""
if self.datatype == self.TYPE_MANY:
self._save_m2m_attr(entity, value)
else:
self._save_single_attr(entity, value) | python | def save_attr(self, entity, value):
"""
Saves given EAV attribute with given value for given entity.
If schema is not many-to-one, the value is saved to the corresponding
Attr instance (which is created or updated).
If schema is many-to-one, the value is processed thusly:
* if value is iterable, all Attr instances for corresponding managed m2m
schemata are updated (those with names from the value list are set to
True, others to False). If a list item is not in available choices,
ValueError is raised;
* if the value is None, all corresponding Attr instances are reset to False;
* if the value is neither a list nor None, it is wrapped into a list and
processed as above (i.e. "foo" --> ["foo"]).
"""
if self.datatype == self.TYPE_MANY:
self._save_m2m_attr(entity, value)
else:
self._save_single_attr(entity, value) | [
"def",
"save_attr",
"(",
"self",
",",
"entity",
",",
"value",
")",
":",
"if",
"self",
".",
"datatype",
"==",
"self",
".",
"TYPE_MANY",
":",
"self",
".",
"_save_m2m_attr",
"(",
"entity",
",",
"value",
")",
"else",
":",
"self",
".",
"_save_single_attr",
"(",
"entity",
",",
"value",
")"
] | Saves given EAV attribute with given value for given entity.
If schema is not many-to-one, the value is saved to the corresponding
Attr instance (which is created or updated).
If schema is many-to-one, the value is processed thusly:
* if value is iterable, all Attr instances for corresponding managed m2m
schemata are updated (those with names from the value list are set to
True, others to False). If a list item is not in available choices,
ValueError is raised;
* if the value is None, all corresponding Attr instances are reset to False;
* if the value is neither a list nor None, it is wrapped into a list and
processed as above (i.e. "foo" --> ["foo"]). | [
"Saves",
"given",
"EAV",
"attribute",
"with",
"given",
"value",
"for",
"given",
"entity",
"."
] | 7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/models.py#L111-L132 | train |
neithere/eav-django | eav/models.py | BaseSchema._save_single_attr | def _save_single_attr(self, entity, value=None, schema=None,
create_nulls=False, extra={}):
"""
Creates or updates an EAV attribute for given entity with given value.
:param schema: schema for attribute. Default it current schema instance.
:param create_nulls: boolean: if True, even attributes with value=None
are created (by default they are skipped).
:param extra: dict: additional data for Attr instance (e.g. title).
"""
# If schema is not many-to-one, the value is saved to the corresponding
# Attr instance (which is created or updated).
schema = schema or self
lookups = dict(get_entity_lookups(entity), schema=schema, **extra)
try:
attr = self.attrs.get(**lookups)
except self.attrs.model.DoesNotExist:
attr = self.attrs.model(**lookups)
if create_nulls or value != attr.value:
attr.value = value
for k,v in extra.items():
setattr(attr, k, v)
attr.save() | python | def _save_single_attr(self, entity, value=None, schema=None,
create_nulls=False, extra={}):
"""
Creates or updates an EAV attribute for given entity with given value.
:param schema: schema for attribute. Default it current schema instance.
:param create_nulls: boolean: if True, even attributes with value=None
are created (by default they are skipped).
:param extra: dict: additional data for Attr instance (e.g. title).
"""
# If schema is not many-to-one, the value is saved to the corresponding
# Attr instance (which is created or updated).
schema = schema or self
lookups = dict(get_entity_lookups(entity), schema=schema, **extra)
try:
attr = self.attrs.get(**lookups)
except self.attrs.model.DoesNotExist:
attr = self.attrs.model(**lookups)
if create_nulls or value != attr.value:
attr.value = value
for k,v in extra.items():
setattr(attr, k, v)
attr.save() | [
"def",
"_save_single_attr",
"(",
"self",
",",
"entity",
",",
"value",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"create_nulls",
"=",
"False",
",",
"extra",
"=",
"{",
"}",
")",
":",
"# If schema is not many-to-one, the value is saved to the corresponding",
"# Attr instance (which is created or updated).",
"schema",
"=",
"schema",
"or",
"self",
"lookups",
"=",
"dict",
"(",
"get_entity_lookups",
"(",
"entity",
")",
",",
"schema",
"=",
"schema",
",",
"*",
"*",
"extra",
")",
"try",
":",
"attr",
"=",
"self",
".",
"attrs",
".",
"get",
"(",
"*",
"*",
"lookups",
")",
"except",
"self",
".",
"attrs",
".",
"model",
".",
"DoesNotExist",
":",
"attr",
"=",
"self",
".",
"attrs",
".",
"model",
"(",
"*",
"*",
"lookups",
")",
"if",
"create_nulls",
"or",
"value",
"!=",
"attr",
".",
"value",
":",
"attr",
".",
"value",
"=",
"value",
"for",
"k",
",",
"v",
"in",
"extra",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"attr",
",",
"k",
",",
"v",
")",
"attr",
".",
"save",
"(",
")"
] | Creates or updates an EAV attribute for given entity with given value.
:param schema: schema for attribute. Default it current schema instance.
:param create_nulls: boolean: if True, even attributes with value=None
are created (by default they are skipped).
:param extra: dict: additional data for Attr instance (e.g. title). | [
"Creates",
"or",
"updates",
"an",
"EAV",
"attribute",
"for",
"given",
"entity",
"with",
"given",
"value",
"."
] | 7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/models.py#L134-L157 | train |
bitesofcode/projexui | projexui/widgets/xcolorbutton.py | pickColor | def pickColor( self ):
"""
Prompts the user to select a color for this button.
"""
color = QColorDialog.getColor( self.color(), self )
if ( color.isValid() ):
self.setColor(color) | python | def pickColor( self ):
"""
Prompts the user to select a color for this button.
"""
color = QColorDialog.getColor( self.color(), self )
if ( color.isValid() ):
self.setColor(color) | [
"def",
"pickColor",
"(",
"self",
")",
":",
"color",
"=",
"QColorDialog",
".",
"getColor",
"(",
"self",
".",
"color",
"(",
")",
",",
"self",
")",
"if",
"(",
"color",
".",
"isValid",
"(",
")",
")",
":",
"self",
".",
"setColor",
"(",
"color",
")"
] | Prompts the user to select a color for this button. | [
"Prompts",
"the",
"user",
"to",
"select",
"a",
"color",
"for",
"this",
"button",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcolorbutton.py#L49-L56 | train |
damnit/pymite | pymite/adapters.py | DefaultReadAdapter.by_id | def by_id(self, id):
"""get adapter data by its id."""
path = partial(_path, self.adapter)
path = path(id)
return self._get(path) | python | def by_id(self, id):
"""get adapter data by its id."""
path = partial(_path, self.adapter)
path = path(id)
return self._get(path) | [
"def",
"by_id",
"(",
"self",
",",
"id",
")",
":",
"path",
"=",
"partial",
"(",
"_path",
",",
"self",
".",
"adapter",
")",
"path",
"=",
"path",
"(",
"id",
")",
"return",
"self",
".",
"_get",
"(",
"path",
")"
] | get adapter data by its id. | [
"get",
"adapter",
"data",
"by",
"its",
"id",
"."
] | 1e9b9bf6aef790af2d8781f9f77c098c54ca0342 | https://github.com/damnit/pymite/blob/1e9b9bf6aef790af2d8781f9f77c098c54ca0342/pymite/adapters.py#L19-L23 | train |
damnit/pymite | pymite/adapters.py | DefaultReadAdapter.by_name | def by_name(self, name, archived=False, limit=None, page=None):
"""get adapter data by name."""
if not archived:
path = _path(self.adapter)
else:
path = _path(self.adapter, 'archived')
return self._get(path, name=name, limit=limit, page=page) | python | def by_name(self, name, archived=False, limit=None, page=None):
"""get adapter data by name."""
if not archived:
path = _path(self.adapter)
else:
path = _path(self.adapter, 'archived')
return self._get(path, name=name, limit=limit, page=page) | [
"def",
"by_name",
"(",
"self",
",",
"name",
",",
"archived",
"=",
"False",
",",
"limit",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
"if",
"not",
"archived",
":",
"path",
"=",
"_path",
"(",
"self",
".",
"adapter",
")",
"else",
":",
"path",
"=",
"_path",
"(",
"self",
".",
"adapter",
",",
"'archived'",
")",
"return",
"self",
".",
"_get",
"(",
"path",
",",
"name",
"=",
"name",
",",
"limit",
"=",
"limit",
",",
"page",
"=",
"page",
")"
] | get adapter data by name. | [
"get",
"adapter",
"data",
"by",
"name",
"."
] | 1e9b9bf6aef790af2d8781f9f77c098c54ca0342 | https://github.com/damnit/pymite/blob/1e9b9bf6aef790af2d8781f9f77c098c54ca0342/pymite/adapters.py#L25-L31 | train |
damnit/pymite | pymite/adapters.py | DefaultReadAdapter.all | def all(self, archived=False, limit=None, page=None):
"""get all adapter data."""
path = partial(_path, self.adapter)
if not archived:
path = _path(self.adapter)
else:
path = _path(self.adapter, 'archived')
return self._get(path, limit=limit, page=page) | python | def all(self, archived=False, limit=None, page=None):
"""get all adapter data."""
path = partial(_path, self.adapter)
if not archived:
path = _path(self.adapter)
else:
path = _path(self.adapter, 'archived')
return self._get(path, limit=limit, page=page) | [
"def",
"all",
"(",
"self",
",",
"archived",
"=",
"False",
",",
"limit",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
"path",
"=",
"partial",
"(",
"_path",
",",
"self",
".",
"adapter",
")",
"if",
"not",
"archived",
":",
"path",
"=",
"_path",
"(",
"self",
".",
"adapter",
")",
"else",
":",
"path",
"=",
"_path",
"(",
"self",
".",
"adapter",
",",
"'archived'",
")",
"return",
"self",
".",
"_get",
"(",
"path",
",",
"limit",
"=",
"limit",
",",
"page",
"=",
"page",
")"
] | get all adapter data. | [
"get",
"all",
"adapter",
"data",
"."
] | 1e9b9bf6aef790af2d8781f9f77c098c54ca0342 | https://github.com/damnit/pymite/blob/1e9b9bf6aef790af2d8781f9f77c098c54ca0342/pymite/adapters.py#L33-L40 | train |
damnit/pymite | pymite/adapters.py | Projects.by_name | def by_name(self, name, archived=False, limit=None, page=None):
""" return a project by it's name.
this only works with the exact name of the project.
"""
# this only works with the exact name
return super(Projects, self).by_name(name, archived=archived,
limit=limit, page=page) | python | def by_name(self, name, archived=False, limit=None, page=None):
""" return a project by it's name.
this only works with the exact name of the project.
"""
# this only works with the exact name
return super(Projects, self).by_name(name, archived=archived,
limit=limit, page=page) | [
"def",
"by_name",
"(",
"self",
",",
"name",
",",
"archived",
"=",
"False",
",",
"limit",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
"# this only works with the exact name",
"return",
"super",
"(",
"Projects",
",",
"self",
")",
".",
"by_name",
"(",
"name",
",",
"archived",
"=",
"archived",
",",
"limit",
"=",
"limit",
",",
"page",
"=",
"page",
")"
] | return a project by it's name.
this only works with the exact name of the project. | [
"return",
"a",
"project",
"by",
"it",
"s",
"name",
".",
"this",
"only",
"works",
"with",
"the",
"exact",
"name",
"of",
"the",
"project",
"."
] | 1e9b9bf6aef790af2d8781f9f77c098c54ca0342 | https://github.com/damnit/pymite/blob/1e9b9bf6aef790af2d8781f9f77c098c54ca0342/pymite/adapters.py#L56-L62 | train |
damnit/pymite | pymite/adapters.py | TimeEntries.delete | def delete(self, id):
""" delete a time entry. """
path = partial(_path, self.adapter)
path = path(id)
return self._delete(path) | python | def delete(self, id):
""" delete a time entry. """
path = partial(_path, self.adapter)
path = path(id)
return self._delete(path) | [
"def",
"delete",
"(",
"self",
",",
"id",
")",
":",
"path",
"=",
"partial",
"(",
"_path",
",",
"self",
".",
"adapter",
")",
"path",
"=",
"path",
"(",
"id",
")",
"return",
"self",
".",
"_delete",
"(",
"path",
")"
] | delete a time entry. | [
"delete",
"a",
"time",
"entry",
"."
] | 1e9b9bf6aef790af2d8781f9f77c098c54ca0342 | https://github.com/damnit/pymite/blob/1e9b9bf6aef790af2d8781f9f77c098c54ca0342/pymite/adapters.py#L212-L216 | train |
damnit/pymite | pymite/adapters.py | Daily.at | def at(self, year, month, day):
""" time entries by year, month and day. """
path = partial(_path, self.adapter)
path = partial(path, int(year))
path = partial(path, int(month))
path = path(int(day))
return self._get(path) | python | def at(self, year, month, day):
""" time entries by year, month and day. """
path = partial(_path, self.adapter)
path = partial(path, int(year))
path = partial(path, int(month))
path = path(int(day))
return self._get(path) | [
"def",
"at",
"(",
"self",
",",
"year",
",",
"month",
",",
"day",
")",
":",
"path",
"=",
"partial",
"(",
"_path",
",",
"self",
".",
"adapter",
")",
"path",
"=",
"partial",
"(",
"path",
",",
"int",
"(",
"year",
")",
")",
"path",
"=",
"partial",
"(",
"path",
",",
"int",
"(",
"month",
")",
")",
"path",
"=",
"path",
"(",
"int",
"(",
"day",
")",
")",
"return",
"self",
".",
"_get",
"(",
"path",
")"
] | time entries by year, month and day. | [
"time",
"entries",
"by",
"year",
"month",
"and",
"day",
"."
] | 1e9b9bf6aef790af2d8781f9f77c098c54ca0342 | https://github.com/damnit/pymite/blob/1e9b9bf6aef790af2d8781f9f77c098c54ca0342/pymite/adapters.py#L226-L232 | train |
damnit/pymite | pymite/adapters.py | Tracker.start | def start(self, id):
""" start a specific tracker. """
path = partial(_path, self.adapter)
path = path(id)
return self._put(path) | python | def start(self, id):
""" start a specific tracker. """
path = partial(_path, self.adapter)
path = path(id)
return self._put(path) | [
"def",
"start",
"(",
"self",
",",
"id",
")",
":",
"path",
"=",
"partial",
"(",
"_path",
",",
"self",
".",
"adapter",
")",
"path",
"=",
"path",
"(",
"id",
")",
"return",
"self",
".",
"_put",
"(",
"path",
")"
] | start a specific tracker. | [
"start",
"a",
"specific",
"tracker",
"."
] | 1e9b9bf6aef790af2d8781f9f77c098c54ca0342 | https://github.com/damnit/pymite/blob/1e9b9bf6aef790af2d8781f9f77c098c54ca0342/pymite/adapters.py#L254-L258 | train |
damnit/pymite | pymite/adapters.py | Tracker.stop | def stop(self, id):
""" stop the tracker. """
path = partial(_path, self.adapter)
path = path(id)
return self._delete(path) | python | def stop(self, id):
""" stop the tracker. """
path = partial(_path, self.adapter)
path = path(id)
return self._delete(path) | [
"def",
"stop",
"(",
"self",
",",
"id",
")",
":",
"path",
"=",
"partial",
"(",
"_path",
",",
"self",
".",
"adapter",
")",
"path",
"=",
"path",
"(",
"id",
")",
"return",
"self",
".",
"_delete",
"(",
"path",
")"
] | stop the tracker. | [
"stop",
"the",
"tracker",
"."
] | 1e9b9bf6aef790af2d8781f9f77c098c54ca0342 | https://github.com/damnit/pymite/blob/1e9b9bf6aef790af2d8781f9f77c098c54ca0342/pymite/adapters.py#L261-L265 | train |
bitesofcode/projexui | projexui/widgets/xrolloutwidget.py | XRolloutWidget.clear | def clear( self ):
"""
Clears out all of the rollout items from the widget.
"""
self.blockSignals(True)
self.setUpdatesEnabled(False)
for child in self.findChildren(XRolloutItem):
child.setParent(None)
child.deleteLater()
self.setUpdatesEnabled(True)
self.blockSignals(False) | python | def clear( self ):
"""
Clears out all of the rollout items from the widget.
"""
self.blockSignals(True)
self.setUpdatesEnabled(False)
for child in self.findChildren(XRolloutItem):
child.setParent(None)
child.deleteLater()
self.setUpdatesEnabled(True)
self.blockSignals(False) | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"for",
"child",
"in",
"self",
".",
"findChildren",
"(",
"XRolloutItem",
")",
":",
"child",
".",
"setParent",
"(",
"None",
")",
"child",
".",
"deleteLater",
"(",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"True",
")",
"self",
".",
"blockSignals",
"(",
"False",
")"
] | Clears out all of the rollout items from the widget. | [
"Clears",
"out",
"all",
"of",
"the",
"rollout",
"items",
"from",
"the",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrolloutwidget.py#L229-L239 | train |
bitesofcode/projexui | projexui/widgets/xchart/xchartaxis.py | XChartAxis.minimumLabelHeight | def minimumLabelHeight(self):
"""
Returns the minimum height that will be required based on this font size
and labels list.
"""
metrics = QFontMetrics(self.labelFont())
return max(self._minimumLabelHeight,
metrics.height() + self.verticalLabelPadding()) | python | def minimumLabelHeight(self):
"""
Returns the minimum height that will be required based on this font size
and labels list.
"""
metrics = QFontMetrics(self.labelFont())
return max(self._minimumLabelHeight,
metrics.height() + self.verticalLabelPadding()) | [
"def",
"minimumLabelHeight",
"(",
"self",
")",
":",
"metrics",
"=",
"QFontMetrics",
"(",
"self",
".",
"labelFont",
"(",
")",
")",
"return",
"max",
"(",
"self",
".",
"_minimumLabelHeight",
",",
"metrics",
".",
"height",
"(",
")",
"+",
"self",
".",
"verticalLabelPadding",
"(",
")",
")"
] | Returns the minimum height that will be required based on this font size
and labels list. | [
"Returns",
"the",
"minimum",
"height",
"that",
"will",
"be",
"required",
"based",
"on",
"this",
"font",
"size",
"and",
"labels",
"list",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/xchartaxis.py#L191-L198 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.