docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Init method.
Args:
*args (): Django's args for a form field.
**kwargs (): Django's kwargs for a form field. | def __init__(self, *args, **kwargs):
if "widget" not in kwargs:
kwargs["widget"] = PasswordStrengthInput(render_value=False)
super(PasswordField, self).__init__(*args, **kwargs) | 589,314 |
Init method.
Args:
*args (): Django's args for a form field.
**kwargs (): Django's kwargs for a form field. Should contain a
confirm_with keyword argument to point to the password field. | def __init__(self, *args, **kwargs):
if "widget" not in kwargs:
kwargs["widget"] = PasswordConfirmationInput(
confirm_with=kwargs.pop('confirm_with', None))
super(PasswordConfirmationField, self).__init__(*args, **kwargs) | 589,315 |
Init method.
Args:
min_score (int): minimum score to accept (between 0 and 4).
user_attributes (tuple): list of user attributes to check. | def __init__(self, min_score=DEFAULT_MIN_SCORE,
user_attributes=DEFAULT_USER_ATTRIBUTES):
if min_score < 1:
min_score = 1
elif min_score > 4:
min_score = 4
self.min_score = min_score
self.user_attributes = user_attributes | 589,316 |
initialize the merger model with a coalescent time
Args:
- Tc: a float or an iterable, if iterable another argument T of same shape is required
- T: an array like of same shape as Tc that specifies the time pivots corresponding to Tc
Returns:
- None | def set_Tc(self, Tc, T=None):
if isinstance(Tc, Iterable):
if len(Tc)==len(T):
x = np.concatenate(([-ttconf.BIG_NUMBER], T, [ttconf.BIG_NUMBER]))
y = np.concatenate(([Tc[0]], Tc, [Tc[-1]]))
self.Tc = interp1d(x,y)
else:
... | 589,616 |
returns the cost associated with a branch starting at t_node
t_node is time before present, the branch goes back in time
Args:
- t_node: time of the node
- branch_length: branch length, determines when this branch merges with sister
- multiplicity: 2... | def cost(self, t_node, branch_length, multiplicity=2.0):
merger_time = t_node+branch_length
return self.integral_merger_rate(merger_time) - self.integral_merger_rate(t_node)\
- np.log(self.total_merger_rate(merger_time))*(multiplicity-1.0)/multiplicity | 589,621 |
returns the skyline, i.e., an estimate of the inverse rate of coalesence.
Here, the skyline is estimated from a sliding window average of the observed
mergers, i.e., without reference to the coalescence likelihood.
parameters:
gen -- number of generations per year. | def skyline_empirical(self, gen=1.0, n_points = 20):
mergers = self.tree_events[:,1]>0
merger_tvals = self.tree_events[mergers,0]
nlineages = self.nbranches(merger_tvals-ttconf.TINY_NUMBER)
expected_merger_density = nlineages*(nlineages-1)*0.5
nmergers = len(mergers)
... | 589,626 |
Instantiate a new grapefruit.Color object.
Parameters:
:values:
The values of this color, in the specified representation.
:mode:
The representation mode used for values.
:alpha:
the alpha value (transparency) of this color.
:wref:
The whitepoint reference, d... | def __init__(self, values, mode='rgb', alpha=1.0, wref=_DEFAULT_WREF):
if not(isinstance(values, tuple)):
raise TypeError('values must be a tuple')
if mode=='rgb':
self.__rgb = values
self.__hsl = Color.RgbToHsl(*values)
elif mode=='hsl':
self.__hsl = values
self.__rgb = ... | 590,863 |
Convert the color from RGB coordinates to HSL.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, l) tuple in the range:
h[0...360],
s[0...1],
... | def RgbToHsl(r, g, b):
minVal = min(r, g, b) # min RGB value
maxVal = max(r, g, b) # max RGB value
l = (maxVal + minVal) / 2.0
if minVal==maxVal:
return (0.0, 0.0, l) # achromatic (gray)
d = maxVal - minVal # delta RGB value
if l < 0.5: s = d / (maxVal + minV... | 590,866 |
Convert the color from HSL coordinates to RGB.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0..... | def HslToRgb(h, s, l):
if s==0: return (l, l, l) # achromatic (gray)
if l<0.5: n2 = l * (1.0 + s)
else: n2 = l+s - (l*s)
n1 = (2.0 * l) - n2
h /= 60.0
hueToRgb = Color._HueToRgb
r = hueToRgb(n1, n2, h + 2)
g = hueToRgb(n1, n2, h)
b = hueToRgb(n1, n2, h - 2)
return (r, ... | 590,868 |
Convert the color from RGB coordinates to HSV.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, v) tuple in the range:
h[0...360],
s[0...1],
... | def RgbToHsv(r, g, b):
v = float(max(r, g, b))
d = v - min(r, g, b)
if d==0: return (0.0, 0.0, v)
s = d / v
dr, dg, db = [(v - val) / d for val in (r, g, b)]
if r==v:
h = db - dg # between yellow & magenta
elif g==v:
h = 2.0 + dr - db # between cyan & yel... | 590,869 |
Convert the color from RGB coordinates to HSV.
Parameters:
:h:
The Hus component value [0...1]
:s:
The Saturation component value [0...1]
:v:
The Value component [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
... | def HsvToRgb(h, s, v):
if s==0: return (v, v, v) # achromatic (gray)
h /= 60.0
h = h % 6.0
i = int(h)
f = h - i
if not(i&1): f = 1-f # if i is even
m = v * (1.0 - s)
n = v * (1.0 - (s * f))
if i==0: return (v, n, m)
if i==1: return (n, v, m)
if i==2: return (m,... | 590,870 |
Convert the color from RGB to YIQ.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (y, i, q) tuple in the range:
y[0...1],
i[0...1],
q[0...1]
... | def RgbToYiq(r, g, b):
y = (r * 0.29895808) + (g * 0.58660979) + (b *0.11443213)
i = (r * 0.59590296) - (g * 0.27405705) - (b *0.32184591)
q = (r * 0.21133576) - (g * 0.52263517) + (b *0.31129940)
return (y, i, q) | 590,871 |
Convert the color from YIQ coordinates to RGB.
Parameters:
:y:
Tte Y component value [0...1]
:i:
The I component value [0...1]
:q:
The Q component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]... | def YiqToRgb(y, i, q):
r = y + (i * 0.9562) + (q * 0.6210)
g = y - (i * 0.2717) - (q * 0.6485)
b = y - (i * 1.1053) + (q * 1.7020)
return (r, g, b) | 590,872 |
Convert the color from RGB coordinates to YUV.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (y, u, v) tuple in the range:
y[0...1],
u[-0.436...0.43... | def RgbToYuv(r, g, b):
y = (r * 0.29900) + (g * 0.58700) + (b * 0.11400)
u = -(r * 0.14713) - (g * 0.28886) + (b * 0.43600)
v = (r * 0.61500) - (g * 0.51499) - (b * 0.10001)
return (y, u, v) | 590,873 |
Convert the color from YUV coordinates to RGB.
Parameters:
:y:
The Y component value [0...1]
:u:
The U component value [-0.436...0.436]
:v:
The V component value [-0.615...0.615]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...... | def YuvToRgb(y, u, v):
r = y + (v * 1.13983)
g = y - (u * 0.39465) - (v * 0.58060)
b = y + (u * 2.03211)
return (r, g, b) | 590,874 |
Convert the color from CMYK coordinates to CMY.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:k:
The Black component value [0...1]
Returns:
The color as an (c, m, y)... | def CmykToCmy(c, m, y, k):
mk = 1-k
return ((c*mk + k), (m*mk + k), (y*mk + k)) | 590,879 |
Convert the color from CMY coordinates to CMYK.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
Returns:
The color as an (c, m, y, k) tuple in the range:
c[0...1],
m[0...... | def CmyToCmyk(c, m, y):
k = min(c, m, y)
if k==1.0: return (0.0, 0.0, 0.0, 1.0)
mk = 1-k
return ((c-k) / mk, (m-k) / mk, (y-k) / mk, k) | 590,880 |
Convert the color from (r, g, b) to an int tuple.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...255],
g[0...2551... | def RgbToIntTuple(r, g, b):
return tuple(int(round(v*255)) for v in (r, g, b)) | 590,881 |
Convert the color from (r, g, b) to #RRGGBB.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A CSS string representation of this color (#RRGGBB).
>>> Color.RgbToHtml(1, 0.5,... | def RgbToHtml(r, g, b):
return '#%02x%02x%02x' % tuple((min(round(v*255), 255) for v in (r, g, b))) | 590,882 |
Convert the color from RGB to a PIL-compatible integer.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A PIL compatible integer (0xBBGGRR).
>>> '0x%06x' % Color.RgbToPil(1,... | def RgbToPil(r, g, b):
r, g, b = [min(int(round(v*255)), 255) for v in (r, g, b)]
return (b << 16) + (g << 8) + r | 590,884 |
Convert the color from a PIL-compatible integer to RGB.
Parameters:
pil: a PIL compatible color representation (0xBBGGRR)
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r: [0...1]
g: [0...1]
b: [0...1]
>>> '(%g, %g, %g)' % Color.PilToRgb(0x0080ff)
... | def PilToRgb(pil):
r = 0xff & pil
g = 0xff & (pil >> 8)
b = 0xff & (pil >> 16)
return tuple((v / 255.0 for v in (r, g, b))) | 590,885 |
Convert a color component to its web safe equivalent.
Parameters:
:c:
The component value [0...1]
:alt:
If True, return the alternative value instead of the nearest one.
Returns:
The web safe equivalent of the component value. | def _WebSafeComponent(c, alt=False):
# This sucks, but floating point between 0 and 1 is quite fuzzy...
# So we just change the scale a while to make the equality tests
# work, otherwise it gets wrong at some decimal far to the right.
sc = c * 100.0
# If the color is already safe, return it st... | 590,886 |
Convert the color from RGB to its greyscale equivalent
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r[0...... | def RgbToGreyscale(r, g, b):
v = (r + g + b) / 3.0
return (v, v, v) | 590,888 |
Maps a hue on the RGB color wheel to Itten's RYB wheel.
Parameters:
:hue:
The hue on the RGB color wheel [0...360]
Returns:
An approximation of the corresponding hue on Itten's RYB wheel.
>>> Color.RgbToRyb(15)
26.0 | def RgbToRyb(hue):
d = hue % 15
i = int(hue / 15)
x0 = _RybWheel[i]
x1 = _RybWheel[i+1]
return x0 + (x1-x0) * d / 15 | 590,889 |
Maps a hue on Itten's RYB color wheel to the standard RGB wheel.
Parameters:
:hue:
The hue on Itten's RYB color wheel [0...360]
Returns:
An approximation of the corresponding hue on the standard RGB wheel.
>>> Color.RybToRgb(15)
8.0 | def RybToRgb(hue):
d = hue % 15
i = int(hue / 15)
x0 = _RgbWheel[i]
x1 = _RgbWheel[i+1]
return x0 + (x1-x0) * d / 15 | 590,890 |
Create a new instance based on the specifed PIL color.
Parameters:
:pil:
A PIL compatible color representation (0xBBGGRR)
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color in... | def NewFromPil(pil, alpha=1.0, wref=_DEFAULT_WREF):
return Color(Color.PilToRgb(pil), 'rgb', alpha, wref) | 590,901 |
Create a new instance based on this one with a new hue.
Parameters:
:hue:
The hue of the new color [0...360].
Returns:
A grapefruit.Color instance.
>>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60)
(1.0, 1.0, 0.0, 1.0)
>>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60).hsl
... | def ColorWithHue(self, hue):
h, s, l = self.__hsl
return Color((hue, s, l), 'hsl', self.__a, self.__wref) | 590,905 |
Create a new instance based on this one with a new saturation value.
.. note::
The saturation is defined for the HSL mode.
Parameters:
:saturation:
The saturation of the new color [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.NewFromHsl(30, 1, 0.5).ColorWithSat... | def ColorWithSaturation(self, saturation):
h, s, l = self.__hsl
return Color((h, saturation, l), 'hsl', self.__a, self.__wref) | 590,906 |
Create a new instance based on this one with a new lightness value.
Parameters:
:lightness:
The lightness of the new color [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25)
(0.5, 0.25, 0.0, 1.0)
>>> Color.NewFromHsl(30, 1,... | def ColorWithLightness(self, lightness):
h, s, l = self.__hsl
return Color((h, s, lightness), 'hsl', self.__a, self.__wref) | 590,907 |
Create a new instance based on this one but lighter.
Parameters:
:level:
The amount by which the color should be lightened to produce
the new one [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.NewFromHsl(30, 1, 0.5).LighterColor(0.25)
(1.0, 0.75, 0.5, 1.0)
>>... | def LighterColor(self, level):
h, s, l = self.__hsl
return Color((h, s, min(l + level, 1)), 'hsl', self.__a, self.__wref) | 590,908 |
Create a new instance which is the complementary color of this one.
Parameters:
:mode:
Select which color wheel to use for the generation (ryb/rgb).
Returns:
A grapefruit.Color instance.
>>> Color.NewFromHsl(30, 1, 0.5).ComplementaryColor(mode='rgb')
(0.0, 0.5, 1.0, 1.0)
>>> ... | def ComplementaryColor(self, mode='ryb'):
h, s, l = self.__hsl
if mode == 'ryb': h = Color.RgbToRyb(h)
h = (h+180)%360
if mode == 'ryb': h = Color.RybToRgb(h)
return Color((h, s, l), 'hsl', self.__a, self.__wref) | 590,911 |
Sort the keys in a JSON-RPC response object.
This has no effect other than making it nicer to read. Useful in Python 3.5 only,
dictionaries are already sorted in newer Python versions.
Example::
>>> json.dumps(sort_response({'id': 2, 'result': 5, 'jsonrpc': '2.0'}))
{"jsonrpc": "2.0", "re... | def sort_response(response: Dict[str, Any]) -> OrderedDict:
root_order = ["jsonrpc", "result", "error", "id"]
error_order = ["code", "message", "data"]
req = OrderedDict(sorted(response.items(), key=lambda k: root_order.index(k[0])))
if "error" in response:
req["error"] = OrderedDict(
... | 590,925 |
Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.
Returns:
A Response object. | async def send_message(
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
with async_timeout.timeout(self.timeout):
async with self.session.post(
self.endpoint, data=request, ssl=self.ssl
) as response:
response... | 590,937 |
Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.
Returns:
A Response object. | async def send_message(
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
await self.socket.send(request)
if response_expected:
response_text = await self.socket.recv()
return Response(response_text)
return Response("") | 590,939 |
A random string.
Not unique, but has around 1 in a million chance of collision (with the default 8
character length). e.g. 'fubui5e6'
Args:
length: Length of the random string.
chars: The characters to randomly choose from. | def random(length: int = 8, chars: str = digits + ascii_lowercase) -> Iterator[str]:
while True:
yield "".join([choice(chars) for _ in range(length)]) | 590,942 |
Converts a deserialized response into a JSONRPCResponse object.
The dictionary be either an error or success response, never a notification.
Args:
response: Deserialized response dictionary. We can assume the response is valid
JSON-RPC here, since it passed the jsonschema validation. | def get_response(response: Dict[str, Any]) -> JSONRPCResponse:
if "error" in response:
return ErrorResponse(**response)
return SuccessResponse(**response) | 590,944 |
Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.
Returns:
A Response object. | async def send_message( # type: ignore
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
headers = dict(self.DEFAULT_HEADERS)
headers.update(kwargs.pop("headers", {}))
response = await self.client.fetch(
self.endpoint, method="POST", bod... | 590,949 |
Log a request or response
Args:
message: JSON-RPC request or response string.
level: Log level.
extra: More details to include in the log entry.
trim: Abbreviate log messages. | def log_(
message: str,
logger: logging.Logger,
level: str = "info",
extra: Optional[Dict] = None,
trim: bool = False,
) -> None:
if extra is None:
extra = {}
# Clean up the message for logging
if message:
message = message.replace("\n", "").replace(" ", " ").replac... | 590,953 |
Sort a JSON-RPC request dict.
This has no effect other than making the request nicer to read.
>>> json.dumps(sort_request(
... {'id': 2, 'params': [2, 3], 'method': 'add', 'jsonrpc': '2.0'}))
'{"jsonrpc": "2.0", "method": "add", "params": [2, 3], "id": 2}'
Args:
request: J... | def sort_request(request: Dict[str, Any]) -> OrderedDict:
sort_order = ["jsonrpc", "method", "params", "id"]
return OrderedDict(sorted(request.items(), key=lambda k: sort_order.index(k[0]))) | 590,954 |
Log a request.
Args:
request: The JSON-RPC request string.
trim_log_values: Log an abbreviated version of the request. | def log_request(
self, request: str, trim_log_values: bool = False, **kwargs: Any
) -> None:
return log_(request, request_log, "info", trim=trim_log_values, **kwargs) | 590,961 |
Log a response.
Note this is different to log_request, in that it takes a Response object, not a
string.
Args:
response: The Response object to log. Note this is different to log_request
which takes a string.
trim_log_values: Log an abbreviated version o... | def log_response(
self, response: Response, trim_log_values: bool = False, **kwargs: Any
) -> None:
return log_(response.text, response_log, "info", trim=trim_log_values, **kwargs) | 590,962 |
Send a JSON-RPC request, without expecting a response.
Args:
method_name: The remote procedure's method name.
args: Positional arguments passed to the remote procedure.
kwargs: Keyword arguments passed to the remote procedure.
trim_log_values: Abbreviate the log ... | def notify(
self,
method_name: str,
*args: Any,
trim_log_values: Optional[bool] = None,
validate_against_schema: Optional[bool] = None,
**kwargs: Any
) -> Response:
return self.send(
Notification(method_name, *args, **kwargs),
... | 590,963 |
Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.
Returns:
A Response object. | def send_message(
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
payload = str(request) + self.delimiter
self.socket.send(payload.encode(self.encoding))
response = bytes()
decoded = None
# Receive the response until we find the de... | 590,967 |
Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.
Returns:
A Response object. | def send_message(
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
response = self.session.post(self.endpoint, data=request.encode(), **kwargs)
return Response(response.text, raw=response) | 590,972 |
Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.
Returns:
A Response object. | def send_message(
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
self.socket.send_string(request)
return Response(self.socket.recv().decode()) | 590,974 |
Get a MemoryStream instance.
Args:
data (bytes, bytearray, BytesIO): (Optional) data to create the stream from.
Returns:
MemoryStream: instance. | def get_stream(data=None):
if len(__mstreams_available__) == 0:
if data:
mstream = MemoryStream(data)
mstream.seek(0)
else:
mstream = MemoryStream()
__mstreams__.append(mstream)
return mstream
mstre... | 591,136 |
Unpack the stream contents according to the specified format in `fmt`.
For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html
Args:
fmt (str): format string.
length (int): amount of bytes to read.
Returns:
variable: th... | def unpack(self, fmt, length=1):
try:
info = struct.unpack(fmt, self.stream.read(length))[0]
except struct.error as e:
raise SDKException(ErrorCode.unpack_error(e.args[0]))
return info | 591,264 |
Read a single byte.
Args:
do_ord (bool): (default True) convert the byte to an ordinal first.
Returns:
bytes: a single byte if successful. 0 (int) if an exception occurred. | def read_byte(self, do_ord=True) -> int:
try:
if do_ord:
return ord(self.stream.read(1))
else:
return self.stream.read(1)
except Exception as e:
raise SDKException(ErrorCode.read_byte_error(e.args[0])) | 591,265 |
Read the specified number of bytes from the stream.
Args:
length (int): number of bytes to read.
Returns:
bytes: `length` number of bytes. | def read_bytes(self, length) -> bytes:
value = self.stream.read(length)
return value | 591,266 |
Read 4 bytes as a float value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
float: | def read_float(self, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.unpack("%sf" % endian, 4) | 591,267 |
Read 8 bytes as a double value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
float: | def read_double(self, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.unpack("%sd" % endian, 8) | 591,268 |
Read 1 byte as a signed integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: | def read_int8(self, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.unpack('%sb' % endian) | 591,269 |
Read 1 byte as an unsigned integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: | def read_uint8(self, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.unpack('%sB' % endian) | 591,270 |
Read 2 byte as a signed integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: | def read_int16(self, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.unpack('%sh' % endian, 2) | 591,271 |
Read 2 byte as an unsigned integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: | def read_uint16(self, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.unpack('%sH' % endian, 2) | 591,272 |
Read 4 bytes as a signed integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: | def read_int32(self, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.unpack('%si' % endian, 4) | 591,273 |
Read 4 bytes as an unsigned integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: | def read_uint32(self, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.unpack('%sI' % endian, 4) | 591,274 |
Read 8 bytes as a signed integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: | def read_int64(self, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.unpack('%sq' % endian, 8) | 591,275 |
Read 8 bytes as an unsigned integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: | def read_uint64(self, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.unpack('%sQ' % endian, 8) | 591,276 |
Read a variable length integer from the stream.
The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
max_size (int): (Optional) maximum number of bytes to read.
Returns:
int: | def read_var_int(self, max_size=sys.maxsize):
fb = self.read_byte()
if fb is 0:
return fb
if hex(fb) == '0xfd':
value = self.read_uint16()
elif hex(fb) == '0xfe':
value = self.read_uint32()
elif hex(fb) == '0xff':
value = s... | 591,277 |
Read a variable length of bytes from the stream.
Args:
max_size (int): (Optional) maximum number of bytes to read.
Returns:
bytes: | def read_var_bytes(self, max_size=sys.maxsize) -> bytes:
length = self.read_var_int(max_size)
return self.read_bytes(length) | 591,278 |
Similar to `ReadString` but expects a variable length indicator instead of the fixed 1 byte indicator.
Args:
max_size (int): (Optional) maximum number of bytes to read.
Returns:
bytes: | def read_var_str(self, max_size=sys.maxsize):
length = self.read_var_int(max_size)
return self.unpack(str(length) + 's', length) | 591,280 |
Deserialize a stream into the object specific by `class_name`.
Args:
class_name (str): a full path to the class to be deserialized into. e.g. 'neo.Core.Block.Block'
max_size (int): (Optional) maximum number of bytes to read.
Returns:
list: list of `class_name` objec... | def read_serializable_array(self, class_name, max_size=sys.maxsize):
module = '.'.join(class_name.split('.')[:-1])
class_name = class_name.split('.')[-1]
class_attr = getattr(importlib.import_module(module), class_name)
length = self.read_var_int(max_size=max_size)
items... | 591,281 |
Write a single byte to the stream.
Args:
value (bytes, str or int): value to write to the stream. | def write_byte(self, value):
if isinstance(value, bytes):
self.stream.write(value)
elif isinstance(value, str):
self.stream.write(value.encode('utf-8'))
elif isinstance(value, int):
self.stream.write(bytes([value])) | 591,294 |
Write bytes by packing them according to the provided format `fmt`.
For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html
Args:
fmt (str): format string.
data (object): the data to write to the raw stream.
Returns:
in... | def pack(self, fmt, data):
return self.write_bytes(struct.pack(fmt, data)) | 591,296 |
Pack the value as a float and write 4 bytes to the stream.
Args:
value (number): the value to write to the stream.
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | def write_float(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack('%sf' % endian, value) | 591,297 |
Pack the value as a double and write 8 bytes to the stream.
Args:
value (number): the value to write to the stream.
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | def write_double(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack('%sd' % endian, value) | 591,298 |
Pack the value as a signed byte and write 1 byte to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | def write_int8(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack('%sb' % endian, value) | 591,299 |
Pack the value as an unsigned byte and write 1 byte to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | def write_uint8(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack('%sB' % endian, value) | 591,300 |
Pack the value as a signed integer and write 2 bytes to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | def write_int16(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack('%sh' % endian, value) | 591,301 |
Pack the value as an unsigned integer and write 2 bytes to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | def write_uint16(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack('%sH' % endian, value) | 591,302 |
Pack the value as a signed integer and write 4 bytes to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | def write_int32(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack('%si' % endian, value) | 591,303 |
Pack the value as an unsigned integer and write 4 bytes to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | def write_uint32(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack('%sI' % endian, value) | 591,304 |
Pack the value as a signed integer and write 8 bytes to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | def write_int64(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack('%sq' % endian, value) | 591,305 |
Pack the value as an unsigned integer and write 8 bytes to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | def write_uint64(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack('%sQ' % endian, value) | 591,306 |
Write an integer value in a space saving way to the stream.
Args:
value (int):
little_endian (bool): specify the endianness. (Default) Little endian.
Raises:
SDKException: if `value` is not of type int.
SDKException: if `value` is < 0.
Returns:
... | def write_var_int(self, value, little_endian=True):
if not isinstance(value, int):
raise SDKException(ErrorCode.param_err('%s not int type.' % value))
if value < 0:
raise SDKException(ErrorCode.param_err('%d too small.' % value))
elif value < 0xfd:
... | 591,307 |
Write a string value to the stream.
Args:
value (str): value to write to the stream.
length (int): length of the string to write. | def write_fixed_str(self, value, length):
towrite = value.encode('utf-8')
slen = len(towrite)
if slen > length:
raise SDKException(ErrorCode.param_err('string longer than fixed length: %s' % length))
self.write_bytes(towrite)
diff = length - slen
whi... | 591,310 |
Write an array of serializable objects to the stream.
Args:
array(list): a list of serializable objects. i.e. extending neo.IO.Mixins.SerializableMixin | def write_serializable_array(self, array):
if array is None:
self.write_byte(0)
else:
self.write_var_int(len(array))
for item in array:
item.Serialize(self) | 591,311 |
Write an array of hashes to the stream.
Args:
arr (list): a list of 32 byte hashes. | def write_hashes(self, arr):
length = len(arr)
self.write_var_int(length)
for item in arr:
ba = bytearray(binascii.unhexlify(item))
ba.reverse()
self.write_bytes(ba) | 591,312 |
Realiza a autenticação no sistema do CartolaFC utilizando o email e password informados.
Args:
email (str): O email do usuário
password (str): A senha do usuário
Raises:
cartolafc.CartolaFCError: Se o conjunto (email, password) não conseguiu realizar a autenticação ... | def set_credentials(self, email, password):
self._email = email
self._password = password
response = requests.post(self._auth_url,
json=dict(payload=dict(email=self._email, password=self._password, serviceId=4728)))
body = response.json()
... | 591,430 |
Realiza a autenticação no servidor Redis utilizando a URL informada.
Args:
redis_url (str): URL para conectar ao servidor Redis, exemplo: redis://user:password@localhost:6379/2.
redis_timeout (int): O timeout padrão (em segundos).
kwargs (dict):
Raises:
... | def set_redis(self, redis_url, redis_timeout=10):
self._redis_url = redis_url
self._redis_timeout = redis_timeout if isinstance(redis_timeout, int) and redis_timeout > 0 else 10
try:
self._redis = redis.StrictRedis.from_url(url=redis_url)
self._redis.ping()
... | 591,431 |
Retorna o resultado da busca ao Cartola por um determinado termo de pesquisa.
Args:
query (str): Termo para utilizar na busca.
Returns:
Uma lista de instâncias de cartolafc.Liga, uma para cada liga contento o termo utilizado na busca. | def ligas(self, query):
url = '{api_url}/ligas'.format(api_url=self._api_url)
data = self._request(url, params=dict(q=query))
return [Liga.from_dict(liga_info) for liga_info in data] | 591,437 |
Retorna o resultado da busca ao Cartola por um determinado termo de pesquisa.
Args:
query (str): Termo para utilizar na busca.
Returns:
Uma lista de instâncias de cartolafc.TimeInfo, uma para cada time contento o termo utilizado na busca. | def times(self, query):
url = '{api_url}/times'.format(api_url=self._api_url)
data = self._request(url, params=dict(q=query))
return [TimeInfo.from_dict(time_info) for time_info in data] | 591,446 |
Logs in to Kindle Cloud Reader.
Args:
max_tries: The maximum number of login attempts that will be made.
Raises:
BrowserError: If method called when browser not at a signin URL.
LoginError: If login unsuccessful after `max_tries` attempts. | def _login(self, max_tries=2):
if not self.current_url.startswith(_KindleCloudReaderBrowser._SIGNIN_URL):
raise BrowserError(
'Current url "%s" is not a signin url ("%s")' %
(self.current_url, _KindleCloudReaderBrowser._SIGNIN_URL))
email_field_loaded = lambda br: br.find_elemen... | 591,662 |
Runs an api call with javascript-formatted arguments.
Args:
function_name: The name of the KindleAPI call to run.
*args: Javascript-formatted arguments to pass to the API call.
Returns:
The result of the API call.
Raises:
APIError: If the API call fails or times out. | def _get_api_call(self, function_name, *args):
api_call = dedent() % {
'api_call': function_name,
'args': ', '.join(args)
}
script = '\n'.join((api.API_SCRIPT, api_call))
try:
return self._browser.execute_async_script(script)
except TimeoutException:
# FIXME: KCR wil... | 591,665 |
Returns a book's metadata.
Args:
asin: The ASIN of the book to be queried.
Returns:
A `KindleBook` instance corresponding to the book associated with
`asin`. | def get_book_metadata(self, asin):
kbm = self._get_api_call('get_book_metadata', '"%s"' % asin)
return KindleCloudReaderAPI._kbm_to_book(kbm) | 591,666 |
Returns the progress data available for a book.
NOTE: A summary of the two progress formats can be found in the
docstring for `ReadingProgress`.
Args:
asin: The asin of the book to be queried.
Returns:
A `ReadingProgress` instance corresponding to the book associated with
`asin`. | def get_book_progress(self, asin):
kbp = self._get_api_call('get_book_progress', '"%s"' % asin)
return KindleCloudReaderAPI._kbp_to_progress(kbp) | 591,667 |
shallow dictionary merge
Args:
a: dict to extend
b: dict to apply to a
Returns:
new instance of the same type as _a_, with _a_ and _b_ merged. | def extend(*args):
if not args:
return {}
first = args[0]
rest = args[1:]
out = type(first)(first)
for each in rest:
out.update(each)
return out | 591,923 |
redux in a nutshell.
observable has been omitted.
Args:
reducer: root reducer function for the state tree
initial_state: optional initial state data
enhancer: optional enhancer function for middleware etc.
Returns:
a Pydux store | def create_store(reducer, initial_state=None, enhancer=None):
if enhancer is not None:
if not hasattr(enhancer, '__call__'):
raise TypeError('Expected the enhancer to be a function.')
return enhancer(create_store)(reducer, initial_state)
if not hasattr(reducer, '__call__'):
... | 591,943 |
chained function composition wrapper
creates function f, where f(x) = arg0(arg1(arg2(...argN(x))))
if *funcs is empty, an identity function is returned.
Args:
*funcs: list of functions to chain
Returns:
a new function composed of chained calls to *args | def compose(*funcs):
if not funcs:
return lambda *args: args[0] if args else None
if len(funcs) == 1:
return funcs[0]
last = funcs[-1]
rest = funcs[0:-1]
return lambda *args: reduce(lambda ax, func: func(ax),
reversed(rest), last(*args)) | 592,000 |
composition tool for creating reducer trees.
Args:
reducers: dict with state keys and reducer functions
that are responsible for each key
Returns:
a new, combined reducer function | def combine_reducers(reducers):
final_reducers = {key: reducer
for key, reducer in reducers.items()
if hasattr(reducer, '__call__')}
sanity_error = None
try:
assert_reducer_sanity(final_reducers)
except Exception as e:
sanity_error = e
... | 592,003 |
creates an enhancer function composed of middleware
Args:
*middlewares: list of middleware functions to apply
Returns:
an enhancer for subsequent calls to create_store() | def apply_middleware(*middlewares):
def inner(create_store_):
def create_wrapper(reducer, enhancer=None):
store = create_store_(reducer, enhancer)
dispatch = store['dispatch']
middleware_api = {
'get_state': store['get_state'],
'dispat... | 592,009 |
Construct a new Ext object.
Args:
type: application-defined type integer
data: application-defined data byte array
Example:
>>> foo = umsgpack.Ext(0x05, b"\x01\x02\x03")
>>> umsgpack.packb({u"special stuff": foo, u"awesome": True})
'\x82\xa7awesome\xc3\x... | def __init__(self, type, data):
# Check type is type int
if not isinstance(type, int):
raise TypeError("ext type is not type integer")
# Check data is type bytes
elif sys.version_info[0] == 3 and not isinstance(data, bytes):
raise TypeError("ext data is n... | 592,293 |
Push created package to PyPI.
Requires the following defined environment variables:
- TWINE_USERNAME: The PyPI username to upload this package under
- TWINE_PASSWORD: The password to the user's account
Args:
dist (str):
The distribution to push. Must be a valid directory; s... | def _pypi_push(dist):
# Register all distributions and wheels with PyPI. We have to list the dist
# directory and register each file individually because `twine` doesn't
# handle globs.
for filename in os.listdir(dist):
full_path = os.path.join(dist, filename)
if os.path.isfile(full... | 592,710 |
Create a StatsRequest with the optional parameters below.
Args:
xid (int): xid to be used on the message header.
body_type (StatsType): One of the OFPST_* constants.
flags (int): OFPSF_REQ_* flags (none yet defined).
body (BinaryData): Body of the request. | def __init__(self, xid=None, body_type=None, flags=0, body=b''):
super().__init__(xid)
self.body_type = body_type
self.flags = flags
self.body = body | 592,897 |
Create a RoleReply with the optional parameters below.
Args:
xid (int): OpenFlow xid to the header.
role (:class:`~.controller2switch.common.ControllerRole`):
Is the new role that the controller wants to assume.
generation_id (int): Master Election Generation... | def __init__(self, xid=None, role=ControllerRole.OFPCR_ROLE_NOCHANGE,
generation_id=UBINT64_MAX_VALUE):
super().__init__(xid, role, generation_id)
self.header.message_type = Type.OFPT_ROLE_REPLY | 592,900 |
Create BucketCounter with the optional parameters below.
Args:
packet_count (int): Number of packets processed by bucket.
byte_count (int): Number of bytes processed by bucket. | def __init__(self, packet_count=None, byte_count=None):
super().__init__()
self.packet_count = packet_count
self.byte_count = byte_count | 592,903 |
Create a RoleBaseMessage with the optional parameters below.
Args:
xid (int): OpenFlow xid to the header.
role (:class:`~.controller2switch.common.ControllerRole`): .
generation_id (int): Master Election Generation Id. | def __init__(self, xid=None, role=None, generation_id=None):
super().__init__(xid)
self.role = role
self.generation_id = generation_id | 592,905 |
Create a SwitchConfig with the optional parameters below.
Args:
xid (int): xid to be used on the message header.
flags (ConfigFlag): OFPC_* flags.
miss_send_len (int): UBInt16 max bytes of new flow that the
datapath should send to the controller. | def __init__(self, xid=None, flags=ConfigFlag.OFPC_FRAG_NORMAL,
miss_send_len=ControllerMaxLen.OFPCML_NO_BUFFER):
super().__init__(xid)
self.flags = flags
self.miss_send_len = miss_send_len | 592,906 |
Create a ExperimenterMultipartHeader with the parameters below.
Args:
experimenter: Experimenter ID which takes the same form as in
struct ofp_experimenter_header (
:class:`~pyof.v0x04.symmetric.experimenter.ExperimenterHeader`)
exp_type: Experimenter def... | def __init__(self, experimenter=None, exp_type=None):
super().__init__()
self.experimenter = experimenter
self.exp_type = exp_type | 592,907 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.