_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q6300 | _get_element_attr_or_none | train | def _get_element_attr_or_none(document, selector, attribute):
"""
Using a CSS selector, get the element and return the given attribute value, or None if no element.
Args:
document (HTMLElement) - HTMLElement document
selector (str) - CSS selector
attribute (str) - The attribute to g... | python | {
"resource": ""
} |
q6301 | parse_profile_from_hcard | train | def parse_profile_from_hcard(hcard: str, handle: str):
"""
Parse all the fields we can from a hCard document to get a Profile.
:arg hcard: HTML hcard document (str)
:arg handle: User handle in username@domain.tld format
:returns: ``federation.entities.diaspora.entities.DiasporaProfile`` instance
... | python | {
"resource": ""
} |
q6302 | retrieve_and_parse_content | train | def retrieve_and_parse_content(
guid: str, handle: str, entity_type: str, sender_key_fetcher: Callable[[str], str]=None,
):
"""Retrieve remote content and return an Entity class instance.
This is basically the inverse of receiving an entity. Instead, we fetch it, then call "handle_receive".
:param... | python | {
"resource": ""
} |
q6303 | retrieve_and_parse_profile | train | def retrieve_and_parse_profile(handle):
"""
Retrieve the remote user and return a Profile object.
:arg handle: User handle in username@domain.tld format
:returns: ``federation.entities.Profile`` instance or None
"""
hcard = retrieve_diaspora_hcard(handle)
if not hcard:
return None
... | python | {
"resource": ""
} |
q6304 | get_private_endpoint | train | def get_private_endpoint(id: str, guid: str) -> str:
"""Get remote endpoint for delivering private payloads."""
_username, domain = id.split("@")
return "https://%s/receive/users/%s" % (domain, guid) | python | {
"resource": ""
} |
q6305 | struct_to_xml | train | def struct_to_xml(node, struct):
"""
Turn a list of dicts into XML nodes with tag names taken from the dict
keys and element text taken from dict values. This is a list of dicts
so that the XML nodes can be ordered in the XML output.
"""
for obj in struct:
for k, v in obj.items():
... | python | {
"resource": ""
} |
q6306 | get_full_xml_representation | train | def get_full_xml_representation(entity, private_key):
"""Get full XML representation of an entity.
This contains the <XML><post>..</post></XML> wrapper.
Accepts either a Base entity or a Diaspora entity.
Author `private_key` must be given so that certain entities can be signed.
"""
from feder... | python | {
"resource": ""
} |
q6307 | add_element_to_doc | train | def add_element_to_doc(doc, tag, value):
"""Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist."""
element = doc.find(".//%s" % tag)
if element is None:
element = etree.SubElement(doc, tag)
element.text = value | python | {
"resource": ""
} |
q6308 | generate_host_meta | train | def generate_host_meta(template=None, *args, **kwargs):
"""Generate a host-meta XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document (str)
"""... | python | {
"resource": ""
} |
q6309 | generate_legacy_webfinger | train | def generate_legacy_webfinger(template=None, *args, **kwargs):
"""Generate a legacy webfinger XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document... | python | {
"resource": ""
} |
q6310 | generate_nodeinfo2_document | train | def generate_nodeinfo2_document(**kwargs):
"""
Generate a NodeInfo2 document.
Pass in a dictionary as per NodeInfo2 1.0 schema:
https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json
Minimum required schema:
{server:
baseUrl
name
software
... | python | {
"resource": ""
} |
q6311 | generate_hcard | train | def generate_hcard(template=None, **kwargs):
"""Generate a hCard document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: HTML document (str)
"""
if template == "diaspo... | python | {
"resource": ""
} |
q6312 | retrieve_remote_content | train | def retrieve_remote_content(
id: str, guid: str=None, handle: str=None, entity_type: str=None, sender_key_fetcher: Callable[[str], str]=None,
):
"""Retrieve remote content and return an Entity object.
Currently, due to no other protocols supported, always use the Diaspora protocol.
:param sender_k... | python | {
"resource": ""
} |
q6313 | retrieve_remote_profile | train | def retrieve_remote_profile(id: str) -> Optional[Profile]:
"""High level retrieve profile method.
Retrieve the profile from a remote location, using protocol based on the given ID.
"""
protocol = identify_protocol_by_id(id)
utils = importlib.import_module(f"federation.utils.{protocol.PROTOCOL_NAME}... | python | {
"resource": ""
} |
q6314 | handle_receive | train | def handle_receive(
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False
) -> Tuple[str, str, List]:
"""Takes a request and passes it to the correct protocol.
Returns a tuple of:
- sender id
... | python | {
"resource": ""
} |
q6315 | identify_id | train | def identify_id(id: str) -> bool:
"""
Try to identify whether this is an ActivityPub ID.
"""
return re.match(r'^https?://', id, flags=re.IGNORECASE) is not None | python | {
"resource": ""
} |
q6316 | identify_request | train | def identify_request(request: RequestType) -> bool:
"""
Try to identify whether this is an ActivityPub request.
"""
# noinspection PyBroadException
try:
data = json.loads(decode_if_bytes(request.body))
if "@context" in data:
return True
except Exception:
pass
... | python | {
"resource": ""
} |
q6317 | Protocol.receive | train | def receive(
self,
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False) -> Tuple[str, dict]:
"""
Receive a request.
For testing purposes, `skip_author_ver... | python | {
"resource": ""
} |
q6318 | get_configuration | train | def get_configuration():
"""
Combine defaults with the Django configuration.
"""
configuration = {
"get_object_function": None,
"hcard_path": "/hcard/users/",
"nodeinfo2_function": None,
"process_payload_function": None,
"search_path": None,
# TODO remove ... | python | {
"resource": ""
} |
q6319 | get_function_from_config | train | def get_function_from_config(item):
"""
Import the function to get profile by handle.
"""
config = get_configuration()
func_path = config.get(item)
module_path, func_name = func_path.rsplit(".", 1)
module = importlib.import_module(module_path)
func = getattr(module, func_name)
return... | python | {
"resource": ""
} |
q6320 | ActivitypubFollow.post_receive | train | def post_receive(self) -> None:
"""
Post receive hook - send back follow ack.
"""
from federation.utils.activitypub import retrieve_and_parse_profile # Circulars
try:
from federation.utils.django import get_function_from_config
except ImportError:
... | python | {
"resource": ""
} |
q6321 | retrieve_and_parse_document | train | def retrieve_and_parse_document(fid: str) -> Optional[Any]:
"""
Retrieve remote document by ID and return the entity.
"""
document, status_code, ex = fetch_document(fid, extra_headers={'accept': 'application/activity+json'})
if document:
document = json.loads(decode_if_bytes(document))
... | python | {
"resource": ""
} |
q6322 | retrieve_and_parse_profile | train | def retrieve_and_parse_profile(fid: str) -> Optional[ActivitypubProfile]:
"""
Retrieve the remote fid and return a Profile object.
"""
profile = retrieve_and_parse_document(fid)
if not profile:
return
try:
profile.validate()
except ValueError as ex:
logger.warning("re... | python | {
"resource": ""
} |
q6323 | identify_protocol | train | def identify_protocol(method, value):
# type: (str, Union[str, RequestType]) -> str
"""
Loop through protocols, import the protocol module and try to identify the id or request.
"""
for protocol_name in PROTOCOLS:
protocol = importlib.import_module(f"federation.protocols.{protocol_name}.prot... | python | {
"resource": ""
} |
q6324 | identify_request | train | def identify_request(request: RequestType):
"""Try to identify whether this is a Diaspora request.
Try first public message. Then private message. The check if this is a legacy payload.
"""
# Private encrypted JSON payload
try:
data = json.loads(decode_if_bytes(request.body))
if "en... | python | {
"resource": ""
} |
q6325 | Protocol.get_json_payload_magic_envelope | train | def get_json_payload_magic_envelope(self, payload):
"""Encrypted JSON payload"""
private_key = self._get_user_key()
return EncryptedPayload.decrypt(payload=payload, private_key=private_key) | python | {
"resource": ""
} |
q6326 | Protocol.store_magic_envelope_doc | train | def store_magic_envelope_doc(self, payload):
"""Get the Magic Envelope, trying JSON first."""
try:
json_payload = json.loads(decode_if_bytes(payload))
except ValueError:
# XML payload
xml = unquote(decode_if_bytes(payload))
xml = xml.lstrip().encod... | python | {
"resource": ""
} |
q6327 | Protocol.receive | train | def receive(
self,
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False) -> Tuple[str, str]:
"""Receive a payload.
For testing purposes, `skip_author_verification`... | python | {
"resource": ""
} |
q6328 | Protocol.get_message_content | train | def get_message_content(self):
"""
Given the Slap XML, extract out the payload.
"""
body = self.doc.find(
".//{http://salmon-protocol.org/ns/magic-env}data").text
body = urlsafe_b64decode(body.encode("ascii"))
logger.debug("diaspora.protocol.get_message_cont... | python | {
"resource": ""
} |
q6329 | Reaction.validate_reaction | train | def validate_reaction(self):
"""Ensure reaction is of a certain type.
Mainly for future expansion.
"""
if self.reaction not in self._reaction_valid_values:
raise ValueError("reaction should be one of: {valid}".format(
valid=", ".join(self._reaction_valid_valu... | python | {
"resource": ""
} |
q6330 | Relationship.validate_relationship | train | def validate_relationship(self):
"""Ensure relationship is of a certain type."""
if self.relationship not in self._relationship_valid_values:
raise ValueError("relationship should be one of: {valid}".format(
valid=", ".join(self._relationship_valid_values)
)) | python | {
"resource": ""
} |
q6331 | activitypub_object_view | train | def activitypub_object_view(func):
"""
Generic ActivityPub object view decorator.
Takes an ID and fetches it using the provided function. Renders the ActivityPub object
in JSON if the object is found. Falls back to decorated view, if the content
type doesn't match.
"""
def inner(request, *... | python | {
"resource": ""
} |
q6332 | BaseEntity.validate | train | def validate(self):
"""Do validation.
1) Check `_required` have been given
2) Make sure all attrs in required have a non-empty value
3) Loop through attributes and call their `validate_<attr>` methods, if any.
4) Validate allowed children
5) Validate signatures
"... | python | {
"resource": ""
} |
q6333 | BaseEntity._validate_required | train | def _validate_required(self, attributes):
"""Ensure required attributes are present."""
required_fulfilled = set(self._required).issubset(set(attributes))
if not required_fulfilled:
raise ValueError(
"Not all required attributes fulfilled. Required: {required}".format... | python | {
"resource": ""
} |
q6334 | BaseEntity._validate_empty_attributes | train | def _validate_empty_attributes(self, attributes):
"""Check that required attributes are not empty."""
attrs_to_check = set(self._required) & set(attributes)
for attr in attrs_to_check:
value = getattr(self, attr) # We should always have a value here
if value is None or v... | python | {
"resource": ""
} |
q6335 | BaseEntity._validate_children | train | def _validate_children(self):
"""Check that the children we have are allowed here."""
for child in self._children:
if child.__class__ not in self._allowed_children:
raise ValueError(
"Child %s is not allowed as a children for this %s type entity." % (
... | python | {
"resource": ""
} |
q6336 | ParticipationMixin.validate_participation | train | def validate_participation(self):
"""Ensure participation is of a certain type."""
if self.participation not in self._participation_valid_values:
raise ValueError("participation should be one of: {valid}".format(
valid=", ".join(self._participation_valid_values)
)... | python | {
"resource": ""
} |
q6337 | RawContentMixin.tags | train | def tags(self):
"""Returns a `set` of unique tags contained in `raw_content`."""
if not self.raw_content:
return set()
return {word.strip("#").lower() for word in self.raw_content.split() if word.startswith("#") and len(word) > 1} | python | {
"resource": ""
} |
q6338 | handle_create_payload | train | def handle_create_payload(
entity: BaseEntity,
author_user: UserType,
protocol_name: str,
to_user_key: RsaKey = None,
parent_user: UserType = None,
) -> str:
"""Create a payload with the given protocol.
Any given user arguments must have ``private_key`` and ``handle`` at... | python | {
"resource": ""
} |
q6339 | MagicEnvelope.get_sender | train | def get_sender(doc):
"""Get the key_id from the `sig` element which contains urlsafe_b64encoded Diaspora handle.
:param doc: ElementTree document
:returns: Diaspora handle
"""
key_id = doc.find(".//{%s}sig" % NAMESPACE).get("key_id")
return urlsafe_b64decode(key_id).deco... | python | {
"resource": ""
} |
q6340 | MagicEnvelope.create_payload | train | def create_payload(self):
"""Create the payload doc.
Returns:
str
"""
doc = etree.fromstring(self.message)
self.payload = etree.tostring(doc, encoding="utf-8")
self.payload = urlsafe_b64encode(self.payload).decode("ascii")
return self.payload | python | {
"resource": ""
} |
q6341 | MagicEnvelope._build_signature | train | def _build_signature(self):
"""Create the signature using the private key."""
sig_contents = \
self.payload + "." + \
b64encode(b"application/xml").decode("ascii") + "." + \
b64encode(b"base64url").decode("ascii") + "." + \
b64encode(b"RSA-SHA256").decode(... | python | {
"resource": ""
} |
q6342 | MagicEnvelope.verify | train | def verify(self):
"""Verify Magic Envelope document against public key."""
if not self.public_key:
self.fetch_public_key()
data = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}data").text
sig = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}sig").text... | python | {
"resource": ""
} |
q6343 | DiasporaEntityMixin.extract_mentions | train | def extract_mentions(self):
"""
Extract mentions from an entity with ``raw_content``.
:return: set
"""
if not hasattr(self, "raw_content"):
return set()
mentions = re.findall(r'@{[^;]+; [\w.-]+@[^}]+}', self.raw_content)
if not mentions:
r... | python | {
"resource": ""
} |
q6344 | fetch_country_by_ip | train | def fetch_country_by_ip(ip):
"""
Fetches country code by IP
Returns empty string if the request fails in non-200 code.
Uses the ipdata.co service which has the following rules:
* Max 1500 requests per day
See: https://ipdata.co/docs.html#python-library
"""
iplookup = ipdata.ipdata()
... | python | {
"resource": ""
} |
q6345 | fetch_document | train | def fetch_document(url=None, host=None, path="/", timeout=10, raise_ssl_errors=True, extra_headers=None):
"""Helper method to fetch remote document.
Must be given either the ``url`` or ``host``.
If ``url`` is given, only that will be tried without falling back to http from https.
If ``host`` given, `pa... | python | {
"resource": ""
} |
q6346 | fetch_host_ip | train | def fetch_host_ip(host: str) -> str:
"""
Fetch ip by host
"""
try:
ip = socket.gethostbyname(host)
except socket.gaierror:
return ''
return ip | python | {
"resource": ""
} |
q6347 | fetch_host_ip_and_country | train | def fetch_host_ip_and_country(host: str) -> Tuple:
"""
Fetch ip and country by host
"""
ip = fetch_host_ip(host)
if not host:
return '', ''
country = fetch_country_by_ip(ip)
return ip, country | python | {
"resource": ""
} |
q6348 | parse_http_date | train | def parse_http_date(date):
"""
Parse a date format as specified by HTTP RFC7231 section 7.1.1.1.
The three formats allowed by the RFC are accepted, even if only the first
one is still in widespread use.
Return an integer expressed in seconds since the epoch, in UTC.
Implementation copied from... | python | {
"resource": ""
} |
q6349 | send_document | train | def send_document(url, data, timeout=10, *args, **kwargs):
"""Helper method to send a document via POST.
Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``.
:arg url: Full url to send to, including protocol
:arg data: Dictionary (will be form-encoded), bytes, or file-like obj... | python | {
"resource": ""
} |
q6350 | get_http_authentication | train | def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth:
"""
Get HTTP signature authentication for a request.
"""
key = private_key.exportKey()
return HTTPSignatureHeaderAuth(
headers=["(request-target)", "user-agent", "host", "date"],
algorit... | python | {
"resource": ""
} |
q6351 | verify_request_signature | train | def verify_request_signature(request: RequestType, public_key: Union[str, bytes]):
"""
Verify HTTP signature in request against a public key.
"""
key = encode_if_text(public_key)
date_header = request.headers.get("Date")
if not date_header:
raise ValueError("Rquest Date header is missing... | python | {
"resource": ""
} |
q6352 | DiasporaRetraction.entity_type_to_remote | train | def entity_type_to_remote(value):
"""Convert entity type between our Entity names and Diaspora names."""
if value in DiasporaRetraction.mapped.values():
values = list(DiasporaRetraction.mapped.values())
index = values.index(value)
return list(DiasporaRetraction.mapped... | python | {
"resource": ""
} |
q6353 | get_base_attributes | train | def get_base_attributes(entity):
"""Build a dict of attributes of an entity.
Returns attributes and their values, ignoring any properties, functions and anything that starts
with an underscore.
"""
attributes = {}
cls = entity.__class__
for attr, _ in inspect.getmembers(cls, lambda o: not i... | python | {
"resource": ""
} |
q6354 | pkcs7_unpad | train | def pkcs7_unpad(data):
"""
Remove the padding bytes that were added at point of encryption.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
"""
if isinstance(data, str):
return data[0:-ord(data[-1])]
else:
... | python | {
"resource": ""
} |
q6355 | EncryptedPayload.decrypt | train | def decrypt(payload, private_key):
"""Decrypt an encrypted JSON payload and return the Magic Envelope document inside."""
cipher = PKCS1_v1_5.new(private_key)
aes_key_str = cipher.decrypt(b64decode(payload.get("aes_key")), sentinel=None)
aes_key = json.loads(aes_key_str.decode("utf-8"))
... | python | {
"resource": ""
} |
q6356 | EncryptedPayload.encrypt | train | def encrypt(payload, public_key):
"""
Encrypt a payload using an encrypted JSON wrapper.
See: https://diaspora.github.io/diaspora_federation/federation/encryption.html
:param payload: Payload document as a string.
:param public_key: Public key of recipient as an RSA object.
... | python | {
"resource": ""
} |
q6357 | ProsaicArgParser.template | train | def template(self):
"""Returns the template in JSON form"""
if self._template:
return self._template
template_json = self.read_template(self.args.tmplname)
self._template = loads(template_json)
return self._template | python | {
"resource": ""
} |
q6358 | BaseFormatter.override_level_names | train | def override_level_names(self, mapping):
"""Rename level names.
:param mapping: Mapping level names to new ones
:type mapping: dict
"""
if not isinstance(mapping, dict):
return
for key, val in mapping.items():
if key in self._level_names:
... | python | {
"resource": ""
} |
q6359 | TextFormatter.override_colors | train | def override_colors(self, colors):
"""Override default color of elements.
:param colors: New color value for given elements
:type colors: dict
"""
if not isinstance(colors, dict):
return
for key in self._color[True]:
if key in colors:
... | python | {
"resource": ""
} |
q6360 | JsonFormatter.__prepare_record | train | def __prepare_record(self, record, enabled_fields):
"""Prepare log record with given fields."""
message = record.getMessage()
if hasattr(record, 'prefix'):
message = "{}{}".format((str(record.prefix) + ' ') if record.prefix else '', message)
obj = {
'name': recor... | python | {
"resource": ""
} |
q6361 | JsonFormatter.__obj2json | train | def __obj2json(self, obj):
"""Serialize obj to a JSON formatted string.
This is useful for pretty printing log records in the console.
"""
return json.dumps(obj, indent=self._indent, sort_keys=self._sort_keys) | python | {
"resource": ""
} |
q6362 | validate_host | train | def validate_host(cert, name):
"""
Validates host name against certificate
@param cert: Certificate returned by host
@param name: Actual host name used for connection
@return: Returns true if host name matches certificate
"""
cn = None
for t, v in cert.get_subject().get_components():
... | python | {
"resource": ""
} |
q6363 | revert_to_clear | train | def revert_to_clear(tds_sock):
"""
Reverts connection back to non-encrypted mode
Used when client sent ENCRYPT_OFF flag
@param tds_sock:
@return:
"""
enc_conn = tds_sock.conn.sock
clear_conn = enc_conn._transport
enc_conn.shutdown()
tds_sock.conn.sock = clear_conn
tds_sock._w... | python | {
"resource": ""
} |
q6364 | tds7_crypt_pass | train | def tds7_crypt_pass(password):
""" Mangle password according to tds rules
:param password: Password str
:returns: Byte-string with encoded password
"""
encoded = bytearray(ucs2_codec.encode(password)[0])
for i, ch in enumerate(encoded):
encoded[i] = ((ch << 4) & 0xff | (ch >> 4)) ^ 0xA5... | python | {
"resource": ""
} |
q6365 | _TdsReader.unpack | train | def unpack(self, struc):
""" Unpacks given structure from stream
:param struc: A struct.Struct instance
:returns: Result of unpacking
"""
buf, offset = readall_fast(self, struc.size)
return struc.unpack_from(buf, offset) | python | {
"resource": ""
} |
q6366 | _TdsReader.read_ucs2 | train | def read_ucs2(self, num_chars):
""" Reads num_chars UCS2 string from the stream """
buf = readall(self, num_chars * 2)
return ucs2_codec.decode(buf)[0] | python | {
"resource": ""
} |
q6367 | _TdsReader._read_packet | train | def _read_packet(self):
""" Reads next TDS packet from the underlying transport
If timeout is happened during reading of packet's header will
cancel current request.
Can only be called when transport's read pointer is at the begining
of the packet.
"""
try:
... | python | {
"resource": ""
} |
q6368 | _TdsReader.read_whole_packet | train | def read_whole_packet(self):
""" Reads single packet and returns bytes payload of the packet
Can only be called when transport's read pointer is at the beginning
of the packet.
"""
self._read_packet()
return readall(self, self._size - _header.size) | python | {
"resource": ""
} |
q6369 | _TdsWriter.write | train | def write(self, data):
""" Writes given bytes buffer into the stream
Function returns only when entire buffer is written
"""
data_off = 0
while data_off < len(data):
left = len(self._buf) - self._pos
if left <= 0:
self._write_packet(final=... | python | {
"resource": ""
} |
q6370 | _TdsWriter.write_string | train | def write_string(self, s, codec):
""" Write string encoding it with codec into stream """
for i in range(0, len(s), self.bufsize):
chunk = s[i:i + self.bufsize]
buf, consumed = codec.encode(chunk)
assert consumed == len(chunk)
self.write(buf) | python | {
"resource": ""
} |
q6371 | _TdsWriter._write_packet | train | def _write_packet(self, final):
""" Writes single TDS packet into underlying transport.
Data for the packet is taken from internal buffer.
:param final: True means this is the final packet in substream.
"""
status = 1 if final else 0
_header.pack_into(self._buf, 0, self... | python | {
"resource": ""
} |
q6372 | _TdsSession.raise_db_exception | train | def raise_db_exception(self):
""" Raises exception from last server message
This function will skip messages: The statement has been terminated
"""
if not self.messages:
raise tds_base.Error("Request failed, server didn't send error message")
msg = None
while... | python | {
"resource": ""
} |
q6373 | _TdsSession.tds7_process_result | train | def tds7_process_result(self):
""" Reads and processes COLMETADATA stream
This stream contains a list of returned columns.
Stream format link: http://msdn.microsoft.com/en-us/library/dd357363.aspx
"""
self.log_response_message('got COLMETADATA')
r = self._reader
... | python | {
"resource": ""
} |
q6374 | _TdsSession.process_param | train | def process_param(self):
""" Reads and processes RETURNVALUE stream.
This stream is used to send OUTPUT parameters from RPC to client.
Stream format url: http://msdn.microsoft.com/en-us/library/dd303881.aspx
"""
self.log_response_message('got RETURNVALUE message')
r = se... | python | {
"resource": ""
} |
q6375 | _TdsSession.process_cancel | train | def process_cancel(self):
"""
Process the incoming token stream until it finds
an end token DONE with the cancel flag set.
At that point the connection should be ready to handle a new query.
In case when no cancel request is pending this function does nothing.
"""
... | python | {
"resource": ""
} |
q6376 | _TdsSession.process_row | train | def process_row(self):
""" Reads and handles ROW stream.
This stream contains list of values of one returned row.
Stream format url: http://msdn.microsoft.com/en-us/library/dd357254.aspx
"""
self.log_response_message("got ROW message")
r = self._reader
info = sel... | python | {
"resource": ""
} |
q6377 | _TdsSession.process_nbcrow | train | def process_nbcrow(self):
""" Reads and handles NBCROW stream.
This stream contains list of values of one returned row in a compressed way,
introduced in TDS 7.3.B
Stream format url: http://msdn.microsoft.com/en-us/library/dd304783.aspx
"""
self.log_response_message("got... | python | {
"resource": ""
} |
q6378 | _TdsSession.process_auth | train | def process_auth(self):
""" Reads and processes SSPI stream.
Stream info: http://msdn.microsoft.com/en-us/library/dd302844.aspx
"""
r = self._reader
w = self._writer
pdu_size = r.get_smallint()
if not self.authentication:
raise tds_base.Error('Got une... | python | {
"resource": ""
} |
q6379 | _TdsSession.set_state | train | def set_state(self, state):
""" Switches state of the TDS session.
It also does state transitions checks.
:param state: New state, one of TDS_PENDING/TDS_READING/TDS_IDLE/TDS_DEAD/TDS_QUERING
"""
prior_state = self.state
if state == prior_state:
return state
... | python | {
"resource": ""
} |
q6380 | _TdsSession.querying_context | train | def querying_context(self, packet_type):
""" Context manager for querying.
Sets state to TDS_QUERYING, and reverts it to TDS_IDLE if exception happens inside managed block,
and to TDS_PENDING if managed block succeeds and flushes buffer.
"""
if self.set_state(tds_base.TDS_QUERYI... | python | {
"resource": ""
} |
q6381 | _TdsSession.cancel_if_pending | train | def cancel_if_pending(self):
""" Cancels current pending request.
Does nothing if no request is pending, otherwise sends cancel request,
and waits for response.
"""
if self.state == tds_base.TDS_IDLE:
return
if not self.in_cancel:
self.put_cancel(... | python | {
"resource": ""
} |
q6382 | _TdsSession.submit_rpc | train | def submit_rpc(self, rpc_name, params, flags=0):
""" Sends an RPC request.
This call will transition session into pending state.
If some operation is currently pending on the session, it will be
cancelled before sending this request.
Spec: http://msdn.microsoft.com/en-us/librar... | python | {
"resource": ""
} |
q6383 | _TdsSession.submit_plain_query | train | def submit_plain_query(self, operation):
""" Sends a plain query to server.
This call will transition session into pending state.
If some operation is currently pending on the session, it will be
cancelled before sending this request.
Spec: http://msdn.microsoft.com/en-us/libra... | python | {
"resource": ""
} |
q6384 | _TdsSession.submit_bulk | train | def submit_bulk(self, metadata, rows):
""" Sends insert bulk command.
Spec: http://msdn.microsoft.com/en-us/library/dd358082.aspx
:param metadata: A list of :class:`Column` instances.
:param rows: A collection of rows, each row is a collection of values.
:return:
"""
... | python | {
"resource": ""
} |
q6385 | _TdsSession.put_cancel | train | def put_cancel(self):
""" Sends a cancel request to the server.
Switches connection to IN_CANCEL state.
"""
logger.info('Sending CANCEL')
self._writer.begin_packet(tds_base.PacketType.CANCEL)
self._writer.flush()
self.in_cancel = 1 | python | {
"resource": ""
} |
q6386 | iterdecode | train | def iterdecode(iterable, codec):
""" Uses an incremental decoder to decode each chunk in iterable.
This function is a generator.
:param iterable: Iterable object which yields raw data to be decoded
:param codec: An instance of codec
"""
decoder = codec.incrementaldecoder()
for chunk in iter... | python | {
"resource": ""
} |
q6387 | skipall | train | def skipall(stm, size):
""" Skips exactly size bytes in stm
If EOF is reached before size bytes are skipped
will raise :class:`ClosedConnectionError`
:param stm: Stream to skip bytes in, should have read method
this read method can return less than requested
number of b... | python | {
"resource": ""
} |
q6388 | read_chunks | train | def read_chunks(stm, size):
""" Reads exactly size bytes from stm and produces chunks
May call stm.read multiple times until required
number of bytes is read.
If EOF is reached before size bytes are read
will raise :class:`ClosedConnectionError`
:param stm: Stream to read bytes from, should ha... | python | {
"resource": ""
} |
q6389 | readall_fast | train | def readall_fast(stm, size):
"""
Slightly faster version of readall, it reads no more than two chunks.
Meaning that it can only be used to read small data that doesn't span
more that two packets.
:param stm: Stream to read from, should have read method.
:param size: Number of bytes to read.
... | python | {
"resource": ""
} |
q6390 | _decode_num | train | def _decode_num(buf):
""" Decodes little-endian integer from buffer
Buffer can be of any size
"""
return functools.reduce(lambda acc, val: acc * 256 + tds_base.my_ord(val), reversed(buf), 0) | python | {
"resource": ""
} |
q6391 | PlpReader.chunks | train | def chunks(self):
""" Generates chunks from stream, each chunk is an instace of bytes.
"""
if self.is_null():
return
total = 0
while True:
chunk_len = self._rdr.get_uint()
if chunk_len == 0:
if not self.is_unknown_len() and tota... | python | {
"resource": ""
} |
q6392 | Date.from_pydate | train | def from_pydate(cls, pydate):
"""
Creates sql date object from Python date object.
@param pydate: Python date
@return: sql date
"""
return cls(days=(datetime.datetime.combine(pydate, datetime.time(0, 0, 0)) - _datetime2_base_date).days) | python | {
"resource": ""
} |
q6393 | Time.to_pytime | train | def to_pytime(self):
"""
Converts sql time object into Python's time object
this will truncate nanoseconds to microseconds
@return: naive time
"""
nanoseconds = self._nsec
hours = nanoseconds // 1000000000 // 60 // 60
nanoseconds -= hours * 60 * 60 * 10000... | python | {
"resource": ""
} |
q6394 | Time.from_pytime | train | def from_pytime(cls, pytime):
"""
Converts Python time object to sql time object
ignoring timezone
@param pytime: Python time object
@return: sql time object
"""
secs = pytime.hour * 60 * 60 + pytime.minute * 60 + pytime.second
nsec = secs * 10 ** 9 + pyti... | python | {
"resource": ""
} |
q6395 | DateTime2.to_pydatetime | train | def to_pydatetime(self):
"""
Converts datetime2 object into Python's datetime.datetime object
@return: naive datetime.datetime
"""
return datetime.datetime.combine(self._date.to_pydate(), self._time.to_pytime()) | python | {
"resource": ""
} |
q6396 | DateTime2.from_pydatetime | train | def from_pydatetime(cls, pydatetime):
"""
Creates sql datetime2 object from Python datetime object
ignoring timezone
@param pydatetime: Python datetime object
@return: sql datetime2 object
"""
return cls(date=Date.from_pydate(pydatetime.date),
t... | python | {
"resource": ""
} |
q6397 | DateTimeOffset.to_pydatetime | train | def to_pydatetime(self):
"""
Converts datetimeoffset object into Python's datetime.datetime object
@return: time zone aware datetime.datetime
"""
dt = datetime.datetime.combine(self._date.to_pydate(), self._time.to_pytime())
from .tz import FixedOffsetTimezone
ret... | python | {
"resource": ""
} |
q6398 | TableSerializer.write_info | train | def write_info(self, w):
"""
Writes TVP_TYPENAME structure
spec: https://msdn.microsoft.com/en-us/library/dd302994.aspx
@param w: TdsWriter
@return:
"""
w.write_b_varchar("") # db_name, should be empty
w.write_b_varchar(self._table_type.typ_schema)
... | python | {
"resource": ""
} |
q6399 | TableSerializer.write | train | def write(self, w, val):
"""
Writes remaining part of TVP_TYPE_INFO structure, resuming from TVP_COLMETADATA
specs:
https://msdn.microsoft.com/en-us/library/dd302994.aspx
https://msdn.microsoft.com/en-us/library/dd305261.aspx
https://msdn.microsoft.com/en-us/library/dd30... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.