uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5ad63397c3d2a97cdad4d18e | train | class | class MenuAction(Action):
"""
Specific action to get a selection menu
"""
def __new__(cls, **kwargs):
default = {f: None for f in _action_fields}
default.update(kwargs)
default['action_type'] = 'select'
return super(MenuAction, cls).__new__(
cls, **default)
| class MenuAction(Action):
| """
Specific action to get a selection menu
"""
def __new__(cls, **kwargs):
default = {f: None for f in _action_fields}
default.update(kwargs)
default['action_type'] = 'select'
return super(MenuAction, cls).__new__(
cls, **default)
| '
if (default['text'] is None and default['value'] is None and
default['name'] is not None):
default['text'] = default['value'] = default['name']
return super(ButtonAction, cls).__new__(
cls, **default)
class MenuAction(Action):
| 64 | 64 | 73 | 5 | 59 | romaryd/lifoid | lifoid/message/__init__.py | Python | MenuAction | MenuAction | 129 | 138 | 129 | 129 | 2a5fccee787c2056d5b69a166e7fe458a3f7db87 | bigcode/the-stack | train |
c4009cae0cb40db03b6f3516 | train | class | class Message(namedtuple('Message', _fields), NamedtupleRecord, LoggingMixin):
"""
Generic Lifoid message
"""
def __new__(cls, **kwargs):
default = {f: None for f in _fields}
default.update(kwargs)
if default['date'] is None:
default['date'] = datetime.datetime.utcnow... | class Message(namedtuple('Message', _fields), NamedtupleRecord, LoggingMixin):
| """
Generic Lifoid message
"""
def __new__(cls, **kwargs):
default = {f: None for f in _fields}
default.update(kwargs)
if default['date'] is None:
default['date'] = datetime.datetime.utcnow().isoformat()[:-3]
if default['ttl'] is None:
default['ttl... | .mixin import LoggingMixin
from lifoid.message.message_types import CHAT, TXT
_fields = ['date', 'ttl', 'from_user', 'to_user', 'payload',
'message_type', 'lifoid_id', 'topic', 'type']
class Message(namedtuple('Message', _fields), NamedtupleRecord, LoggingMixin):
| 68 | 68 | 227 | 17 | 51 | romaryd/lifoid | lifoid/message/__init__.py | Python | Message | Message | 12 | 33 | 12 | 12 | 59ae78e1cd0ea9c7ab0a5582391d0a960b8f001f | bigcode/the-stack | train |
e4a1ed87b18e83e60511b6a3 | train | class | class Option(namedtuple('Option', _option_fields)):
"""
Option
"""
def __new__(cls, **kwargs):
default = {f: None for f in _option_fields}
default.update(kwargs)
return super(Option, cls).__new__(
cls, **default)
| class Option(namedtuple('Option', _option_fields)):
| """
Option
"""
def __new__(cls, **kwargs):
default = {f: None for f in _option_fields}
default.update(kwargs)
return super(Option, cls).__new__(
cls, **default)
| new__(cls, **kwargs):
default = {f: None for f in _option_group_fields}
default.update(kwargs)
return super(OptionGroup, cls).__new__(
cls, **default)
_option_fields = ['text', 'value']
class Option(namedtuple('Option', _option_fields)):
| 64 | 64 | 63 | 11 | 53 | romaryd/lifoid | lifoid/message/__init__.py | Python | Option | Option | 158 | 166 | 158 | 158 | 7c749ae5229ee31c9904e9580779f8b754bada7e | bigcode/the-stack | train |
1fe41894ef325bcf3022a6f5 | train | class | class Chat(namedtuple('Chat', _chat_fields)):
def __new__(cls, **kwargs):
default = {f: None for f in _chat_fields}
default.update(kwargs)
#if isinstance(default['attachments'], dict):
# default['attachments'] = Attachment(**default['attachments'])
return super(Chat, cls).... | class Chat(namedtuple('Chat', _chat_fields)):
| def __new__(cls, **kwargs):
default = {f: None for f in _chat_fields}
default.update(kwargs)
#if isinstance(default['attachments'], dict):
# default['attachments'] = Attachment(**default['attachments'])
return super(Chat, cls).__new__(
cls, **default)
| payload'] = Chat(**default['payload'])
if default['message_type'] == TXT:
default['payload'] = default['payload']
return super(Message, cls).__new__(
cls, **default)
_chat_fields = ['text', 'attachments']
class Chat(namedtuple('Chat', _chat_fields)):
| 64 | 64 | 79 | 11 | 53 | romaryd/lifoid | lifoid/message/__init__.py | Python | Chat | Chat | 39 | 46 | 39 | 39 | ca5a31a8dbe99b8055629cf21d0467d1c1bf04f1 | bigcode/the-stack | train |
01630c01b1c7a26115e35615 | train | class | class AutocompleteContext:
"""Represents context for a slash command's option autocomplete.
This class is not created manually and is instead passed to an Option's autocomplete callback.
.. versionadded:: 2.0
Attributes
-----------
bot: :class:`.Bot`
The bot that the command belongs t... | class AutocompleteContext:
| """Represents context for a slash command's option autocomplete.
This class is not created manually and is instead passed to an Option's autocomplete callback.
.. versionadded:: 2.0
Attributes
-----------
bot: :class:`.Bot`
The bot that the command belongs to.
interaction: :class:... | await self.interaction.delete_original_message()
@property
def edit(self) -> Callable[..., Awaitable[InteractionMessage]]:
return self.interaction.edit_original_message
@property
def cog(self) -> Optional[Cog]:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's... | 101 | 101 | 337 | 5 | 95 | badewen/pycord | discord/commands/context.py | Python | AutocompleteContext | AutocompleteContext | 279 | 319 | 279 | 279 | 146afa11080673bb310f3fcca0077c8232cd32b5 | bigcode/the-stack | train |
5664653dfabae25a415768b3 | train | class | class ApplicationContext(discord.abc.Messageable):
"""Represents a Discord application command interaction context.
This class is not created manually and is instead passed to application
commands as the first parameter.
.. versionadded:: 2.0
Attributes
-----------
bot: :class:`.Bot`
... | class ApplicationContext(discord.abc.Messageable):
| """Represents a Discord application command interaction context.
This class is not created manually and is instead passed to application
commands as the first parameter.
.. versionadded:: 2.0
Attributes
-----------
bot: :class:`.Bot`
The bot that the command belongs to.
intera... | DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, List, Optional, TypeVar, Union
import discord.abc
from discord.interactions import InteractionMessage
if TYPE_CHECKING:
from typing_extensions import ParamSpec
import discord
from .. import Bot
f... | 256 | 256 | 1,537 | 10 | 246 | badewen/pycord | discord/commands/context.py | Python | ApplicationContext | ApplicationContext | 67 | 276 | 67 | 67 | 29cca14199b95d468f4e36e2effc36807628955f | bigcode/the-stack | train |
d58f442cdc58db769c6d0b8c | train | function | def create_segmented_line(
pos1, pos2, scene, segment_len,
colour=None, thickness=0.01): # pragma nocover
"""
Create a dashed line from position 1 to position 2.
:param scene: The scene in which to draw the object
:type scene: class:`vpython.canvas`
:param pos1: 3D position of one ... | def create_segmented_line(
pos1, pos2, scene, segment_len,
colour=None, thickness=0.01): # pragma nocover
| """
Create a dashed line from position 1 to position 2.
:param scene: The scene in which to draw the object
:type scene: class:`vpython.canvas`
:param pos1: 3D position of one end of the line.
:type pos1: class:`vpython.vector`
:param pos2: 3D position of the other end of the line.
:typ... | .0:
raise ValueError("RGB values must be normalised between 0 and 1")
if thickness < 0.0:
raise ValueError("Thickness must be greater than 0")
# Length of the line using the magnitude
line_len = mag(pos2 - pos1)
# Position of the line is the midpoint (centre) between the ends
posi... | 243 | 243 | 811 | 34 | 209 | looch-huang/robotics-toolbox-python | roboticstoolbox/backends/VPython/grid.py | Python | create_segmented_line | create_segmented_line | 461 | 544 | 461 | 463 | 2c82a7209dc4a44d32485d8244bfa8a7ccbf7622 | bigcode/the-stack | train |
2d6528f365cd4a17bc474343 | train | class | class GridMMap(MutableMapping): # pragma nocover
def __init__(self, *args, **kwargs):
self.__dict__.update(*args, **kwargs)
def __setitem__(self, key, value):
self.__dict__[key] = value
def __getitem__(self, key):
return self.__dict__[key]
def __delitem__(self, key):
... | class GridMMap(MutableMapping): # pragma nocover
| def __init__(self, *args, **kwargs):
self.__dict__.update(*args, **kwargs)
def __setitem__(self, key, value):
self.__dict__[key] = value
def __getitem__(self, key):
return self.__dict__[key]
def __delitem__(self, key):
del self.__dict__[key]
def __iter__(self):
... | ceil, arange
from roboticstoolbox.backends.VPython.text import update_grid_numbers
from roboticstoolbox.backends.VPython.object2d import Marker2D
from spatialmath import SE2
from collections.abc import MutableMapping
class GridMMap(MutableMapping): # pragma nocover
| 64 | 64 | 124 | 14 | 49 | looch-huang/robotics-toolbox-python | roboticstoolbox/backends/VPython/grid.py | Python | GridMMap | GridMMap | 14 | 31 | 14 | 14 | 627a8d254019eacf891a9886b14ad08ab9227fae | bigcode/the-stack | train |
0fa69acdceca2eea2a5b3a7e | train | class | class GraphicsGrid: # pragma nocover
"""
This class holds the current grid displayed in the canvas
:param scene: The scene in which to add the grid
:type scene: class:`vpython.canvas`
"""
def __init__(self, scene, colour=None):
# Save the scene the grid is placed in
self.__sc... | class GraphicsGrid: # pragma nocover
| """
This class holds the current grid displayed in the canvas
:param scene: The scene in which to add the grid
:type scene: class:`vpython.canvas`
"""
def __init__(self, scene, colour=None):
# Save the scene the grid is placed in
self.__scene = scene
self.__is_3d = Tru... | #!/usr/bin/env python
"""
@author Micah Huth
"""
from vpython import vector, compound, mag, box, curve
from numpy import sign, ceil, arange
from roboticstoolbox.backends.VPython.text import update_grid_numbers
from roboticstoolbox.backends.VPython.object2d import Marker2D
from spatialmath import SE2
from collections.a... | 217 | 256 | 3,480 | 10 | 207 | looch-huang/robotics-toolbox-python | roboticstoolbox/backends/VPython/grid.py | Python | GraphicsGrid | GraphicsGrid | 34 | 402 | 34 | 34 | 6948da0f1c7b7a7239d8b4f6c762cabcc574a81b | bigcode/the-stack | train |
ddb52a1342a7e0a59123b4ca | train | function | def create_line(pos1, pos2, scene,
colour=None, thickness=0.01, opacity=1): # pragma nocover
"""
Create a line from position 1 to position 2.
:param scene: The scene in which to draw the object
:type scene: class:`vpython.canvas`
:param pos1: 3D position of one end of the line.
... | def create_line(pos1, pos2, scene,
colour=None, thickness=0.01, opacity=1): # pragma nocover
| """
Create a line from position 1 to position 2.
:param scene: The scene in which to draw the object
:type scene: class:`vpython.canvas`
:param pos1: 3D position of one end of the line.
:type pos1: class:`vpython.vector`
:param pos2: 3D position of the other end of the line.
:type pos2:... | (Unnecessary)
if not self.grid_object.get('xy_plane').visible:
return
value = max(min(value, 100), 0.1) # Between 0.1 and 100
self.__scale = value
# Turn off grid then delete
self.grid_object.get('xy_plane').clear()
self.grid_object.get('xz_plane').clear()
... | 163 | 163 | 545 | 31 | 132 | looch-huang/robotics-toolbox-python | roboticstoolbox/backends/VPython/grid.py | Python | create_line | create_line | 405 | 458 | 405 | 406 | 222b7c7606a17af2add47f065a0af7a28f5bd72e | bigcode/the-stack | train |
5b3dc89de0af652a0c4c9ca3 | train | function | def create_marker(scene, x, y, shape, colour=None): # pragma nocover
"""
Draw the shape at the given position
:param scene: The scene in which to draw the object
:type scene: class:`vpython.canvas`
:param x: The x location to draw the object at
:type x: `float`
:param y: The y location to ... | def create_marker(scene, x, y, shape, colour=None): # pragma nocover
| """
Draw the shape at the given position
:param scene: The scene in which to draw the object
:type scene: class:`vpython.canvas`
:param x: The x location to draw the object at
:type x: `float`
:param y: The y location to draw the object at
:type y: `float`
:param shape: The shape of... | ,
pos=xyz,
axis=axis_dir,
length=length,
width=thickness,
height=thickness,
color=vector(colour[0], colour[1], colour[2])
)
)
return compound(boxes)
def create_marker(scene, x, y, shape, colour=None)... | 76 | 76 | 255 | 20 | 56 | looch-huang/robotics-toolbox-python | roboticstoolbox/backends/VPython/grid.py | Python | create_marker | create_marker | 547 | 573 | 547 | 547 | a482264baa09f093ee46d7ba0fcf058f22368033 | bigcode/the-stack | train |
c36bbb030f152bf7529255ac | train | function | def vectors_approx_equal(v1, v2): # pragma nocover
"""
Check whether the vectors are approximately equal.
This is used where there is VERY minor floating point differences
that can occur in VPython.
:param v1: Vector 1
:type v1: class:`vpython.vector`
:param v2: Vector 2
:type v2: clas... | def vectors_approx_equal(v1, v2): # pragma nocover
| """
Check whether the vectors are approximately equal.
This is used where there is VERY minor floating point differences
that can occur in VPython.
:param v1: Vector 1
:type v1: class:`vpython.vector`
:param v2: Vector 2
:type v2: class:`vpython.vector`
:returns: True if vectors are... | SE2 for the object
obj_se2 = SE2(x=x, y=y, theta=0)
# Create the object and return it
return Marker2D(obj_se2, scene, shape, colour)
def vectors_approx_equal(v1, v2): # pragma nocover
| 64 | 64 | 161 | 17 | 47 | looch-huang/robotics-toolbox-python | roboticstoolbox/backends/VPython/grid.py | Python | vectors_approx_equal | vectors_approx_equal | 576 | 590 | 576 | 576 | bf0bb7580d071b55ac92ac47ef77dd54def61756 | bigcode/the-stack | train |
541c362db9ce0b7fa55f1b8d | train | class | class MediaPlayerTemplate(TemplateEntity, MediaPlayerEntity):
"""Representation of a Template Media player."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
unique_id,
entity_picture_template,
availabil... | class MediaPlayerTemplate(TemplateEntity, MediaPlayerEntity):
| """Representation of a Template Media player."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
unique_id,
entity_picture_template,
availability_template,
current_source_template,
on_acti... | _template = device_config.get(CURRENT_POSITION_TEMPLATE)
media_duration_template = device_config.get(MEDIA_DURATION_TEMPLATE)
sound_mode_templates = device_config[CONF_SOUND_MODES]
current_sound_mode_template = device_config.get(CURRENT_SOUND_MODE_TEMPLATE)
media_players.append(
... | 256 | 256 | 4,020 | 12 | 243 | chbartsch/media_player.template | custom_components/media_player_template/media_player.py | Python | MediaPlayerTemplate | MediaPlayerTemplate | 243 | 807 | 243 | 243 | 8c9099976d369fc19e5a176ae9daa9087016564e | bigcode/the-stack | train |
7f93a821c53a9f4ce26818b0 | train | function | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template binary sensors."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
| async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
| """Set up the template binary sensors."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
| }
)
SUPPORT_TEMPLATE = SUPPORT_TURN_OFF | SUPPORT_TURN_ON
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_MEDIAPLAYER): cv.schema_with_slug_keys(MEDIA_PLAYER_SCHEMA)}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
| 64 | 64 | 57 | 18 | 46 | chbartsch/media_player.template | custom_components/media_player_template/media_player.py | Python | async_setup_platform | async_setup_platform | 149 | 153 | 149 | 149 | b3b8b7cb399950f7e00a60b8ecfebf8cd8e11f62 | bigcode/the-stack | train |
1db82ca0a600d237fc2a0c68 | train | function | async def _async_create_entities(hass, config):
"""Set up the Template switch."""
media_players = []
for device, device_config in config[CONF_MEDIAPLAYER].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config[CONF_VALUE_TEMPLATE]
icon_... | async def _async_create_entities(hass, config):
| """Set up the Template switch."""
media_players = []
for device, device_config in config[CONF_MEDIAPLAYER].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config[CONF_VALUE_TEMPLATE]
icon_template = device_config.get(CONF_ICON_TEMPLATE)... | vol.Optional(MEDIA_SERIES_TITLE_TEMPLATE): cv.template,
vol.Optional(MEDIA_ALBUM_ARTIST_TEMPLATE): cv.template,
vol.Optional(SEEK_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(CURRENT_POSITION_TEMPLATE): cv.template,
vol.Optional(MEDIA_DURATION_TEMPLATE): cv.template,
vol.Optio... | 209 | 209 | 697 | 11 | 198 | chbartsch/media_player.template | custom_components/media_player_template/media_player.py | Python | _async_create_entities | _async_create_entities | 156 | 240 | 156 | 156 | 7c36621920f6434cef862e9abbfe14fadc0e1c66 | bigcode/the-stack | train |
ea0c22c3168223988ad16aa7 | train | function | def EncodeArray(obj_list, item_desc, enc, out):
"""
Args:
obj_list: List of Obj values
Returns:
ref
"""
array_chunk = bytearray()
enc.Int(len(obj_list), array_chunk) # Length prefix
if isinstance(item_desc, asdl.IntType) or \
isinstance(item_desc, asdl.BoolType):
for item in obj_list:... | def EncodeArray(obj_list, item_desc, enc, out):
| """
Args:
obj_list: List of Obj values
Returns:
ref
"""
array_chunk = bytearray()
enc.Int(len(obj_list), array_chunk) # Length prefix
if isinstance(item_desc, asdl.IntType) or \
isinstance(item_desc, asdl.BoolType):
for item in obj_list:
enc.Int(item, array_chunk)
elif isinst... | def Bytes(self, buf, chunk):
n = len(buf)
if n >= self.max_index:
raise EncodeError("bytes object is too long (%d)" % n)
for i in xrange(self.index_width):
chunk.append(n & 0xFF)
n >>= 8
chunk.extend(buf)
def PaddedBytes(self, buf):
chunk = bytearray()
self.Bytes(buf, chunk... | 126 | 126 | 420 | 13 | 113 | gnprice/oil | asdl/encode.py | Python | EncodeArray | EncodeArray | 144 | 197 | 144 | 144 | 78b88e5d36c48ae96f286537309a387c2598bc77 | bigcode/the-stack | train |
99d3b8fe933caa2320b7ef34 | train | function | def EncodeObj(obj, enc, out):
"""
Args:
obj: Obj to encode
enc: encoding params
out: output file
Returns:
ref: Reference to the last block
"""
# Algorithm: Depth first, post-order traversal. First obj is the first leaf.
# last obj is the root.
#
# Array is a homogeneous type.
this_c... | def EncodeObj(obj, enc, out):
| """
Args:
obj: Obj to encode
enc: encoding params
out: output file
Returns:
ref: Reference to the last block
"""
# Algorithm: Depth first, post-order traversal. First obj is the first leaf.
# last obj is the root.
#
# Array is a homogeneous type.
this_chunk = bytearray()
assert is... | _desc, asdl.SumType) or \
isinstance(item_desc, asdl.CompoundType), item_desc
# This is like vector<T*>
# Later:
# - Product types can be put in line
# - Sum types can even be put in line, if you have List<T> rather than
# Array<T>. Array implies O(1) random access; List doesn't.
for i... | 187 | 187 | 624 | 9 | 177 | gnprice/oil | asdl/encode.py | Python | EncodeObj | EncodeObj | 200 | 280 | 200 | 200 | 48caccbbc30791bdd0823e26c70035ee683113bc | bigcode/the-stack | train |
62b4ba71b5bdc60484f6e956 | train | class | class Params(object):
"""Encoding parameters.
Hm most of these settings should be per-field, expressed in the schema. The
only global one is the ref/pointer alignment. 4 and 8 are the most likely
choices, and 4 is probably fine, because you have 64 MB of addressable memory
with 24 bit pointers.
"""
de... | class Params(object):
| """Encoding parameters.
Hm most of these settings should be per-field, expressed in the schema. The
only global one is the ref/pointer alignment. 4 and 8 are the most likely
choices, and 4 is probably fine, because you have 64 MB of addressable memory
with 24 bit pointers.
"""
def __init__(self, align... | .__init__(self, *args, **kwargs)
self.details_printed = False
_DEFAULT_ALIGNMENT = 4
class BinOutput(object):
"""Write aligned blocks here. Keeps track of block indexes for refs."""
def __init__(self, f, alignment=_DEFAULT_ALIGNMENT):
self.f = f
# index of last block, to return as a ref.
self.l... | 244 | 244 | 814 | 4 | 239 | gnprice/oil | asdl/encode.py | Python | Params | Params | 52 | 141 | 52 | 52 | 7ab055fe1ae13bc7f807ea4ee5d21c4f8ea7ebec | bigcode/the-stack | train |
0c106a557d0978ef7352982c | train | function | def EncodeRoot(obj, enc, out):
ref = out.Write(b'OHP\x01') # header, version 1
assert ref == 0
# 4-byte alignment, then 3 byte placeholder for the root ref.
ref = out.Write(b'\4\0\0\0')
assert ref == 1
root_ref = EncodeObj(obj, enc, out)
chunk = bytearray()
enc.Ref(root_ref, chunk)
out.WriteRootRef(... | def EncodeRoot(obj, enc, out):
| ref = out.Write(b'OHP\x01') # header, version 1
assert ref == 0
# 4-byte alignment, then 3 byte placeholder for the root ref.
ref = out.Write(b'\4\0\0\0')
assert ref == 1
root_ref = EncodeObj(obj, enc, out)
chunk = bytearray()
enc.Ref(root_ref, chunk)
out.WriteRootRef(chunk) # back up and write it
| val %s)", name, e, field_val)
e.details_printed = True
raise
enc.Ref(ref, this_chunk)
# Write the parent record
this_ref = out.Write(enc.PaddedBlock(this_chunk))
return this_ref
def EncodeRoot(obj, enc, out):
| 64 | 64 | 115 | 9 | 54 | gnprice/oil | asdl/encode.py | Python | EncodeRoot | EncodeRoot | 283 | 293 | 283 | 283 | dd201a7b810fbbe7d61018b198cd4941278bed80 | bigcode/the-stack | train |
0f9b58a5515a77a1670f7f58 | train | class | class EncodeError(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.details_printed = False
| class EncodeError(Exception):
| def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.details_printed = False
| """
encode.py
"""
from asdl import asdl_ as asdl
from asdl import py_meta
from asdl import const
from core import util
class EncodeError(Exception):
| 39 | 64 | 39 | 5 | 33 | gnprice/oil | asdl/encode.py | Python | EncodeError | EncodeError | 12 | 15 | 12 | 12 | a4f1385ba9c4e6c7961319b58f047ea8165f9375 | bigcode/the-stack | train |
d18699398f30bb4e1e91cff2 | train | class | class BinOutput(object):
"""Write aligned blocks here. Keeps track of block indexes for refs."""
def __init__(self, f, alignment=_DEFAULT_ALIGNMENT):
self.f = f
# index of last block, to return as a ref.
self.last_block = 0
self.alignment = alignment
def WriteRootRef(self, chunk):
self.f.se... | class BinOutput(object):
| """Write aligned blocks here. Keeps track of block indexes for refs."""
def __init__(self, f, alignment=_DEFAULT_ALIGNMENT):
self.f = f
# index of last block, to return as a ref.
self.last_block = 0
self.alignment = alignment
def WriteRootRef(self, chunk):
self.f.seek(5) # seek past 'OHP\x... | py_meta
from asdl import const
from core import util
class EncodeError(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.details_printed = False
_DEFAULT_ALIGNMENT = 4
class BinOutput(object):
| 64 | 64 | 215 | 5 | 58 | gnprice/oil | asdl/encode.py | Python | BinOutput | BinOutput | 20 | 49 | 20 | 20 | ab8b9699274854de6b67244755e1aeac6190a10d | bigcode/the-stack | train |
d096d6c221be9297236b1899 | train | function | def file_enum_to_policy(enum: "pb.FilesItem.PolicyType.V") -> str:
if enum == pb.FilesItem.PolicyType.NOW:
policy = "now"
elif enum == pb.FilesItem.PolicyType.END:
policy = "end"
elif enum == pb.FilesItem.PolicyType.LIVE:
policy = "live"
return policy
| def file_enum_to_policy(enum: "pb.FilesItem.PolicyType.V") -> str:
| if enum == pb.FilesItem.PolicyType.NOW:
policy = "now"
elif enum == pb.FilesItem.PolicyType.END:
policy = "end"
elif enum == pb.FilesItem.PolicyType.LIVE:
policy = "live"
return policy
| .FilesItem.PolicyType.NOW
elif policy == "end":
enum = pb.FilesItem.PolicyType.END
elif policy == "live":
enum = pb.FilesItem.PolicyType.LIVE
return enum
def file_enum_to_policy(enum: "pb.FilesItem.PolicyType.V") -> str:
| 64 | 64 | 75 | 18 | 45 | joe733/client | wandb/sdk/interface/interface.py | Python | file_enum_to_policy | file_enum_to_policy | 55 | 62 | 55 | 55 | 175e83c258bb6ad6aa948ad06728fb412dd4a986 | bigcode/the-stack | train |
ec043830185488fd9738ab7c | train | class | class InterfaceBase(object):
_run: Optional["Run"]
_drop: bool
def __init__(self) -> None:
self._run = None
self._drop = False
def _hack_set_run(self, run: "Run") -> None:
self._run = run
current_pid = os.getpid()
self._run._set_iface_pid(current_pid)
def p... | class InterfaceBase(object):
| _run: Optional["Run"]
_drop: bool
def __init__(self) -> None:
self._run = None
self._drop = False
def _hack_set_run(self, run: "Run") -> None:
self._run = run
current_pid = os.getpid()
self._run._set_iface_pid(current_pid)
def publish_header(self) -> None:
... | _h5_typename,
json_dumps_safer,
json_dumps_safer_history,
json_friendly,
json_friendly_val,
maybe_compress_summary,
WandBJSONEncoderOld,
)
from . import summary_record as sr
from .artifacts import ArtifactManifest
from .message_future import MessageFuture
from ..wandb_artifacts import Artifact
... | 256 | 256 | 4,179 | 5 | 250 | joe733/client | wandb/sdk/interface/interface.py | Python | InterfaceBase | InterfaceBase | 65 | 603 | 65 | 65 | 8d5af3ed146b2c6337ba88b49a668572bde80ea8 | bigcode/the-stack | train |
8eeca5a0487de2da2a978018 | train | function | def file_policy_to_enum(policy: str) -> "pb.FilesItem.PolicyType.V":
if policy == "now":
enum = pb.FilesItem.PolicyType.NOW
elif policy == "end":
enum = pb.FilesItem.PolicyType.END
elif policy == "live":
enum = pb.FilesItem.PolicyType.LIVE
return enum
| def file_policy_to_enum(policy: str) -> "pb.FilesItem.PolicyType.V":
| if policy == "now":
enum = pb.FilesItem.PolicyType.NOW
elif policy == "end":
enum = pb.FilesItem.PolicyType.END
elif policy == "live":
enum = pb.FilesItem.PolicyType.LIVE
return enum
| artifacts import ArtifactManifest
from .message_future import MessageFuture
from ..wandb_artifacts import Artifact
if TYPE_CHECKING:
from ..wandb_run import Run
logger = logging.getLogger("wandb")
def file_policy_to_enum(policy: str) -> "pb.FilesItem.PolicyType.V":
| 64 | 64 | 75 | 18 | 46 | joe733/client | wandb/sdk/interface/interface.py | Python | file_policy_to_enum | file_policy_to_enum | 45 | 52 | 45 | 45 | 99b33317265cc58fae2529a4cc7aeb1c0d3b3376 | bigcode/the-stack | train |
d9280c4ffcfb3176e4b2b00f | train | class | class ResourceFieldSelector(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_m... | class ResourceFieldSelector(object):
| """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
... | # coding: utf-8
"""
Seldon Deploy API
API to interact and manage the lifecycle of your machine learning models deployed through Seldon Deploy. # noqa: E501
OpenAPI spec version: v1alpha1
Contact: hello@seldon.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint... | 99 | 256 | 1,006 | 6 | 92 | adriangonz/seldon-deploy-sdk | python/seldon_deploy_sdk/models/resource_field_selector.py | Python | ResourceFieldSelector | ResourceFieldSelector | 20 | 171 | 20 | 20 | 542626257544001ff4d32124f5576f16db9fa5de | bigcode/the-stack | train |
1c875d4476b03dd392493174 | train | function | def table_print(table):
print(table[0], "\n",
table[1], "\n",
table[2], "\n",
table[3]
)
| def table_print(table):
| print(table[0], "\n",
table[1], "\n",
table[2], "\n",
table[3]
)
| 1.1, 0.5, 0.5, 0,0,0],
[0.012, 0.05, 0.9, constants.manapercent[3], constants.manapercent[4], constants.manapercent[5]]
]
def table_print(table):
| 64 | 64 | 37 | 5 | 59 | asvae/TableflipperExtreme | random-value-generator/random_values_calculator_2.py | Python | table_print | table_print | 46 | 51 | 46 | 46 | 0a68d77f147dee3017c4e19b21704f05ff48cb86 | bigcode/the-stack | train |
34a5130046972515b8c5a596 | train | function | def swag_table_print(table):
new_table = []
for tb in table:
tb1 = []
for elem in tb:
tb1.append(round(elem,3))
new_table.append(tb1)
print(tb1)
| def swag_table_print(table):
| new_table = []
for tb in table:
tb1 = []
for elem in tb:
tb1.append(round(elem,3))
new_table.append(tb1)
print(tb1)
| .manapercent[3], constants.manapercent[4], constants.manapercent[5]]
]
def table_print(table):
print(table[0], "\n",
table[1], "\n",
table[2], "\n",
table[3]
)
def swag_table_print(table):
| 64 | 64 | 49 | 6 | 58 | asvae/TableflipperExtreme | random-value-generator/random_values_calculator_2.py | Python | swag_table_print | swag_table_print | 53 | 60 | 53 | 53 | b5f41e3c6b9ae973618b3da4cb05f76eb3f5a925 | bigcode/the-stack | train |
ead4cd585294b0d49d7b4726 | train | class | class Solution():
def __init__(self, table):
self.table = [
table[0][:],
table[1][:],
table[2][:],
table[3][:]
]
self.score = 9999999999999.0
def _sumcolumn(self, table, column):
return table[0][column] + table[1][column] + table[2... | class Solution():
| def __init__(self, table):
self.table = [
table[0][:],
table[1][:],
table[2][:],
table[3][:]
]
self.score = 9999999999999.0
def _sumcolumn(self, table, column):
return table[0][column] + table[1][column] + table[2][column] + table[... | ,3))
new_table.append(tb1)
print(tb1)
def swag_table_print_pull_chance_related(table):
new_table = []
for i, tb in enumerate(table):
tb1 = []
for elem in tb:
if i==0:
elem /= constants.a0
if i==1:
elem /= constants.a1
... | 140 | 140 | 467 | 3 | 137 | asvae/TableflipperExtreme | random-value-generator/random_values_calculator_2.py | Python | Solution | Solution | 82 | 127 | 82 | 82 | 4f00264602d6828a75601e9b9f8dd45191aee3d8 | bigcode/the-stack | train |
839ca3c2429c9f26ee0aff3f | train | class | class Constants():
def __init__(self):
# self.a0 = 0.2
# self.a1 = 0.5
# self.a2 = 0.15
# self.a3 = 0.15
self.a0 = 0.05
self.a1 = 0.65
self.a2 = 0.25
self.a3 = 0.05
mana0 = 3389.0
mana1 = 15998.0
mana2 = 1891.0
mana3 = 3... | class Constants():
| def __init__(self):
# self.a0 = 0.2
# self.a1 = 0.5
# self.a2 = 0.15
# self.a3 = 0.15
self.a0 = 0.05
self.a1 = 0.65
self.a2 = 0.25
self.a3 = 0.05
mana0 = 3389.0
mana1 = 15998.0
mana2 = 1891.0
mana3 = 313.0
mana4 ... | import math
import random
class Constants():
| 9 | 81 | 270 | 3 | 5 | asvae/TableflipperExtreme | random-value-generator/random_values_calculator_2.py | Python | Constants | Constants | 5 | 34 | 5 | 5 | 7bdb644387d86c6220a541fb32f740e4fe3ba460 | bigcode/the-stack | train |
80b41f5da335faf4bac22e0b | train | function | def swag_table_print_pull_chance_related(table):
new_table = []
for i, tb in enumerate(table):
tb1 = []
for elem in tb:
if i==0:
elem /= constants.a0
if i==1:
elem /= constants.a1
if i==2:
elem /= constants.a2
... | def swag_table_print_pull_chance_related(table):
| new_table = []
for i, tb in enumerate(table):
tb1 = []
for elem in tb:
if i==0:
elem /= constants.a0
if i==1:
elem /= constants.a1
if i==2:
elem /= constants.a2
if i==3:
elem /= consta... | [3]
)
def swag_table_print(table):
new_table = []
for tb in table:
tb1 = []
for elem in tb:
tb1.append(round(elem,3))
new_table.append(tb1)
print(tb1)
def swag_table_print_pull_chance_related(table):
| 64 | 64 | 122 | 10 | 54 | asvae/TableflipperExtreme | random-value-generator/random_values_calculator_2.py | Python | swag_table_print_pull_chance_related | swag_table_print_pull_chance_related | 62 | 79 | 62 | 62 | 8453e00610d836c96d0954ac5ca0b5f5edc6335f | bigcode/the-stack | train |
cdc66f31cb146279a4fc6b61 | train | function | def decode_from_file(args: argparse.Namespace) -> int:
"""Decode messages from a file-like object."""
if not args.in_file:
# This is needed, because it is not possible to open STDOUT in binary mode (it is text mode by default)
# Therefore it is None by default and we interact with the buffer... | def decode_from_file(args: argparse.Namespace) -> int:
| """Decode messages from a file-like object."""
if not args.in_file:
# This is needed, because it is not possible to open STDOUT in binary mode (it is text mode by default)
# Therefore it is None by default and we interact with the buffer directly
file = sys.stdin.buffer
else:
... | for msg in messages if isinstance(msg, str)]
for msg in ByteStream(messages_as_bytes):
print(msg.decode(), file=args.out_file)
if not msg.is_valid:
print_error("WARNING: Checksum invalid")
return 0
def decode_from_file(args: argparse.Namespace) -> int:
| 64 | 64 | 178 | 12 | 51 | cglewis/pyais | pyais/main.py | Python | decode_from_file | decode_from_file | 121 | 139 | 121 | 121 | 7ab1a5d5ac86e5111136eacb11ffb20be61af889 | bigcode/the-stack | train |
0ecea9fe47b617679d42eb96 | train | function | def main() -> int:
main_parser = arg_parser()
namespace: argparse.Namespace = main_parser.parse_args()
exit_code: int = namespace.func(namespace)
return exit_code
| def main() -> int:
| main_parser = arg_parser()
namespace: argparse.Namespace = main_parser.parse_args()
exit_code: int = namespace.func(namespace)
return exit_code
| for msg in s:
decoded_message = msg.decode(silent=True)
print(decoded_message, file=args.out_file)
except KeyboardInterrupt:
# Catch KeyboardInterrupts in order to close the file descriptor and free associated resources
return 0
return 0
def mai... | 64 | 64 | 39 | 6 | 57 | cglewis/pyais | pyais/main.py | Python | main | main | 142 | 146 | 142 | 142 | 8ee39f37b18c36e2454ebe6800a4fafe7d82df1c | bigcode/the-stack | train |
2a6bdf8e35d3be3bda0c515e | train | function | def decode_single(args: argparse.Namespace) -> int:
"""Decode a list of messages."""
messages: List[str] = args.messages
messages_as_bytes: List[bytes] = [msg.encode() for msg in messages if isinstance(msg, str)]
for msg in ByteStream(messages_as_bytes):
print(msg.decode(), file=args.out_fi... | def decode_single(args: argparse.Namespace) -> int:
| """Decode a list of messages."""
messages: List[str] = args.messages
messages_as_bytes: List[bytes] = [msg.encode() for msg in messages if isinstance(msg, str)]
for msg in ByteStream(messages_as_bytes):
print(msg.decode(), file=args.out_file)
if not msg.is_valid:
print_... | :
decoded_message = msg.decode(silent=True)
print(decoded_message, file=args.out_file)
except KeyboardInterrupt:
# Catch KeyboardInterrupts in order to close the socket and free associated resources
return 0
return 0
def decode_single(args: argpa... | 64 | 64 | 96 | 11 | 52 | cglewis/pyais | pyais/main.py | Python | decode_single | decode_single | 110 | 118 | 110 | 110 | 864eab2c943ded26f3e60b9c9d4b13a146a33c98 | bigcode/the-stack | train |
168684be2d8052e7802a0c06 | train | function | def arg_parser() -> argparse.ArgumentParser:
"""Create a new ArgumentParser instance that serves as a entry point to the pyais application.
All possible commandline options and parameters must be defined here.
The goal is to create a grep-like interface:
Usage: ais-decode [OPTION]... PATTERNS [F... | def arg_parser() -> argparse.ArgumentParser:
| """Create a new ArgumentParser instance that serves as a entry point to the pyais application.
All possible commandline options and parameters must be defined here.
The goal is to create a grep-like interface:
Usage: ais-decode [OPTION]... PATTERNS [FILE]...
"""
main_parser: argparse.Ar... | import argparse
import sys
from typing import List, Tuple, Type, Any, Union
from pyais.stream import ByteStream, TCPStream, UDPStream, BinaryIOStream
SOCKET_OPTIONS: Tuple[str, str] = ('udp', 'tcp')
# Error Codes
INVALID_CHECKSUM_ERROR = 21
def arg_parser() -> argparse.ArgumentParser:
| 74 | 141 | 471 | 9 | 64 | cglewis/pyais | pyais/main.py | Python | arg_parser | arg_parser | 13 | 80 | 13 | 13 | 8119a456f2972c003f15c3327570ca660ec88bab | bigcode/the-stack | train |
045807b0f6ead22c981d674e | train | function | def decode_from_socket(args: argparse.Namespace) -> int:
"""Connect a socket and start decoding."""
t: str = args.type
stream_cls: Type[Union[UDPStream, TCPStream]]
if t == "udp":
stream_cls = UDPStream
elif t == "tcp":
stream_cls = TCPStream
else:
raise ValueErr... | def decode_from_socket(args: argparse.Namespace) -> int:
| """Connect a socket and start decoding."""
t: str = args.type
stream_cls: Type[Union[UDPStream, TCPStream]]
if t == "udp":
stream_cls = UDPStream
elif t == "tcp":
stream_cls = TCPStream
else:
raise ValueError("args.type must be either TCP or UDP.")
with str... | =sys.stdout
)
return main_parser
def print_error(*args: Any, **kwargs: Any) -> None:
"""Wrapper around the default print function that writes to STDERR."""
print(*args, **kwargs, file=sys.stdout)
def decode_from_socket(args: argparse.Namespace) -> int:
| 64 | 64 | 164 | 12 | 52 | cglewis/pyais | pyais/main.py | Python | decode_from_socket | decode_from_socket | 88 | 107 | 88 | 88 | 038237b0f0d9a205af4728c6e38f2fc79025d709 | bigcode/the-stack | train |
876e94ac361cca9b3699f441 | train | function | def print_error(*args: Any, **kwargs: Any) -> None:
"""Wrapper around the default print function that writes to STDERR."""
print(*args, **kwargs, file=sys.stdout)
| def print_error(*args: Any, **kwargs: Any) -> None:
| """Wrapper around the default print function that writes to STDERR."""
print(*args, **kwargs, file=sys.stdout)
| can be any file
main_parser.add_argument(
"-o",
"--out-file",
dest="out_file",
type=argparse.FileType("w"),
default=sys.stdout
)
return main_parser
def print_error(*args: Any, **kwargs: Any) -> None:
| 64 | 64 | 42 | 16 | 47 | cglewis/pyais | pyais/main.py | Python | print_error | print_error | 83 | 85 | 83 | 83 | 02258992153ec32db27463adbe781b3dd45f9947 | bigcode/the-stack | train |
48aed79d56e464dcf024772d | train | function | def scale_dataframe(dataframe: pd.DataFrame,
scaling_method: str,):
"""new_df = dataframe_scaling(old_df, 'std')
Scaling features in dataframe according to specific scaling strategy.
TODO: More scaling options and selective feature(col) scaling for dataframe.
Args:
datafram... | def scale_dataframe(dataframe: pd.DataFrame,
scaling_method: str,):
| """new_df = dataframe_scaling(old_df, 'std')
Scaling features in dataframe according to specific scaling strategy.
TODO: More scaling options and selective feature(col) scaling for dataframe.
Args:
dataframe (pandas.Dataframe): dataframe to be scaled.
scaling_method (str): 'std', 'minm... | .6
File Description:
"""
import logging
import pandas as pd
from sklearn.preprocessing import StandardScaler, MinMaxScaler
logger = logging.getLogger(__name__)
SCALING_METHODS = ['none', 'std', 'minmax']
def scale_dataframe(dataframe: pd.DataFrame,
scaling_method: str,):
| 68 | 68 | 228 | 17 | 51 | CBIIT/NCI-DOE-Collab-Pilot1-Unified-Drug-Response-Predictor-Multi-tasking | Pilot1/UnoMT/utils/data_processing/dataframe_scaling.py | Python | scale_dataframe | scale_dataframe | 20 | 52 | 20 | 21 | 893fc8c122a00d1811c14d9d7c723b801d94145f | bigcode/the-stack | train |
0d6fe6ea9b1862f8a9dcb7fa | train | class | class RunTests:
__CONNECTION = None
__ENDPOINT = None
def __init__(self, conn):
self.__CONNECTION = conn
self.__ENDPOINT = self.__CONNECTION.CONNECTION_DETAILS["instance_url"] + '/services/data/v' + \
str(self.__CONNECTION.VERSION) + '/tooling/runTestsAsynchronous'... | class RunTests:
| __CONNECTION = None
__ENDPOINT = None
def __init__(self, conn):
self.__CONNECTION = conn
self.__ENDPOINT = self.__CONNECTION.CONNECTION_DETAILS["instance_url"] + '/services/data/v' + \
str(self.__CONNECTION.VERSION) + '/tooling/runTestsAsynchronous'
"""
#F... | from json import dumps
"""
# Class: runTestsAsynchronous
# Purpose: Implements the runTests Interface
"""
#TODO: convert the print statements to ValueErrors and add contents as messages
class RunTests:
| 45 | 168 | 562 | 4 | 40 | FernandoPicazo/sfdc_api | sfdc_api/tooling/runtests.py | Python | RunTests | RunTests | 9 | 50 | 9 | 9 | 439fba0941b578772574292d986535316f8455b4 | bigcode/the-stack | train |
a0fd492e3fda45f5c0cd53fc | train | class | class Migration(migrations.Migration):
dependencies = [
('orders', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='order',
old_name='oder_id',
new_name='order_id',
),
]
| class Migration(migrations.Migration):
| dependencies = [
('orders', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='order',
old_name='oder_id',
new_name='order_id',
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-11-04 10:19
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
| 50 | 64 | 56 | 7 | 42 | FrezeSteve/Python | Web_Development/Django_Ecommerce_Site/orders/migrations/0002_auto_20181104_1319.py | Python | Migration | Migration | 8 | 20 | 8 | 9 | 629752191585f33bafa10d51ca7c769a5826a6a5 | bigcode/the-stack | train |
7f6bba97735c4c23ce7298cf | train | function | @pytest.fixture
def tutk_platform_lib():
return MockTutkLibrary()
| @pytest.fixture
def tutk_platform_lib():
| return MockTutkLibrary()
| import pytest
import wyzecam.iotc
from wyzecam.mock.mock_tutk_library import MockTutkLibrary # type: ignore
@pytest.fixture
def tutk_platform_lib():
| 39 | 64 | 15 | 8 | 30 | kingrollsdice/wyzecam | tests/test_wyzecam_iotc.py | Python | tutk_platform_lib | tutk_platform_lib | 6 | 8 | 6 | 7 | a7c10ec78b99396428cb725b68aec3990eadcd03 | bigcode/the-stack | train |
fb617a68d626ead5f0d2c4b6 | train | function | @pytest.fixture
def iotc(tutk_platform_lib):
return wyzecam.iotc.WyzeIOTC(tutk_platform_lib)
| @pytest.fixture
def iotc(tutk_platform_lib):
| return wyzecam.iotc.WyzeIOTC(tutk_platform_lib)
| import pytest
import wyzecam.iotc
from wyzecam.mock.mock_tutk_library import MockTutkLibrary # type: ignore
@pytest.fixture
def tutk_platform_lib():
return MockTutkLibrary()
@pytest.fixture
def iotc(tutk_platform_lib):
| 59 | 64 | 32 | 13 | 46 | kingrollsdice/wyzecam | tests/test_wyzecam_iotc.py | Python | iotc | iotc | 11 | 13 | 11 | 12 | 6ac0cfded7772ef255aadba343d1205a75552283 | bigcode/the-stack | train |
a34487c22e0946308473e577 | train | function | def test_get_version(iotc: wyzecam.iotc.WyzeIOTC) -> None:
with iotc:
assert iotc.version == 0xDEADBEEF
| def test_get_version(iotc: wyzecam.iotc.WyzeIOTC) -> None:
| with iotc:
assert iotc.version == 0xDEADBEEF
| _lib():
return MockTutkLibrary()
@pytest.fixture
def iotc(tutk_platform_lib):
return wyzecam.iotc.WyzeIOTC(tutk_platform_lib)
def test_get_version(iotc: wyzecam.iotc.WyzeIOTC) -> None:
| 64 | 64 | 43 | 23 | 41 | kingrollsdice/wyzecam | tests/test_wyzecam_iotc.py | Python | test_get_version | test_get_version | 16 | 18 | 16 | 16 | 25e6f9b8491fb7f4448832ceba13e417c5e969f2 | bigcode/the-stack | train |
5a14cfe17bb7a1549b6066c6 | train | class | class P2SH:
def pubkeys_to_redeem_script(self, pubkeys):
raise NotImplementedError()
def pubkeys_to_address(self, pubkey):
redeem_script = self.pubkeys_to_redeem_script(pubkey)
return bitcoin.hash160_to_p2sh(hash_160(redeem_script.decode('hex')))
| class P2SH:
| def pubkeys_to_redeem_script(self, pubkeys):
raise NotImplementedError()
def pubkeys_to_address(self, pubkey):
redeem_script = self.pubkeys_to_redeem_script(pubkey)
return bitcoin.hash160_to_p2sh(hash_160(redeem_script.decode('hex')))
| ):
pubkey = self.keystore.import_key(pk, pw)
self.save_keystore()
addr = self.pubkeys_to_address(pubkey)
self.receiving_addresses.append(addr)
self.save_addresses()
self.storage.write()
self.add_address(addr)
return addr
class P2SH:
| 64 | 64 | 71 | 5 | 58 | Bryangoodson/electrum-vtc-tor | lib/wallet.py | Python | P2SH | P2SH | 1,651 | 1,658 | 1,651 | 1,652 | 5e8516c5b2a91b6de1e21e82a481d24e4b3d607b | bigcode/the-stack | train |
34c0c9b4771384baa3807ff6 | train | function | def register_constructor(wallet_type, constructor):
wallet_constructors[wallet_type] = constructor
| def register_constructor(wallet_type, constructor):
| wallet_constructors[wallet_type] = constructor
| 'imported']
def register_wallet_type(category):
wallet_types.append(category)
wallet_constructors = {
'standard': Standard_Wallet,
'old': Standard_Wallet,
'xpub': Standard_Wallet,
'imported': Imported_Wallet
}
def register_constructor(wallet_type, constructor):
| 64 | 64 | 19 | 8 | 56 | Bryangoodson/electrum-vtc-tor | lib/wallet.py | Python | register_constructor | register_constructor | 1,776 | 1,777 | 1,776 | 1,776 | 2ec1278f794c8b0d2b6507f5327923c97ca29262 | bigcode/the-stack | train |
42692876b0aba85f0cbffc1b | train | class | class Imported_Wallet(Abstract_Wallet):
# wallet made of imported addresses
wallet_type = 'imported'
txin_type = 'address'
def __init__(self, storage):
Abstract_Wallet.__init__(self, storage)
def load_keystore(self):
pass
def load_addresses(self):
self.addresses = sel... | class Imported_Wallet(Abstract_Wallet):
# wallet made of imported addresses
| wallet_type = 'imported'
txin_type = 'address'
def __init__(self, storage):
Abstract_Wallet.__init__(self, storage)
def load_keystore(self):
pass
def load_addresses(self):
self.addresses = self.storage.get('addresses', [])
self.receiving_addresses = self.addresses
... | _payment_request(x, config), self.receive_requests.keys()), key=f)
def get_fingerprint(self):
raise NotImplementedError()
def can_import_privkey(self):
return False
def can_import_address(self):
return False
def can_delete_address(self):
return False
def add_addr... | 133 | 133 | 445 | 16 | 117 | Bryangoodson/electrum-vtc-tor | lib/wallet.py | Python | Imported_Wallet | Imported_Wallet | 1,346 | 1,428 | 1,346 | 1,348 | a09656faa32c24f0d8fab5e0ca6e9446ea74db64 | bigcode/the-stack | train |
13cc5fa1082445d666befa68 | train | class | class Simple_Deterministic_Wallet(Deterministic_Wallet, Simple_Wallet):
def __init__(self, storage):
Deterministic_Wallet.__init__(self, storage)
def get_master_public_key(self):
return self.keystore.get_master_public_key()
def derive_pubkeys(self, c, i):
return self.keystore.deri... | class Simple_Deterministic_Wallet(Deterministic_Wallet, Simple_Wallet):
| def __init__(self, storage):
Deterministic_Wallet.__init__(self, storage)
def get_master_public_key(self):
return self.keystore.get_master_public_key()
def derive_pubkeys(self, c, i):
return self.keystore.derive_pubkey(c, i)
def get_keystore(self):
return self.keystore... | in['signatures'] = [None]
txin['num_sig'] = 1
def sign_message(self, address, message, password):
index = self.get_address_index(address)
return self.keystore.sign_message(index, message, password)
def decrypt_message(self, pubkey, message, password):
addr = self.pubkeys_to_add... | 118 | 118 | 396 | 18 | 100 | Bryangoodson/electrum-vtc-tor | lib/wallet.py | Python | Simple_Deterministic_Wallet | Simple_Deterministic_Wallet | 1,589 | 1,648 | 1,589 | 1,590 | 7088d82d6d1e07dee63f99e9f3a4feb6f8b65705 | bigcode/the-stack | train |
720f7ddb3c47183c2d534746 | train | class | class Multisig_Wallet(Deterministic_Wallet, P2SH):
# generic m of n
gap_limit = 20
txin_type = 'p2sh'
def __init__(self, storage):
self.wallet_type = storage.get('wallet_type')
self.m, self.n = multisig_type(self.wallet_type)
Deterministic_Wallet.__init__(self, storage)
def... | class Multisig_Wallet(Deterministic_Wallet, P2SH):
# generic m of n
| gap_limit = 20
txin_type = 'p2sh'
def __init__(self, storage):
self.wallet_type = storage.get('wallet_type')
self.m, self.n = multisig_type(self.wallet_type)
Deterministic_Wallet.__init__(self, storage)
def get_pubkeys(self, c, i):
return self.derive_pubkeys(c, i)
... | raise NotImplementedError()
def pubkeys_to_address(self, pubkey):
redeem_script = self.pubkeys_to_redeem_script(pubkey)
return bitcoin.hash160_to_p2sh(hash_160(redeem_script.decode('hex')))
class Standard_Wallet(Simple_Deterministic_Wallet):
wallet_type = 'standard'
def pubkeys_t... | 213 | 214 | 714 | 24 | 189 | Bryangoodson/electrum-vtc-tor | lib/wallet.py | Python | Multisig_Wallet | Multisig_Wallet | 1,681 | 1,761 | 1,681 | 1,682 | ef97ec8c6a556f6185b3ca5a3658496f2717044e | bigcode/the-stack | train |
9e74e4b91e4e67e40b477677 | train | class | class Abstract_Wallet(PrintError):
"""
Wallet classes are created to handle various address generation methods.
Completion states (watching-only, single account, no seed, etc) are handled inside classes.
"""
max_change_outputs = 3
def __init__(self, storage):
self.electrum_version = EL... | class Abstract_Wallet(PrintError):
| """
Wallet classes are created to handle various address generation methods.
Completion states (watching-only, single account, no seed, etc) are handled inside classes.
"""
max_change_outputs = 3
def __init__(self, storage):
self.electrum_version = ELECTRUM_VERSION
self.storage... | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Wallet classes:
- Imported_Wallet: imported address, no keystore
- Standard_Wallet: one keystore, P2PKH
- Multisig_Wallet: several keystores, P2SH
"""
import os
import hashlib
import ast
import threading
import random
import tim... | 255 | 256 | 10,523 | 7 | 248 | Bryangoodson/electrum-vtc-tor | lib/wallet.py | Python | Abstract_Wallet | Abstract_Wallet | 80 | 1,343 | 80 | 80 | 8e1e549b8eef63c5b972ee277db6236662329e66 | bigcode/the-stack | train |
af260923e4b20a003cac3f70 | train | class | class Standard_Wallet(Simple_Deterministic_Wallet):
wallet_type = 'standard'
def pubkeys_to_redeem_script(self, pubkey):
if self.is_segwit:
return transaction.segwit_script(pubkey)
def pubkeys_to_address(self, pubkey):
if not self.is_segwit:
return bitcoin.public_ke... | class Standard_Wallet(Simple_Deterministic_Wallet):
| wallet_type = 'standard'
def pubkeys_to_redeem_script(self, pubkey):
if self.is_segwit:
return transaction.segwit_script(pubkey)
def pubkeys_to_address(self, pubkey):
if not self.is_segwit:
return bitcoin.public_key_to_p2pkh(pubkey.decode('hex'))
elif bitcoi... | raise NotImplementedError()
def pubkeys_to_address(self, pubkey):
redeem_script = self.pubkeys_to_redeem_script(pubkey)
return bitcoin.hash160_to_p2sh(hash_160(redeem_script.decode('hex')))
class Standard_Wallet(Simple_Deterministic_Wallet):
| 63 | 64 | 136 | 11 | 52 | Bryangoodson/electrum-vtc-tor | lib/wallet.py | Python | Standard_Wallet | Standard_Wallet | 1,661 | 1,675 | 1,661 | 1,661 | dad9097b017977983fa28fb4feea0896874d5f97 | bigcode/the-stack | train |
e748664f34db5892d0bf714a | train | function | def register_wallet_type(category):
wallet_types.append(category)
| def register_wallet_type(category):
| wallet_types.append(category)
| txin['pubkeys'] = None
# we need n place holders
txin['signatures'] = [None] * self.n
txin['num_sig'] = self.m
wallet_types = ['standard', 'multisig', 'imported']
def register_wallet_type(category):
| 64 | 64 | 12 | 6 | 58 | Bryangoodson/electrum-vtc-tor | lib/wallet.py | Python | register_wallet_type | register_wallet_type | 1,766 | 1,767 | 1,766 | 1,766 | e88a6566f22069710cf07678ef75f628c9da2d0c | bigcode/the-stack | train |
269ddd8a7766547c349f8345 | train | class | class Simple_Wallet(Abstract_Wallet):
""" Wallet with a single pubkey per address """
def load_keystore(self):
self.keystore = load_keystore(self.storage, 'keystore')
self.is_segwit = self.keystore.is_segwit()
self.txin_type = 'p2wpkh-p2sh' if self.is_segwit else 'p2pkh'
def get_p... | class Simple_Wallet(Abstract_Wallet):
| """ Wallet with a single pubkey per address """
def load_keystore(self):
self.keystore = load_keystore(self.storage, 'keystore')
self.is_segwit = self.keystore.is_segwit()
self.txin_type = 'p2wpkh-p2sh' if self.is_segwit else 'p2pkh'
def get_pubkey(self, c, i):
return self.... | len(prev_addresses) < limit:
return False
prev_addresses = prev_addresses[max(0, i - limit):]
for addr in prev_addresses:
if self.history.get(addr):
return False
return True
def get_master_public_keys(self):
return [self.get_master_public_key... | 89 | 90 | 303 | 8 | 81 | Bryangoodson/electrum-vtc-tor | lib/wallet.py | Python | Simple_Wallet | Simple_Wallet | 1,554 | 1,586 | 1,554 | 1,555 | 809bd47c430dabf3dce4959c5e832a9a05ad8b56 | bigcode/the-stack | train |
e53d4cb8451c9130b977096f | train | class | class Wallet(object):
"""The main wallet "entry point".
This class is actually a factory that will return a wallet of the correct
type when passed a WalletStorage instance."""
def __new__(self, storage):
wallet_type = storage.get('wallet_type')
WalletClass = Wallet.wallet_class(wallet_t... | class Wallet(object):
| """The main wallet "entry point".
This class is actually a factory that will return a wallet of the correct
type when passed a WalletStorage instance."""
def __new__(self, storage):
wallet_type = storage.get('wallet_type')
WalletClass = Wallet.wallet_class(wallet_type)
wallet = ... | _types.append(category)
wallet_constructors = {
'standard': Standard_Wallet,
'old': Standard_Wallet,
'xpub': Standard_Wallet,
'imported': Imported_Wallet
}
def register_constructor(wallet_type, constructor):
wallet_constructors[wallet_type] = constructor
# former WalletFactory
class Wallet(object... | 72 | 72 | 242 | 4 | 67 | Bryangoodson/electrum-vtc-tor | lib/wallet.py | Python | Wallet | Wallet | 1,780 | 1,805 | 1,780 | 1,780 | d2ae49e21fe0de25d0f01478ec5ee2be7475c122 | bigcode/the-stack | train |
3970550ba96908b43bc85297 | train | class | class Deterministic_Wallet(Abstract_Wallet):
def __init__(self, storage):
Abstract_Wallet.__init__(self, storage)
self.gap_limit = storage.get('gap_limit', 20)
def has_seed(self):
return self.keystore.has_seed()
def is_deterministic(self):
return self.keystore.is_determini... | class Deterministic_Wallet(Abstract_Wallet):
| def __init__(self, storage):
Abstract_Wallet.__init__(self, storage)
self.gap_limit = storage.get('gap_limit', 20)
def has_seed(self):
return self.keystore.has_seed()
def is_deterministic(self):
return self.keystore.is_deterministic()
def get_receiving_addresses(self):... | eyond_limit(self, address, is_change):
return False
def get_fingerprint(self):
return ''
def get_addresses(self, include_change=False):
return self.addresses
def import_address(self, address):
if address in self.addresses:
return
self.addresses.append(a... | 255 | 256 | 892 | 10 | 245 | Bryangoodson/electrum-vtc-tor | lib/wallet.py | Python | Deterministic_Wallet | Deterministic_Wallet | 1,433 | 1,549 | 1,433 | 1,434 | 4b30279a6a03858753ffe2b98d3a0aba6f652cf5 | bigcode/the-stack | train |
0f30bbf93faf74a112db51a2 | train | function | def register(cb):
cb(TestMod())
| def register(cb):
| cb(TestMod())
| # -*- coding: future_fstrings -*-
import logging
from io import BytesIO
from .. import loader, utils
def register(cb):
| 28 | 64 | 9 | 4 | 23 | intellivoid/Friendly-Telegram-Lydia | modules/test.py | Python | register | register | 8 | 9 | 8 | 8 | 3c0f64df9b74754b9871d595ce07c3582361b42b | bigcode/the-stack | train |
f2977ab72973d2c1ed785743 | train | class | class TestMod(loader.Module):
"""Self-tests"""
def __init__(self):
self.commands = {'ping':self.pingcmd, 'dump':self.dumpcmd, 'logs':self.logcmd}
self.config = {}
self.name = "Tester"
async def pingcmd(self, message):
"""Does nothing"""
await message.edit('Pong')
... | class TestMod(loader.Module):
| """Self-tests"""
def __init__(self):
self.commands = {'ping':self.pingcmd, 'dump':self.dumpcmd, 'logs':self.logcmd}
self.config = {}
self.name = "Tester"
async def pingcmd(self, message):
"""Does nothing"""
await message.edit('Pong')
async def dumpcmd(self, mess... | # -*- coding: future_fstrings -*-
import logging
from io import BytesIO
from .. import loader, utils
def register(cb):
cb(TestMod())
class TestMod(loader.Module):
| 39 | 115 | 384 | 6 | 33 | intellivoid/Friendly-Telegram-Lydia | modules/test.py | Python | TestMod | TestMod | 11 | 48 | 11 | 11 | cda7d6d3e32274fb1cf138f56b5916dfbb31d108 | bigcode/the-stack | train |
135b837c481ecefc58853142 | train | class | class RandomPolicy(Policy):
def __init__(self,
action_mapper,
epsilon=0.1,
epsilon_decay_step=0.0001,
epsilon_decay_epoch=0.,
epsilon_min=0.001,
reset_on_game_changed=True,
dropout=0.4,
... | class RandomPolicy(Policy):
| def __init__(self,
action_mapper,
epsilon=0.1,
epsilon_decay_step=0.0001,
epsilon_decay_epoch=0.,
epsilon_min=0.001,
reset_on_game_changed=True,
dropout=0.4,
reset_on_epoch_start=F... | import random
import numpy as np
from rl.policies import Policy
class RandomPolicy(Policy):
| 21 | 130 | 435 | 6 | 14 | valiro21/MarioLearningCompany | rl/policies/RandomPolicy.py | Python | RandomPolicy | RandomPolicy | 7 | 64 | 7 | 7 | 6743def97b2cb093ca9552355f86809478a0e7a8 | bigcode/the-stack | train |
87cd3a7c9bd66b021db57b42 | train | class | class OpenTypeControlsView(vanilla.ScrollView):
def __init__(self, posSize, callback):
self._callback = callback
# put the controls group into a flipped group.
# this will give better scroll behavior.
width = posSize[2] - NSScroller.scrollerWidth() - 2
view = DefconAppKitTop... | class OpenTypeControlsView(vanilla.ScrollView):
| def __init__(self, posSize, callback):
self._callback = callback
# put the controls group into a flipped group.
# this will give better scroll behavior.
width = posSize[2] - NSScroller.scrollerWidth() - 2
view = DefconAppKitTopAnchoredNSView.alloc().init()
view.setFra... | from AppKit import NSScroller, NSColor, NSAttributedString, NSMenuItem, NSShadowAttributeName, NSShadow, \
NSForegroundColorAttributeName, NSFont, NSFontAttributeName, NSSmallControlSize, NSView
import vanilla
class OpenTypeControlsView(vanilla.ScrollView):
| 64 | 256 | 2,163 | 11 | 52 | andyclymer/defconAppKit | Lib/defconAppKit/controls/openTypeControlsView.py | Python | OpenTypeControlsView | OpenTypeControlsView | 6 | 208 | 6 | 7 | 24628c1d28482a307ba58a3a33e6f1c738ea0ff1 | bigcode/the-stack | train |
68b78bba897b05a19097141c | train | class | class DefconAppKitTopAnchoredNSView(NSView):
def isFlipped(self):
return True
| class DefconAppKitTopAnchoredNSView(NSView):
| def isFlipped(self):
return True
| script=script,
language=language,
gsub=gsubStates,
gpos=gposStates,
rightToLeft=rightToLeft
)
return status
# --------------------
# Misc. Internal Stuff
# --------------------
class DefconAppKitTopAnchoredNSView(NSView):
| 64 | 64 | 24 | 13 | 51 | andyclymer/defconAppKit | Lib/defconAppKit/controls/openTypeControlsView.py | Python | DefconAppKitTopAnchoredNSView | DefconAppKitTopAnchoredNSView | 215 | 218 | 215 | 216 | 67cce5be855d0418593c6e5c7ffe9c40b507677a | bigcode/the-stack | train |
727a3e45b3dbab8ae734069b | train | class | class StepsOperations(object):
"""StepsOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param seri... | class StepsOperations(object):
| """StepsOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model seriali... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 109 | 256 | 2,651 | 5 | 103 | iscai-msft/azure-sdk-for-python | sdk/deploymentmanager/azure-mgmt-deploymentmanager/azure/mgmt/deploymentmanager/operations/_steps_operations.py | Python | StepsOperations | StepsOperations | 19 | 288 | 19 | 19 | 6a7cee031decd859b6affb873343a05f102f3c8d | bigcode/the-stack | train |
bac61899e7583db516a3f679 | train | class | class App(app_test.AppTest):
def __init__(self, **kwargs):
super().__init__('org.sufficientlysecure.keychain.debug',
'org.sufficientlysecure.keychain.ui.MainActivity',
**kwargs)
def warmup(self):
self.find_element_by_res_id('create_key_create_ke... | class App(app_test.AppTest):
| def __init__(self, **kwargs):
super().__init__('org.sufficientlysecure.keychain.debug',
'org.sufficientlysecure.keychain.ui.MainActivity',
**kwargs)
def warmup(self):
self.find_element_by_res_id('create_key_create_key_button').click()
ti... | import logging
import time
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.support.wait import WebDriverWait
from .. import app_test
logger = logging.getLogger(__name__)
FILES_APP = 'com.android.documentsui'
class App(app_test.AppTest):
| 57 | 190 | 635 | 7 | 50 | qiangxu1996/android-appium-profiler | android_appium_profiler/apps/ok.py | Python | App | App | 14 | 80 | 14 | 14 | 1951250a040a0fdaa5f9eb423f80c459de1c990f | bigcode/the-stack | train |
88de8e8a42d13ae83c03cf6d | train | class | class RepoInitChromeBotTests(RepoInitTests):
"""Test that Re-init works with the chrome-bot account.
In testing, repo init behavior on the buildbots is different from a
local run, because there is some logic in 'repo' that filters changes based on
GIT_COMMITTER_IDENT. So for sanity's sake, try to emulate runn... | class RepoInitChromeBotTests(RepoInitTests):
| """Test that Re-init works with the chrome-bot account.
In testing, repo init behavior on the buildbots is different from a
local run, because there is some logic in 'repo' that filters changes based on
GIT_COMMITTER_IDENT. So for sanity's sake, try to emulate running on the
buildbots.
"""
def setUp(sel... | Initialize('master')
# Test that a failed re-init due to bad branch doesn't leave repo in bad
# state.
self.assertRaises(Exception, self._Initialize, 'monkey')
self._Initialize('release-R20-2268.B')
class RepoInitChromeBotTests(RepoInitTests):
| 64 | 64 | 134 | 11 | 53 | marineam/chromite | buildbot/repository_unittest.py | Python | RepoInitChromeBotTests | RepoInitChromeBotTests | 73 | 83 | 73 | 73 | 3bd3329d65c56aa4663052e6823590ce561df1af | bigcode/the-stack | train |
b15debe96da9ba1b08015b7c | train | class | class RepoInitTests(cros_test_lib.MoxTempDirTestCase):
def _Initialize(self, branch='master'):
repo = repository.RepoRepository(constants.MANIFEST_URL, self.tempdir,
branch=branch)
repo.Initialize()
def testReInitialization(self):
"""Test ability to switch between ... | class RepoInitTests(cros_test_lib.MoxTempDirTestCase):
| def _Initialize(self, branch='master'):
repo = repository.RepoRepository(constants.MANIFEST_URL, self.tempdir,
branch=branch)
repo.Initialize()
def testReInitialization(self):
"""Test ability to switch between branches."""
self._Initialize('release-R19-2046.B')
... | :39291/bla/manifest-internal.git',
]
for test in tests:
cros_build_lib.RunCommand = functools.partial(self.RunCommand_Mock, test)
self.assertTrue(repository.IsInternalRepoCheckout('.'))
class RepoInitTests(cros_test_lib.MoxTempDirTestCase):
| 63 | 64 | 136 | 15 | 48 | marineam/chromite | buildbot/repository_unittest.py | Python | RepoInitTests | RepoInitTests | 55 | 70 | 55 | 56 | 1c9e01036a2bb8178f15aca3ad43a6eb53deb4c5 | bigcode/the-stack | train |
10136ae790ecaeb848363625 | train | class | class RepositoryTests(cros_test_lib.MoxTestCase):
def RunCommand_Mock(self, result, *args, **kwargs):
output = self.mox.CreateMockAnything()
output.output = result
return output
def testExternalRepoCheckout(self):
"""Test we detect external checkouts properly."""
self.mox.StubOutWithMock(cros_... | class RepositoryTests(cros_test_lib.MoxTestCase):
| def RunCommand_Mock(self, result, *args, **kwargs):
output = self.mox.CreateMockAnything()
output.output = result
return output
def testExternalRepoCheckout(self):
"""Test we detect external checkouts properly."""
self.mox.StubOutWithMock(cros_build_lib, 'RunCommand')
tests = [
'htt... | Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import functools
import os
import sys
import constants
sys.path.insert(0, constants.SOURCE_ROOT)
from chromite.buildbot import repository
from chromite.lib import cros_build... | 112 | 112 | 375 | 12 | 99 | marineam/chromite | buildbot/repository_unittest.py | Python | RepositoryTests | RepositoryTests | 18 | 52 | 18 | 19 | ed3fb94016b5d6aca1b954b17b2a6f59d6c7b959 | bigcode/the-stack | train |
aba6c70a94eb5c1c3622b9bc | train | function | def test_large_image_tiff_source(host):
"""Run large image tiff tests."""
activate = "source /root/.virtualenvs/large_image/bin/activate"
run = "pytest /request_tile_in_container.py"
cmd = host.run("bash -c '{} && {}'".format(activate, run))
assert cmd.rc == 0
| def test_large_image_tiff_source(host):
| """Run large image tiff tests."""
activate = "source /root/.virtualenvs/large_image/bin/activate"
run = "pytest /request_tile_in_container.py"
cmd = host.run("bash -c '{} && {}'".format(activate, run))
assert cmd.rc == 0
| (host):
"""Check python dependencies for tiff tile source."""
pipPath = '~/.virtualenvs/large_image/bin/pip'
packages = host.pip_package.get_packages(pip_path=pipPath)
assert 'libtiff' in packages
def test_large_image_tiff_source(host):
| 64 | 64 | 76 | 9 | 54 | girder/ansible-role-large-image | molecule/tiff/tests/test_tiff_tile_source.py | Python | test_large_image_tiff_source | test_large_image_tiff_source | 18 | 23 | 18 | 18 | 4375252aeb941669b9b0093044d0c10a6fb8559b | bigcode/the-stack | train |
4a847870132f8b312244d0c3 | train | function | def test_pip_packages(host):
"""Check python dependencies for tiff tile source."""
pipPath = '~/.virtualenvs/large_image/bin/pip'
packages = host.pip_package.get_packages(pip_path=pipPath)
assert 'libtiff' in packages
| def test_pip_packages(host):
| """Check python dependencies for tiff tile source."""
pipPath = '~/.virtualenvs/large_image/bin/pip'
packages = host.pip_package.get_packages(pip_path=pipPath)
assert 'libtiff' in packages
| """Test the default libtiff based tile source."""
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_pip_packages(host):
| 63 | 64 | 60 | 7 | 56 | girder/ansible-role-large-image | molecule/tiff/tests/test_tiff_tile_source.py | Python | test_pip_packages | test_pip_packages | 11 | 15 | 11 | 11 | 2e352d2b4df1fbc7d30c73c1b32fb6567da28408 | bigcode/the-stack | train |
2484cd624924a4b0e197afe0 | train | class | class IrAttr:
def __init__(self):
self.dict_values = {
'axis' : 0 # axis to compute
, 'axes' : [] # list of axis
, 'broadcast' : 0 # enable broadcasting
, 'keepdims' : 1 # 1: keep reduced dimension
... | class IrAttr:
| def __init__(self):
self.dict_values = {
'axis' : 0 # axis to compute
, 'axes' : [] # list of axis
, 'broadcast' : 0 # enable broadcasting
, 'keepdims' : 1 # 1: keep reduced dimension
, 'kernel_sh... | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys, os, os.path
import numpy as np
class IrTensor:
def __init__(self):
self.name = ... | 256 | 256 | 956 | 4 | 252 | MIPS/MIVisionX | model_compiler/python/nnir.py | Python | IrAttr | IrAttr | 51 | 132 | 51 | 51 | 92d4af8394de209468dd4d8af2843fe1b788edd8 | bigcode/the-stack | train |
81dd0112a2c379694d30215a | train | class | class IrNode:
def __init__(self):
self.type = 'Unknown'
self.inputs = []
self.outputs = []
self.attr = IrAttr()
self.dict_types = {
'conv' : 1,
'conv_transpose' : 1,
'batch_norm' : 1,
'avg_pool' : 1,
'max_pool' : 1,
... | class IrNode:
| def __init__(self):
self.type = 'Unknown'
self.inputs = []
self.outputs = []
self.attr = IrAttr()
self.dict_types = {
'conv' : 1,
'conv_transpose' : 1,
'batch_norm' : 1,
'avg_pool' : 1,
'max_pool' : 1,
'r... | ):
for sa in s.split(';'):
saL = sa.split('=')
name = saL[0]
value = saL[1]
value_type = type(self.dict_values[name]).__name__
if value_type == 'list':
list_type = value.split(',')
self.set(name, [int(x) for x in list_ty... | 143 | 143 | 479 | 4 | 139 | MIPS/MIVisionX | model_compiler/python/nnir.py | Python | IrNode | IrNode | 134 | 191 | 134 | 134 | 37523b2b1a6807b41d5a5c0a73212a95d4f515a4 | bigcode/the-stack | train |
905bd0b5d97c81959a22896a | train | class | class IrGraph:
def __init__(self):
self.inputs = []
self.outputs = []
self.output_names = []
self.initializers = []
self.locals = []
self.nodes = []
self.binaries = {}
self.tensor_dict = {}
self.tensor_types = {}
self.tensor_shapes = {}... | class IrGraph:
| def __init__(self):
self.inputs = []
self.outputs = []
self.output_names = []
self.initializers = []
self.locals = []
self.nodes = []
self.binaries = {}
self.tensor_dict = {}
self.tensor_types = {}
self.tensor_shapes = {}
self.a... | 1,
'crop_and_resize': 1,
'permute' : 1,
'prior_box' : 1,
'flatten' : 1
}
def set(self,type,inputs,outputs,attr):
if not type in self.dict_types or self.dict_types[type] == 0:
print('ERROR: IrNode.set: operation "%s" not supported' % (typ... | 256 | 256 | 9,056 | 4 | 252 | MIPS/MIVisionX | model_compiler/python/nnir.py | Python | IrGraph | IrGraph | 193 | 1,048 | 193 | 193 | 28ca26c5535b38259a640a6f32a9c1208638627d | bigcode/the-stack | train |
5fdba848e378c1bcbb2f4435 | train | class | class IrTensor:
def __init__(self):
self.name = 'Unknown'
self.type = 'F032'
self.shape = [0]
self.format = 'NCHW'
def setName(self,name):
self.name = name
def setInfo(self,type,shape):
self.type = type
self.shape = shape
def setFormat(self,form... | class IrTensor:
| def __init__(self):
self.name = 'Unknown'
self.type = 'F032'
self.shape = [0]
self.format = 'NCHW'
def setName(self,name):
self.name = name
def setInfo(self,type,shape):
self.type = type
self.shape = shape
def setFormat(self,format):
sel... | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys, os, os.path
import numpy as np
class IrTensor:
| 64 | 64 | 191 | 4 | 59 | MIPS/MIVisionX | model_compiler/python/nnir.py | Python | IrTensor | IrTensor | 24 | 49 | 24 | 24 | a1e52c7673255a137bd7eef92018846d7ff10870 | bigcode/the-stack | train |
43ea94a7e74ca60ef4b0f370 | train | function | def parse_args():
parser = argparse.ArgumentParser(description="Train CornerNet")
parser.add_argument("cfg_file", help="config file", type=str)
parser.add_argument("--iter", dest="start_iter",
help="train at iteration i",
default=0, type=int)
parser.add_ar... | def parse_args():
| parser = argparse.ArgumentParser(description="Train CornerNet")
parser.add_argument("cfg_file", help="config file", type=str)
parser.add_argument("--iter", dest="start_iter",
help="train at iteration i",
default=0, type=int)
parser.add_argument("--threads"... | import stdout_to_tqdm
from config import system_configs
from nnet.py_factory import NetworkFactory
from torch.multiprocessing import Process, Queue, Pool
from db.datasets import datasets
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
def parse_args():
| 64 | 64 | 101 | 4 | 59 | sanderisbestok/ExtremeNet | train.py | Python | parse_args | parse_args | 26 | 36 | 26 | 26 | 4c539719b747bb15cd5ca7f6298a67776174f1e6 | bigcode/the-stack | train |
1b97606bca21f981c0b00cb0 | train | function | def pin_memory(data_queue, pinned_data_queue, sema):
while True:
data = data_queue.get()
data["xs"] = [x.pin_memory() for x in data["xs"]]
data["ys"] = [y.pin_memory() for y in data["ys"]]
pinned_data_queue.put(data)
if sema.acquire(blocking=False):
return
| def pin_memory(data_queue, pinned_data_queue, sema):
| while True:
data = data_queue.get()
data["xs"] = [x.pin_memory() for x in data["xs"]]
data["ys"] = [y.pin_memory() for y in data["ys"]]
pinned_data_queue.put(data)
if sema.acquire(blocking=False):
return
| (os.getpid())
while True:
try:
data, ind = sample_data(db, ind, data_aug=data_aug, debug=debug)
queue.put(data)
except Exception as e:
traceback.print_exc()
raise e
def pin_memory(data_queue, pinned_data_queue, sema):
| 64 | 64 | 81 | 13 | 50 | sanderisbestok/ExtremeNet | train.py | Python | pin_memory | pin_memory | 68 | 78 | 68 | 68 | 8bfd70bbb59d3e68bae7f42babafbb4be3435706 | bigcode/the-stack | train |
d113277f52b0d9878a7abc32 | train | function | def train(training_dbs, validation_db, start_iter=0, debug=False):
learning_rate = system_configs.learning_rate
max_iteration = system_configs.max_iter
pretrained_model = system_configs.pretrain
snapshot = system_configs.snapshot
# val_iter = system_configs.val_iter
display... | def train(training_dbs, validation_db, start_iter=0, debug=False):
| learning_rate = system_configs.learning_rate
max_iteration = system_configs.max_iter
pretrained_model = system_configs.pretrain
snapshot = system_configs.snapshot
# val_iter = system_configs.val_iter
display = system_configs.display
decay_rate = system_co... |
def prefetch_data(db, queue, sample_data, data_aug, debug=False):
ind = 0
print("start prefetching data...")
np.random.seed(os.getpid())
while True:
try:
data, ind = sample_data(db, ind, data_aug=data_aug, debug=debug)
queue.put(data)
except Exception as e:
... | 256 | 256 | 944 | 17 | 238 | sanderisbestok/ExtremeNet | train.py | Python | train | train | 88 | 198 | 88 | 88 | 8af0642a78acfe84137edff03abc2f6d40a8cc24 | bigcode/the-stack | train |
341af25e618c493298b1e008 | train | function | def prefetch_data(db, queue, sample_data, data_aug, debug=False):
ind = 0
print("start prefetching data...")
np.random.seed(os.getpid())
while True:
try:
data, ind = sample_data(db, ind, data_aug=data_aug, debug=debug)
queue.put(data)
except Exception as e:
... | def prefetch_data(db, queue, sample_data, data_aug, debug=False):
| ind = 0
print("start prefetching data...")
np.random.seed(os.getpid())
while True:
try:
data, ind = sample_data(db, ind, data_aug=data_aug, debug=debug)
queue.put(data)
except Exception as e:
traceback.print_exc()
raise e
| update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
if self.count > 0:
self.avg = self.sum / self.count
def prefetch_data(db, queue, sample_data, data_aug, debug=False):
| 64 | 64 | 87 | 17 | 46 | sanderisbestok/ExtremeNet | train.py | Python | prefetch_data | prefetch_data | 56 | 66 | 56 | 56 | b4a42b81e881b4cf9594f5c0f90733631b7e5a3a | bigcode/the-stack | train |
6e008a980c16513a72e16d30 | train | class | class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val... | class AverageMeter(object):
| """Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n... | _iter",
help="train at iteration i",
default=0, type=int)
parser.add_argument("--threads", dest="threads", default=4, type=int)
parser.add_argument("--debug", action="store_true")
args = parser.parse_args()
return args
class AverageMeter(object):
| 64 | 64 | 110 | 5 | 58 | sanderisbestok/ExtremeNet | train.py | Python | AverageMeter | AverageMeter | 38 | 54 | 38 | 38 | 01905e0cd701e0828e2cf5724394dec8f5f20c69 | bigcode/the-stack | train |
198efe63cfafcde9ea1235ea | train | function | def init_parallel_jobs(dbs, queue, fn, data_aug, debug=False):
tasks = [Process(target=prefetch_data,
args=(db, queue, fn, data_aug, debug)) for db in dbs]
for task in tasks:
task.daemon = True
task.start()
return tasks
| def init_parallel_jobs(dbs, queue, fn, data_aug, debug=False):
| tasks = [Process(target=prefetch_data,
args=(db, queue, fn, data_aug, debug)) for db in dbs]
for task in tasks:
task.daemon = True
task.start()
return tasks
| () for x in data["xs"]]
data["ys"] = [y.pin_memory() for y in data["ys"]]
pinned_data_queue.put(data)
if sema.acquire(blocking=False):
return
def init_parallel_jobs(dbs, queue, fn, data_aug, debug=False):
| 64 | 64 | 70 | 17 | 46 | sanderisbestok/ExtremeNet | train.py | Python | init_parallel_jobs | init_parallel_jobs | 80 | 86 | 80 | 80 | 32f3f19391d28ad7cea706006469b1d1bb90202d | bigcode/the-stack | train |
17d140813ed9dd08ae651848 | train | class | class TestLdapLoginManager(TestCase):
"""
Unit test for the package constructor.
"""
def setUp(self):
"""
Prepare the mocks for dependencies used by the module.
"""
# patch the logging module
self.patcher_logging = patch.object(ldap, 'logging')
mock_loggi... | class TestLdapLoginManager(TestCase):
| """
Unit test for the package constructor.
"""
def setUp(self):
"""
Prepare the mocks for dependencies used by the module.
"""
# patch the logging module
self.patcher_logging = patch.object(ldap, 'logging')
mock_logging = self.patcher_logging.start()
... | # Copyright 2016, 2017 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | 213 | 256 | 3,614 | 9 | 204 | tessia-project/tessia | tests/unit/auth/ldap.py | Python | TestLdapLoginManager | TestLdapLoginManager | 39 | 521 | 39 | 39 | 10101b1959989544e76041d9ba11426204857308 | bigcode/the-stack | train |
6b456da282f1e8bc64a7a56e | train | function | def test_hyperparameter_existence_and_defaults():
hp = hp_module.HyperParameters()
hypermodel = resnet.HyperResNet(input_shape=(256, 256, 3), classes=10)
hypermodel.build(hp)
assert hp.get("version") == "v2"
assert hp.get("conv3_depth") == 4
assert hp.get("conv4_depth") == 6
assert hp.get("l... | def test_hyperparameter_existence_and_defaults():
| hp = hp_module.HyperParameters()
hypermodel = resnet.HyperResNet(input_shape=(256, 256, 3), classes=10)
hypermodel.build(hp)
assert hp.get("version") == "v2"
assert hp.get("conv3_depth") == 4
assert hp.get("conv4_depth") == 6
assert hp.get("learning_rate") == 0.01
assert hp.get("pooling"... | _on_batch(np.ones((1, 128, 128, 3)), np.ones((1, 10)))
out = model.predict(np.ones((1, 128, 128, 3)))
assert out.shape == (1, 10)
def test_hyperparameter_existence_and_defaults():
| 64 | 64 | 115 | 10 | 54 | kayzhu/keras-tuner | tests/keras_tuner/applications/resnet_test.py | Python | test_hyperparameter_existence_and_defaults | test_hyperparameter_existence_and_defaults | 42 | 50 | 42 | 42 | d952ed451c0d62b980ddf8fd34e50f15bdd516da | bigcode/the-stack | train |
3b57e290c3eec65132c2c0d6 | train | function | def test_hyperparameter_override():
hp = hp_module.HyperParameters()
hp.Choice("version", ["v1"])
hp.Fixed("conv3_depth", 10)
hypermodel = resnet.HyperResNet(input_shape=(256, 256, 3), classes=10)
hypermodel.build(hp)
assert hp.get("version") == "v1"
assert hp.get("conv3_depth") == 10
as... | def test_hyperparameter_override():
| hp = hp_module.HyperParameters()
hp.Choice("version", ["v1"])
hp.Fixed("conv3_depth", 10)
hypermodel = resnet.HyperResNet(input_shape=(256, 256, 3), classes=10)
hypermodel.build(hp)
assert hp.get("version") == "v1"
assert hp.get("conv3_depth") == 10
assert hp.get("conv4_depth") == 6
| ()
hypermodel = resnet.HyperResNet(
input_shape=(256, 256, 3), classes=10, include_top=False
)
model = hypermodel.build(hp)
# Check that model wasn't compiled.
assert not model.optimizer
def test_hyperparameter_override():
| 64 | 64 | 108 | 7 | 56 | kayzhu/keras-tuner | tests/keras_tuner/applications/resnet_test.py | Python | test_hyperparameter_override | test_hyperparameter_override | 63 | 71 | 63 | 63 | 11d292123cdc9e3c05bd79fdbdc093f10721120d | bigcode/the-stack | train |
fd2948d43edd8e0f8e6d14f2 | train | function | def test_include_top_false():
hp = hp_module.HyperParameters()
hypermodel = resnet.HyperResNet(
input_shape=(256, 256, 3), classes=10, include_top=False
)
model = hypermodel.build(hp)
# Check that model wasn't compiled.
assert not model.optimizer
| def test_include_top_false():
| hp = hp_module.HyperParameters()
hypermodel = resnet.HyperResNet(
input_shape=(256, 256, 3), classes=10, include_top=False
)
model = hypermodel.build(hp)
# Check that model wasn't compiled.
assert not model.optimizer
| ") == "v2"
assert hp.get("conv3_depth") == 4
assert hp.get("conv4_depth") == 6
assert hp.get("learning_rate") == 0.01
assert hp.get("pooling") == "avg"
def test_include_top_false():
| 64 | 64 | 71 | 6 | 58 | kayzhu/keras-tuner | tests/keras_tuner/applications/resnet_test.py | Python | test_include_top_false | test_include_top_false | 53 | 60 | 53 | 53 | dc9115223fd306bc0080394274aba64046e7f0a6 | bigcode/the-stack | train |
a5c3d9111fd8d2c9ae9191a1 | train | function | def test_input_tensor():
hp = hp_module.HyperParameters()
inputs = tf.keras.Input(shape=(256, 256, 3))
hypermodel = resnet.HyperResNet(input_tensor=inputs, include_top=False)
model = hypermodel.build(hp)
assert model.inputs == [inputs]
| def test_input_tensor():
| hp = hp_module.HyperParameters()
inputs = tf.keras.Input(shape=(256, 256, 3))
hypermodel = resnet.HyperResNet(input_tensor=inputs, include_top=False)
model = hypermodel.build(hp)
assert model.inputs == [inputs]
| _shape=(256, 256, 3), classes=10)
hypermodel.build(hp)
assert hp.get("version") == "v1"
assert hp.get("conv3_depth") == 10
assert hp.get("conv4_depth") == 6
def test_input_tensor():
| 64 | 64 | 66 | 5 | 58 | kayzhu/keras-tuner | tests/keras_tuner/applications/resnet_test.py | Python | test_input_tensor | test_input_tensor | 74 | 79 | 74 | 74 | ece71d7451607b607fb96495deef9313cefd8131 | bigcode/the-stack | train |
2c6fda52135cf55a0a5de23b | train | function | @pytest.mark.skipif("TRAVIS" in os.environ, reason="Causes CI to stall")
@pytest.mark.parametrize("version", ["v1", "v2", "next"])
def test_model_construction(version):
hp = hp_module.HyperParameters()
hp.Choice("version", [version])
hypermodel = resnet.HyperResNet(input_shape=(128, 128, 3), classes=10)
... | @pytest.mark.skipif("TRAVIS" in os.environ, reason="Causes CI to stall")
@pytest.mark.parametrize("version", ["v1", "v2", "next"])
def test_model_construction(version):
| hp = hp_module.HyperParameters()
hp.Choice("version", [version])
hypermodel = resnet.HyperResNet(input_shape=(128, 128, 3), classes=10)
model = hypermodel.build(hp)
assert hp.values["version"] == version
assert model.layers
assert model.name == "ResNet"
assert model.output_shape == (None... | uner.applications import resnet
from keras_tuner.engine import hyperparameters as hp_module
@pytest.mark.skipif("TRAVIS" in os.environ, reason="Causes CI to stall")
@pytest.mark.parametrize("version", ["v1", "v2", "next"])
def test_model_construction(version):
| 64 | 64 | 191 | 45 | 18 | kayzhu/keras-tuner | tests/keras_tuner/applications/resnet_test.py | Python | test_model_construction | test_model_construction | 26 | 39 | 26 | 28 | 93898b6db7fd85ff019e1ddceeb61a1ff1810a73 | bigcode/the-stack | train |
c8d81559acf20040dd0af8b6 | train | class | class Migration(migrations.Migration):
dependencies = [
('countries_plus', '__first__'),
]
operations = [
migrations.CreateModel(
name='CultureCode',
fields=[
('code', models.CharField(max_length=10, serialize=False, primary_key=True)),
... | class Migration(migrations.Migration):
| dependencies = [
('countries_plus', '__first__'),
]
operations = [
migrations.CreateModel(
name='CultureCode',
fields=[
('code', models.CharField(max_length=10, serialize=False, primary_key=True)),
('country', models.ForeignKey(to='cou... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| 31 | 134 | 449 | 7 | 23 | OskarPersson/django-languages-plus | languages_plus/migrations/0001_initial.py | Python | Migration | Migration | 7 | 64 | 7 | 8 | 534f30ef6b7c8fd8899a7c4f3139b85e41073e31 | bigcode/the-stack | train |
8ef806d19a23162c10d71d46 | train | class | class SawyerPegUnplugSideEnv(SawyerXYZEnv):
def __init__(self):
liftThresh = 0.04
hand_low = (-0.5, 0.40, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = (-0.25, 0.6, 0.05)
obj_high = (-0.15, 0.8, 0.05)
goal_low = (-0.05, 0.6, 0.019)
goal_high = (0.2, 0.8, 0.021)
... | class SawyerPegUnplugSideEnv(SawyerXYZEnv):
| def __init__(self):
liftThresh = 0.04
hand_low = (-0.5, 0.40, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = (-0.25, 0.6, 0.05)
obj_high = (-0.15, 0.8, 0.05)
goal_low = (-0.05, 0.6, 0.019)
goal_high = (0.2, 0.8, 0.021)
super().__init__(
self.m... | import numpy as np
from gym.spaces import Box
from metaworld.envs.asset_path_utils import full_v1_path_for
from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set
class SawyerPegUnplugSideEnv(SawyerXYZEnv):
| 71 | 256 | 1,371 | 13 | 57 | rmrafailov/metaworld | metaworld/envs/mujoco/sawyer_xyz/v1/sawyer_peg_unplug_side.py | Python | SawyerPegUnplugSideEnv | SawyerPegUnplugSideEnv | 8 | 148 | 8 | 9 | 3f94ad58728dd52dd65dda2c8c2afd385587d70b | bigcode/the-stack | train |
8663270a69659d61cc5b8048 | train | function | def delete(name, resource_group, server):
'''
Required Parameters:
- name -- The name of the Failover Group
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
- server -- Name of the Azure SQL server. You can configure t... | def delete(name, resource_group, server):
| '''
Required Parameters:
- name -- The name of the Failover Group
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
- server -- Name of the Azure SQL server. You can configure the default using `az configure --defaults ... | databases to remove from Failover Group
- set -- Update an object by specifying a property path and value to set. Example: --set property1.property2=<value>
'''
return _call_az("az sql failover-group update", locals())
def delete(name, resource_group, server):
| 64 | 64 | 99 | 9 | 55 | py-az-cli/py-az-cli | pyaz/sql/failover_group/__init__.py | Python | delete | delete | 67 | 76 | 67 | 67 | aaa283933df59bc4d393433560141e35eef2d8e2 | bigcode/the-stack | train |
e95d9deaf87d082db7b9aea9 | train | function | def create(name, partner_server, resource_group, server, add_db=None, failover_policy=None, grace_period=None, partner_resource_group=None):
'''
Creates a failover group.
Required Parameters:
- name -- The name of the Failover Group
- partner_server -- The name of the partner server of a Failover G... | def create(name, partner_server, resource_group, server, add_db=None, failover_policy=None, grace_period=None, partner_resource_group=None):
| '''
Creates a failover group.
Required Parameters:
- name -- The name of the Failover Group
- partner_server -- The name of the partner server of a Failover Group
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
- s... | =<name>`
- server -- Name of the Azure SQL server. You can configure the default using `az configure --defaults sql-server=<name>`
'''
return _call_az("az sql failover-group list", locals())
def create(name, partner_server, resource_group, server, add_db=None, failover_policy=None, grace_period=None, partne... | 78 | 78 | 261 | 30 | 48 | py-az-cli/py-az-cli | pyaz/sql/failover_group/__init__.py | Python | create | create | 26 | 42 | 26 | 26 | e0270d4808cfddadc9ce59925b9d4e6a884c9ab9 | bigcode/the-stack | train |
7a1394f5f3bb3ed1dfac5070 | train | function | def list(resource_group, server):
'''
Required Parameters:
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
- server -- Name of the Azure SQL server. You can configure the default using `az configure --defaults sql-server=... | def list(resource_group, server):
| '''
Required Parameters:
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
- server -- Name of the Azure SQL server. You can configure the default using `az configure --defaults sql-server=<name>`
'''
return _call_a... | default group using `az configure --defaults group=<name>`
- server -- Name of the Azure SQL server. You can configure the default using `az configure --defaults sql-server=<name>`
'''
return _call_az("az sql failover-group show", locals())
def list(resource_group, server):
| 64 | 64 | 85 | 7 | 57 | py-az-cli/py-az-cli | pyaz/sql/failover_group/__init__.py | Python | list | list | 15 | 23 | 15 | 15 | c86caecb294ab3f00522cbe47c5d62a85f8b1eb4 | bigcode/the-stack | train |
ea31c4ac69fe084beb70ab67 | train | function | def update(name, resource_group, server, add=None, add_db=None, failover_policy=None, force_string=None, grace_period=None, remove=None, remove_db=None, set=None):
'''
Updates the failover group.
Required Parameters:
- name -- The name of the Failover Group
- resource_group -- Name of resource grou... | def update(name, resource_group, server, add=None, add_db=None, failover_policy=None, force_string=None, grace_period=None, remove=None, remove_db=None, set=None):
| '''
Updates the failover group.
Required Parameters:
- name -- The name of the Failover Group
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
- server -- Name of the Azure SQL server. You can configure the default usin... | SQL Database will not initiate automatic failover before the grace period expires. Please note that failover operation with --allow-data-loss option might cause data loss due to the nature of asynchronous synchronization.
- partner_resource_group -- The name of the resource group of the partner server
'''
... | 112 | 112 | 376 | 39 | 73 | py-az-cli/py-az-cli | pyaz/sql/failover_group/__init__.py | Python | update | update | 45 | 64 | 45 | 45 | 3dab154ae62562ce5f373c140614952ec1aad500 | bigcode/the-stack | train |
d69b79b432c08e74cc023d90 | train | function | def show(name, resource_group, server):
'''
Required Parameters:
- name -- The name of the Failover Group
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
- server -- Name of the Azure SQL server. You can configure the... | def show(name, resource_group, server):
| '''
Required Parameters:
- name -- The name of the Failover Group
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
- server -- Name of the Azure SQL server. You can configure the default using `az configure --defaults ... | from ... pyaz_utils import _call_az
def show(name, resource_group, server):
| 20 | 64 | 99 | 9 | 10 | py-az-cli/py-az-cli | pyaz/sql/failover_group/__init__.py | Python | show | show | 3 | 12 | 3 | 3 | f6e8d875297264338d044c69b412d2515f029773 | bigcode/the-stack | train |
55b24b728e4c3c6f5ba98dbd | train | function | def set_primary(name, resource_group, server, allow_data_loss=None):
'''
Set the primary of the failover group by failing over all databases from the current primary server.
Required Parameters:
- name -- The name of the Failover Group
- resource_group -- Name of resource group. You can configure t... | def set_primary(name, resource_group, server, allow_data_loss=None):
| '''
Set the primary of the failover group by failing over all databases from the current primary server.
Required Parameters:
- name -- The name of the Failover Group
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
- s... | group=<name>`
- server -- Name of the Azure SQL server. You can configure the default using `az configure --defaults sql-server=<name>`
'''
return _call_az("az sql failover-group delete", locals())
def set_primary(name, resource_group, server, allow_data_loss=None):
| 64 | 64 | 166 | 15 | 49 | py-az-cli/py-az-cli | pyaz/sql/failover_group/__init__.py | Python | set_primary | set_primary | 79 | 91 | 79 | 79 | ce7fbfbbf05d8c94991db4051af8a982604796cd | bigcode/the-stack | train |
6ad57b163bfe2ee3a032fe6b | train | function | def Reader():
global x
print('Reader is Reading!')
lock.acquire() #Acquire the lock before Reading (mutex approach)
print('Shared Data:', x)
lock.release() #Release the lock after Reading
print()
| def Reader():
| global x
print('Reader is Reading!')
lock.acquire() #Acquire the lock before Reading (mutex approach)
print('Shared Data:', x)
lock.release() #Release the lock after Reading
print()
| 2021 Edgar Barrera
#In this example, we will see how to implement a simple reader Writer program using Python (Mutex)
import threading as thread
import random
global x #Shared Data
x = 0
lock = thread.Lock() #Lock for synchronising access
def Reader():
| 64 | 64 | 52 | 3 | 60 | EdgarCastillo101/Python | Python Programs & Projects/P36_SimpleReaderWriter.py | Python | Reader | Reader | 13 | 19 | 13 | 13 | 26434c2002d124264456de75ed3e7c6113a0bc16 | bigcode/the-stack | train |
ac59a443b82d56eb7e970172 | train | function | def Writer():
global x
print('Writer is Writing!')
lock.acquire() #Acquire the lock before Writing
x += 1 #Write on the shared memory
print('Writer is Releasing the lock!')
lock.release() #Release the lock after Writing
print()
| def Writer():
| global x
print('Writer is Writing!')
lock.acquire() #Acquire the lock before Writing
x += 1 #Write on the shared memory
print('Writer is Releasing the lock!')
lock.release() #Release the lock after Writing
print()
| () #Lock for synchronising access
def Reader():
global x
print('Reader is Reading!')
lock.acquire() #Acquire the lock before Reading (mutex approach)
print('Shared Data:', x)
lock.release() #Release the lock after Reading
print()
def Writer():
| 64 | 64 | 64 | 3 | 61 | EdgarCastillo101/Python | Python Programs & Projects/P36_SimpleReaderWriter.py | Python | Writer | Writer | 21 | 28 | 21 | 21 | 2446ec14ed140d2bba0dbad0b0b31dc364a6ad1c | bigcode/the-stack | train |
e60b50f371f8b81e836fdb7c | train | function | async def system():
train = Train('My Train')
| async def system():
| train = Train('My Train')
| await sleep(3)
for i in range(100,10,-10):
self.message_info(f'ramping down speed {i}')
await self.motor.ramp_speed(i, 900) # Ramp to new speed in 0.9 seconds
await sleep(3)
async def system():
| 64 | 64 | 12 | 4 | 60 | ElTentakel/bricknil | examples/train_iv.py | Python | system | system | 37 | 38 | 37 | 37 | e9b610d7e5aba118d696fa3f0200cd1ea26ea5c1 | bigcode/the-stack | train |
6d9e6d738917d0635bc05548 | train | class | @attach(CurrentSensor, name='current', capabilities=[('sense_l', 2)])
@attach(TrainMotor, name='motor')
class Train(PoweredUpHub):
async def voltage_change(self):
mv = self.voltage.value
self.message_info(f'train voltage {mv}')
async def current_change(self):
ma = self.current.value
... | @attach(CurrentSensor, name='current', capabilities=[('sense_l', 2)])
@attach(TrainMotor, name='motor')
class Train(PoweredUpHub):
| async def voltage_change(self):
mv = self.voltage.value
self.message_info(f'train voltage {mv}')
async def current_change(self):
ma = self.current.value
self.message_info(f'train current {ma}')
async def run(self):
self.message_info("Running")
await self.mo... | import PoweredUpHub
from bricknil.sensor import TrainMotor, VisionSensor, Button, LED, VoltageSensor, CurrentSensor
from bricknil.const import Color
@attach(CurrentSensor, name='current', capabilities=[('sense_l', 2)])
@attach(TrainMotor, name='motor')
class Train(PoweredUpHub):
| 68 | 68 | 227 | 35 | 32 | ElTentakel/bricknil | examples/train_iv.py | Python | Train | Train | 9 | 34 | 9 | 12 | 7b156cc20816764c4897a4dd06f5be9ffaa6299a | bigcode/the-stack | train |
40fd121b46a30785d1723d2b | train | class | class Commodity(Document):
pass
| class Commodity(Document):
| pass
| # -*- coding: utf-8 -*-
# Copyright (c) 2018, Zaqout and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Commodity(Document):
| 55 | 64 | 6 | 4 | 50 | ahmadRagheb/tripoli | tripoli/basic/doctype/commodity/commodity.py | Python | Commodity | Commodity | 9 | 10 | 9 | 9 | 42bf525211fc79d17d737b34a2d31e449ed33daf | bigcode/the-stack | train |
c2527b4813938286176909b3 | train | class | class MyTime:
def __init__(self, hours:int, minutes: int, seconds: int):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def __eq__(self, other):
return (
self.hours == other.hours and
self.minutes == other.minutes and
self.s... | class MyTime:
| def __init__(self, hours:int, minutes: int, seconds: int):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def __eq__(self, other):
return (
self.hours == other.hours and
self.minutes == other.minutes and
self.seconds == other... | """
Создать класс MyTime. Атрибуты: hours, minutes, seconds. Методы: переопределить магические методы сравнения
(==, !=, >=, <=, <, >).
"""
class MyTime:
| 49 | 64 | 77 | 4 | 45 | ZemlikSasha/lessons | lesson10/solution_1.py | Python | MyTime | MyTime | 6 | 18 | 6 | 7 | 2e80449de2bc660ac8aeb062fe5a8d88931f4842 | bigcode/the-stack | train |
583fdf4da35a41a63938e2a7 | train | function | def execute_cmd (cmd):
if os.name=="nt":
process = Popen(cmd.split(),stdin=PIPE, shell=True)
else:
process = Popen(cmd.split(),stdin=PIPE)
stdout, stderr = process.communicate()
if (stderr is not None):
raise Exception(stderr)
| def execute_cmd (cmd):
| if os.name=="nt":
process = Popen(cmd.split(),stdin=PIPE, shell=True)
else:
process = Popen(cmd.split(),stdin=PIPE)
stdout, stderr = process.communicate()
if (stderr is not None):
raise Exception(stderr)
| #This version of the script is for the "new" platform version in the July release
# requires installation of Docker: https://docs.docker.com/install/
from subprocess import check_output, CalledProcessError, STDOUT, Popen, PIPE
import os
import getpass
def execute_cmd (cmd):
| 64 | 64 | 65 | 6 | 57 | daveRendon/azure_arc | arc_data_services/deploy/scripts/pull-and-push-arc-data-services-images-to-private-registry.py | Python | execute_cmd | execute_cmd | 9 | 16 | 9 | 9 | 13b106e946e925701bd94e112fbd735a7178d9b8 | bigcode/the-stack | train |
562625d8b3e2726854bb4eb4 | train | function | async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(
file_name='AnimatedSticker.tgs') in reply_message.media.document.a... | async def check_media(reply_message):
| if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(
file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return Fals... | main image and sharpen the hell out of it
img = Image.blend(img, overlay, uniform(0.1, 0.4))
img = ImageEnhance.Sharpness(img).enhance(randint(5, 300))
return img
async def check_media(reply_message):
| 64 | 64 | 125 | 7 | 56 | aashiq075/PepeBot | stdplugins/deepfry.py | Python | check_media | check_media | 115 | 134 | 115 | 115 | 25ccce929915f0870e3e96ed92c4efdae70032fe | bigcode/the-stack | train |
120dfb1706d0fa2e5da84bee | train | function | @borg.on(admin_cmd(pattern="deep(?: |$)(.*)", outgoing=True))
async def deepfryer(event):
try:
frycount = int(event.pattern_match.group(1))
if frycount < 1:
raise ValueError
except ValueError:
frycount = 1
if event.is_reply:
reply_message = await event.get_reply_... | @borg.on(admin_cmd(pattern="deep(?: |$)(.*)", outgoing=True))
async def deepfryer(event):
| try:
frycount = int(event.pattern_match.group(1))
if frycount < 1:
raise ValueError
except ValueError:
frycount = 1
if event.is_reply:
reply_message = await event.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, boo... | IN THE
# SOFTWARE.
""" Userbot module for frying stuff. ported by @NeoMatrix90 """
import io
from random import randint, uniform
from PIL import Image, ImageEnhance, ImageOps
from telethon.tl.types import DocumentAttributeFilename
from uniborg.util import admin_cmd
@borg.on(admin_cmd(pattern="deep(?: |$)(.*)", outg... | 88 | 88 | 296 | 24 | 63 | aashiq075/PepeBot | stdplugins/deepfry.py | Python | deepfryer | deepfryer | 42 | 78 | 42 | 43 | 532ee5757a5dd4bdf6b719033f51594acba211eb | bigcode/the-stack | train |
602db57eefb2c8bdb357cb41 | train | function | async def deepfry(img: Image) -> Image:
colours = (
(randint(50, 200), randint(40, 170), randint(40, 190)),
(randint(190, 255), randint(170, 240), randint(180, 250))
)
img = img.copy().convert("RGB")
# Crush image to hell and back
img = img.convert("RGB")
width, height = img.wi... | async def deepfry(img: Image) -> Image:
| colours = (
(randint(50, 200), randint(40, 170), randint(40, 190)),
(randint(190, 255), randint(170, 240), randint(180, 250))
)
img = img.copy().convert("RGB")
# Crush image to hell and back
img = img.convert("RGB")
width, height = img.width, img.height
img = img.resize((in... | image = io.BytesIO()
await event.client.download_media(data, image)
image = Image.open(image)
# fry the image
await event.edit("`Petrol dal ke Phook Rela Hoon....\nWait...`")
for _ in range(frycount):
image = await deepfry(image)
fried_io = io.BytesIO()
fried_io.name = "image.j... | 125 | 125 | 417 | 12 | 113 | aashiq075/PepeBot | stdplugins/deepfry.py | Python | deepfry | deepfry | 81 | 112 | 81 | 81 | 396f13816745d734f355e9386937de1a923b4c2c | bigcode/the-stack | train |
d78940f62d23dd4cfc6a39e9 | train | class | class OperatorInfoModel(object):
def __init__(self):
self._cid = None
self._email = None
self._job_id = None
self._job_tree = None
self._mobile = None
self._name = None
self._nick_name = None
self._operator_id = None
self._operator_type = None... | class OperatorInfoModel(object):
| def __init__(self):
self._cid = None
self._email = None
self._job_id = None
self._job_tree = None
self._mobile = None
self._name = None
self._nick_name = None
self._operator_id = None
self._operator_type = None
self._role_id = None
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class OperatorInfoModel(object):
| 37 | 256 | 1,544 | 6 | 31 | articuly/alipay-sdk-python-all | alipay/aop/api/domain/OperatorInfoModel.py | Python | OperatorInfoModel | OperatorInfoModel | 8 | 226 | 8 | 9 | daa09f6502bafbd134fb5e0b811f65b52cb0e1c2 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.