body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
d7e1ac9340803b625c3617750588889c09883bfc53b20ad7e94dc1220579a4bd | def manage_stocks(request):
'Представление: управление складами.'
from catalog.models import Stock
if (request.user.has_perm('catalog.add_stock') or request.user.has_perm('catalog.change_stock') or request.user.has_perm('catalog.delete_stock')):
stocks = Stock.objects.all().order_by('alias')
ret... | Представление: управление складами. | views.py | manage_stocks | anodos-ru/catalog | 2 | python | def manage_stocks(request):
from catalog.models import Stock
if (request.user.has_perm('catalog.add_stock') or request.user.has_perm('catalog.change_stock') or request.user.has_perm('catalog.delete_stock')):
stocks = Stock.objects.all().order_by('alias')
return render(request, 'catalog/manage_s... | def manage_stocks(request):
from catalog.models import Stock
if (request.user.has_perm('catalog.add_stock') or request.user.has_perm('catalog.change_stock') or request.user.has_perm('catalog.delete_stock')):
stocks = Stock.objects.all().order_by('alias')
return render(request, 'catalog/manage_s... |
1147f6fe5b40b296c3e821efffa46228cb3d8b60ae98f22680cf02ae94b76fcd | def manage_vendors(request):
'Представление: список производителей.'
from catalog.models import Vendor
vendors = Vendor.objects.all().order_by('name')
return render(request, 'catalog/manage_vendors.html', locals()) | Представление: список производителей. | views.py | manage_vendors | anodos-ru/catalog | 2 | python | def manage_vendors(request):
from catalog.models import Vendor
vendors = Vendor.objects.all().order_by('name')
return render(request, 'catalog/manage_vendors.html', locals()) | def manage_vendors(request):
from catalog.models import Vendor
vendors = Vendor.objects.all().order_by('name')
return render(request, 'catalog/manage_vendors.html', locals())<|docstring|>Представление: список производителей.<|endoftext|> |
649fbaffb74221ef1a8d7711f9b046224ef2d00d6bb23b0d890ed16e01220757 | def manage_categories(request):
'Представление: управление категорями.'
from catalog.models import Category
categories = []
categories = Category.objects.get_category_tree(categories)
for category in categories:
category.name = (('— ' * category.level) + category.name)
return render(requ... | Представление: управление категорями. | views.py | manage_categories | anodos-ru/catalog | 2 | python | def manage_categories(request):
from catalog.models import Category
categories = []
categories = Category.objects.get_category_tree(categories)
for category in categories:
category.name = (('— ' * category.level) + category.name)
return render(request, 'catalog/manage_categories.html', ... | def manage_categories(request):
from catalog.models import Category
categories = []
categories = Category.objects.get_category_tree(categories)
for category in categories:
category.name = (('— ' * category.level) + category.name)
return render(request, 'catalog/manage_categories.html', ... |
f8994b03af6c35b9f24c293c3e8896a9a727f6e3273671f75159c85519b9c793 | def manage_products(request, **kwargs):
'Представление: управление продуктами'
from django.db.models import Q
from catalog.models import Product, Category, Vendor
parameters_ = {}
url = '/catalog/manage/products/'
for parameter in kwargs.get('string', '').split('/'):
name = parameter.spl... | Представление: управление продуктами | views.py | manage_products | anodos-ru/catalog | 2 | python | def manage_products(request, **kwargs):
from django.db.models import Q
from catalog.models import Product, Category, Vendor
parameters_ = {}
url = '/catalog/manage/products/'
for parameter in kwargs.get('string', ).split('/'):
name = parameter.split('=')[0]
try:
valu... | def manage_products(request, **kwargs):
from django.db.models import Q
from catalog.models import Product, Category, Vendor
parameters_ = {}
url = '/catalog/manage/products/'
for parameter in kwargs.get('string', ).split('/'):
name = parameter.split('=')[0]
try:
valu... |
5b62ee829c412a77da69e613f58b33a969cef3d90374d01188499b5657917ffd | def units(request):
'Представление: список единиц измерения.'
from catalog.models import Unit
units = Unit.objects.all()
return render(request, 'catalog/units.html', locals()) | Представление: список единиц измерения. | views.py | units | anodos-ru/catalog | 2 | python | def units(request):
from catalog.models import Unit
units = Unit.objects.all()
return render(request, 'catalog/units.html', locals()) | def units(request):
from catalog.models import Unit
units = Unit.objects.all()
return render(request, 'catalog/units.html', locals())<|docstring|>Представление: список единиц измерения.<|endoftext|> |
0ee32a6ed3ea658a22909ea37883172d9974e29445a9d68570faa8a2529ad025 | def pricetypes(request):
'Представление: список типов цен.'
from catalog.models import PriceType
if (request.user.has_perm('catalog.add_pricetype') or request.user.has_perm('catalog.change_pricetype') or request.user.has_perm('catalog.delete_pricetype')):
pricetypes = PriceType.objects.all().order_b... | Представление: список типов цен. | views.py | pricetypes | anodos-ru/catalog | 2 | python | def pricetypes(request):
from catalog.models import PriceType
if (request.user.has_perm('catalog.add_pricetype') or request.user.has_perm('catalog.change_pricetype') or request.user.has_perm('catalog.delete_pricetype')):
pricetypes = PriceType.objects.all().order_by('name')
return render(reques... | def pricetypes(request):
from catalog.models import PriceType
if (request.user.has_perm('catalog.add_pricetype') or request.user.has_perm('catalog.change_pricetype') or request.user.has_perm('catalog.delete_pricetype')):
pricetypes = PriceType.objects.all().order_by('name')
return render(reques... |
ab07b2eea2d2630a47bd9ee431d00040ad203d79437bf8a9d28583b774d84edf | def currencies(request):
'Представление: список валют.'
from catalog.models import Currency
currencies = Currency.objects.all()
return render(request, 'catalog/currencies.html', locals()) | Представление: список валют. | views.py | currencies | anodos-ru/catalog | 2 | python | def currencies(request):
from catalog.models import Currency
currencies = Currency.objects.all()
return render(request, 'catalog/currencies.html', locals()) | def currencies(request):
from catalog.models import Currency
currencies = Currency.objects.all()
return render(request, 'catalog/currencies.html', locals())<|docstring|>Представление: список валют.<|endoftext|> |
fd3d8f4be0dd3bcef0ab62e52152b43710aecec6c13d55a3837b9d64e4bc8bc1 | def products(request, **kwargs):
'Представление: список продуктов.'
import unidecode
from lxml import etree
from django.db.models import Q
from catalog.models import Product, Category, Vendor
parameters_ = {}
url = '/catalog/products/'
for parameter in kwargs.get('string', '').split('/')... | Представление: список продуктов. | views.py | products | anodos-ru/catalog | 2 | python | def products(request, **kwargs):
import unidecode
from lxml import etree
from django.db.models import Q
from catalog.models import Product, Category, Vendor
parameters_ = {}
url = '/catalog/products/'
for parameter in kwargs.get('string', ).split('/'):
name = parameter.split('='... | def products(request, **kwargs):
import unidecode
from lxml import etree
from django.db.models import Q
from catalog.models import Product, Category, Vendor
parameters_ = {}
url = '/catalog/products/'
for parameter in kwargs.get('string', ).split('/'):
name = parameter.split('='... |
4b62c40b8e0f5d6ad42b95433c138899788c66b93850502daf1a7893d1762c42 | def product(request, id=None, vendor=None, article=None):
'Представление: продукт.'
from catalog.models import Vendor, Product, ProductPhoto
if id:
product = Product.objects.get(id=id)
elif (vendor and article):
vendor = Vendor.objects.get(alias=vendor)
product = Product.objects.... | Представление: продукт. | views.py | product | anodos-ru/catalog | 2 | python | def product(request, id=None, vendor=None, article=None):
from catalog.models import Vendor, Product, ProductPhoto
if id:
product = Product.objects.get(id=id)
elif (vendor and article):
vendor = Vendor.objects.get(alias=vendor)
product = Product.objects.get(vendor=vendor, articl... | def product(request, id=None, vendor=None, article=None):
from catalog.models import Vendor, Product, ProductPhoto
if id:
product = Product.objects.get(id=id)
elif (vendor and article):
vendor = Vendor.objects.get(alias=vendor)
product = Product.objects.get(vendor=vendor, articl... |
f6124b0b69498f30eab05d9304b54d9d462cb4d50f4bb8a15ac6cef53a033c79 | def ajax_get(request, *args, **kwargs):
'AJAX-представление: Get Object.'
import json
import catalog.models
model_name = kwargs.get('model_name', '')
model = catalog.models.models[model_name]
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
... | AJAX-представление: Get Object. | views.py | ajax_get | anodos-ru/catalog | 2 | python | def ajax_get(request, *args, **kwargs):
import json
import catalog.models
model_name = kwargs.get('model_name', )
model = catalog.models.models[model_name]
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
open_models = ['product', 'vendor',... | def ajax_get(request, *args, **kwargs):
import json
import catalog.models
model_name = kwargs.get('model_name', )
model = catalog.models.models[model_name]
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
open_models = ['product', 'vendor',... |
8b87ef05dc7d74407d1f8435da5a145a0bd781b098ec3dcf1903f29c3cd42a15 | def ajax_save(request, *args, **kwargs):
'AJAX-представление: Save Object.'
import json
from django.utils import timezone
import catalog.models
model = catalog.models.models[kwargs['model_name']]
result = {'status': 'success', 'reload': False}
if ((not request.is_ajax()) or (request.method !... | AJAX-представление: Save Object. | views.py | ajax_save | anodos-ru/catalog | 2 | python | def ajax_save(request, *args, **kwargs):
import json
from django.utils import timezone
import catalog.models
model = catalog.models.models[kwargs['model_name']]
result = {'status': 'success', 'reload': False}
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpRes... | def ajax_save(request, *args, **kwargs):
import json
from django.utils import timezone
import catalog.models
model = catalog.models.models[kwargs['model_name']]
result = {'status': 'success', 'reload': False}
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpRes... |
9636a11b9c356b9e8cb96ca490333b308734e77bb0ef9d6b92048132db68988b | def ajax_switch_state(request, *args, **kwargs):
'AJAX-представление: Switch State.'
import json
from django.utils import timezone
import catalog.models
model = catalog.models.models[kwargs['model_name']]
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(sta... | AJAX-представление: Switch State. | views.py | ajax_switch_state | anodos-ru/catalog | 2 | python | def ajax_switch_state(request, *args, **kwargs):
import json
from django.utils import timezone
import catalog.models
model = catalog.models.models[kwargs['model_name']]
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if (not request.user.h... | def ajax_switch_state(request, *args, **kwargs):
import json
from django.utils import timezone
import catalog.models
model = catalog.models.models[kwargs['model_name']]
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if (not request.user.h... |
6759321fe6cc767edc332964b7d3762488e8d4431be574ba81e62d979b68dfbf | def ajax_delete(request, *args, **kwargs):
'AJAX-представление: Delete Object.'
import json
import catalog.models
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if (not request.user.has_perm('catalog.delete_{}'.format(kwargs['model_name']))):
... | AJAX-представление: Delete Object. | views.py | ajax_delete | anodos-ru/catalog | 2 | python | def ajax_delete(request, *args, **kwargs):
import json
import catalog.models
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if (not request.user.has_perm('catalog.delete_{}'.format(kwargs['model_name']))):
return HttpResponse(status=403)
... | def ajax_delete(request, *args, **kwargs):
import json
import catalog.models
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if (not request.user.has_perm('catalog.delete_{}'.format(kwargs['model_name']))):
return HttpResponse(status=403)
... |
ac9a8c8375c52de702b674f190295edac1df34482b138aa7e4284c8e9ad298ea | def ajax_link(request, *args, **kwargs):
'AJAX-представление: Link Model.'
import json
from django.utils import timezone
import catalog.models
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if ((not request.user.has_perm('catalog.change_{}'.fo... | AJAX-представление: Link Model. | views.py | ajax_link | anodos-ru/catalog | 2 | python | def ajax_link(request, *args, **kwargs):
import json
from django.utils import timezone
import catalog.models
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))) or (... | def ajax_link(request, *args, **kwargs):
import json
from django.utils import timezone
import catalog.models
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))) or (... |
b0d415f1c98c3edc82f685ad99a7078e03945ee296eb28169302f891c094d93b | def ajax_link_same_foreign(request, *args, **kwargs):
'AJAX-представление: Link Model to Same Foreign.'
import json
from django.utils import timezone
import catalog.models
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if ((not request.user.ha... | AJAX-представление: Link Model to Same Foreign. | views.py | ajax_link_same_foreign | anodos-ru/catalog | 2 | python | def ajax_link_same_foreign(request, *args, **kwargs):
import json
from django.utils import timezone
import catalog.models
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_n... | def ajax_link_same_foreign(request, *args, **kwargs):
import json
from django.utils import timezone
import catalog.models
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_n... |
bc64410c88dd0fe4d6e8957cd5f3829583ed387ba8dff52957b80902a94b4e32 | def ajax_get_parties(request):
'AJAX-представление: Get Parties.'
import json
from catalog.models import Product, Party
items = []
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if request.POST.get('product_id'):
try:
produ... | AJAX-представление: Get Parties. | views.py | ajax_get_parties | anodos-ru/catalog | 2 | python | def ajax_get_parties(request):
import json
from catalog.models import Product, Party
items = []
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if request.POST.get('product_id'):
try:
product = Product.objects.get(id=reques... | def ajax_get_parties(request):
import json
from catalog.models import Product, Party
items = []
if ((not request.is_ajax()) or (request.method != 'POST')):
return HttpResponse(status=400)
if request.POST.get('product_id'):
try:
product = Product.objects.get(id=reques... |
5256303914371b40916521dd5ba37dafe035955f6c88c3c619b4af9429083a15 | @transaction.atomic()
def _process_row(self, row, cleaned_data):
'Save the data from a single row'
if row['closing']:
return 0
chain = None
if (row['zentrale'] != NULL):
(chain, __) = SupermarketChain.objects.get_or_create(name=row['zentrale'])
address = Address.objects.create(street... | Save the data from a single row | marktzeit/supermarkets/views.py | _process_row | firstdayofjune/marktzeit | 0 | python | @transaction.atomic()
def _process_row(self, row, cleaned_data):
if row['closing']:
return 0
chain = None
if (row['zentrale'] != NULL):
(chain, __) = SupermarketChain.objects.get_or_create(name=row['zentrale'])
address = Address.objects.create(street=row['strasse'], street_number=ro... | @transaction.atomic()
def _process_row(self, row, cleaned_data):
if row['closing']:
return 0
chain = None
if (row['zentrale'] != NULL):
(chain, __) = SupermarketChain.objects.get_or_create(name=row['zentrale'])
address = Address.objects.create(street=row['strasse'], street_number=ro... |
6f5a10a53193f6f670b6a61b9a4d13bad2e1030ac8ea1637842705b7db9f4a19 | def create_supermarkets(self, reader, cleaned_data):
'Create the supermarkets from the uploaded data'
created = 0
for (idx, row) in enumerate(reader):
try:
created += self._process_row(row, cleaned_data)
except Exception as e:
messages.add_message(self.request, messag... | Create the supermarkets from the uploaded data | marktzeit/supermarkets/views.py | create_supermarkets | firstdayofjune/marktzeit | 0 | python | def create_supermarkets(self, reader, cleaned_data):
created = 0
for (idx, row) in enumerate(reader):
try:
created += self._process_row(row, cleaned_data)
except Exception as e:
messages.add_message(self.request, messages.ERROR, _('Error occurred on row {}: {!r}. Row... | def create_supermarkets(self, reader, cleaned_data):
created = 0
for (idx, row) in enumerate(reader):
try:
created += self._process_row(row, cleaned_data)
except Exception as e:
messages.add_message(self.request, messages.ERROR, _('Error occurred on row {}: {!r}. Row... |
4db4b8f76f81c5ae74bcd1a574b78366db830746983ba857d71da9844f667d7c | @pytest.mark.asyncio
async def test_task_catches_cancel():
'A nasty task catches all exceptions'
async def nasty():
while True:
try:
(await asyncio.sleep(1))
print('loop')
except asyncio.CancelledError:
pass
before = time.time(... | A nasty task catches all exceptions | tests/test_cancel.py | test_task_catches_cancel | RouquinBlanc/traio | 3 | python | @pytest.mark.asyncio
async def test_task_catches_cancel():
async def nasty():
while True:
try:
(await asyncio.sleep(1))
print('loop')
except asyncio.CancelledError:
pass
before = time.time()
with pytest.raises(OSError):
... | @pytest.mark.asyncio
async def test_task_catches_cancel():
async def nasty():
while True:
try:
(await asyncio.sleep(1))
print('loop')
except asyncio.CancelledError:
pass
before = time.time()
with pytest.raises(OSError):
... |
97c7c78b90c2810f3af9389962ce4d64975a6a4f45f8c2db7f623947e4a6ebff | @pytest.mark.asyncio
async def test_external_cancel():
'Raise an external cancellation'
async def run_me():
n = Scope()
async with n:
n.spawn(run10())
assert n.cancelled()
task = asyncio.ensure_future(run_me())
try:
(await asyncio.wait_for(asyncio.shield(task... | Raise an external cancellation | tests/test_cancel.py | test_external_cancel | RouquinBlanc/traio | 3 | python | @pytest.mark.asyncio
async def test_external_cancel():
async def run_me():
n = Scope()
async with n:
n.spawn(run10())
assert n.cancelled()
task = asyncio.ensure_future(run_me())
try:
(await asyncio.wait_for(asyncio.shield(task), 0.1))
except asyncio.Time... | @pytest.mark.asyncio
async def test_external_cancel():
async def run_me():
n = Scope()
async with n:
n.spawn(run10())
assert n.cancelled()
task = asyncio.ensure_future(run_me())
try:
(await asyncio.wait_for(asyncio.shield(task), 0.1))
except asyncio.Time... |
563d3dae259d7e672d24e5417820ad2da6abf289f8f07f69c286851647f22d35 | @pytest.mark.asyncio
async def test_external_cancel_nasty():
'Raise an external cancellation with task which fails cancelling'
async def nasty():
try:
(await asyncio.sleep(10))
except asyncio.CancelledError:
raise ValueError('boom')
async def run_me():
n = S... | Raise an external cancellation with task which fails cancelling | tests/test_cancel.py | test_external_cancel_nasty | RouquinBlanc/traio | 3 | python | @pytest.mark.asyncio
async def test_external_cancel_nasty():
async def nasty():
try:
(await asyncio.sleep(10))
except asyncio.CancelledError:
raise ValueError('boom')
async def run_me():
n = Scope()
async with n:
n.spawn(nasty())
... | @pytest.mark.asyncio
async def test_external_cancel_nasty():
async def nasty():
try:
(await asyncio.sleep(10))
except asyncio.CancelledError:
raise ValueError('boom')
async def run_me():
n = Scope()
async with n:
n.spawn(nasty())
... |
972d0a6f053fc0d4eea8f89cae5113e45e224095b702061e71c1cb0af2202805 | @pytest.mark.asyncio
async def test_internal_cancel():
'Test an internal cancellation'
before = time.time()
async with Scope() as n:
n.spawn(run10())
(await asyncio.sleep(0.2))
n.cancel()
after = time.time()
assert ((after - before) < 0.5) | Test an internal cancellation | tests/test_cancel.py | test_internal_cancel | RouquinBlanc/traio | 3 | python | @pytest.mark.asyncio
async def test_internal_cancel():
before = time.time()
async with Scope() as n:
n.spawn(run10())
(await asyncio.sleep(0.2))
n.cancel()
after = time.time()
assert ((after - before) < 0.5) | @pytest.mark.asyncio
async def test_internal_cancel():
before = time.time()
async with Scope() as n:
n.spawn(run10())
(await asyncio.sleep(0.2))
n.cancel()
after = time.time()
assert ((after - before) < 0.5)<|docstring|>Test an internal cancellation<|endoftext|> |
d13232f8220fd3cebd8788495e79bb84409174dde790edfeb49318b2baf45287 | @pytest.mark.asyncio
async def test_cancelling_going_bad():
'Test cancelling a pending task, but things go wrong...'
async def nasty():
try:
(await asyncio.sleep(10))
except asyncio.CancelledError:
raise ValueError('boom')
with pytest.raises(TimeoutError):
as... | Test cancelling a pending task, but things go wrong... | tests/test_cancel.py | test_cancelling_going_bad | RouquinBlanc/traio | 3 | python | @pytest.mark.asyncio
async def test_cancelling_going_bad():
async def nasty():
try:
(await asyncio.sleep(10))
except asyncio.CancelledError:
raise ValueError('boom')
with pytest.raises(TimeoutError):
async with Scope(timeout=0.5) as n:
n.spawn(na... | @pytest.mark.asyncio
async def test_cancelling_going_bad():
async def nasty():
try:
(await asyncio.sleep(10))
except asyncio.CancelledError:
raise ValueError('boom')
with pytest.raises(TimeoutError):
async with Scope(timeout=0.5) as n:
n.spawn(na... |
98073373456853662c57b669964d1e4e9bf1cc7e30d2e65e322e5d6dd83b7d05 | @pytest.mark.asyncio
async def test_cancel_not_joined_yet():
"\n When we cancel the nursery, it hasn't been joined yet.\n This should cancel it anyway.\n "
async def cleaner():
(await asyncio.sleep(0.2))
Scope.get_current().cancel()
(await asyncio.sleep(10))
before = time.t... | When we cancel the nursery, it hasn't been joined yet.
This should cancel it anyway. | tests/test_cancel.py | test_cancel_not_joined_yet | RouquinBlanc/traio | 3 | python | @pytest.mark.asyncio
async def test_cancel_not_joined_yet():
"\n When we cancel the nursery, it hasn't been joined yet.\n This should cancel it anyway.\n "
async def cleaner():
(await asyncio.sleep(0.2))
Scope.get_current().cancel()
(await asyncio.sleep(10))
before = time.t... | @pytest.mark.asyncio
async def test_cancel_not_joined_yet():
"\n When we cancel the nursery, it hasn't been joined yet.\n This should cancel it anyway.\n "
async def cleaner():
(await asyncio.sleep(0.2))
Scope.get_current().cancel()
(await asyncio.sleep(10))
before = time.t... |
9d9900f2bbbf49e0a02cd8ac79887a6c68db845792ec3d68dab0321100f3775a | @pytest.mark.asyncio
async def test_cancel_double():
'\n Cancelled externally, twice\n '
async def cleaner(scope):
(await asyncio.sleep(0.2))
scope.cancel()
scope.cancel()
scope = Scope()
task = asyncio.ensure_future(cleaner(scope))
async with scope:
(scope << ... | Cancelled externally, twice | tests/test_cancel.py | test_cancel_double | RouquinBlanc/traio | 3 | python | @pytest.mark.asyncio
async def test_cancel_double():
'\n \n '
async def cleaner(scope):
(await asyncio.sleep(0.2))
scope.cancel()
scope.cancel()
scope = Scope()
task = asyncio.ensure_future(cleaner(scope))
async with scope:
(scope << run10())
(await task)
... | @pytest.mark.asyncio
async def test_cancel_double():
'\n \n '
async def cleaner(scope):
(await asyncio.sleep(0.2))
scope.cancel()
scope.cancel()
scope = Scope()
task = asyncio.ensure_future(cleaner(scope))
async with scope:
(scope << run10())
(await task)
... |
b1ca58292b6478f6752b6235fd3898195465acd84aa079cfddfc80df6cd68eed | @pytest.mark.asyncio
async def test_cancel_double_exception():
'\n Cancelled externally, twice, with exception\n '
async def cleaner(scope):
(await asyncio.sleep(0.2))
scope.cancel(ValueError('boom'))
scope.cancel(ValueError('boom'))
scope = Scope()
task = asyncio.ensure_f... | Cancelled externally, twice, with exception | tests/test_cancel.py | test_cancel_double_exception | RouquinBlanc/traio | 3 | python | @pytest.mark.asyncio
async def test_cancel_double_exception():
'\n \n '
async def cleaner(scope):
(await asyncio.sleep(0.2))
scope.cancel(ValueError('boom'))
scope.cancel(ValueError('boom'))
scope = Scope()
task = asyncio.ensure_future(cleaner(scope))
with pytest.raise... | @pytest.mark.asyncio
async def test_cancel_double_exception():
'\n \n '
async def cleaner(scope):
(await asyncio.sleep(0.2))
scope.cancel(ValueError('boom'))
scope.cancel(ValueError('boom'))
scope = Scope()
task = asyncio.ensure_future(cleaner(scope))
with pytest.raise... |
68ba9d90edb684c89244772be373b11c64e6df8c521e28d529a358d4a72ae857 | @pytest.mark.asyncio
async def test_cancel_double_internal():
'\n Cancelled internally, twice\n '
async def cleaner():
(await asyncio.sleep(0.2))
Scope.get_current().cancel()
Scope.get_current().cancel()
async with Scope() as scope:
(scope << cleaner()) | Cancelled internally, twice | tests/test_cancel.py | test_cancel_double_internal | RouquinBlanc/traio | 3 | python | @pytest.mark.asyncio
async def test_cancel_double_internal():
'\n \n '
async def cleaner():
(await asyncio.sleep(0.2))
Scope.get_current().cancel()
Scope.get_current().cancel()
async with Scope() as scope:
(scope << cleaner()) | @pytest.mark.asyncio
async def test_cancel_double_internal():
'\n \n '
async def cleaner():
(await asyncio.sleep(0.2))
Scope.get_current().cancel()
Scope.get_current().cancel()
async with Scope() as scope:
(scope << cleaner())<|docstring|>Cancelled internally, twice<|e... |
e6cedeaeda19daecca7478fc2b3ab435af6601759525e82118e69b82e8b76b67 | @pytest.mark.asyncio
async def test_cancel_double_internal_exception():
'\n Cancelled internally, twice, with exception\n '
async def cleaner():
(await asyncio.sleep(0.2))
Scope.get_current().cancel(ValueError('boom'))
Scope.get_current().cancel(ValueError('boom'))
with pytest... | Cancelled internally, twice, with exception | tests/test_cancel.py | test_cancel_double_internal_exception | RouquinBlanc/traio | 3 | python | @pytest.mark.asyncio
async def test_cancel_double_internal_exception():
'\n \n '
async def cleaner():
(await asyncio.sleep(0.2))
Scope.get_current().cancel(ValueError('boom'))
Scope.get_current().cancel(ValueError('boom'))
with pytest.raises(ValueError):
async with Sco... | @pytest.mark.asyncio
async def test_cancel_double_internal_exception():
'\n \n '
async def cleaner():
(await asyncio.sleep(0.2))
Scope.get_current().cancel(ValueError('boom'))
Scope.get_current().cancel(ValueError('boom'))
with pytest.raises(ValueError):
async with Sco... |
3a93e3d45e9bd5ef6a2ca6b461441aa77158f5769330412ef9d01295975b29eb | @pytest.mark.asyncio
async def test_cancel_finally_cancel():
'\n Cancelled internally, twice\n '
async def cleaner():
(await asyncio.sleep(0.2))
raise ValueError('boom')
scope = Scope()
with pytest.raises(ValueError):
try:
async with scope:
(sco... | Cancelled internally, twice | tests/test_cancel.py | test_cancel_finally_cancel | RouquinBlanc/traio | 3 | python | @pytest.mark.asyncio
async def test_cancel_finally_cancel():
'\n \n '
async def cleaner():
(await asyncio.sleep(0.2))
raise ValueError('boom')
scope = Scope()
with pytest.raises(ValueError):
try:
async with scope:
(scope << cleaner())
fi... | @pytest.mark.asyncio
async def test_cancel_finally_cancel():
'\n \n '
async def cleaner():
(await asyncio.sleep(0.2))
raise ValueError('boom')
scope = Scope()
with pytest.raises(ValueError):
try:
async with scope:
(scope << cleaner())
fi... |
45cd9d31ee59a958813992915bfcfa183ed75afd2c68ded05fc3598432db122f | def validate_email_config(self) -> None:
'Validates SMTP server configuration.\n\n Returns:\n None\n Raises:\n smtplib.SMTPHeloError\n smtplib.SMTPAuthenticationError\n smtplib.SMTPNotSupportedError\n smtplib.SMTPException\n RuntimeErro... | Validates SMTP server configuration.
Returns:
None
Raises:
smtplib.SMTPHeloError
smtplib.SMTPAuthenticationError
smtplib.SMTPNotSupportedError
smtplib.SMTPException
RuntimeError | package/cloudshell/email/email_service.py | validate_email_config | QualiSystemsLab/cloudshell-email | 0 | python | def validate_email_config(self) -> None:
'Validates SMTP server configuration.\n\n Returns:\n None\n Raises:\n smtplib.SMTPHeloError\n smtplib.SMTPAuthenticationError\n smtplib.SMTPNotSupportedError\n smtplib.SMTPException\n RuntimeErro... | def validate_email_config(self) -> None:
'Validates SMTP server configuration.\n\n Returns:\n None\n Raises:\n smtplib.SMTPHeloError\n smtplib.SMTPAuthenticationError\n smtplib.SMTPNotSupportedError\n smtplib.SMTPException\n RuntimeErro... |
5822e73f6b3020b36b287fe39bbcf1f3596cbdc4dd528cd56a9e9bf9feeba98a | def rotate_crop(image, angle):
'Rotate the given image counterclockwise by the specified angle (degrees), removing whitespace.'
(h, w) = image.shape[:2]
(cX, cY) = ((w // 2), (h // 2))
M = cv.getRotationMatrix2D((cX, cY), angle, 1.0)
cos = np.abs(M[(0, 0)])
sin = np.abs(M[(0, 1)])
nW = int((... | Rotate the given image counterclockwise by the specified angle (degrees), removing whitespace. | im_tools.py | rotate_crop | wwilliamcook/floop | 0 | python | def rotate_crop(image, angle):
(h, w) = image.shape[:2]
(cX, cY) = ((w // 2), (h // 2))
M = cv.getRotationMatrix2D((cX, cY), angle, 1.0)
cos = np.abs(M[(0, 0)])
sin = np.abs(M[(0, 1)])
nW = int((((h * sin) + (w * cos)) - (2 * min((h * sin), (w * cos)))))
nH = int((((h * cos) + (w * sin)... | def rotate_crop(image, angle):
(h, w) = image.shape[:2]
(cX, cY) = ((w // 2), (h // 2))
M = cv.getRotationMatrix2D((cX, cY), angle, 1.0)
cos = np.abs(M[(0, 0)])
sin = np.abs(M[(0, 1)])
nW = int((((h * sin) + (w * cos)) - (2 * min((h * sin), (w * cos)))))
nH = int((((h * cos) + (w * sin)... |
fdf8bcf712eb4884fd47db047d01da4966c72ca5878b58a47811c8ad15c6fc8b | def openPDF(name, page_index=None):
'Open a page of the given PDF as an OpenCV image.'
name = str(name)
if os.path.exists(name):
doc = fitz.open(name)
if (page_index is None):
page = doc.loadPage(np.random.randint(0, doc.pageCount))
else:
page = doc.loadPage(p... | Open a page of the given PDF as an OpenCV image. | im_tools.py | openPDF | wwilliamcook/floop | 0 | python | def openPDF(name, page_index=None):
name = str(name)
if os.path.exists(name):
doc = fitz.open(name)
if (page_index is None):
page = doc.loadPage(np.random.randint(0, doc.pageCount))
else:
page = doc.loadPage(page_index)
pix = page.getPixmap()
... | def openPDF(name, page_index=None):
name = str(name)
if os.path.exists(name):
doc = fitz.open(name)
if (page_index is None):
page = doc.loadPage(np.random.randint(0, doc.pageCount))
else:
page = doc.loadPage(page_index)
pix = page.getPixmap()
... |
7f4efc33772b23936a51bf2197b2898310bb8ded84d6ced589d16264fdd6bce2 | def generate_sample(image, output_res, min_src_res=(150, 150)):
'Generate an image/label pair from the given image'
angle = (np.random.random() * 360)
image = rotate_crop(image, angle)
w = np.random.randint(min(min_src_res[0], image.shape[1]), image.shape[1])
h = np.random.randint(min(min_src_res[1]... | Generate an image/label pair from the given image | im_tools.py | generate_sample | wwilliamcook/floop | 0 | python | def generate_sample(image, output_res, min_src_res=(150, 150)):
angle = (np.random.random() * 360)
image = rotate_crop(image, angle)
w = np.random.randint(min(min_src_res[0], image.shape[1]), image.shape[1])
h = np.random.randint(min(min_src_res[1], image.shape[0]), image.shape[0])
x = np.rando... | def generate_sample(image, output_res, min_src_res=(150, 150)):
angle = (np.random.random() * 360)
image = rotate_crop(image, angle)
w = np.random.randint(min(min_src_res[0], image.shape[1]), image.shape[1])
h = np.random.randint(min(min_src_res[1], image.shape[0]), image.shape[0])
x = np.rando... |
f83cbcaa4d0a8e7c09b2661b03b94f4ab19e318c0a3b97b557778da261847617 | def rotatePDF(name, relative_orientation):
'Permanently rotate the given PDF by the specified angle (multiple of 90).'
doc = fitz.open(name)
for i in range(doc.pageCount):
page = doc.loadPage(i)
page.setRotation((page.rotation + relative_orientation))
doc.saveIncr()
doc.close() | Permanently rotate the given PDF by the specified angle (multiple of 90). | im_tools.py | rotatePDF | wwilliamcook/floop | 0 | python | def rotatePDF(name, relative_orientation):
doc = fitz.open(name)
for i in range(doc.pageCount):
page = doc.loadPage(i)
page.setRotation((page.rotation + relative_orientation))
doc.saveIncr()
doc.close() | def rotatePDF(name, relative_orientation):
doc = fitz.open(name)
for i in range(doc.pageCount):
page = doc.loadPage(i)
page.setRotation((page.rotation + relative_orientation))
doc.saveIncr()
doc.close()<|docstring|>Permanently rotate the given PDF by the specified angle (multiple of... |
982d567a33b877936860deb9e3246b029c363fe3a26baeadc8cdf0c29937be6f | def spin(img):
"animates rotating 'img' using 'rotate_crop'"
a = 0
while True:
cv.imshow('spin', rotate_clip(img, a))
k = cv.waitKey(1)
if (k == 27):
break
a = ((a + 0.01) % 360)
cv.destroyAllWindows() | animates rotating 'img' using 'rotate_crop' | im_tools.py | spin | wwilliamcook/floop | 0 | python | def spin(img):
a = 0
while True:
cv.imshow('spin', rotate_clip(img, a))
k = cv.waitKey(1)
if (k == 27):
break
a = ((a + 0.01) % 360)
cv.destroyAllWindows() | def spin(img):
a = 0
while True:
cv.imshow('spin', rotate_clip(img, a))
k = cv.waitKey(1)
if (k == 27):
break
a = ((a + 0.01) % 360)
cv.destroyAllWindows()<|docstring|>animates rotating 'img' using 'rotate_crop'<|endoftext|> |
6c56e68d0bf4a624e0d1ea35ece03af3af470270bc3274304a50497300bc71d9 | def AttachEOLMarker(self):
"Attach an EOL marker '$' to the pattern."
self.pattern += '$'
self._regex = re.compile(self.pattern) | Attach an EOL marker '$' to the pattern. | ashierlib/reactive.py | AttachEOLMarker | google/ashier | 26 | python | def AttachEOLMarker(self):
self.pattern += '$'
self._regex = re.compile(self.pattern) | def AttachEOLMarker(self):
self.pattern += '$'
self._regex = re.compile(self.pattern)<|docstring|>Attach an EOL marker '$' to the pattern.<|endoftext|> |
19b00fdd52414d019a9278abfc3eb346ed525b26ddfbcd6f3a7ca9f032059371 | def Match(self, text, bindings):
'Match a string to a pattern.\n\n Check if the string argument matches the pattern and, if so,\n extact substrings into the bindings dictionary.\n\n Args:\n text: the string to match.\n bindings: dictionary to store extracted substrings.\n\n Returns:\n A B... | Match a string to a pattern.
Check if the string argument matches the pattern and, if so,
extact substrings into the bindings dictionary.
Args:
text: the string to match.
bindings: dictionary to store extracted substrings.
Returns:
A Boolean value that indicates match success. | ashierlib/reactive.py | Match | google/ashier | 26 | python | def Match(self, text, bindings):
'Match a string to a pattern.\n\n Check if the string argument matches the pattern and, if so,\n extact substrings into the bindings dictionary.\n\n Args:\n text: the string to match.\n bindings: dictionary to store extracted substrings.\n\n Returns:\n A B... | def Match(self, text, bindings):
'Match a string to a pattern.\n\n Check if the string argument matches the pattern and, if so,\n extact substrings into the bindings dictionary.\n\n Args:\n text: the string to match.\n bindings: dictionary to store extracted substrings.\n\n Returns:\n A B... |
ca05fb3497e70f1e07ba42ab9d5ddc79c01f67f79fe082a89a50a5d0c20964df | def PatternSize(self):
'Return pattern length (in lines).'
return len(self._patterns) | Return pattern length (in lines). | ashierlib/reactive.py | PatternSize | google/ashier | 26 | python | def PatternSize(self):
return len(self._patterns) | def PatternSize(self):
return len(self._patterns)<|docstring|>Return pattern length (in lines).<|endoftext|> |
2e2409a740c1e97b873507feb17b1eef21b5b78c779691a2e04984db107ed69c | def React(self, nesting, buf, bound, channels):
'React if there is a match from line buffer.\n\n Args:\n nesting: persistent state to support nested matching.\n Initialize with a fresh empty mutable list and reuse the same\n list for subsequent calls.\n buf: a Buffer object that contains ... | React if there is a match from line buffer.
Args:
nesting: persistent state to support nested matching.
Initialize with a fresh empty mutable list and reuse the same
list for subsequent calls.
buf: a Buffer object that contains the terminal output to match.
bound: integer index matching upper limit (non-... | ashierlib/reactive.py | React | google/ashier | 26 | python | def React(self, nesting, buf, bound, channels):
'React if there is a match from line buffer.\n\n Args:\n nesting: persistent state to support nested matching.\n Initialize with a fresh empty mutable list and reuse the same\n list for subsequent calls.\n buf: a Buffer object that contains ... | def React(self, nesting, buf, bound, channels):
'React if there is a match from line buffer.\n\n Args:\n nesting: persistent state to support nested matching.\n Initialize with a fresh empty mutable list and reuse the same\n list for subsequent calls.\n buf: a Buffer object that contains ... |
62ee2f15010a9c521663618af474d69854c76e2456f4a3f220249c04a4ae36e4 | def iter_py_files(files_and_dirs: Iterable[pathlib.Path], recursive: bool=False) -> Iterable[pathlib.Path]:
'\n\tIterate over all ``.py`` files in the given directories.\n\n\tTODO: Wildcards in filename/directory\n\n\t:param files_and_dirs: An iterable of filenames and directories\n\t:param recursive: Whether subdi... | Iterate over all ``.py`` files in the given directories.
TODO: Wildcards in filename/directory
:param files_and_dirs: An iterable of filenames and directories
:param recursive: Whether subdirectories should be recursed. | pyupgrade_directories/__init__.py | iter_py_files | domdfcoding/pyupgrade-directories | 8 | python | def iter_py_files(files_and_dirs: Iterable[pathlib.Path], recursive: bool=False) -> Iterable[pathlib.Path]:
'\n\tIterate over all ``.py`` files in the given directories.\n\n\tTODO: Wildcards in filename/directory\n\n\t:param files_and_dirs: An iterable of filenames and directories\n\t:param recursive: Whether subdi... | def iter_py_files(files_and_dirs: Iterable[pathlib.Path], recursive: bool=False) -> Iterable[pathlib.Path]:
'\n\tIterate over all ``.py`` files in the given directories.\n\n\tTODO: Wildcards in filename/directory\n\n\t:param files_and_dirs: An iterable of filenames and directories\n\t:param recursive: Whether subdi... |
7642a72d5bd0285a7a02c69ced4d37d879d624ee4c5d405036f47986d076d670 | @course_bp.route('', methods=['POST', 'GET'])
def retrieve_courses():
'Endpoint for courses, GET will return all courses in db by default,\n POST allows user to add a course to the database.'
if (request.method == 'POST'):
data = request.get_json(force=True)
try:
new_course = Cour... | Endpoint for courses, GET will return all courses in db by default,
POST allows user to add a course to the database. | flask_app/course_views.py | retrieve_courses | kentblock/golf-api | 0 | python | @course_bp.route(, methods=['POST', 'GET'])
def retrieve_courses():
'Endpoint for courses, GET will return all courses in db by default,\n POST allows user to add a course to the database.'
if (request.method == 'POST'):
data = request.get_json(force=True)
try:
new_course = Course... | @course_bp.route(, methods=['POST', 'GET'])
def retrieve_courses():
'Endpoint for courses, GET will return all courses in db by default,\n POST allows user to add a course to the database.'
if (request.method == 'POST'):
data = request.get_json(force=True)
try:
new_course = Course... |
00fff9c1e768129254c7f98ebfa54f025c3f936935161ec95ab67711bd1d27c9 | @course_bp.route('/<int:id>', methods=['GET', 'PATCH'])
def course_detail(id):
'Course detail endpoint, retrieve data for course with GET, update \n course with PATCH'
if (request.method == 'GET'):
course = Course.query.get(id)
if course:
return (jsonify(course.detail_format()), 2... | Course detail endpoint, retrieve data for course with GET, update
course with PATCH | flask_app/course_views.py | course_detail | kentblock/golf-api | 0 | python | @course_bp.route('/<int:id>', methods=['GET', 'PATCH'])
def course_detail(id):
'Course detail endpoint, retrieve data for course with GET, update \n course with PATCH'
if (request.method == 'GET'):
course = Course.query.get(id)
if course:
return (jsonify(course.detail_format()), 2... | @course_bp.route('/<int:id>', methods=['GET', 'PATCH'])
def course_detail(id):
'Course detail endpoint, retrieve data for course with GET, update \n course with PATCH'
if (request.method == 'GET'):
course = Course.query.get(id)
if course:
return (jsonify(course.detail_format()), 2... |
f7c898f93eefc8913a5787192917286c5987b67fea856310018dfb80f0c549af | @course_bp.route('/<int:id>/holes', methods=['GET', 'POST'])
def retrieve_holes(id):
'Retrieves holes for course with given id, you can also add holes\n for a course with a POST request, one at a time, or in bulk.'
course = Course.query.get(id)
if (not course):
return abort(404, f'Course with id:... | Retrieves holes for course with given id, you can also add holes
for a course with a POST request, one at a time, or in bulk. | flask_app/course_views.py | retrieve_holes | kentblock/golf-api | 0 | python | @course_bp.route('/<int:id>/holes', methods=['GET', 'POST'])
def retrieve_holes(id):
'Retrieves holes for course with given id, you can also add holes\n for a course with a POST request, one at a time, or in bulk.'
course = Course.query.get(id)
if (not course):
return abort(404, f'Course with id:... | @course_bp.route('/<int:id>/holes', methods=['GET', 'POST'])
def retrieve_holes(id):
'Retrieves holes for course with given id, you can also add holes\n for a course with a POST request, one at a time, or in bulk.'
course = Course.query.get(id)
if (not course):
return abort(404, f'Course with id:... |
302eedcc8f452579eb9fc149f122a7fbcf883fbce97cbd7a26a3460aa42a62d1 | @course_bp.route('/<int:id>/holes/<int:hole_id>', methods=['GET', 'PATCH'])
def hole_detail(id, hole_id):
'Endpoint for hole detail, update a hole record with a PATCH request, \n retrieve course data with a GET request.'
course = Course.query.get(id)
if (not course):
abort(404, f'Cource with id: ... | Endpoint for hole detail, update a hole record with a PATCH request,
retrieve course data with a GET request. | flask_app/course_views.py | hole_detail | kentblock/golf-api | 0 | python | @course_bp.route('/<int:id>/holes/<int:hole_id>', methods=['GET', 'PATCH'])
def hole_detail(id, hole_id):
'Endpoint for hole detail, update a hole record with a PATCH request, \n retrieve course data with a GET request.'
course = Course.query.get(id)
if (not course):
abort(404, f'Cource with id: ... | @course_bp.route('/<int:id>/holes/<int:hole_id>', methods=['GET', 'PATCH'])
def hole_detail(id, hole_id):
'Endpoint for hole detail, update a hole record with a PATCH request, \n retrieve course data with a GET request.'
course = Course.query.get(id)
if (not course):
abort(404, f'Cource with id: ... |
4a3f2b852e0e027d9782a36133e91dfbb0e5057827c760274130eddb81ecd7fe | @course_bp.route('/<int:id>/tees', methods=['GET', 'POST'])
def retrieve_tees(id):
'Endpoint for the tees of a course, retrieve all tees with a GET, \n add a new tee to the course with a POST'
course = Course.query.get(id)
if (not course):
abort(404, f'Course with id: {id}, does not exist.')
... | Endpoint for the tees of a course, retrieve all tees with a GET,
add a new tee to the course with a POST | flask_app/course_views.py | retrieve_tees | kentblock/golf-api | 0 | python | @course_bp.route('/<int:id>/tees', methods=['GET', 'POST'])
def retrieve_tees(id):
'Endpoint for the tees of a course, retrieve all tees with a GET, \n add a new tee to the course with a POST'
course = Course.query.get(id)
if (not course):
abort(404, f'Course with id: {id}, does not exist.')
... | @course_bp.route('/<int:id>/tees', methods=['GET', 'POST'])
def retrieve_tees(id):
'Endpoint for the tees of a course, retrieve all tees with a GET, \n add a new tee to the course with a POST'
course = Course.query.get(id)
if (not course):
abort(404, f'Course with id: {id}, does not exist.')
... |
c99f31cdc7dbaa21e122758109b78f842c47bd1723c84e60e569227850961141 | @course_bp.route('<id>/tees/<tee_id>', methods=['GET', 'PATCH'])
def tee_detail(id, tee_id):
'Endpoint for tee detail, retrieve detailed tee data with a GET, \n update tee detail with a PATCH'
course = Course.query.get(id)
tee = Tee.query.get(tee_id)
if ((not course) or (not tee)):
abort(404,... | Endpoint for tee detail, retrieve detailed tee data with a GET,
update tee detail with a PATCH | flask_app/course_views.py | tee_detail | kentblock/golf-api | 0 | python | @course_bp.route('<id>/tees/<tee_id>', methods=['GET', 'PATCH'])
def tee_detail(id, tee_id):
'Endpoint for tee detail, retrieve detailed tee data with a GET, \n update tee detail with a PATCH'
course = Course.query.get(id)
tee = Tee.query.get(tee_id)
if ((not course) or (not tee)):
abort(404,... | @course_bp.route('<id>/tees/<tee_id>', methods=['GET', 'PATCH'])
def tee_detail(id, tee_id):
'Endpoint for tee detail, retrieve detailed tee data with a GET, \n update tee detail with a PATCH'
course = Course.query.get(id)
tee = Tee.query.get(tee_id)
if ((not course) or (not tee)):
abort(404,... |
9791826c6f930b21d685eda574f2613146cd503a6c44342350cb66f8dd8d0cb5 | def testV1NonResourceRule(self):
'\n Test V1NonResourceRule\n '
pass | Test V1NonResourceRule | kubernetes/test/test_v1_non_resource_rule.py | testV1NonResourceRule | zq-david-wang/python | 1 | python | def testV1NonResourceRule(self):
'\n \n '
pass | def testV1NonResourceRule(self):
'\n \n '
pass<|docstring|>Test V1NonResourceRule<|endoftext|> |
15896c441b8fe6e1467186e86e54cdfc271a361532e210c3ec6555dc8a5d693f | @register.inclusion_tag('analytics/tracker.html')
def show_tracker(secure=False):
'\n Output the analytics tracker code.\n '
google = getattr(settings, 'ANALYTICS', {})
if google:
analytics_code = google.get('ANALYTICS_CODE')
if analytics_code:
return {'analytics_code': ana... | Output the analytics tracker code. | apps/sso/accounts/templatetags/analytics.py | show_tracker | g10f/sso | 3 | python | @register.inclusion_tag('analytics/tracker.html')
def show_tracker(secure=False):
'\n \n '
google = getattr(settings, 'ANALYTICS', {})
if google:
analytics_code = google.get('ANALYTICS_CODE')
if analytics_code:
return {'analytics_code': analytics_code}
return {} | @register.inclusion_tag('analytics/tracker.html')
def show_tracker(secure=False):
'\n \n '
google = getattr(settings, 'ANALYTICS', {})
if google:
analytics_code = google.get('ANALYTICS_CODE')
if analytics_code:
return {'analytics_code': analytics_code}
return {}<|docstr... |
b8930fdb949b4267f8b530cd2f50327fd4abc4b2e7cd3cebcf3c421b01ac9ebb | def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5):
'\n Return a factor having root ``v``\n It is assumed that one of the factors has root ``v``.\n '
if isinstance(factors[0], tuple):
factors = [f[0] for f in factors]
if (len(factors) == 1):
return factors[0]
points = ... | Return a factor having root ``v``
It is assumed that one of the factors has root ``v``. | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _choose_factor | RivtLib/replit01 | 603 | python | def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5):
'\n Return a factor having root ``v``\n It is assumed that one of the factors has root ``v``.\n '
if isinstance(factors[0], tuple):
factors = [f[0] for f in factors]
if (len(factors) == 1):
return factors[0]
points = ... | def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5):
'\n Return a factor having root ``v``\n It is assumed that one of the factors has root ``v``.\n '
if isinstance(factors[0], tuple):
factors = [f[0] for f in factors]
if (len(factors) == 1):
return factors[0]
points = ... |
54a832c48d80061ff3b1adee1eb320faa203fddb63987d2b02f25ae8a9c38854 | def _separate_sq(p):
'\n helper function for ``_minimal_polynomial_sq``\n\n It selects a rational ``g`` such that the polynomial ``p``\n consists of a sum of terms whose surds squared have gcd equal to ``g``\n and a sum of terms with surds squared prime with ``g``;\n then it takes the field norm to e... | helper function for ``_minimal_polynomial_sq``
It selects a rational ``g`` such that the polynomial ``p``
consists of a sum of terms whose surds squared have gcd equal to ``g``
and a sum of terms with surds squared prime with ``g``;
then it takes the field norm to eliminate ``sqrt(g)``
See simplify.simplify.split_sur... | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _separate_sq | RivtLib/replit01 | 603 | python | def _separate_sq(p):
'\n helper function for ``_minimal_polynomial_sq``\n\n It selects a rational ``g`` such that the polynomial ``p``\n consists of a sum of terms whose surds squared have gcd equal to ``g``\n and a sum of terms with surds squared prime with ``g``;\n then it takes the field norm to e... | def _separate_sq(p):
'\n helper function for ``_minimal_polynomial_sq``\n\n It selects a rational ``g`` such that the polynomial ``p``\n consists of a sum of terms whose surds squared have gcd equal to ``g``\n and a sum of terms with surds squared prime with ``g``;\n then it takes the field norm to e... |
2b6b0726943a4499275b166a375f9a7570c10bc8113b080cdfc7bf6ebb1b33e4 | def _minimal_polynomial_sq(p, n, x):
'\n Returns the minimal polynomial for the ``nth-root`` of a sum of surds\n or ``None`` if it fails.\n\n Parameters\n ==========\n\n p : sum of surds\n n : positive integer\n x : variable of the returned polynomial\n\n Examples\n ========\n\n >>> fr... | Returns the minimal polynomial for the ``nth-root`` of a sum of surds
or ``None`` if it fails.
Parameters
==========
p : sum of surds
n : positive integer
x : variable of the returned polynomial
Examples
========
>>> from sympy.polys.numberfields import _minimal_polynomial_sq
>>> from sympy import sqrt
>>> from sym... | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _minimal_polynomial_sq | RivtLib/replit01 | 603 | python | def _minimal_polynomial_sq(p, n, x):
'\n Returns the minimal polynomial for the ``nth-root`` of a sum of surds\n or ``None`` if it fails.\n\n Parameters\n ==========\n\n p : sum of surds\n n : positive integer\n x : variable of the returned polynomial\n\n Examples\n ========\n\n >>> fr... | def _minimal_polynomial_sq(p, n, x):
'\n Returns the minimal polynomial for the ``nth-root`` of a sum of surds\n or ``None`` if it fails.\n\n Parameters\n ==========\n\n p : sum of surds\n n : positive integer\n x : variable of the returned polynomial\n\n Examples\n ========\n\n >>> fr... |
0ee1ac210be56e4e5b733b4de3d27cd8116376def6e17ec8b73ab7cdb7efef11 | def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None):
'\n return the minimal polynomial for ``op(ex1, ex2)``\n\n Parameters\n ==========\n\n op : operation ``Add`` or ``Mul``\n ex1, ex2 : expressions for the algebraic elements\n x : indeterminate of the polynomials\n dom:... | return the minimal polynomial for ``op(ex1, ex2)``
Parameters
==========
op : operation ``Add`` or ``Mul``
ex1, ex2 : expressions for the algebraic elements
x : indeterminate of the polynomials
dom: ground domain
mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None
Examples
========
>>> from sympy import ... | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _minpoly_op_algebraic_element | RivtLib/replit01 | 603 | python | def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None):
'\n return the minimal polynomial for ``op(ex1, ex2)``\n\n Parameters\n ==========\n\n op : operation ``Add`` or ``Mul``\n ex1, ex2 : expressions for the algebraic elements\n x : indeterminate of the polynomials\n dom:... | def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None):
'\n return the minimal polynomial for ``op(ex1, ex2)``\n\n Parameters\n ==========\n\n op : operation ``Add`` or ``Mul``\n ex1, ex2 : expressions for the algebraic elements\n x : indeterminate of the polynomials\n dom:... |
aecbdc2f93ace1fc02954b0694bc9cc9ed7cc62579e50cb4a9843e6d7900c3d4 | def _invertx(p, x):
'\n Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))``\n '
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [(c * (x ** (n - i))) for ((i,), c) in p1.terms()]
return Add(*a) | Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))`` | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _invertx | RivtLib/replit01 | 603 | python | def _invertx(p, x):
'\n \n '
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [(c * (x ** (n - i))) for ((i,), c) in p1.terms()]
return Add(*a) | def _invertx(p, x):
'\n \n '
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [(c * (x ** (n - i))) for ((i,), c) in p1.terms()]
return Add(*a)<|docstring|>Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))``<|endoftext|> |
baca23eea9540fd31e8e3d028e160bcb5642f5530e5cf80ee6106406a28aac11 | def _muly(p, x, y):
'\n Returns ``_mexpand(y**deg*p.subs({x:x / y}))``\n '
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [((c * (x ** i)) * (y ** (n - i))) for ((i,), c) in p1.terms()]
return Add(*a) | Returns ``_mexpand(y**deg*p.subs({x:x / y}))`` | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _muly | RivtLib/replit01 | 603 | python | def _muly(p, x, y):
'\n \n '
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [((c * (x ** i)) * (y ** (n - i))) for ((i,), c) in p1.terms()]
return Add(*a) | def _muly(p, x, y):
'\n \n '
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [((c * (x ** i)) * (y ** (n - i))) for ((i,), c) in p1.terms()]
return Add(*a)<|docstring|>Returns ``_mexpand(y**deg*p.subs({x:x / y}))``<|endoftext|> |
d5d3c39472349ad531a7733fc5efe8c4fa4fd4dfc72004b31f2b26ee8d6a59a7 | def _minpoly_pow(ex, pw, x, dom, mp=None):
'\n Returns ``minpoly(ex**pw, x)``\n\n Parameters\n ==========\n\n ex : algebraic element\n pw : rational number\n x : indeterminate of the polynomial\n dom: ground domain\n mp : minimal polynomial of ``p``\n\n Examples\n ========\n\n >>> f... | Returns ``minpoly(ex**pw, x)``
Parameters
==========
ex : algebraic element
pw : rational number
x : indeterminate of the polynomial
dom: ground domain
mp : minimal polynomial of ``p``
Examples
========
>>> from sympy import sqrt, QQ, Rational
>>> from sympy.polys.numberfields import _minpoly_pow, minpoly
>>> from ... | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _minpoly_pow | RivtLib/replit01 | 603 | python | def _minpoly_pow(ex, pw, x, dom, mp=None):
'\n Returns ``minpoly(ex**pw, x)``\n\n Parameters\n ==========\n\n ex : algebraic element\n pw : rational number\n x : indeterminate of the polynomial\n dom: ground domain\n mp : minimal polynomial of ``p``\n\n Examples\n ========\n\n >>> f... | def _minpoly_pow(ex, pw, x, dom, mp=None):
'\n Returns ``minpoly(ex**pw, x)``\n\n Parameters\n ==========\n\n ex : algebraic element\n pw : rational number\n x : indeterminate of the polynomial\n dom: ground domain\n mp : minimal polynomial of ``p``\n\n Examples\n ========\n\n >>> f... |
1660cd1aad49f767601b417579b199c95f10ec3e8071d675342d90ff3df617ab | def _minpoly_add(x, dom, *a):
'\n returns ``minpoly(Add(*a), dom, x)``\n '
mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom)
p = (a[0] + a[1])
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp)
p = (p + px)
return mp | returns ``minpoly(Add(*a), dom, x)`` | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _minpoly_add | RivtLib/replit01 | 603 | python | def _minpoly_add(x, dom, *a):
'\n \n '
mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom)
p = (a[0] + a[1])
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp)
p = (p + px)
return mp | def _minpoly_add(x, dom, *a):
'\n \n '
mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom)
p = (a[0] + a[1])
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp)
p = (p + px)
return mp<|docstring|>returns ``minpoly(Add(*a), dom, x)``<|endoftex... |
262558677b3fd698d9ed4eeab5b117da7d4941a3737bee7efc281c504dc5b94c | def _minpoly_mul(x, dom, *a):
'\n returns ``minpoly(Mul(*a), dom, x)``\n '
mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom)
p = (a[0] * a[1])
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp)
p = (p * px)
return mp | returns ``minpoly(Mul(*a), dom, x)`` | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _minpoly_mul | RivtLib/replit01 | 603 | python | def _minpoly_mul(x, dom, *a):
'\n \n '
mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom)
p = (a[0] * a[1])
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp)
p = (p * px)
return mp | def _minpoly_mul(x, dom, *a):
'\n \n '
mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom)
p = (a[0] * a[1])
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp)
p = (p * px)
return mp<|docstring|>returns ``minpoly(Mul(*a), dom, x)``<|endoftex... |
557737f853744626e4b00301b6b92ddfe1c3dd47093b1a897826c4451600d96c | def _minpoly_sin(ex, x):
'\n Returns the minimal polynomial of ``sin(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n '
(c, a) = ex.args[0].as_coeff_Mul()
if (a is pi):
if c.is_rational:
n = c.q
q = sympify(n)
if q.is_prime:
... | Returns the minimal polynomial of ``sin(ex)``
see http://mathworld.wolfram.com/TrigonometryAngles.html | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _minpoly_sin | RivtLib/replit01 | 603 | python | def _minpoly_sin(ex, x):
'\n Returns the minimal polynomial of ``sin(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n '
(c, a) = ex.args[0].as_coeff_Mul()
if (a is pi):
if c.is_rational:
n = c.q
q = sympify(n)
if q.is_prime:
... | def _minpoly_sin(ex, x):
'\n Returns the minimal polynomial of ``sin(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n '
(c, a) = ex.args[0].as_coeff_Mul()
if (a is pi):
if c.is_rational:
n = c.q
q = sympify(n)
if q.is_prime:
... |
07d77096d0f44f92e6283744a15335467629a0d5d827b7980f7dd002ee03b4df | def _minpoly_cos(ex, x):
'\n Returns the minimal polynomial of ``cos(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n '
from sympy import sqrt
(c, a) = ex.args[0].as_coeff_Mul()
if (a is pi):
if c.is_rational:
if (c.p == 1):
if (c.q == 7):
... | Returns the minimal polynomial of ``cos(ex)``
see http://mathworld.wolfram.com/TrigonometryAngles.html | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _minpoly_cos | RivtLib/replit01 | 603 | python | def _minpoly_cos(ex, x):
'\n Returns the minimal polynomial of ``cos(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n '
from sympy import sqrt
(c, a) = ex.args[0].as_coeff_Mul()
if (a is pi):
if c.is_rational:
if (c.p == 1):
if (c.q == 7):
... | def _minpoly_cos(ex, x):
'\n Returns the minimal polynomial of ``cos(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n '
from sympy import sqrt
(c, a) = ex.args[0].as_coeff_Mul()
if (a is pi):
if c.is_rational:
if (c.p == 1):
if (c.q == 7):
... |
f235692a6405e26abdeb4845d72d607ffb92badd0f1d46352d2867209b3db3b5 | def _minpoly_exp(ex, x):
'\n Returns the minimal polynomial of ``exp(ex)``\n '
(c, a) = ex.args[0].as_coeff_Mul()
q = sympify(c.q)
if (a == (I * pi)):
if c.is_rational:
if ((c.p == 1) or (c.p == (- 1))):
if (q == 3):
return (((x ** 2) - x) + ... | Returns the minimal polynomial of ``exp(ex)`` | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _minpoly_exp | RivtLib/replit01 | 603 | python | def _minpoly_exp(ex, x):
'\n \n '
(c, a) = ex.args[0].as_coeff_Mul()
q = sympify(c.q)
if (a == (I * pi)):
if c.is_rational:
if ((c.p == 1) or (c.p == (- 1))):
if (q == 3):
return (((x ** 2) - x) + 1)
if (q == 4):
... | def _minpoly_exp(ex, x):
'\n \n '
(c, a) = ex.args[0].as_coeff_Mul()
q = sympify(c.q)
if (a == (I * pi)):
if c.is_rational:
if ((c.p == 1) or (c.p == (- 1))):
if (q == 3):
return (((x ** 2) - x) + 1)
if (q == 4):
... |
21a74cd718233e266b9379a1bbf8f44cf9fab17d46535c6519cfe4803bde5e68 | def _minpoly_rootof(ex, x):
'\n Returns the minimal polynomial of a ``CRootOf`` object.\n '
p = ex.expr
p = p.subs({ex.poly.gens[0]: x})
(_, factors) = factor_list(p, x)
result = _choose_factor(factors, x, ex)
return result | Returns the minimal polynomial of a ``CRootOf`` object. | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _minpoly_rootof | RivtLib/replit01 | 603 | python | def _minpoly_rootof(ex, x):
'\n \n '
p = ex.expr
p = p.subs({ex.poly.gens[0]: x})
(_, factors) = factor_list(p, x)
result = _choose_factor(factors, x, ex)
return result | def _minpoly_rootof(ex, x):
'\n \n '
p = ex.expr
p = p.subs({ex.poly.gens[0]: x})
(_, factors) = factor_list(p, x)
result = _choose_factor(factors, x, ex)
return result<|docstring|>Returns the minimal polynomial of a ``CRootOf`` object.<|endoftext|> |
08f3351ee554cf0bff9af0e7c3caabec17497d0141d44820f0b2fd512a5a1c1b | def _minpoly_compose(ex, x, dom):
'\n Computes the minimal polynomial of an algebraic element\n using operations on minimal polynomials\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x, y\n >>> minimal_polynomial(sqrt(2) + 3*Rati... | Computes the minimal polynomial of an algebraic element
using operations on minimal polynomials
Examples
========
>>> from sympy import minimal_polynomial, sqrt, Rational
>>> from sympy.abc import x, y
>>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True)
x**2 - 2*x - 1
>>> minimal_polynomial(sqrt(y) + ... | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _minpoly_compose | RivtLib/replit01 | 603 | python | def _minpoly_compose(ex, x, dom):
'\n Computes the minimal polynomial of an algebraic element\n using operations on minimal polynomials\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x, y\n >>> minimal_polynomial(sqrt(2) + 3*Rati... | def _minpoly_compose(ex, x, dom):
'\n Computes the minimal polynomial of an algebraic element\n using operations on minimal polynomials\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x, y\n >>> minimal_polynomial(sqrt(2) + 3*Rati... |
6b1cca3133e517e9e4ff2ead81e2104faf0bd86637978876ad160f6790b741b0 | @public
def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None):
'\n Computes the minimal polynomial of an algebraic element.\n\n Parameters\n ==========\n\n ex : Expr\n Element or expression whose minimal polynomial is to be calculated.\n\n x : Symbol, optional\n Ind... | Computes the minimal polynomial of an algebraic element.
Parameters
==========
ex : Expr
Element or expression whose minimal polynomial is to be calculated.
x : Symbol, optional
Independent variable of the minimal polynomial
compose : boolean, optional (default=True)
Method to use for computing minimal ... | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | minimal_polynomial | RivtLib/replit01 | 603 | python | @public
def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None):
'\n Computes the minimal polynomial of an algebraic element.\n\n Parameters\n ==========\n\n ex : Expr\n Element or expression whose minimal polynomial is to be calculated.\n\n x : Symbol, optional\n Ind... | @public
def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None):
'\n Computes the minimal polynomial of an algebraic element.\n\n Parameters\n ==========\n\n ex : Expr\n Element or expression whose minimal polynomial is to be calculated.\n\n x : Symbol, optional\n Ind... |
039b63a672bf0ba93e36060661887fc84230849dbda5ff81cfc0235405498750 | def _minpoly_groebner(ex, x, cls):
'\n Computes the minimal polynomial of an algebraic number\n using Groebner bases\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x\n >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose... | Computes the minimal polynomial of an algebraic number
using Groebner bases
Examples
========
>>> from sympy import minimal_polynomial, sqrt, Rational
>>> from sympy.abc import x
>>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False)
x**2 - 2*x - 1 | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | _minpoly_groebner | RivtLib/replit01 | 603 | python | def _minpoly_groebner(ex, x, cls):
'\n Computes the minimal polynomial of an algebraic number\n using Groebner bases\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x\n >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose... | def _minpoly_groebner(ex, x, cls):
'\n Computes the minimal polynomial of an algebraic number\n using Groebner bases\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x\n >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose... |
0c6e5c96a5b98850c5efd74afa6d0500c4674b903baf5e8b91de01528f237e0d | @public
def primitive_element(extension, x=None, *, ex=False, polys=False):
'Construct a common number field for all extensions. '
if (not extension):
raise ValueError("can't compute primitive element for empty extension")
if (x is not None):
(x, cls) = (sympify(x), Poly)
else:
(... | Construct a common number field for all extensions. | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | primitive_element | RivtLib/replit01 | 603 | python | @public
def primitive_element(extension, x=None, *, ex=False, polys=False):
' '
if (not extension):
raise ValueError("can't compute primitive element for empty extension")
if (x is not None):
(x, cls) = (sympify(x), Poly)
else:
(x, cls) = (Dummy('x'), PurePoly)
if (not ex):
... | @public
def primitive_element(extension, x=None, *, ex=False, polys=False):
' '
if (not extension):
raise ValueError("can't compute primitive element for empty extension")
if (x is not None):
(x, cls) = (sympify(x), Poly)
else:
(x, cls) = (Dummy('x'), PurePoly)
if (not ex):
... |
778926c2eb2ce4870eb5eda995434d3f7c75fe62063b0f844ec6448f3a0758d9 | def is_isomorphism_possible(a, b):
'Returns `True` if there is a chance for isomorphism. '
n = a.minpoly.degree()
m = b.minpoly.degree()
if ((m % n) != 0):
return False
if (n == m):
return True
da = a.minpoly.discriminant()
db = b.minpoly.discriminant()
(i, k, half) = (1,... | Returns `True` if there is a chance for isomorphism. | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | is_isomorphism_possible | RivtLib/replit01 | 603 | python | def is_isomorphism_possible(a, b):
' '
n = a.minpoly.degree()
m = b.minpoly.degree()
if ((m % n) != 0):
return False
if (n == m):
return True
da = a.minpoly.discriminant()
db = b.minpoly.discriminant()
(i, k, half) = (1, (m // n), (db // 2))
while True:
p = si... | def is_isomorphism_possible(a, b):
' '
n = a.minpoly.degree()
m = b.minpoly.degree()
if ((m % n) != 0):
return False
if (n == m):
return True
da = a.minpoly.discriminant()
db = b.minpoly.discriminant()
(i, k, half) = (1, (m // n), (db // 2))
while True:
p = si... |
150fe6e62ebf7d5d9d86ad1e714c73cb3fa8a4e06001d337ba92b426af170f6c | def field_isomorphism_pslq(a, b):
'Construct field isomorphism using PSLQ algorithm. '
if ((not a.root.is_real) or (not b.root.is_real)):
raise NotImplementedError("PSLQ doesn't support complex coefficients")
f = a.minpoly
g = b.minpoly.replace(f.gen)
(n, m, prev) = (100, b.minpoly.degree(),... | Construct field isomorphism using PSLQ algorithm. | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | field_isomorphism_pslq | RivtLib/replit01 | 603 | python | def field_isomorphism_pslq(a, b):
' '
if ((not a.root.is_real) or (not b.root.is_real)):
raise NotImplementedError("PSLQ doesn't support complex coefficients")
f = a.minpoly
g = b.minpoly.replace(f.gen)
(n, m, prev) = (100, b.minpoly.degree(), None)
for i in range(1, 5):
A = a.ro... | def field_isomorphism_pslq(a, b):
' '
if ((not a.root.is_real) or (not b.root.is_real)):
raise NotImplementedError("PSLQ doesn't support complex coefficients")
f = a.minpoly
g = b.minpoly.replace(f.gen)
(n, m, prev) = (100, b.minpoly.degree(), None)
for i in range(1, 5):
A = a.ro... |
02107afe918d47bb7b8c761a9aba102558b027e496d2be4a3a2c5e3f81f99e91 | def field_isomorphism_factor(a, b):
'Construct field isomorphism via factorization. '
(_, factors) = factor_list(a.minpoly, extension=b)
for (f, _) in factors:
if (f.degree() == 1):
coeffs = f.rep.TC().to_sympy_list()
(d, terms) = ((len(coeffs) - 1), [])
for (i, c... | Construct field isomorphism via factorization. | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | field_isomorphism_factor | RivtLib/replit01 | 603 | python | def field_isomorphism_factor(a, b):
' '
(_, factors) = factor_list(a.minpoly, extension=b)
for (f, _) in factors:
if (f.degree() == 1):
coeffs = f.rep.TC().to_sympy_list()
(d, terms) = ((len(coeffs) - 1), [])
for (i, coeff) in enumerate(coeffs):
te... | def field_isomorphism_factor(a, b):
' '
(_, factors) = factor_list(a.minpoly, extension=b)
for (f, _) in factors:
if (f.degree() == 1):
coeffs = f.rep.TC().to_sympy_list()
(d, terms) = ((len(coeffs) - 1), [])
for (i, coeff) in enumerate(coeffs):
te... |
76e9d1b2692c537e7be92214b2d7090d2a3b2520c1ed6eb198a09f466a773321 | @public
def field_isomorphism(a, b, *, fast=True):
'Construct an isomorphism between two number fields. '
(a, b) = (sympify(a), sympify(b))
if (not a.is_AlgebraicNumber):
a = AlgebraicNumber(a)
if (not b.is_AlgebraicNumber):
b = AlgebraicNumber(b)
if (a == b):
return a.coeffs... | Construct an isomorphism between two number fields. | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | field_isomorphism | RivtLib/replit01 | 603 | python | @public
def field_isomorphism(a, b, *, fast=True):
' '
(a, b) = (sympify(a), sympify(b))
if (not a.is_AlgebraicNumber):
a = AlgebraicNumber(a)
if (not b.is_AlgebraicNumber):
b = AlgebraicNumber(b)
if (a == b):
return a.coeffs()
n = a.minpoly.degree()
m = b.minpoly.deg... | @public
def field_isomorphism(a, b, *, fast=True):
' '
(a, b) = (sympify(a), sympify(b))
if (not a.is_AlgebraicNumber):
a = AlgebraicNumber(a)
if (not b.is_AlgebraicNumber):
b = AlgebraicNumber(b)
if (a == b):
return a.coeffs()
n = a.minpoly.degree()
m = b.minpoly.deg... |
9df13d1fd803ce61ca9f0ffe7bd4eec5504126ef27c52d1ee3eb0e9c56642106 | @public
def to_number_field(extension, theta=None, *, gen=None):
'Express `extension` in the field generated by `theta`. '
if hasattr(extension, '__iter__'):
extension = list(extension)
else:
extension = [extension]
if ((len(extension) == 1) and (type(extension[0]) is tuple)):
re... | Express `extension` in the field generated by `theta`. | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | to_number_field | RivtLib/replit01 | 603 | python | @public
def to_number_field(extension, theta=None, *, gen=None):
' '
if hasattr(extension, '__iter__'):
extension = list(extension)
else:
extension = [extension]
if ((len(extension) == 1) and (type(extension[0]) is tuple)):
return AlgebraicNumber(extension[0])
(minpoly, coeff... | @public
def to_number_field(extension, theta=None, *, gen=None):
' '
if hasattr(extension, '__iter__'):
extension = list(extension)
else:
extension = [extension]
if ((len(extension) == 1) and (type(extension[0]) is tuple)):
return AlgebraicNumber(extension[0])
(minpoly, coeff... |
9be35c67f3fddb8fb9e5b23ed0032ab90cfed0c4caf81b918a010ddece4dea03 | @public
def isolate(alg, eps=None, fast=False):
'Give a rational isolating interval for an algebraic number. '
alg = sympify(alg)
if alg.is_Rational:
return (alg, alg)
elif (not alg.is_real):
raise NotImplementedError('complex algebraic numbers are not supported')
func = lambdify((),... | Give a rational isolating interval for an algebraic number. | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | isolate | RivtLib/replit01 | 603 | python | @public
def isolate(alg, eps=None, fast=False):
' '
alg = sympify(alg)
if alg.is_Rational:
return (alg, alg)
elif (not alg.is_real):
raise NotImplementedError('complex algebraic numbers are not supported')
func = lambdify((), alg, modules='mpmath', printer=IntervalPrinter())
poly... | @public
def isolate(alg, eps=None, fast=False):
' '
alg = sympify(alg)
if alg.is_Rational:
return (alg, alg)
elif (not alg.is_real):
raise NotImplementedError('complex algebraic numbers are not supported')
func = lambdify((), alg, modules='mpmath', printer=IntervalPrinter())
poly... |
2a30b9002327df8ab7e6f732da67dd6d74c1c426c0300591df00b6ac080562f5 | def simpler_inverse(ex):
'\n Returns True if it is more likely that the minimal polynomial\n algorithm works better with the inverse\n '
if ex.is_Pow:
if ((1 / ex.exp).is_integer and (ex.exp < 0)):
if ex.base.is_Add:
return True
if ex.is_Mul:
... | Returns True if it is more likely that the minimal polynomial
algorithm works better with the inverse | .venv/lib/python3.8/site-packages/sympy/polys/numberfields.py | simpler_inverse | RivtLib/replit01 | 603 | python | def simpler_inverse(ex):
'\n Returns True if it is more likely that the minimal polynomial\n algorithm works better with the inverse\n '
if ex.is_Pow:
if ((1 / ex.exp).is_integer and (ex.exp < 0)):
if ex.base.is_Add:
return True
if ex.is_Mul:
... | def simpler_inverse(ex):
'\n Returns True if it is more likely that the minimal polynomial\n algorithm works better with the inverse\n '
if ex.is_Pow:
if ((1 / ex.exp).is_integer and (ex.exp < 0)):
if ex.base.is_Add:
return True
if ex.is_Mul:
... |
0ce59989e387908231b502caf13a399f5dc3bfc7088374bd89714f127fe65821 | def make_accessors(strategy='strategy', storage='storage'):
'\n Instead of using this generator, the methods can be implemented manually.\n A third way is to overwrite the getter/setter methods in StrategyFactory.\n '
def make_getter(attr):
def getter(self):
return getattr(self, a... | Instead of using this generator, the methods can be implemented manually.
A third way is to overwrite the getter/setter methods in StrategyFactory. | rpython/rlib/rstrategies/rstrategies.py | make_accessors | yxzoro/pypy | 381 | python | def make_accessors(strategy='strategy', storage='storage'):
'\n Instead of using this generator, the methods can be implemented manually.\n A third way is to overwrite the getter/setter methods in StrategyFactory.\n '
def make_getter(attr):
def getter(self):
return getattr(self, a... | def make_accessors(strategy='strategy', storage='storage'):
'\n Instead of using this generator, the methods can be implemented manually.\n A third way is to overwrite the getter/setter methods in StrategyFactory.\n '
def make_getter(attr):
def getter(self):
return getattr(self, a... |
f5b44397b082c68b7224b9fc7f97754692862b7758b9155ced093ef489099074 | def strategy(generalize=None, singleton=True):
'\n Strategy classes must be decorated with this.\n generalize is a list of other strategies, that can be switched to from the decorated strategy.\n If the singleton flag is set to False, new strategy instances will be created,\n instead of always reusing t... | Strategy classes must be decorated with this.
generalize is a list of other strategies, that can be switched to from the decorated strategy.
If the singleton flag is set to False, new strategy instances will be created,
instead of always reusing the singleton object. | rpython/rlib/rstrategies/rstrategies.py | strategy | yxzoro/pypy | 381 | python | def strategy(generalize=None, singleton=True):
'\n Strategy classes must be decorated with this.\n generalize is a list of other strategies, that can be switched to from the decorated strategy.\n If the singleton flag is set to False, new strategy instances will be created,\n instead of always reusing t... | def strategy(generalize=None, singleton=True):
'\n Strategy classes must be decorated with this.\n generalize is a list of other strategies, that can be switched to from the decorated strategy.\n If the singleton flag is set to False, new strategy instances will be created,\n instead of always reusing t... |
720737c06cc64ac37635b6d4f0f6d6291ae6c3e438a77d45d2bac3eda90f84b2 | def switch_strategy(self, w_self, new_strategy_type, new_element=None):
'\n Switch the strategy of w_self to the new type.\n new_element can be given as as hint, purely for logging purposes.\n It should be the object that was added to w_self, causing the strategy switch.\n '
old_stra... | Switch the strategy of w_self to the new type.
new_element can be given as as hint, purely for logging purposes.
It should be the object that was added to w_self, causing the strategy switch. | rpython/rlib/rstrategies/rstrategies.py | switch_strategy | yxzoro/pypy | 381 | python | def switch_strategy(self, w_self, new_strategy_type, new_element=None):
'\n Switch the strategy of w_self to the new type.\n new_element can be given as as hint, purely for logging purposes.\n It should be the object that was added to w_self, causing the strategy switch.\n '
old_stra... | def switch_strategy(self, w_self, new_strategy_type, new_element=None):
'\n Switch the strategy of w_self to the new type.\n new_element can be given as as hint, purely for logging purposes.\n It should be the object that was added to w_self, causing the strategy switch.\n '
old_stra... |
37f61ea697596c68bdb7964fc83123cf25c8de87f3fb5aa9797652e83d573bfd | def set_initial_strategy(self, w_self, strategy_type, size, elements=None):
'\n Initialize the strategy and storage fields of w_self.\n This must be called before switch_strategy or any strategy method can be used.\n elements is an optional list of values initially stored in w_self.\n If... | Initialize the strategy and storage fields of w_self.
This must be called before switch_strategy or any strategy method can be used.
elements is an optional list of values initially stored in w_self.
If given, then len(elements) == size must hold. | rpython/rlib/rstrategies/rstrategies.py | set_initial_strategy | yxzoro/pypy | 381 | python | def set_initial_strategy(self, w_self, strategy_type, size, elements=None):
'\n Initialize the strategy and storage fields of w_self.\n This must be called before switch_strategy or any strategy method can be used.\n elements is an optional list of values initially stored in w_self.\n If... | def set_initial_strategy(self, w_self, strategy_type, size, elements=None):
'\n Initialize the strategy and storage fields of w_self.\n This must be called before switch_strategy or any strategy method can be used.\n elements is an optional list of values initially stored in w_self.\n If... |
35a1b26dada01ff3639b39e51308b9a3144aa6e0f5a9b17babbfa86289a5c6eb | @jit.unroll_safe
def strategy_type_for(self, objects):
'\n Return the best-fitting strategy to hold all given objects.\n '
specialized_strategies = len(self.strategies)
can_handle = ([True] * specialized_strategies)
for obj in objects:
if (specialized_strategies <= 1):
... | Return the best-fitting strategy to hold all given objects. | rpython/rlib/rstrategies/rstrategies.py | strategy_type_for | yxzoro/pypy | 381 | python | @jit.unroll_safe
def strategy_type_for(self, objects):
'\n \n '
specialized_strategies = len(self.strategies)
can_handle = ([True] * specialized_strategies)
for obj in objects:
if (specialized_strategies <= 1):
break
for (i, strategy) in enumerate(self.strategie... | @jit.unroll_safe
def strategy_type_for(self, objects):
'\n \n '
specialized_strategies = len(self.strategies)
can_handle = ([True] * specialized_strategies)
for obj in objects:
if (specialized_strategies <= 1):
break
for (i, strategy) in enumerate(self.strategie... |
c7dc4ebc8a6e6fd49044caf51196b1e5c827ead390c33b0402792578fe6d3453 | @not_rpython
def decorate_strategies(self, transitions):
"\n As an alternative to decorating all strategies with @strategy,\n invoke this in the constructor of your StrategyFactory subclass, before\n calling __init__. transitions is a dict mapping all strategy classes to\n their 'general... | As an alternative to decorating all strategies with @strategy,
invoke this in the constructor of your StrategyFactory subclass, before
calling __init__. transitions is a dict mapping all strategy classes to
their 'generalize' list parameter (see @strategy decorator). | rpython/rlib/rstrategies/rstrategies.py | decorate_strategies | yxzoro/pypy | 381 | python | @not_rpython
def decorate_strategies(self, transitions):
"\n As an alternative to decorating all strategies with @strategy,\n invoke this in the constructor of your StrategyFactory subclass, before\n calling __init__. transitions is a dict mapping all strategy classes to\n their 'general... | @not_rpython
def decorate_strategies(self, transitions):
"\n As an alternative to decorating all strategies with @strategy,\n invoke this in the constructor of your StrategyFactory subclass, before\n calling __init__. transitions is a dict mapping all strategy classes to\n their 'general... |
edd1fc2ed97b9ea9e5e55b496a84ff771085328605319d2d858bd9296988bd65 | def instantiate_strategy(self, strategy_type, w_self=None, initial_size=0):
'\n Return a functional instance of strategy_type.\n Overwrite this if you need a non-default constructor.\n The two additional parameters should be ignored for singleton-strategies.\n '
return strategy_type(... | Return a functional instance of strategy_type.
Overwrite this if you need a non-default constructor.
The two additional parameters should be ignored for singleton-strategies. | rpython/rlib/rstrategies/rstrategies.py | instantiate_strategy | yxzoro/pypy | 381 | python | def instantiate_strategy(self, strategy_type, w_self=None, initial_size=0):
'\n Return a functional instance of strategy_type.\n Overwrite this if you need a non-default constructor.\n The two additional parameters should be ignored for singleton-strategies.\n '
return strategy_type(... | def instantiate_strategy(self, strategy_type, w_self=None, initial_size=0):
'\n Return a functional instance of strategy_type.\n Overwrite this if you need a non-default constructor.\n The two additional parameters should be ignored for singleton-strategies.\n '
return strategy_type(... |
983c94a78382ecfcfc991f282356f6d6f0e2e438cf303c42e81784a8a6cfc6db | def log(self, w_self, new_strategy, old_strategy=None, new_element=None):
'\n This can be overwritten into a more appropriate call to self.logger.log\n '
if (not self.logger.active):
return
new_strategy_str = self.log_string_for_object(new_strategy)
old_strategy_str = self.log_stri... | This can be overwritten into a more appropriate call to self.logger.log | rpython/rlib/rstrategies/rstrategies.py | log | yxzoro/pypy | 381 | python | def log(self, w_self, new_strategy, old_strategy=None, new_element=None):
'\n \n '
if (not self.logger.active):
return
new_strategy_str = self.log_string_for_object(new_strategy)
old_strategy_str = self.log_string_for_object(old_strategy)
element_typename = self.log_string_for_... | def log(self, w_self, new_strategy, old_strategy=None, new_element=None):
'\n \n '
if (not self.logger.active):
return
new_strategy_str = self.log_string_for_object(new_strategy)
old_strategy_str = self.log_string_for_object(old_strategy)
element_typename = self.log_string_for_... |
a5e394966654b880479b065bbcd725b0e90e20eb7e56c80620697a8f8f6c11bd | @specialize.call_location()
def log_string_for_object(self, obj):
'\n This can be overwritten instead of the entire log() method.\n Keep the specialize-annotation in order to handle different kinds of objects here.\n '
return (obj.__class__.__name__ if obj else '') | This can be overwritten instead of the entire log() method.
Keep the specialize-annotation in order to handle different kinds of objects here. | rpython/rlib/rstrategies/rstrategies.py | log_string_for_object | yxzoro/pypy | 381 | python | @specialize.call_location()
def log_string_for_object(self, obj):
'\n This can be overwritten instead of the entire log() method.\n Keep the specialize-annotation in order to handle different kinds of objects here.\n '
return (obj.__class__.__name__ if obj else ) | @specialize.call_location()
def log_string_for_object(self, obj):
'\n This can be overwritten instead of the entire log() method.\n Keep the specialize-annotation in order to handle different kinds of objects here.\n '
return (obj.__class__.__name__ if obj else )<|docstring|>This can be ove... |
3b6e17a11b37626c2f186aa2f81e9af0697e69f5d07c967b493ce1b7ab2337a7 | def force_unicode(value):
'\n Forces a bytestring to become a Unicode string.\n '
if IS_PY3:
if isinstance(value, bytes):
value = value.decode('utf-8', errors='replace')
elif (not isinstance(value, str)):
value = str(value)
elif isinstance(value, str):
v... | Forces a bytestring to become a Unicode string. | pysolr.py | force_unicode | sxalexander/pysolr | 0 | python | def force_unicode(value):
'\n \n '
if IS_PY3:
if isinstance(value, bytes):
value = value.decode('utf-8', errors='replace')
elif (not isinstance(value, str)):
value = str(value)
elif isinstance(value, str):
value = value.decode('utf-8', 'replace')
eli... | def force_unicode(value):
'\n \n '
if IS_PY3:
if isinstance(value, bytes):
value = value.decode('utf-8', errors='replace')
elif (not isinstance(value, str)):
value = str(value)
elif isinstance(value, str):
value = value.decode('utf-8', 'replace')
eli... |
b7d1e464fa61401108dda128682cb8ffbe6970b5ac44ffd16ff50d309a2a2392 | def force_bytes(value):
'\n Forces a Unicode string to become a bytestring.\n '
if IS_PY3:
if isinstance(value, str):
value = value.encode('utf-8')
elif isinstance(value, unicode):
value = value.encode('utf-8')
return value | Forces a Unicode string to become a bytestring. | pysolr.py | force_bytes | sxalexander/pysolr | 0 | python | def force_bytes(value):
'\n \n '
if IS_PY3:
if isinstance(value, str):
value = value.encode('utf-8')
elif isinstance(value, unicode):
value = value.encode('utf-8')
return value | def force_bytes(value):
'\n \n '
if IS_PY3:
if isinstance(value, str):
value = value.encode('utf-8')
elif isinstance(value, unicode):
value = value.encode('utf-8')
return value<|docstring|>Forces a Unicode string to become a bytestring.<|endoftext|> |
b8abd55ec3e727d7ba2b759e49817a9d8d70aaf939b0302a444cb8dbde019153 | def unescape_html(text):
'\n Removes HTML or XML character references and entities from a text string.\n\n @param text The HTML (or XML) source text.\n @return The plain text, as a Unicode string, if necessary.\n\n Source: http://effbot.org/zone/re-sub.htm#unescape-html\n '
def fixup(m):
... | Removes HTML or XML character references and entities from a text string.
@param text The HTML (or XML) source text.
@return The plain text, as a Unicode string, if necessary.
Source: http://effbot.org/zone/re-sub.htm#unescape-html | pysolr.py | unescape_html | sxalexander/pysolr | 0 | python | def unescape_html(text):
'\n Removes HTML or XML character references and entities from a text string.\n\n @param text The HTML (or XML) source text.\n @return The plain text, as a Unicode string, if necessary.\n\n Source: http://effbot.org/zone/re-sub.htm#unescape-html\n '
def fixup(m):
... | def unescape_html(text):
'\n Removes HTML or XML character references and entities from a text string.\n\n @param text The HTML (or XML) source text.\n @return The plain text, as a Unicode string, if necessary.\n\n Source: http://effbot.org/zone/re-sub.htm#unescape-html\n '
def fixup(m):
... |
bf80685693d9c5be2eab106428729c9abc8172f822ddb278150cf1bbff9ea8df | def safe_urlencode(params, doseq=0):
"\n UTF-8-safe version of safe_urlencode\n\n The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values\n which can't fail down to ascii.\n "
if IS_PY3:
return urlencode(params, doseq)
if hasattr(params, 'items'):
params = params.ite... | UTF-8-safe version of safe_urlencode
The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values
which can't fail down to ascii. | pysolr.py | safe_urlencode | sxalexander/pysolr | 0 | python | def safe_urlencode(params, doseq=0):
"\n UTF-8-safe version of safe_urlencode\n\n The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values\n which can't fail down to ascii.\n "
if IS_PY3:
return urlencode(params, doseq)
if hasattr(params, 'items'):
params = params.ite... | def safe_urlencode(params, doseq=0):
"\n UTF-8-safe version of safe_urlencode\n\n The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values\n which can't fail down to ascii.\n "
if IS_PY3:
return urlencode(params, doseq)
if hasattr(params, 'items'):
params = params.ite... |
6a5792bdc6a3854a197a58f998694d0671d6c5d6e914fe99efc1951a8a5927c1 | def _extract_error(self, resp):
'\n Extract the actual error message from a solr response.\n '
reason = resp.headers.get('reason', None)
full_html = None
if (reason is None):
(reason, full_html) = self._scrape_response(resp.headers, resp.content)
msg = ('[Reason: %s]' % reason)... | Extract the actual error message from a solr response. | pysolr.py | _extract_error | sxalexander/pysolr | 0 | python | def _extract_error(self, resp):
'\n \n '
reason = resp.headers.get('reason', None)
full_html = None
if (reason is None):
(reason, full_html) = self._scrape_response(resp.headers, resp.content)
msg = ('[Reason: %s]' % reason)
if (reason is None):
msg += ('\n%s' % une... | def _extract_error(self, resp):
'\n \n '
reason = resp.headers.get('reason', None)
full_html = None
if (reason is None):
(reason, full_html) = self._scrape_response(resp.headers, resp.content)
msg = ('[Reason: %s]' % reason)
if (reason is None):
msg += ('\n%s' % une... |
19736f67eb930385f2a2c8dbebca60eacc0ec8cd377cbc536035d897dd520d90 | def _scrape_response(self, headers, response):
'\n Scrape the html response.\n '
server_type = None
server_string = headers.get('server', '')
if (server_string and ('jetty' in server_string.lower())):
server_type = 'jetty'
if (server_string and ('coyote' in server_string.lower(... | Scrape the html response. | pysolr.py | _scrape_response | sxalexander/pysolr | 0 | python | def _scrape_response(self, headers, response):
'\n \n '
server_type = None
server_string = headers.get('server', )
if (server_string and ('jetty' in server_string.lower())):
server_type = 'jetty'
if (server_string and ('coyote' in server_string.lower())):
import lxml.ht... | def _scrape_response(self, headers, response):
'\n \n '
server_type = None
server_string = headers.get('server', )
if (server_string and ('jetty' in server_string.lower())):
server_type = 'jetty'
if (server_string and ('coyote' in server_string.lower())):
import lxml.ht... |
a46b632856636043bb0fa9f20c1752faa8765888a0c7d0043e53ff9c72494149 | def _update(self, message, clean_ctrl_chars=True, commit=True, waitFlush=None, waitSearcher=None):
"\n Posts the given xml message to http://<self.url>/update and\n returns the result.\n\n Passing `sanitize` as False will prevent the message from being cleaned\n of control characters (de... | Posts the given xml message to http://<self.url>/update and
returns the result.
Passing `sanitize` as False will prevent the message from being cleaned
of control characters (default True). This is done by default because
these characters would cause Solr to fail to parse the XML. Only pass
False if you're positive yo... | pysolr.py | _update | sxalexander/pysolr | 0 | python | def _update(self, message, clean_ctrl_chars=True, commit=True, waitFlush=None, waitSearcher=None):
"\n Posts the given xml message to http://<self.url>/update and\n returns the result.\n\n Passing `sanitize` as False will prevent the message from being cleaned\n of control characters (de... | def _update(self, message, clean_ctrl_chars=True, commit=True, waitFlush=None, waitSearcher=None):
"\n Posts the given xml message to http://<self.url>/update and\n returns the result.\n\n Passing `sanitize` as False will prevent the message from being cleaned\n of control characters (de... |
abd0dfb427e59bbaa7cd1b3bc3b3aabfdcb4a2d1d72febb39ce208e2b383e977 | def _from_python(self, value):
'\n Converts python values to a form suitable for insertion into the xml\n we send to solr.\n '
if hasattr(value, 'strftime'):
if hasattr(value, 'hour'):
value = ('%sZ' % value.isoformat())
else:
value = ('%sT00:00:00Z' ... | Converts python values to a form suitable for insertion into the xml
we send to solr. | pysolr.py | _from_python | sxalexander/pysolr | 0 | python | def _from_python(self, value):
'\n Converts python values to a form suitable for insertion into the xml\n we send to solr.\n '
if hasattr(value, 'strftime'):
if hasattr(value, 'hour'):
value = ('%sZ' % value.isoformat())
else:
value = ('%sT00:00:00Z' ... | def _from_python(self, value):
'\n Converts python values to a form suitable for insertion into the xml\n we send to solr.\n '
if hasattr(value, 'strftime'):
if hasattr(value, 'hour'):
value = ('%sZ' % value.isoformat())
else:
value = ('%sT00:00:00Z' ... |
87917024ec14a09d2b772ec644a6cf4038ee87c64b152394e406d0117d445461 | def _to_python(self, value):
'\n Converts values from Solr to native Python values.\n '
if isinstance(value, (int, float, long, complex)):
return value
if isinstance(value, (list, tuple)):
value = value[0]
if (value == 'true'):
return True
elif (value == 'false'... | Converts values from Solr to native Python values. | pysolr.py | _to_python | sxalexander/pysolr | 0 | python | def _to_python(self, value):
'\n \n '
if isinstance(value, (int, float, long, complex)):
return value
if isinstance(value, (list, tuple)):
value = value[0]
if (value == 'true'):
return True
elif (value == 'false'):
return False
is_string = False
... | def _to_python(self, value):
'\n \n '
if isinstance(value, (int, float, long, complex)):
return value
if isinstance(value, (list, tuple)):
value = value[0]
if (value == 'true'):
return True
elif (value == 'false'):
return False
is_string = False
... |
e176a45cc2ac3088daf00445526bc119285c0ad422af430583157d919b0ec181 | def _is_null_value(self, value):
"\n Check if a given value is ``null``.\n\n Criteria for this is based on values that shouldn't be included\n in the Solr ``add`` request at all.\n "
if (value is None):
return True
if IS_PY3:
if (isinstance(value, str) and (len(va... | Check if a given value is ``null``.
Criteria for this is based on values that shouldn't be included
in the Solr ``add`` request at all. | pysolr.py | _is_null_value | sxalexander/pysolr | 0 | python | def _is_null_value(self, value):
"\n Check if a given value is ``null``.\n\n Criteria for this is based on values that shouldn't be included\n in the Solr ``add`` request at all.\n "
if (value is None):
return True
if IS_PY3:
if (isinstance(value, str) and (len(va... | def _is_null_value(self, value):
"\n Check if a given value is ``null``.\n\n Criteria for this is based on values that shouldn't be included\n in the Solr ``add`` request at all.\n "
if (value is None):
return True
if IS_PY3:
if (isinstance(value, str) and (len(va... |
6ca32e6850954a7332c1c6df4e092a36435983dec7a081fcd56c0d9f466d272c | def search(self, q, **kwargs):
"\n Performs a search and returns the results.\n\n Requires a ``q`` for a string version of the query to run.\n\n Optionally accepts ``**kwargs`` for additional options to be passed\n through the Solr URL.\n\n Usage::\n\n # All docs.\n ... | Performs a search and returns the results.
Requires a ``q`` for a string version of the query to run.
Optionally accepts ``**kwargs`` for additional options to be passed
through the Solr URL.
Usage::
# All docs.
results = solr.search('*:*')
# Search with highlighting.
results = solr.search('ponies'... | pysolr.py | search | sxalexander/pysolr | 0 | python | def search(self, q, **kwargs):
"\n Performs a search and returns the results.\n\n Requires a ``q`` for a string version of the query to run.\n\n Optionally accepts ``**kwargs`` for additional options to be passed\n through the Solr URL.\n\n Usage::\n\n # All docs.\n ... | def search(self, q, **kwargs):
"\n Performs a search and returns the results.\n\n Requires a ``q`` for a string version of the query to run.\n\n Optionally accepts ``**kwargs`` for additional options to be passed\n through the Solr URL.\n\n Usage::\n\n # All docs.\n ... |
19580121e9eeb78f51e26d0e031020eee3a782bf4ea00cb206de454e1114122c | def more_like_this(self, q, mltfl, **kwargs):
"\n Finds and returns results similar to the provided query.\n\n Requires Solr 1.3+.\n\n Usage::\n\n similar = solr.more_like_this('id:doc_234', 'text')\n\n "
params = {'q': q, 'mlt.fl': mltfl}
params.update(kwargs)
res... | Finds and returns results similar to the provided query.
Requires Solr 1.3+.
Usage::
similar = solr.more_like_this('id:doc_234', 'text') | pysolr.py | more_like_this | sxalexander/pysolr | 0 | python | def more_like_this(self, q, mltfl, **kwargs):
"\n Finds and returns results similar to the provided query.\n\n Requires Solr 1.3+.\n\n Usage::\n\n similar = solr.more_like_this('id:doc_234', 'text')\n\n "
params = {'q': q, 'mlt.fl': mltfl}
params.update(kwargs)
res... | def more_like_this(self, q, mltfl, **kwargs):
"\n Finds and returns results similar to the provided query.\n\n Requires Solr 1.3+.\n\n Usage::\n\n similar = solr.more_like_this('id:doc_234', 'text')\n\n "
params = {'q': q, 'mlt.fl': mltfl}
params.update(kwargs)
res... |
2ca098c6c46917db2c1a8c3a39b6271cea47ad551b33b7fcbddf37429536c5ad | def suggest_terms(self, fields, prefix, **kwargs):
'\n Accepts a list of field names and a prefix\n\n Returns a dictionary keyed on field name containing a list of\n ``(term, count)`` pairs\n\n Requires Solr 1.4+.\n '
params = {'terms.fl': fields, 'terms.prefix': prefix}
p... | Accepts a list of field names and a prefix
Returns a dictionary keyed on field name containing a list of
``(term, count)`` pairs
Requires Solr 1.4+. | pysolr.py | suggest_terms | sxalexander/pysolr | 0 | python | def suggest_terms(self, fields, prefix, **kwargs):
'\n Accepts a list of field names and a prefix\n\n Returns a dictionary keyed on field name containing a list of\n ``(term, count)`` pairs\n\n Requires Solr 1.4+.\n '
params = {'terms.fl': fields, 'terms.prefix': prefix}
p... | def suggest_terms(self, fields, prefix, **kwargs):
'\n Accepts a list of field names and a prefix\n\n Returns a dictionary keyed on field name containing a list of\n ``(term, count)`` pairs\n\n Requires Solr 1.4+.\n '
params = {'terms.fl': fields, 'terms.prefix': prefix}
p... |
0f2f8a1850db521077d209ef3b0c07fe65a30dfc574ab10466c11a89de2507cb | def add(self, docs, commit=True, boost=None, commitWithin=None, waitFlush=None, waitSearcher=None):
'\n Adds or updates documents.\n\n Requires ``docs``, which is a list of dictionaries. Each key is the\n field name and each value is the value to index.\n\n Optionally accepts ``commit``.... | Adds or updates documents.
Requires ``docs``, which is a list of dictionaries. Each key is the
field name and each value is the value to index.
Optionally accepts ``commit``. Default is ``True``.
Optionally accepts ``boost``. Default is ``None``.
Optionally accepts ``commitWithin``. Default is ``None``.
Optionally... | pysolr.py | add | sxalexander/pysolr | 0 | python | def add(self, docs, commit=True, boost=None, commitWithin=None, waitFlush=None, waitSearcher=None):
'\n Adds or updates documents.\n\n Requires ``docs``, which is a list of dictionaries. Each key is the\n field name and each value is the value to index.\n\n Optionally accepts ``commit``.... | def add(self, docs, commit=True, boost=None, commitWithin=None, waitFlush=None, waitSearcher=None):
'\n Adds or updates documents.\n\n Requires ``docs``, which is a list of dictionaries. Each key is the\n field name and each value is the value to index.\n\n Optionally accepts ``commit``.... |
75289f38ff47d9392d33529450f8108f98a298646e114f9c4f1a99d644f8b20b | def delete(self, id=None, q=None, commit=True, waitFlush=None, waitSearcher=None):
"\n Deletes documents.\n\n Requires *either* ``id`` or ``query``. ``id`` is if you know the\n specific document id to remove. ``query`` is a Lucene-style query\n indicating a collection of documents to del... | Deletes documents.
Requires *either* ``id`` or ``query``. ``id`` is if you know the
specific document id to remove. ``query`` is a Lucene-style query
indicating a collection of documents to delete.
Optionally accepts ``commit``. Default is ``True``.
Optionally accepts ``waitFlush``. Default is ``None``.
Optionally ... | pysolr.py | delete | sxalexander/pysolr | 0 | python | def delete(self, id=None, q=None, commit=True, waitFlush=None, waitSearcher=None):
"\n Deletes documents.\n\n Requires *either* ``id`` or ``query``. ``id`` is if you know the\n specific document id to remove. ``query`` is a Lucene-style query\n indicating a collection of documents to del... | def delete(self, id=None, q=None, commit=True, waitFlush=None, waitSearcher=None):
"\n Deletes documents.\n\n Requires *either* ``id`` or ``query``. ``id`` is if you know the\n specific document id to remove. ``query`` is a Lucene-style query\n indicating a collection of documents to del... |
8a659b9c0b01fc28a9da2ad37f0d4a249b22146595ef871b5116cf2e28162985 | def commit(self, waitFlush=None, waitSearcher=None, expungeDeletes=None):
'\n Forces Solr to write the index data to disk.\n\n Optionally accepts ``expungeDeletes``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. D... | Forces Solr to write the index data to disk.
Optionally accepts ``expungeDeletes``. Default is ``None``.
Optionally accepts ``waitFlush``. Default is ``None``.
Optionally accepts ``waitSearcher``. Default is ``None``.
Usage::
solr.commit() | pysolr.py | commit | sxalexander/pysolr | 0 | python | def commit(self, waitFlush=None, waitSearcher=None, expungeDeletes=None):
'\n Forces Solr to write the index data to disk.\n\n Optionally accepts ``expungeDeletes``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. D... | def commit(self, waitFlush=None, waitSearcher=None, expungeDeletes=None):
'\n Forces Solr to write the index data to disk.\n\n Optionally accepts ``expungeDeletes``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. D... |
e845101921b8a12e4470e8992191e1857574eecd4679374646d91d1434bfdd2a | def optimize(self, waitFlush=None, waitSearcher=None, maxSegments=None):
'\n Tells Solr to streamline the number of segments used, essentially a\n defragmentation operation.\n\n Optionally accepts ``maxSegments``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``No... | Tells Solr to streamline the number of segments used, essentially a
defragmentation operation.
Optionally accepts ``maxSegments``. Default is ``None``.
Optionally accepts ``waitFlush``. Default is ``None``.
Optionally accepts ``waitSearcher``. Default is ``None``.
Usage::
solr.optimize() | pysolr.py | optimize | sxalexander/pysolr | 0 | python | def optimize(self, waitFlush=None, waitSearcher=None, maxSegments=None):
'\n Tells Solr to streamline the number of segments used, essentially a\n defragmentation operation.\n\n Optionally accepts ``maxSegments``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``No... | def optimize(self, waitFlush=None, waitSearcher=None, maxSegments=None):
'\n Tells Solr to streamline the number of segments used, essentially a\n defragmentation operation.\n\n Optionally accepts ``maxSegments``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``No... |
8ded1cebf5a05532b511a7db6307d5e911ca423dbaee42b26fa151c4a42c9666 | def extract(self, file_obj, extractOnly=True, **kwargs):
"\n POSTs a file to the Solr ExtractingRequestHandler so rich content can\n be processed using Apache Tika. See the Solr wiki for details:\n\n http://wiki.apache.org/solr/ExtractingRequestHandler\n\n The ExtractingRequestHandle... | POSTs a file to the Solr ExtractingRequestHandler so rich content can
be processed using Apache Tika. See the Solr wiki for details:
http://wiki.apache.org/solr/ExtractingRequestHandler
The ExtractingRequestHandler has a very simply model: it extracts
contents and metadata from the uploaded file and inserts it di... | pysolr.py | extract | sxalexander/pysolr | 0 | python | def extract(self, file_obj, extractOnly=True, **kwargs):
"\n POSTs a file to the Solr ExtractingRequestHandler so rich content can\n be processed using Apache Tika. See the Solr wiki for details:\n\n http://wiki.apache.org/solr/ExtractingRequestHandler\n\n The ExtractingRequestHandle... | def extract(self, file_obj, extractOnly=True, **kwargs):
"\n POSTs a file to the Solr ExtractingRequestHandler so rich content can\n be processed using Apache Tika. See the Solr wiki for details:\n\n http://wiki.apache.org/solr/ExtractingRequestHandler\n\n The ExtractingRequestHandle... |
fd9be8845f84bcb40b78aec56dd24ebf9115c9e03ac46a9b225d434e93f5454d | def status(self, core=None):
'http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953'
params = {'action': 'STATUS'}
if (core is not None):
params.update(core=core)
return self._get_url(params=params) | http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953 | pysolr.py | status | sxalexander/pysolr | 0 | python | def status(self, core=None):
params = {'action': 'STATUS'}
if (core is not None):
params.update(core=core)
return self._get_url(params=params) | def status(self, core=None):
params = {'action': 'STATUS'}
if (core is not None):
params.update(core=core)
return self._get_url(params=params)<|docstring|>http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.