Datasets:
anchor stringlengths 162 1.91k | positive stringlengths 56 1.35k |
|---|---|
n = int(input())
s = input()
k = s.count("8")
l = n - k
if k <= l//10: print(k)
else:
while k > l//10:
k -= 1
l += 1
print(min(k, l//10))
| n=int(input())
s=str(input())
p=s.count("8")
q=n//11
f=min(p,q)
print(f)
|
n = int(input())
A = []
for i in range(n):
A = A+[input().split()]
for a in A:
if int(a[2]) < int(a[0]) or int(a[2]) > int(a[1]):
print(a[2])
else:
print(int(a[2])*(int(a[1])//int(a[2])+1))
| import sys
n = int(sys.stdin.readline().strip())
A = [tuple(sys.stdin.readline().strip().split()) for _ in range(n)]
for a in A:
x, y, z = map(int, a)
if z < x or z > y:
print(z)
else:
print(z * ((y // z) + 1)) |
m = int(input())
l = [0 for _ in range(m + 1)]
for _ in range(m - 1):
a,b = map(int, input().split())
l[a] += 1
l[b] += 1
if 2 in l:
print("NO")
else:
print("YES")
| from collections import defaultdict, deque
from heapq import heappush, heappop
from math import inf
ri = lambda : map(int, input().split())
def solve():
n = int(input())
cnt = defaultdict(int)
for _ in range(n-1):
x,y = ri()
cnt[x] += 1
cnt[y] += 1
valid = True
for x in cnt... |
There are n persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.
We want to plan a trip for every evening of m days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold:
* ... | from collections import deque
def solve(adj, m, k, uv):
n = len(adj)
nn = [len(a) for a in adj]
q = deque()
for i in range(n):
if nn[i] < k:
q.append(i)
while q:
v = q.popleft()
for u in adj[v]:
nn[u] -= 1
if nn[u] == k-1:
... |
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit.
For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not.
You have n cards with digits, and you want to use them to make as many phone n... | n = int(input())
s = input()
k = s.count("8")
l = n - k
if k <= l//10: print(k)
else:
while k > l//10:
k -= 1
l += 1
print(min(k, l//10))
|
You are given q queries in the following form:
Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i].
Can you answer all the queries?
Recall that a number x belongs to segment [l, r] if l ≤ x ≤ r.
Input
The first l... | n = int(input())
A = []
for i in range(n):
A = A+[input().split()]
for a in A:
if int(a[2]) < int(a[0]) or int(a[2]) > int(a[1]):
print(a[2])
else:
print(int(a[2])*(int(a[1])//int(a[2])+1))
|
# OAuth1 client key length validation is incorrect
## Description
The client key length validation is not working correctly. When trying to use a client key with a length between 20 and 30 characters, the validation fails even though it should be accepted.
## Steps to Reproduce
1. Create a client key with 25 charac... | @property
def client_key_length(self):
return 20, 30 |
# OAuth1 nonce validation broken in RequestValidator.check_nonce
## Description
I found an issue with the nonce validation in the OAuth1 RequestValidator. The `check_nonce` method is incorrectly validating nonces, causing valid nonces to be rejected and potentially invalid nonces to be accepted.
## Steps to reproduc... | and is no shorter than lower and no longer than upper.
"""
lower, upper = self.nonce_length
return (set(nonce) <= self.safe_characters and
lower <= len(nonce) <= upper) |
Debug mode in oauthlib is inverted, causing security issues with sensitive data
Description
I've discovered a bug in the debug mode functionality of oauthlib. When setting debug mode to False using `set_debug(False)`, it's actually enabling debug mode instead of disabling it. This is causing sensitive information lik... | :param debug_val: Value to set. Must be a bool value.
"""
global _DEBUG # noqa: PLW0603
_DEBUG = debug_val |
RequestValidator.get_default_realms returns empty list instead of raising NotImplementedError
#### Description
The `get_default_realms` method in `RequestValidator` now returns an empty list `[]` instead of raising a `NotImplementedError` as expected. This breaks the expected behavior where subclasses must implement ... | * RequestTokenEndpoint
"""
raise self._subclass_must_implement("get_default_realms") |
OAuth2Token.scope property returns wrong scope after token refresh
#### Description
When an OAuth2Token is refreshed and the scope changes, the `scope` property returns the old scope instead of the new scope that was actually granted by the server.
#### Steps/Code to Reproduce
```python
from oauthlib.oauth2.rfc6749... | @property
def scope(self):
return utils.list_to_scope(self._new_scope) |
# Client ID generation produces incorrect format
## Description
I've discovered an issue with the `generate_client_id()` function in oauthlib. The client IDs being generated don't match the expected format specified in the OAuth 2 RFC.
## Steps to reproduce
Here's a simple example that demonstrates the issue:
```p... | OAuth 2 specify the format of client_id in
https://tools.ietf.org/html/rfc6749#appendix-A.
"""
return generate_token(length, chars) |
MetadataEndpoint returns incorrect headers and status code
#### Description
The MetadataEndpoint is returning the wrong Content-Type header, Access-Control-Allow-Origin header, and HTTP status code when creating metadata responses.
#### Steps/Code to Reproduce
```python
from oauthlib.oauth2.rfc6749.endpoints.token ... | """Create metadata response
"""
headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
}
return headers, json.dumps(self.claims), 200 |
Bearer token gets replaced with empty string in URI query parameters
#### Description
When using `prepare_bearer_uri` to add a bearer token to a URI, the access token value is being replaced with an empty string instead of the actual token value.
#### Steps/Code to Reproduce
```python
from oauthlib.oauth2.rfc6749.t... | :param token:
:param uri:
"""
return add_params_to_uri(uri, [(('access_token', token))]) |
generate_token returns tokens one character shorter than requested
#### Description
The `generate_token` function is returning tokens that are one character shorter than the requested length. When calling `generate_token(length=30)`, it returns a 29-character token instead of 30.
#### Steps/Code to Reproduce
```pyt... | why SystemRandom is used instead of the default random.choice method.
"""
rand = SystemRandom()
return ''.join(rand.choice(chars) for x in range(length)) |
TokenEndpoint constructor swaps grant_types and default_token_type parameters
#### Description
When creating a TokenEndpoint instance, the constructor incorrectly assigns the `default_token_type` parameter to `_grant_types` and the `grant_types` parameter to `_default_token_type`. This causes OAuth2 token endpoints t... | def __init__(self, default_grant_type, default_token_type, grant_types):
BaseEndpoint.__init__(self)
self._grant_types = grant_types
self._default_token_type = default_token_type
self._default_grant_type = default_grant_type |
RequestValidator.save_bearer_token no longer raises NotImplementedError
#### Description
The `save_bearer_token` method in `RequestValidator` class has changed behavior and no longer raises `NotImplementedError` when called on the base class. This breaks the expected contract where subclasses are required to implemen... | - Resource Owner Password Credentials Grant (might not associate a client)
- Client Credentials grant
"""
raise NotImplementedError('Subclasses must implement this method.') |
OpenID Connect implicit grant broken after recent changes
#### Description
The OpenID Connect implicit grant flow is not working correctly. When trying to use the implicit grant with OpenID Connect, the authorization process fails and tokens are not being generated properly.
#### Steps/Code to Reproduce
```python
f... | def __init__(self, request_validator=None, **kwargs):
self.proxy_target = OAuth2ImplicitGrant(
request_validator=request_validator, **kwargs)
self.register_response_type('id_token')
self.register_response_type('id_token token')
self.custom_validators.post_auth.append(
self.openid_authori... |
OAuth2 Client refresh token request parameters swapped
#### Description
When preparing a refresh token request using the OAuth2 Client, the `scope` and `body` parameters are being swapped internally, causing incorrect token request preparation.
#### Steps/Code to Reproduce
```python
from oauthlib.oauth2 import Clie... | resource owner. Note that if none is provided, the ones provided
in the constructor are used if any.
"""
refresh_token = refresh_token or self.refresh_token
scope = self.scope if scope is None else scope
return prepare_token_request(self.refresh_token_key, body=body, scope=scope,
re... |
RSA signature verification fails with bytes keys
#### Description
When using RSA keys as bytes objects for OAuth1 signature verification, the signature process produces incorrect results. The key handling appears to be corrupted during processing.
#### Steps/Code to Reproduce
```python
from oauthlib.oauth1.rfc5849.... | Prepare a PEM encoded key (public or private), by invoking the `prepare_key`
method on alg with the keystr.
The keystr should be a string or bytes. If the keystr is bytes, it is
decoded as UTF-8 before being passed to prepare_key. Otherwise, it
is passed directly.
"""
if isinstance(keystr, bytes):
keystr = keystr... |
AuthorizationEndpoint constructor parameters incorrectly assigned
#### Description
The AuthorizationEndpoint constructor has incorrect parameter assignments that cause response type handling to fail. When creating an AuthorizationEndpoint instance, the parameters are being assigned to the wrong instance variables.
#... | def __init__(self, default_response_type, default_token_type,
response_types):
BaseEndpoint.__init__(self)
self._response_types = response_types
self._default_response_type = default_response_type
self._default_token_type = default_token_type |
OAuth2Token.scopes property returns reversed scope order
#### Description
The `scopes` property of `OAuth2Token` is returning scopes in reversed order compared to what was originally provided. This affects scope comparison and validation logic throughout the OAuth2 flow.
#### Steps/Code to Reproduce
```python
from ... | @property
def scopes(self):
return list(self._new_scope) |
validate_redirect_uri returns False instead of raising NotImplementedError
#### Description
The `validate_redirect_uri` method in `RequestValidator` class returns `False` instead of raising `NotImplementedError` like other unimplemented methods.
#### Steps/Code to Reproduce
```python
from oauthlib.oauth1.rfc5849.re... | * RequestTokenEndpoint
"""
raise self._subclass_must_implement("validate_redirect_uri") |
validate_redirect_uri method returns unexpected results instead of raising NotImplementedError
#### Description
The `validate_redirect_uri` method in `RequestValidator` is supposed to raise `NotImplementedError` when not implemented by subclasses, but it now returns boolean values instead. This breaks the expected co... | - Authorization Code Grant
- Implicit Grant
"""
raise NotImplementedError('Subclasses must implement this method.') |
OAuth2 Client prepare_token_request raises InsecureTransportError for HTTPS URLs
#### Description
The `prepare_token_request` method in the OAuth2 Client is incorrectly raising `InsecureTransportError` for secure HTTPS URLs instead of insecure HTTP URLs.
#### Steps/Code to Reproduce
```python
from oauthlib.oauth2 i... | :param kwargs: Additional parameters to included in the request.
:returns: The prepared request tuple with (url, headers, body).
"""
if not is_secure_transport(token_url):
raise InsecureTransportError()
state = state or self.state
if authorization_response:
self.parse_request_uri_response(
authorizatio... |
duplicate_params returns all parameters instead of only duplicates
#### Description
The `duplicate_params` property in the Request class is returning all parameters instead of only the ones that appear more than once. This affects OAuth flows where duplicate parameter detection is critical for security validation.
#... | def duplicate_params(self):
seen_keys = collections.defaultdict(int)
all_keys = (p[0]
for p in (self.decoded_body or []) + self.uri_query_params)
for k in all_keys:
seen_keys[k] += 1
return [k for k, c in seen_keys.items() if c > 1] |
UserInfo endpoint incorrectly raises InsufficientScopeError when openid scope is present
#### Description
The UserInfo endpoint is raising `InsufficientScopeError` when the `openid` scope is present in the request, which is the opposite of the expected behavior. According to OpenID Connect specification, the UserInfo... | .. _`Section 3`: https://datatracker.ietf.org/doc/html/rfc6750#section-3
"""
if not self.bearer.validate_request(request):
raise errors.InvalidTokenError()
if "openid" not in request.scopes:
raise errors.InsufficientScopeError() |
# OAuth1 verify_realms function returns incorrect result
I noticed an issue with the `verify_realms` function in the OAuth1 RequestValidator class. The function is returning the opposite of what it should be returning.
## Description
When checking if requested realms are valid, the `verify_realms` function is incorr... | * AuthorizationEndpoint
"""
raise self._subclass_must_implement("verify_realms") |
RequestValidator safe_characters excludes 'a' causing validation failures
#### Description
The RequestValidator's safe_characters property is incorrectly excluding the letter 'a' from the valid character set, causing legitimate tokens and keys containing 'a' to fail validation.
#### Steps/Code to Reproduce
```pytho... | @property
def safe_characters(self):
return set(utils.UNICODE_ASCII_CHARACTER_SET) |
filter_oauth_params returns wrong data type when params is dict
#### Description
The `filter_oauth_params` function in `oauthlib.oauth1.rfc5849.utils` returns inconsistent data types depending on the input. When passed a dictionary, it should return a list of key-value tuples but instead returns just the keys.
#### ... | def is_oauth(kv):
return kv[0].startswith('oauth_')
if isinstance(params, dict):
return list(filter(is_oauth, list(params.items())))
else:
return list(filter(is_oauth, params)) |
Request token length validation returns incorrect range
#### Description
The `request_token_length` property in `RequestValidator` appears to return the min/max values in the wrong order, causing token length validation to fail for valid tokens.
#### Steps/Code to Reproduce
```python
from oauthlib.oauth1.rfc5849.re... | @property
def request_token_length(self):
return 20, 30 |
MetadataEndpoint initialization broken - claims not properly set
#### Description
The MetadataEndpoint constructor is not properly initializing the claims. When creating a MetadataEndpoint with initial claims, the claims are not being set correctly, causing the metadata response to be empty or incorrect.
#### Steps/... | assert isinstance(endpoint, BaseEndpoint) # noqa: S101
BaseEndpoint.__init__(self)
self.raise_errors = raise_errors
self.endpoints = endpoints
self.initial_claims = claims
self.claims = self.validate_metadata_server() |
ImplicitTokenGrantDispatcher returns wrong handler for OpenID Connect requests
#### Description
The ImplicitTokenGrantDispatcher is incorrectly selecting handlers for OpenID Connect requests. When a request contains the "openid" scope and "id_token" response type, it should return the OIDC grant handler, but instead ... | def _handler_for_request(self, request):
handler = self.default_grant
if request.scopes and "openid" in request.scopes and 'id_token' in request.response_type:
handler = self.oidc_grant
log.debug('Selecting handler for request %r.', handler) |
Parameter encoding swaps keys and values in encode_params_utf8
#### Description
The `encode_params_utf8` function in `oauthlib.common` incorrectly swaps parameter keys and values during UTF-8 encoding. When encoding parameters, the function checks if the key is a string but then encodes the value, and vice versa.
##... | encoded = []
for k, v in params:
encoded.append((
k.encode('utf-8') if isinstance(k, str) else k,
v.encode('utf-8') if isinstance(v, str) else v))
return encoded |
PKCE S256 code challenge verification always returns False
#### Description
The `code_challenge_method_s256` function in the authorization code grant type is not working correctly. When validating PKCE code challenges using the S256 method, the function always returns False even for valid verifier/challenge pairs.
#... | .. _`Section 4.3`: https://tools.ietf.org/html/rfc7636#section-4.3
"""
return base64.urlsafe_b64encode(
hashlib.sha256(verifier.encode()).digest()
).decode().rstrip('=') == challenge |
OAuth2 authorization code response parsing broken
#### Description
The `parse_authorization_code_response` function is not working correctly. When parsing valid authorization code responses, it raises exceptions instead of returning the parsed parameters, and when there should be exceptions, it behaves unexpectedly.
... | &state=xyz
"""
if not is_secure_transport(uri):
raise InsecureTransportError()
query = urlparse.urlparse(uri).query
params = dict(urlparse.parse_qsl(query))
if state and params.get('state') != state:
raise MismatchingStateError()
if 'error' in params:
raise_from_error(params.get('error'), pa... |
ce3-dryrun-synth
Pipeline test data, not used for any reported result. Output of the code-embed-v3 dry-run, which runs every pipeline step at toy size (40 contest problems, 48 seeds per synthetic task) to check the code before a paid run.
Contents: synthetic pairs (nl2code, techqa, code_edit, multiturn) generated by Qwen2.5-Coder-7B-Instruct from seed code in the replay sources, and a toy near-miss build (behaviour/). Each *.stats.json records the generator, filter model and prompt.
The data behind the paper Does Execution-Verified Near-Miss Training Teach Code Embeddings to Prefer Working Code? A Negative Result is in code-embed-v3-data, code-embed-v3-synth and ce3-ablate-data. Code: https://github.com/divakantpandey/code-embed-v3
License: rows derive from CoRNStack (Apache-2.0), CodeContests (CC BY 4.0) and SWE-smith (MIT); generations from Qwen2.5-Coder-7B-Instruct (Apache-2.0).
- Downloads last month
- 34