blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 777
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
sequencelengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6b65d35046b48be71a3df21e7ab47327a6e56a42 | 49c2492d91789b3c2def7d654a7396e8c6ce6d9f | /ROS/ros_archive/dyros_backup/original/catkin_ws_right/build/gps_test/catkin_generated/pkg.installspace.context.pc.py | 562b7a65ea657b1e00388349bb7282ec2cc8d76f | [] | no_license | DavidHan008/lockdpwn | edd571165f9188e0ee93da7222c0155abb427927 | 5078a1b08916b84c5c3723fc61a1964d7fb9ae20 | refs/heads/master | 2021-01-23T14:10:53.209406 | 2017-09-02T18:02:50 | 2017-09-02T18:02:50 | 102,670,531 | 0 | 2 | null | 2017-09-07T00:11:33 | 2017-09-07T00:11:33 | null | UTF-8 | Python | false | false | 414 | py | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "roscpp;std_msgs".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lgps_test".split(';') if "-lgps_test" != "" else []
PROJECT_NAME = "gps_test"
PROJECT_SPACE_DIR = "/home/dyros-vehicle/catkin_ws/install"
PROJECT_VERSION = "0.0.0"
| [
"[email protected]"
] | |
b5e7c3e35e02e537e325be2564d2639f88a3b296 | 98fe2f95d7fba400c592996681099014279bff70 | /voomza/apps/books_common/tests/yearbook_signs.py | f38d5cbb32ad58c562791185ed125b22280af276 | [] | no_license | bcattle/monkeybook | 51435a3c0416314597adcbb5f958c2761d92bfea | e01f2c371d124449f053ee37eb71ce9a64732e56 | refs/heads/master | 2016-09-06T13:28:23.332786 | 2013-03-22T02:04:15 | 2013-03-22T02:04:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,308 | py | import random
from django.test import TestCase
class YearbookSignPaginationTestCase(TestCase):
short_sign = "Remember when we snuck into the pastry shop on 23rd street??? " \
"I wont' forget the epic nights out in 2012."
long_sign = "Remember when we snuck into the pastry shop on 23rd street??? " \
"I won't forget the epic nights out in 2012. I won't forget " \
"the epic nights out in 2012. To many more in 2013!!"
def get_signs(self, short=0, long=0):
signs = []
[signs.append(self.short_sign) for n in range(short)]
[signs.append(self.long_sign) for n in range(long)]
random.shuffle(signs)
return signs
def test_all_short(self):
import ipdb
ipdb.set_trace()
signs = self.get_signs(short=8)
pages = assign_signs_to_pages(signs)
# 2 pages: 6 on the first, 2 on the second
self.assertEqual(len(pages), 2)
self.assertEqual(len(pages[0]), 6)
self.assertEqual(len(pages[1]), 2)
def test_all_long(self):
self.assertEqual(1 + 1, 2)
def test_1_long(self):
self.assertEqual(1 + 1, 2)
def test_2_long(self):
self.assertEqual(1 + 1, 2)
def test_5_long(self):
self.assertEqual(1 + 1, 2)
| [
"[email protected]"
] | |
a17d73746b0631f4641d030ccdf9928550f5a492 | ea262de505a1dd5ae1c7b546b85184309c3fdd35 | /src/losses/lovasz_losses.py | a09413d3a11bef1f69614032be1062e97d76acec | [
"MIT"
] | permissive | Runki2018/CvPytorch | 306ff578c5f8d3d196d0834e5cad5adba7a89676 | 1e1c468e5971c1c2b037334f7911ae0a5087050f | refs/heads/master | 2023-08-25T09:48:48.764117 | 2021-10-15T05:11:21 | 2021-10-15T05:11:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,504 | py | """
Lovasz-Softmax and Jaccard hinge loss in PyTorch
Maxim Berman 2018 ESAT-PSI KU Leuven (MIT License)
https://github.com/bermanmaxim/LovaszSoftmax/blob/master/pytorch/lovasz_losses.py
"""
from __future__ import print_function, division
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
try:
from itertools import ifilterfalse
except ImportError: # py3k
from itertools import filterfalse as ifilterfalse
def lovasz_grad(gt_sorted):
"""
Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper
"""
p = len(gt_sorted)
gts = gt_sorted.sum()
intersection = gts - gt_sorted.float().cumsum(0)
union = gts + (1 - gt_sorted).float().cumsum(0)
jaccard = 1. - intersection / union
if p > 1: # cover 1-pixel case
jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]
return jaccard
def iou_binary(preds, labels, EMPTY=1., ignore=None, per_image=True):
"""
IoU for foreground class
binary: 1 foreground, 0 background
"""
if not per_image:
preds, labels = (preds,), (labels,)
ious = []
for pred, label in zip(preds, labels):
intersection = ((label == 1) & (pred == 1)).sum()
union = ((label == 1) | ((pred == 1) & (label != ignore))).sum()
if not union:
iou = EMPTY
else:
iou = float(intersection) / float(union)
ious.append(iou)
iou = mean(ious) # mean accross images if per_image
return 100 * iou
def iou(preds, labels, C, EMPTY=1., ignore=None, per_image=False):
"""
Array of IoU for each (non ignored) class
"""
if not per_image:
preds, labels = (preds,), (labels,)
ious = []
for pred, label in zip(preds, labels):
iou = []
for i in range(C):
if i != ignore: # The ignored label is sometimes among predicted classes (ENet - CityScapes)
intersection = ((label == i) & (pred == i)).sum()
union = ((label == i) | ((pred == i) & (label != ignore))).sum()
if not union:
iou.append(EMPTY)
else:
iou.append(float(intersection) / float(union))
ious.append(iou)
ious = [mean(iou) for iou in zip(*ious)] # mean accross images if per_image
return 100 * np.array(ious)
# --------------------------- BINARY LOSSES ---------------------------
def lovasz_hinge(logits, labels, per_image=True, ignore=None):
"""
Binary Lovasz hinge loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
per_image: compute the loss per image instead of per batch
ignore: void class id
"""
if per_image:
loss = mean(lovasz_hinge_flat(*flatten_binary_scores(log.unsqueeze(0), lab.unsqueeze(0), ignore))
for log, lab in zip(logits, labels))
else:
loss = lovasz_hinge_flat(*flatten_binary_scores(logits, labels, ignore))
return loss
def lovasz_hinge_flat(logits, labels):
"""
Binary Lovasz hinge loss
logits: [P] Variable, logits at each prediction (between -\infty and +\infty)
labels: [P] Tensor, binary ground truth labels (0 or 1)
ignore: label to ignore
"""
if len(labels) == 0:
# only void pixels, the gradients should be 0
return logits.sum() * 0.
signs = 2. * labels.float() - 1.
errors = (1. - logits * Variable(signs))
errors_sorted, perm = torch.sort(errors, dim=0, descending=True)
perm = perm.data
gt_sorted = labels[perm]
grad = lovasz_grad(gt_sorted)
loss = torch.dot(F.relu(errors_sorted), Variable(grad))
return loss
def flatten_binary_scores(scores, labels, ignore=None):
"""
Flattens predictions in the batch (binary case)
Remove labels equal to 'ignore'
"""
scores = scores.view(-1)
labels = labels.view(-1)
if ignore is None:
return scores, labels
valid = (labels != ignore)
vscores = scores[valid]
vlabels = labels[valid]
return vscores, vlabels
class StableBCELoss(torch.nn.modules.Module):
def __init__(self):
super(StableBCELoss, self).__init__()
def forward(self, input, target):
neg_abs = - input.abs()
loss = input.clamp(min=0) - input * target + (1 + neg_abs.exp()).log()
return loss.mean()
def binary_xloss(logits, labels, ignore=None):
"""
Binary Cross entropy loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
ignore: void class id
"""
logits, labels = flatten_binary_scores(logits, labels, ignore)
loss = StableBCELoss()(logits, Variable(labels.float()))
return loss
# --------------------------- MULTICLASS LOSSES ---------------------------
def lovasz_softmax(probas, labels, classes='present', per_image=False, ignore=None):
"""
Multi-class Lovasz-Softmax loss
probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1).
Interpreted as binary (sigmoid) output with outputs of size [B, H, W].
labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1)
classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average.
per_image: compute the loss per image instead of per batch
ignore: void class labels
"""
if per_image:
loss = mean(lovasz_softmax_flat(*flatten_probas(prob.unsqueeze(0), lab.unsqueeze(0), ignore), classes=classes)
for prob, lab in zip(probas, labels))
else:
loss = lovasz_softmax_flat(*flatten_probas(probas, labels, ignore), classes=classes)
return loss
def lovasz_softmax_flat(probas, labels, classes='present'):
"""
Multi-class Lovasz-Softmax loss
probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1)
labels: [P] Tensor, ground truth labels (between 0 and C - 1)
classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average.
"""
if probas.numel() == 0:
# only void pixels, the gradients should be 0
return probas * 0.
C = probas.size(1)
losses = []
class_to_sum = list(range(C)) if classes in ['all', 'present'] else classes
for c in class_to_sum:
fg = (labels == c).float() # foreground for class c
if (classes == 'present' and fg.sum() == 0):
continue
if C == 1:
if len(classes) > 1:
raise ValueError('Sigmoid output possible only with 1 class')
class_pred = probas[:, 0]
else:
class_pred = probas[:, c]
errors = (Variable(fg) - class_pred).abs()
errors_sorted, perm = torch.sort(errors, 0, descending=True)
perm = perm.data
fg_sorted = fg[perm]
losses.append(torch.dot(errors_sorted, Variable(lovasz_grad(fg_sorted))))
return mean(losses)
def flatten_probas(probas, labels, ignore=None):
"""
Flattens predictions in the batch
"""
if probas.dim() == 3:
# assumes output of a sigmoid layer
B, H, W = probas.size()
probas = probas.view(B, 1, H, W)
B, C, H, W = probas.size()
probas = probas.permute(0, 2, 3, 1).contiguous().view(-1, C) # B * H * W, C = P, C
labels = labels.view(-1)
if ignore is None:
return probas, labels
valid = (labels != ignore)
# vprobas = probas[valid.nonzero().squeeze()]
vprobas = probas[torch.nonzero(valid, as_tuple=False).squeeze()]
vlabels = labels[valid]
return vprobas, vlabels
def xloss(logits, labels, ignore=None):
"""
Cross entropy loss
"""
return F.cross_entropy(logits, Variable(labels), ignore_index=255)
# --------------------------- HELPER FUNCTIONS ---------------------------
def isnan(x):
return x != x
def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
return empty
for n, v in enumerate(l, 2):
acc += v
if n == 1:
return acc
return acc / n
| [
"[email protected]"
] | |
9f0f9a18fd94e3ee3b6e016fcc1957d57a35bd41 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03805/s294798234.py | 6299c897ff1f6ded8b87e4e179c3be4d195d7f46 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 355 | py | from itertools import permutations
N, M, *ab = map(int, open(0).read().split())
g = [[0] * N for _ in range(N)]
for a, b in zip(*[iter(ab)] * 2):
g[a - 1][b - 1] = 1
g[b - 1][a - 1] = 1
ans = 0
for path in permutations(range(1, N)):
path = [0] + list(path)
if all(g[v][nv] for v, nv in zip(path, path[1:])):
ans += 1
print(ans)
| [
"[email protected]"
] | |
ea31f37141bfa7d31525e6ecb85ea0031e0c6fa7 | 673e829dda9583c8dd2ac8d958ba1dc304bffeaf | /data/multilingual/Latn.ILO/Sans_16/pdf_to_json_test_Latn.ILO_Sans_16.py | 7498107868f61c7e89533ff42e20ed1ada2c1374 | [
"BSD-3-Clause"
] | permissive | antoinecarme/pdf_to_json_tests | 58bab9f6ba263531e69f793233ddc4d33b783b7e | d57a024fde862e698d916a1178f285883d7a3b2f | refs/heads/master | 2021-01-26T08:41:47.327804 | 2020-02-27T15:54:48 | 2020-02-27T15:54:48 | 243,359,934 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 303 | py | import pdf_to_json as p2j
import json
url = "file:data/multilingual/Latn.ILO/Sans_16/udhr_Latn.ILO_Sans_16.pdf"
lConverter = p2j.pdf_to_json.pdf_to_json_converter()
lConverter.mImageHashOnly = True
lDict = lConverter.convert(url)
print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True))
| [
"[email protected]"
] | |
d94f312791ea3d44722cbec54149613205bd4fb5 | 1a2bf34d7fc1d227ceebf05edf00287de74259c5 | /Django/Day08/Day08Django/Day08Django/wsgi.py | 0968ce766de35b9635af8d718732d6bee6fea12b | [] | no_license | lzn9423362/Django- | de69fee75160236e397b3bbc165281eadbe898f0 | 8c1656d20dcc4dfc29fb942b2db54ec07077e3ae | refs/heads/master | 2020-03-29T18:03:47.323734 | 2018-11-28T12:07:12 | 2018-11-28T12:07:12 | 150,192,771 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 400 | py | """
WSGI config for Day08Django project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Day08Django.settings")
application = get_wsgi_application()
| [
"[email protected]"
] | |
56751f665d6f39f031d7ee6f74bd53bd870f34a5 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02779/s937101909.py | b02559befcddd5c22429364f9ffb7192ce49ce64 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 103 | py | N = int(input())
number = set(map(int,input().split()))
if len(number)==N:print("YES")
else:print("NO") | [
"[email protected]"
] | |
133c880358e31259569b80e438475e23bc74d029 | 172e2da04fc84d2fe366e79539c6ab06d50a580f | /backend/chocolate_23135/settings.py | 804ba5930fcf2868173176c571c1fa7eafd441d5 | [] | no_license | crowdbotics-apps/chocolate-23135 | ff3c3a0e0e9ae0eefb7811868cb9e1281af2981b | 64060aef4a3a3bd1fb61c2fc457fdbd46b072ca6 | refs/heads/master | 2023-03-05T07:34:50.965348 | 2021-02-18T16:13:56 | 2021-02-18T16:13:56 | 317,985,795 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,018 | py | """
Django settings for chocolate_23135 project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import environ
import logging
env = environ.Env()
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DEBUG", default=False)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str("SECRET_KEY")
ALLOWED_HOSTS = env.list("HOST", default=["*"])
SITE_ID = 1
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = env.bool("SECURE_REDIRECT", default=False)
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django.contrib.sites",
]
LOCAL_APPS = [
"home",
"users.apps.UsersConfig",
]
THIRD_PARTY_APPS = [
"rest_framework",
"rest_framework.authtoken",
"rest_auth",
"rest_auth.registration",
"bootstrap4",
"allauth",
"allauth.account",
"allauth.socialaccount",
"allauth.socialaccount.providers.google",
"django_extensions",
"drf_yasg",
"storages",
# start fcm_django push notifications
"fcm_django",
# end fcm_django push notifications
]
INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "chocolate_23135.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "chocolate_23135.wsgi.application"
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
}
}
if env.str("DATABASE_URL", default=None):
DATABASES = {"default": env.db()}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = "/static/"
MIDDLEWARE += ["whitenoise.middleware.WhiteNoiseMiddleware"]
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
# allauth / users
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
ACCOUNT_UNIQUE_EMAIL = True
LOGIN_REDIRECT_URL = "users:redirect"
ACCOUNT_ADAPTER = "users.adapters.AccountAdapter"
SOCIALACCOUNT_ADAPTER = "users.adapters.SocialAccountAdapter"
ACCOUNT_ALLOW_REGISTRATION = env.bool("ACCOUNT_ALLOW_REGISTRATION", True)
SOCIALACCOUNT_ALLOW_REGISTRATION = env.bool("SOCIALACCOUNT_ALLOW_REGISTRATION", True)
REST_AUTH_SERIALIZERS = {
# Replace password reset serializer to fix 500 error
"PASSWORD_RESET_SERIALIZER": "home.api.v1.serializers.PasswordSerializer",
}
REST_AUTH_REGISTER_SERIALIZERS = {
# Use custom serializer that has no username and matches web signup
"REGISTER_SERIALIZER": "home.api.v1.serializers.SignupSerializer",
}
# Custom user model
AUTH_USER_MODEL = "users.User"
EMAIL_HOST = env.str("EMAIL_HOST", "smtp.sendgrid.net")
EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "")
EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# AWS S3 config
AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", "")
AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", "")
AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", "")
AWS_STORAGE_REGION = env.str("AWS_STORAGE_REGION", "")
USE_S3 = (
AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
and AWS_STORAGE_BUCKET_NAME
and AWS_STORAGE_REGION
)
if USE_S3:
AWS_S3_CUSTOM_DOMAIN = env.str("AWS_S3_CUSTOM_DOMAIN", "")
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_DEFAULT_ACL = env.str("AWS_DEFAULT_ACL", "public-read")
AWS_MEDIA_LOCATION = env.str("AWS_MEDIA_LOCATION", "media")
AWS_AUTO_CREATE_BUCKET = env.bool("AWS_AUTO_CREATE_BUCKET", True)
DEFAULT_FILE_STORAGE = env.str(
"DEFAULT_FILE_STORAGE", "home.storage_backends.MediaStorage"
)
MEDIA_URL = "/mediafiles/"
MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles")
# start fcm_django push notifications
FCM_DJANGO_SETTINGS = {"FCM_SERVER_KEY": env.str("FCM_SERVER_KEY", "")}
# end fcm_django push notifications
# Swagger settings for api docs
SWAGGER_SETTINGS = {
"DEFAULT_INFO": f"{ROOT_URLCONF}.api_info",
}
if DEBUG or not (EMAIL_HOST_USER and EMAIL_HOST_PASSWORD):
# output email to console instead of sending
if not DEBUG:
logging.warning(
"You should setup `SENDGRID_USERNAME` and `SENDGRID_PASSWORD` env vars to send emails."
)
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
| [
"[email protected]"
] | |
2786bd4521b775c949294da93fc52e7ff191eced | 7ce2b2000cfefe8fbefc2271ebc7df2061c88194 | /CAIL2020/sfzyzb/main.py | 81c4fd79e0ccba4eebf1f25f8dfbbd916da8e606 | [
"Apache-2.0"
] | permissive | generalzgd/CAIL | f06d79acf42ac2188938c02087f7d07b9b43095c | 57529e64ee2f602324a500ff9bed660ddcde10bb | refs/heads/master | 2023-01-24T01:14:05.382525 | 2020-11-20T03:40:47 | 2020-11-20T03:40:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,135 | py | """Test model for SMP-CAIL2020-Argmine.
Author: Yixu GAO [email protected]
Usage:
python main.py --model_config 'config/bert_config.json' \
--in_file 'data/SMP-CAIL2020-test1.csv' \
--out_file 'bert-submission-test-1.csv'
python main.py --model_config 'config/rnn_config.json' \
--in_file 'data/SMP-CAIL2020-test1.csv' \
--out_file 'rnn-submission-test-1.csv'
"""
import argparse
import json
import os
from types import SimpleNamespace
import fire
import pandas
import pandas as pd
import torch
from torch.utils.data import DataLoader
from data import Data
from evaluate import evaluate
from model import BertForClassification, RnnForSentencePairClassification, LogisticRegression
from utils import load_torch_model
LABELS = ['0', '1']
MODEL_MAP = {
'bert': BertForClassification,
'rnn': RnnForSentencePairClassification,
'lr': LogisticRegression
}
def main(in_file='/data/SMP-CAIL2020-test1.csv',
out_file='/output/result1.csv',
model_config='config/bert_config.json'):
"""Test model for given test set on 1 GPU or CPU.
Args:
in_file: file to be tested
out_file: output file
model_config: config file
"""
# 0. Load config
with open(model_config) as fin:
config = json.load(fin, object_hook=lambda d: SimpleNamespace(**d))
if torch.cuda.is_available():
device = torch.device('cuda')
# device = torch.device('cpu')
else:
device = torch.device('cpu')
#0. preprocess file
tag_sents = []
para_id = 0
with open(in_file, 'r', encoding='utf-8') as fin:
for line in fin:
sents = json.loads(line.strip())
text = sents['text']
sentences = [item['sentence'] for item in text]
for sent in sentences:
tag_sents.append((para_id, sent))
para_id += 1
df = pandas.DataFrame(tag_sents, columns=['para', 'content'])
df.to_csv("data/para_content_test.csv", columns=['para', 'content'], index=False)
# 1. Load data
data = Data(vocab_file=os.path.join(config.model_path, 'vocab.txt'),
max_seq_len=config.max_seq_len,
model_type=config.model_type, config=config)
test_set = data.load_file("data/para_content_test.csv", train=False)
data_loader_test = DataLoader(
test_set, batch_size=config.batch_size, shuffle=False)
# 2. Load model
model = MODEL_MAP[config.model_type](config)
model = load_torch_model(
model, model_path=os.path.join(config.model_path, 'model.bin'))
model.to(device)
# 3. Evaluate
answer_list = evaluate(model, data_loader_test, device)
# 4. Write answers to file
df = pd.read_csv("data/para_content_test.csv")
idcontent_list = list(df.itertuples(index=False))
filter_list = [k for k,v in zip(idcontent_list, answer_list) if v]
df = pd.DataFrame(filter_list, columns=['para', 'content'])
df.to_csv(out_file, columns=['para', 'content'], index=False)
if __name__ == '__main__':
fire.Fire(main)
| [
"[email protected]"
] | |
4f14f1f037cb2454bf6a63efb237c3c8c970e2ab | 26c4426d2c9cd10fd7d4a73609512e69e31b64ba | /html2ex/h2e_openpyxl.py | 9dae85c7684b7fa2b0f2370c7e75e7a9298de7c7 | [] | no_license | KirillUdod/html2exc | 550761213eb6edd7d3ea4787938cce65584606c3 | 60569f01822a15b2e5b6884a42774cd428953700 | refs/heads/master | 2021-01-15T17:07:05.906492 | 2016-01-06T11:51:38 | 2016-01-06T11:51:38 | 34,809,072 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,578 | py | from openpyxl.cell import get_column_letter
from openpyxl.styles import Alignment, Font, Border, Side, PatternFill
from openpyxl.workbook import Workbook
from openpyxl import load_workbook, drawing
from lxml.html import document_fromstring, HTMLParser
# Value must be one of set(['hair', 'medium', 'dashDot', 'dotted', 'mediumDashDot', 'dashed',
# 'mediumDashed', 'mediumDashDotDot', 'dashDotDot', 'slantDashDot', 'double', None, 'thick', 'thin'])
_BORDER_STYLE = {
'0': None,
'1': 'thin',
'2': 'medium',
'3': 'thick',
}
_TEXT_SIZE = {
'h1': 32,
'h2': 24,
'h3': 18,
'h4': 16,
'h5': 14,
'h6': 11,
}
BORDER_COLOR = '000000'
WHITE_COLOR = 'FFFFFF'
TH_COLOR = '00FFFF'
BLACK_COLOR = '000000'
class Html2Excel(object):
def __init__(self):
self.list = []
self.start_row = 0
self.start_col = 0
self.workbook = Workbook(encoding='utf8')
self.worksheet = self.workbook.active
def use_existing_wb(self, name_workbook):
self.workbook = load_workbook(filename=name_workbook)
self.worksheet = self.workbook.get_active_sheet()
def create_new_sheet(self, name_sheet):
self.worksheet = self.workbook.create_sheet()
self.worksheet.title = name_sheet
def set_col_width(self, cols_width):
for col_i in cols_width.keys():
self.worksheet.column_dimensions[get_column_letter(col_i)].width = int(cols_width.get(col_i))
def add_logo(self, logo_filename):
img = drawing.Image(logo_filename)
img.anchor(self.worksheet.cell('D3'))
self.worksheet.add_image(img)
def append_html_table(self, html_string, start_row=1, start_col=1):
html_string = document_fromstring(html_string, HTMLParser(encoding='utf8'))
last_row = start_row - 1
last_col = start_col
for table_el in html_string.xpath('//table'):
last_row += 1
for row_i, row in enumerate(table_el.xpath('./tr'), start=last_row):
for col_i, col in enumerate(row.xpath('./td|./th'), start=last_col):
colspan = int(col.get('colspan', 0))
rowspan = int(col.get('rowspan', 0))
font_bold = False
font_size = 11
font_color = BLACK_COLOR
if rowspan:
rowspan -= 1
if colspan:
colspan -= 1
col_data = col.text_content().encode("utf8")
valign = 'center' if col_i == start_col and col.tag != 'th' else 'top'
while (row_i, col_i) in self.list:
col_i += 1
cell = self.worksheet.cell(row=row_i, column=col_i)
if rowspan or colspan:
self.worksheet.merge_cells(start_row=row_i, end_row=row_i+rowspan, start_column=col_i,
end_column=col_i+colspan)
cell.value = col_data
cell.alignment = Alignment(
horizontal=row.get('align', col.get('align')) or 'left',
vertical=row.get('valign', col.get('valign')) or valign,
shrink_to_fit=True, wrap_text=True
)
bgcolor = row.get('bgcolor', col.get('bgcolor'))
if bgcolor:
cell.fill = PatternFill(fill_type='solid', start_color=bgcolor, end_color=bgcolor)
for el in col.iter():
if el.tag == 'font':
font_color = el.get('color')
elif el.tag == 'b':
font_bold = True
elif el.tag in _TEXT_SIZE:
font_bold = True,
font_size = _TEXT_SIZE.get(el)
cell.font = Font(
color=font_color,
bold=font_bold,
size=font_size,
)
if col.tag == 'th':
cell.font = Font(
bold=True
)
cell.fill = PatternFill(
fill_type='solid',
start_color=TH_COLOR,
end_color=TH_COLOR
)
for i in range(0, rowspan+1, 1):
for j in range(0, colspan+1, 1):
if i == rowspan:
last_row = row_i + i
self.list.append((row_i+i, col_i+j))
cell = self.worksheet.cell(row=row_i+i, column=col_i+j)
cell.border = Border(
left=Side(border_style=_BORDER_STYLE.get(table_el.get('border') or None),
color=BORDER_COLOR),
right=Side(border_style=_BORDER_STYLE.get(table_el.get('border') or None),
color=BORDER_COLOR),
top=Side(border_style=_BORDER_STYLE.get(table_el.get('border') or None),
color=BORDER_COLOR),
bottom=Side(border_style=_BORDER_STYLE.get(table_el.get('border') or None),
color=BORDER_COLOR),
)
return last_row, last_col
def save_wb(self, name):
self.workbook.save(name)
if __name__ == '__main__':
# html_filename = sys.argv[1]
# xls_filename = sys.argv[2] if len(sys.argv) > 2 else (html_filename + ".xls")
html_filename = '13.html'
xls_filename = '22.xlsx'
logo_filename = 'test.jpg'
# converter = Html2Excel()
# converter.create_new_sheet('1')
# last_row, last_col = converter.append_html_table('1.html', 0, 1)
# converter.append_html_table('2.html', last_row + 2, 1)
# converter.save_wb(xls_filename)
cols_width = {
1: 5,
2: 15,
3: 25,
4: 35,
5: 5,
6: 15,
}
converter = Html2Excel()
converter.use_existing_wb(xls_filename)
converter.set_col_width(cols_width)
converter.add_logo(logo_filename)
converter.append_html_table(open(html_filename, 'rb').read(), 8, 2)
# converter.create_new_sheet('test')
converter.save_wb(xls_filename)
| [
"[email protected]"
] | |
86ed9f46f1c2d2d11c6802437d45c5809fb30eeb | 56befbe23e56995f9772010f47dcbf38c8c150bc | /0x04-python-more_data_structures/3-common_elements.py | eea467f21330bd685f084a863c29e797149a3f26 | [] | no_license | lemejiamo/holbertonschool-higher_level_programming | a48175156816a856dba0ddc6888b76f6e04b7223 | 3f756ed3a907044bfc811f108d5ae98bb0e9802c | refs/heads/main | 2023-08-14T13:22:13.481356 | 2021-09-28T04:09:50 | 2021-09-28T04:09:50 | 361,910,906 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 188 | py | #!/usr/bin/python3
def common_elements(set_1, set_2):
equals = []
for i in set_1:
for j in set_2:
if j == i:
equals.append(j)
return equals
| [
"[email protected]"
] | |
d08111070c3529eb1b9536a6fd1e806deb33d6b9 | ed3025b8b0831e91cf589b8c0aa8f7c9087042c0 | /ComputerSecurity/SecurityScripts/venv/lib/python2.7/encodings/johab.py | 8bc3565a0128ac71e3d1a2f7726065e023806f3a | [] | no_license | zacharygolla/OtherSchoolProjects | dd8c58beac94c46516ea67f49afc2f41b35cfb6a | 554588d4968db7b70b9ee3b30612f1b8b4402f84 | refs/heads/master | 2021-11-03T23:10:31.652887 | 2019-04-26T21:37:26 | 2019-04-26T21:37:26 | 171,918,593 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 89 | py | /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/johab.py | [
"[email protected]"
] | |
507cd795dbf7e45744f5e18ad7e1ef3c718b70a3 | acb8e84e3b9c987fcab341f799f41d5a5ec4d587 | /langs/8/s_m.py | 476a366de2d7e31ba0206c1757d5c30e6587f466 | [] | no_license | G4te-Keep3r/HowdyHackers | 46bfad63eafe5ac515da363e1c75fa6f4b9bca32 | fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2 | refs/heads/master | 2020-08-01T12:08:10.782018 | 2016-11-13T20:45:50 | 2016-11-13T20:45:50 | 73,624,224 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 486 | py | import sys
def printFunction(lineRemaining):
if lineRemaining[0] == '"' and lineRemaining[-1] == '"':
if len(lineRemaining) > 2:
#data to print
lineRemaining = lineRemaining[1:-1]
print ' '.join(lineRemaining)
else:
print
def main(fileName):
with open(fileName) as f:
for line in f:
data = line.split()
if data[0] == 's_M':
printFunction(data[1:])
else:
print 'ERROR'
return
if __name__ == '__main__':
main(sys.argv[1]) | [
"[email protected]"
] | |
92d266e20d45decea2259482e7dbe7c41e05d9d5 | 1feae7286c5d61981b40520e2c1e1028b86bb8cc | /blog_newsapi/urls.py | 46e7c93bc0e248b4e634b884b7678d8d184d306a | [] | no_license | mukeshrakesh123/newsapp-blog | b97adb486f2d463e11fc054243833a2db6944865 | 596eac8981792fc368d2abfc4e19650332347f08 | refs/heads/main | 2023-06-16T11:44:10.665862 | 2021-07-10T16:34:50 | 2021-07-10T16:34:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 799 | py | """blog_newsapi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog14.urls'))
]
| [
"[email protected]"
] | |
d3f4ba1961c78164f76c03bb013ed36231123fa8 | be471cdee10e2273ce41631c4a58f16227f18b5b | /server/walt/server/threads/blocking/images/publish.py | c0d87e832bd7edbf59ba092d26d354f78180beb8 | [
"BSD-3-Clause"
] | permissive | dia38/walt-python-packages | d91d477c90dbc4bd134fdcc31d7cb404ef9885b8 | e6fa1f166f45e73173195d57840d22bef87b88f5 | refs/heads/master | 2020-04-29T17:41:19.936575 | 2019-11-26T10:11:58 | 2019-11-26T10:11:58 | 176,303,546 | 0 | 0 | BSD-3-Clause | 2019-03-18T14:27:56 | 2019-03-18T14:27:56 | null | UTF-8 | Python | false | false | 516 | py | from walt.server.threads.blocking.images.metadata import \
update_user_metadata_for_image
# this implements walt image publish
def publish(requester, server, dh_peer, auth_conf, image_fullname):
# push image
server.docker.hub.push(image_fullname, dh_peer, auth_conf, requester)
# update user metadata ('walt_metadata' image on user's hub account)
update_user_metadata_for_image(server.docker, dh_peer, auth_conf,
requester, image_fullname)
| [
"[email protected]"
] | |
484e6d6524860d2e105423312211ef8bece01452 | e13542cc246837c0f91f87506fc75a2d946f115c | /aula1/beta/bin/wheel | 0dc4c3b65acc995f2e7f7bec7b3abab2907ee749 | [] | no_license | Gamboua/python-520 | a042d265cd1d1b9d6c0839d1d4dbdde3e7d401a6 | 52aa4f7c9688be88855e81c473e10cd88788dd64 | refs/heads/master | 2021-09-18T10:23:21.900421 | 2018-07-12T21:44:40 | 2018-07-12T21:44:40 | 109,701,445 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 233 | #!/var/www/html/python/beta/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from wheel.tool import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"[email protected]"
] | ||
f501eef3959ee7b7694575e29d87512d48a2abc3 | 3a9f2b3d79cf214704829427ee280f4b49dca70a | /saigon/rat/RuckusAutoTest/tests/zd/CB_ZD_Get_Mgmt_IPV6_ACLs.py | eab30af67937b2aaea57f45e04f394791f085722 | [] | no_license | jichunwei/MyGitHub-1 | ae0c1461fe0a337ef459da7c0d24d4cf8d4a4791 | f826fc89a030c6c4e08052d2d43af0b1b4b410e3 | refs/heads/master | 2021-01-21T10:19:22.900905 | 2016-08-20T03:34:52 | 2016-08-20T03:34:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,440 | py | # Copyright (C) 2011 Ruckus Wireless, Inc. All rights reserved.
# Please make sure the following module docstring is accurate since it will be used in report generation.
"""
Description:
@author: Cherry Cheng
@contact: [email protected]
@since: Oct 2011
Prerequisite (Assumptions about the state of the test bed/DUT):
1. Build under test is loaded on the AP and Zone Director
Required components: 'ZoneDirectorCLI'
Test parameters:
- 'ap_mac_list': 'AP mac address list',
- 'ip_cfg': 'AP IP configuration.'
Test procedure:
1. Config:
- initialize test parameters
2. Test:
- Set AP device IP setting as specified via CLI
3. Cleanup:
- N/A
Result type: PASS/FAIL
Results: PASS: If set device IP setting successfully
FAIL: If any item is incorrect
Messages: If FAIL the test script returns a message related to the criterion that is not satisfied
"""
import logging
from RuckusAutoTest.models import Test
from RuckusAutoTest.components.lib.zd import mgmt_ip_acl
class CB_ZD_Get_Mgmt_IPV6_ACLs(Test):
required_components = ['ZoneDirector']
parameters_description = {}
def config(self, conf):
self._cfg_init_test_params(conf)
def test(self):
try:
logging.info("Get all management ipv6 acls via ZD GUI")
self.gui_all_acls_list = mgmt_ip_acl.get_all_mgmt_ipv6_acl(self.zd)
except Exception, ex:
self.errmsg = 'Get mgmt ipv6 acl failed:%s' % (ex.message)
if self.errmsg:
return self.returnResult("FAIL",self.errmsg)
else:
self._update_carrier_bag()
pass_msg = 'Get management ivp6 acl via ZD GUI successfully'
return self.returnResult('PASS', pass_msg)
def cleanup(self):
pass
def _update_carrier_bag(self):
self.carrierbag['gui_mgmt_ipv6_acl_list'] = self.gui_all_acls_list
def _cfg_init_test_params(self, conf):
'''
Mgmt acl dict sample:
{'name': 'mgmt ip acl name',
'type': 'single|prefix,
'addr': 'single addr|addr and prefix split with /',
}
'''
self.conf = {}
self.conf.update(conf)
self.errmsg = ''
self.zd = self.testbed.components['ZoneDirector'] | [
"[email protected]"
] | |
df48824f457902ed3e11b5e29e8b28c3cabb0ba9 | 2067c90b12a5b10fbb97bb2fe52a30f79d502b7b | /booking/migrations/0006_auto_20200216_1826.py | 3c6f8b2d33482cc143f75329a8b5d7acec770d3f | [] | no_license | info3g/payapal_integration | bc632841abd0284a6757f31cf13d9ee1946bba33 | a8e745df3497f553d437988c799cd9882602d3b8 | refs/heads/master | 2022-12-10T01:15:46.167005 | 2020-03-03T16:36:48 | 2020-03-03T16:36:48 | 243,932,807 | 0 | 1 | null | 2022-12-08T03:43:42 | 2020-02-29T08:34:31 | Python | UTF-8 | Python | false | false | 528 | py | # Generated by Django 3.0.3 on 2020-02-16 17:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('booking', '0005_customer_price'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='address',
field=models.CharField(max_length=120),
),
migrations.AlterField(
model_name='customer',
name='price',
field=models.FloatField(),
),
]
| [
"[email protected]"
] | |
d3fc4e749b5623648d7755c22b43adbca799339d | 1fe8d4133981e53e88abf633046060b56fae883e | /venv/lib/python3.8/site-packages/keras/datasets/cifar10.py | 863c9df822d0ee351f438d2d076f8030cbbc3a5f | [] | no_license | Akira331/flask-cifar10 | 6c49db8485038731ce67d23f0972b9574746c7a7 | 283e7a2867c77d4b6aba7aea9013bf241d35d76c | refs/heads/master | 2023-06-14T16:35:06.384755 | 2021-07-05T14:09:15 | 2021-07-05T14:09:15 | 382,864,970 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 129 | py | version https://git-lfs.github.com/spec/v1
oid sha256:63d66a0e745552af02799b65d4289ea59046aeae4e0e92fffe1446ff879f32e4
size 3548
| [
"[email protected]"
] | |
4a038d6d8e29aa9d971a322946e73c4ec8ca1a05 | 72b00923d4aa11891f4a3038324c8952572cc4b2 | /python/introducing_python/chp5/sources/daily.py | 55a0f21679917f7a6c05056be45b146dddf69271 | [] | no_license | taowuwen/codec | 3698110a09a770407e8fb631e21d86ba5a885cd5 | d92933b07f21dae950160a91bb361fa187e26cd2 | refs/heads/master | 2022-03-17T07:43:55.574505 | 2022-03-10T05:20:44 | 2022-03-10T05:20:44 | 87,379,261 | 0 | 0 | null | 2019-03-25T15:40:27 | 2017-04-06T02:50:54 | C | UTF-8 | Python | false | false | 45 | py |
def forecast():
return 'like yesterday'
| [
"[email protected]"
] | |
99152c525e224ec0a365e21d77b3ebc4c22869d4 | b15d2787a1eeb56dfa700480364337216d2b1eb9 | /samples/cli/accelbyte_py_sdk_cli/platform/_anonymize_subscription.py | 556651d3616d6ab2c798987dcb97a5bca11c71d0 | [
"MIT"
] | permissive | AccelByte/accelbyte-python-sdk | dedf3b8a592beef5fcf86b4245678ee3277f953d | 539c617c7e6938892fa49f95585b2a45c97a59e0 | refs/heads/main | 2023-08-24T14:38:04.370340 | 2023-08-22T01:08:03 | 2023-08-22T01:08:03 | 410,735,805 | 2 | 1 | MIT | 2022-08-02T03:54:11 | 2021-09-27T04:00:10 | Python | UTF-8 | Python | false | false | 2,178 | py | # Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template_file: python-cli-command.j2
# AGS Platform Service (4.32.1)
# pylint: disable=duplicate-code
# pylint: disable=line-too-long
# pylint: disable=missing-function-docstring
# pylint: disable=missing-module-docstring
# pylint: disable=too-many-arguments
# pylint: disable=too-many-branches
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-lines
# pylint: disable=too-many-locals
# pylint: disable=too-many-public-methods
# pylint: disable=too-many-return-statements
# pylint: disable=too-many-statements
# pylint: disable=unused-import
import json
import yaml
from typing import Optional
import click
from .._utils import login_as as login_as_internal
from .._utils import to_dict
from accelbyte_py_sdk.api.platform import (
anonymize_subscription as anonymize_subscription_internal,
)
@click.command()
@click.argument("user_id", type=str)
@click.option("--namespace", type=str)
@click.option("--login_as", type=click.Choice(["client", "user"], case_sensitive=False))
@click.option("--login_with_auth", type=str)
@click.option("--doc", type=bool)
def anonymize_subscription(
user_id: str,
namespace: Optional[str] = None,
login_as: Optional[str] = None,
login_with_auth: Optional[str] = None,
doc: Optional[bool] = None,
):
if doc:
click.echo(anonymize_subscription_internal.__doc__)
return
x_additional_headers = None
if login_with_auth:
x_additional_headers = {"Authorization": login_with_auth}
else:
login_as_internal(login_as)
result, error = anonymize_subscription_internal(
user_id=user_id,
namespace=namespace,
x_additional_headers=x_additional_headers,
)
if error:
raise Exception(f"anonymizeSubscription failed: {str(error)}")
click.echo(yaml.safe_dump(to_dict(result), sort_keys=False))
anonymize_subscription.operation_id = "anonymizeSubscription"
anonymize_subscription.is_deprecated = False
| [
"[email protected]"
] | |
aed3c3dee24a3b469803135f19b9e7d540ed0040 | c4b8e1e09dedbccd37ca008ecaaca4438610bbaf | /cpmpy/send_more_money_any_base.py | 0a301f379ecfc9bc8758bc64492faf87ba6b7502 | [
"MIT"
] | permissive | hakank/hakank | 4806598b98cb36dd51b24b0ab688f52dadfe9626 | c337aaf8187f15dcdc4d5b09cd2ed0dbdb2e72c2 | refs/heads/master | 2023-08-15T00:21:52.750270 | 2023-07-27T16:21:40 | 2023-07-27T16:21:40 | 11,933,517 | 336 | 97 | MIT | 2023-07-27T11:19:42 | 2013-08-06T20:12:10 | JavaScript | UTF-8 | Python | false | false | 2,291 | py | """
Send more money in any base problem in cpmpy.
Send More Money
SEND
+ MORE
------
MONEY
using any base.
Examples:
Base 10 has one solution:
{9, 5, 6, 7, 1, 0, 8, 2}
Base 11 has three soltutions:
{10, 5, 6, 8, 1, 0, 9, 2}
{10, 6, 7, 8, 1, 0, 9, 3}
{10, 7, 8, 6, 1, 0, 9, 2}
Model created by Hakan Kjellerstrand, [email protected]
See also my CPMpy page: http://www.hakank.org/cpmpy/
"""
from cpmpy import *
from cpmpy.solvers import *
import numpy as np
from cpmpy_hakank import *
def print_solution(x):
print(x[0].value(),x[1].value(),x[2].value(),x[3].value(), " + ",
x[4].value(),x[5].value(),x[6].value(),x[7].value(), " = ",
x[8].value(),x[9].value(),x[10].value(),x[11].value(),x[12].value())
def send_more_money_any_base(base=10,num_sols=0,num_procs=1):
print("\nbase: ", base)
x = intvar(0,base-1,shape=8,name="x")
s,e,n,d,m,o,r,y = x
model = Model([
s*base**3 + e*base**2 + n*base + d +
m*base**3 + o*base**2 + r*base + e ==
m*base**4 + o*base**3 + n*base**2 + e*base + y,
s > 0,
m > 0,
AllDifferent((s,e,n,d,m,o,r,y))
]
)
xs = [s,e,n,d,
m,o,r,e,
m,o,n,e,y]
def print_sol():
print(x.value())
# Use OR-tools CP-SAT for speeding up the program.
ss = CPM_ortools(model)
# Flags to experiment with
# ss.ort_solver.parameters.search_branching = ort.PORTFOLIO_SEARCH
# ss.ort_solver.parameters.cp_model_presolve = False
ss.ort_solver.parameters.linearization_level = 0
ss.ort_solver.parameters.cp_model_probing_level = 0
num_solutions = ss.solveAll(display=print_sol)
print("Nr solutions:", num_solutions)
print("Num conflicts:", ss.ort_solver.NumConflicts())
print("NumBranches:", ss.ort_solver.NumBranches())
print("WallTime:", ss.ort_solver.WallTime())
return num_solutions
b = 10
send_more_money_any_base(b)
start_val = 8
end_val = 30
num_sols_per_base = []
for b in range(start_val,end_val+1):
num_sols_per_base += [send_more_money_any_base(b)]
print(f"\nNum sols per base ({start_val}..{end_val}):", num_sols_per_base)
| [
"[email protected]"
] | |
05d6b26ebd7a5f04611f8d54877b900714b3c030 | cd073757b17465635da3fd30f770bbd8df0dff99 | /tests/pytests/unit/beacons/test_swapusage.py | 35b5ce28cdcad2d140bfeea54240048ddca33b61 | [
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | marmarek/salt | cadc939ecbda915e2f4246f198d72f507c9c1960 | 974497174252ab46ee7dc31332ffb5b2f8395813 | refs/heads/master | 2022-11-19T14:05:28.778983 | 2021-03-12T00:30:45 | 2021-05-06T16:45:38 | 160,296,073 | 0 | 1 | Apache-2.0 | 2018-12-04T04:19:43 | 2018-12-04T04:19:41 | null | UTF-8 | Python | false | false | 1,571 | py | """
tests.pytests.unit.beacons.test_swapusage
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Swap usage beacon test cases
"""
from collections import namedtuple
import pytest
import salt.beacons.swapusage as swapusage
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {}
@pytest.fixture
def stub_swap_usage():
return namedtuple("sswap", "total used free percent sin sout")(
17179865088, 1674412032, 15505453056, 9.7, 1572110336, 3880046592,
)
def test_non_list_config():
config = {}
ret = swapusage.validate(config)
assert ret == (False, "Configuration for swapusage beacon must be a list.")
def test_empty_config():
config = [{}]
ret = swapusage.validate(config)
assert ret == (False, "Configuration for swapusage beacon requires percent.")
def test_swapusage_match(stub_swap_usage):
with patch("psutil.swap_memory", MagicMock(return_value=stub_swap_usage)):
config = [{"percent": "9%"}, {"interval": 30}]
ret = swapusage.validate(config)
assert ret == (True, "Valid beacon configuration")
ret = swapusage.beacon(config)
assert ret == [{"swapusage": 9.7}]
def test_swapusage_nomatch(stub_swap_usage):
with patch("psutil.swap_memory", MagicMock(return_value=stub_swap_usage)):
config = [{"percent": "10%"}]
ret = swapusage.validate(config)
assert ret == (True, "Valid beacon configuration")
ret = swapusage.beacon(config)
assert ret != [{"swapusage": 9.7}]
| [
"[email protected]"
] | |
7aa94aeceb0e3cabb97bd080fad37fcef5af03d7 | 9f59a910a6512fe7dc2d97c1ea4866c0def18ff4 | /utils/cfgs_bdb/pydb/cfg_pandaboard.py | 958348202147941b5c6ab55c18ad36eae0c69229 | [
"MIT"
] | permissive | YuanYuLin/PackMan_IOPC | ec3b0c97499275744ae50ef5c6315042a2167fd8 | 51333e1635c55478477c7ad5536e94ebd6976525 | refs/heads/master | 2021-01-19T04:38:51.408655 | 2020-03-31T09:11:04 | 2020-03-31T09:11:04 | 87,382,334 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 20,294 | py | #!/usr/bin/python -Wall
#coding:utf-8
import btdb
platform_name = "pandaboard"
def gen_cfg_platform(db):
btdb.set_uint32 (db,"platform.cfg.size", 1)
btdb.set_boolean (db,"platform.cfg[0].is_host", 1)
btdb.set_boolean (db,"platform.cfg[0].is_init_console", 0)
btdb.set_string (db,"platform.cfg[0].tty_name", "/dev/tty1")
btdb.set_boolean (db,"platform.cfg[0].is_init_zram_swap", 1)
btdb.set_string (db,"platform.cfg[0].zram_disksize", "512M")
btdb.set_string (db,"platform.cfg[0].platform_name", platform_name)
btdb.set_uint32 (db,"platform.cfg[0].raid.size", 1)
btdb.set_string (db,"platform.cfg[0].raid[0].name", "raid_hdd0")
btdb.set_string (db,"platform.cfg[0].raid[0].type", "btrfs_raid1")
btdb.set_boolean (db,"platform.cfg[0].raid[0].enabled", 0)
btdb.set_uint32 (db,"platform.cfg[0].raid[0].device.size", 4)
btdb.set_boolean (db,"platform.cfg[0].raid[0].device[0].enabled", 0)
btdb.set_string (db,"platform.cfg[0].raid[0].device[0].path", "/dev/sdb")
btdb.set_boolean (db,"platform.cfg[0].raid[0].device[1].enabled", 0)
btdb.set_string (db,"platform.cfg[0].raid[0].device[1].path", "/dev/sdc")
btdb.set_boolean (db,"platform.cfg[0].raid[0].device[2].enabled", 0)
btdb.set_string (db,"platform.cfg[0].raid[0].device[2].path", "")
btdb.set_boolean (db,"platform.cfg[0].raid[0].device[3].enabled", 0)
btdb.set_string (db,"platform.cfg[0].raid[0].device[3].path", "")
btdb.set_uint32 (db,"platform.cfg[0].partition.size", 1)
btdb.set_string (db,"platform.cfg[0].partition[0].name", "system")
btdb.set_string (db,"platform.cfg[0].partition[0].src", "/dev/mmcblk0p1")
btdb.set_string (db,"platform.cfg[0].partition[0].dst", "/hdd/part1")
btdb.set_string (db,"platform.cfg[0].partition[0].type", "vfat")
btdb.set_boolean (db,"platform.cfg[0].partition[0].fixed", 1)
btdb.set_boolean (db,"platform.cfg[0].partition[0].enabled", 1)
btdb.set_uint32 (db,"platform.cfg[0].partition.size", 2)
btdb.set_string (db,"platform.cfg[0].partition[1].name", "data")
btdb.set_string (db,"platform.cfg[0].partition[1].src", "/dev/mmcblk0p2")
btdb.set_string (db,"platform.cfg[0].partition[1].dst", "/hdd/part2")
btdb.set_string (db,"platform.cfg[0].partition[1].type", "btrfs")
btdb.set_boolean (db,"platform.cfg[0].partition[1].fixed", 1)
btdb.set_boolean (db,"platform.cfg[0].partition[1].enabled", 1)
btdb.set_uint32 (db,"platform.cfg[0].partition.size", 3)
btdb.set_string (db,"platform.cfg[0].partition[2].name", "persist")
btdb.set_string (db,"platform.cfg[0].partition[2].src", "/hdd/part2/persist")
btdb.set_string (db,"platform.cfg[0].partition[2].dst", "/persist")
btdb.set_string (db,"platform.cfg[0].partition[2].type", "binddir")
btdb.set_boolean (db,"platform.cfg[0].partition[2].fixed", 1)
btdb.set_boolean (db,"platform.cfg[0].partition[2].enabled", 1)
btdb.set_uint32 (db,"platform.cfg[0].partition.size", 4)
btdb.set_string (db,"platform.cfg[0].partition[3].name", "vms")
btdb.set_string (db,"platform.cfg[0].partition[3].src", "/hdd/part2/VMs")
btdb.set_string (db,"platform.cfg[0].partition[3].dst", "/vmlist")
btdb.set_string (db,"platform.cfg[0].partition[3].type", "binddir")
btdb.set_boolean (db,"platform.cfg[0].partition[3].fixed", 0)
btdb.set_boolean (db,"platform.cfg[0].partition[3].enabled", 0)
btdb.set_uint32 (db,"platform.cfg[0].partition.size", 5)
btdb.set_string (db,"platform.cfg[0].partition[4].name", "vmbase")
btdb.set_string (db,"platform.cfg[0].partition[4].src", "/hdd/part2/VMbase")
btdb.set_string (db,"platform.cfg[0].partition[4].dst", "/vmbase")
btdb.set_string (db,"platform.cfg[0].partition[4].type", "binddir")
btdb.set_boolean (db,"platform.cfg[0].partition[4].fixed", 0)
btdb.set_boolean (db,"platform.cfg[0].partition[4].enabled", 0)
btdb.set_uint32 (db,"platform.cfg[0].partition.size", 6)
btdb.set_string (db,"platform.cfg[0].partition[5].name", "")
btdb.set_string (db,"platform.cfg[0].partition[5].src", "")
btdb.set_string (db,"platform.cfg[0].partition[5].dst", "")
btdb.set_string (db,"platform.cfg[0].partition[5].type", "")
btdb.set_boolean (db,"platform.cfg[0].partition[5].fixed", 0)
btdb.set_boolean (db,"platform.cfg[0].partition[5].enabled", 0)
btdb.set_uint32 (db,"platform.cfg[0].partition.size", 7)
btdb.set_string (db,"platform.cfg[0].partition[6].name", "")
btdb.set_string (db,"platform.cfg[0].partition[6].src", "")
btdb.set_string (db,"platform.cfg[0].partition[6].dst", "")
btdb.set_string (db,"platform.cfg[0].partition[6].type", "")
btdb.set_boolean (db,"platform.cfg[0].partition[6].fixed", 0)
btdb.set_boolean (db,"platform.cfg[0].partition[6].enabled", 0)
btdb.set_uint32 (db,"platform.cfg[0].partition.size", 8)
btdb.set_string (db,"platform.cfg[0].partition[7].name", "")
btdb.set_string (db,"platform.cfg[0].partition[7].src", "")
btdb.set_string (db,"platform.cfg[0].partition[7].dst", "")
btdb.set_string (db,"platform.cfg[0].partition[7].type", "")
btdb.set_boolean (db,"platform.cfg[0].partition[7].fixed", 0)
btdb.set_boolean (db,"platform.cfg[0].partition[7].enabled", 0)
btdb.set_uint32 (db,"platform.cfg[0].partition.size", 9)
btdb.set_string (db,"platform.cfg[0].partition[8].name", "")
btdb.set_string (db,"platform.cfg[0].partition[8].src", "")
btdb.set_string (db,"platform.cfg[0].partition[8].dst", "")
btdb.set_string (db,"platform.cfg[0].partition[8].type", "")
btdb.set_boolean (db,"platform.cfg[0].partition[8].fixed", 0)
btdb.set_boolean (db,"platform.cfg[0].partition[8].enabled", 0)
btdb.set_uint32 (db,"platform.cfg[0].partition.size", 10)
btdb.set_string (db,"platform.cfg[0].partition[9].name", "")
btdb.set_string (db,"platform.cfg[0].partition[9].src", "")
btdb.set_string (db,"platform.cfg[0].partition[9].dst", "")
btdb.set_string (db,"platform.cfg[0].partition[9].type", "")
btdb.set_boolean (db,"platform.cfg[0].partition[9].fixed", 0)
btdb.set_boolean (db,"platform.cfg[0].partition[9].enabled", 0)
def gen_cfg_vm_base_image(db):
btdb.set_uint32 (db,"vmbsimg.cfg.size", 0)
btdb.set_boolean (db,"vmbsimg.cfg[0].autostart", 0)
btdb.set_string (db,"vmbsimg.cfg[0].name", "")
btdb.set_string (db,"vmbsimg.cfg[0].img_path", "")
btdb.set_string (db,"vmbsimg.cfg[0].img_dst", "")
def gen_cfg_vm(db):
btdb.set_uint32 (db,"vm.cfg.size", 1)
btdb.set_boolean (db,"vm.cfg[0].autostart", 0)
btdb.set_string (db,"vm.cfg[0].base_path", "")
btdb.set_string (db,"vm.cfg[0].name", "vm000")
btdb.set_string (db,"vm.cfg[0].nethwaddr", btdb.generate_mac(platform_name, 0))
btdb.set_string (db,"vm.cfg[0].nethwlink", "br0")
btdb.set_string (db,"vm.cfg[0].nettype", "veth")
btdb.set_uint32 (db,"vm.cfg.size", 2)
btdb.set_boolean (db,"vm.cfg[1].autostart", 0)
btdb.set_string (db,"vm.cfg[1].base_path", "")
btdb.set_string (db,"vm.cfg[1].name", "vm001")
btdb.set_string (db,"vm.cfg[1].nethwaddr", btdb.generate_mac(platform_name, 1))
btdb.set_string (db,"vm.cfg[1].nethwlink", "br0")
btdb.set_string (db,"vm.cfg[1].nettype", "veth")
btdb.set_uint32 (db,"vm.cfg.size", 3)
btdb.set_boolean (db,"vm.cfg[2].autostart", 0)
btdb.set_string (db,"vm.cfg[2].base_path", "")
btdb.set_string (db,"vm.cfg[2].name", "vm002")
btdb.set_string (db,"vm.cfg[2].nethwaddr", btdb.generate_mac(platform_name, 2))
btdb.set_string (db,"vm.cfg[2].nethwlink", "br0")
btdb.set_string (db,"vm.cfg[2].nettype", "veth")
btdb.set_uint32 (db,"vm.cfg.size", 4)
btdb.set_boolean (db,"vm.cfg[3].autostart", 0)
btdb.set_string (db,"vm.cfg[3].base_path", "")
btdb.set_string (db,"vm.cfg[3].name", "vm003")
btdb.set_string (db,"vm.cfg[3].nethwaddr", btdb.generate_mac(platform_name, 3))
btdb.set_string (db,"vm.cfg[3].nethwlink", "br0")
btdb.set_string (db,"vm.cfg[3].nettype", "veth")
btdb.set_uint32 (db,"vm.cfg.size", 5)
btdb.set_boolean (db,"vm.cfg[4].autostart", 0)
btdb.set_string (db,"vm.cfg[4].base_path", "")
btdb.set_string (db,"vm.cfg[4].name", "vm004")
btdb.set_string (db,"vm.cfg[4].nethwaddr", btdb.generate_mac(platform_name, 4))
btdb.set_string (db,"vm.cfg[4].nethwlink", "br0")
btdb.set_string (db,"vm.cfg[4].nettype", "veth")
btdb.set_uint32 (db,"vm.cfg.size", 6)
btdb.set_boolean (db,"vm.cfg[5].autostart", 0)
btdb.set_string (db,"vm.cfg[5].base_path", "")
btdb.set_string (db,"vm.cfg[5].name", "vm005")
btdb.set_string (db,"vm.cfg[5].nethwaddr", btdb.generate_mac(platform_name, 5))
btdb.set_string (db,"vm.cfg[5].nethwlink", "br0")
btdb.set_string (db,"vm.cfg[5].nettype", "veth")
btdb.set_uint32 (db,"vm.cfg.size", 7)
btdb.set_boolean (db,"vm.cfg[6].autostart", 0)
btdb.set_string (db,"vm.cfg[6].base_path", "")
btdb.set_string (db,"vm.cfg[6].name", "vm006")
btdb.set_string (db,"vm.cfg[6].nethwaddr", btdb.generate_mac(platform_name, 6))
btdb.set_string (db,"vm.cfg[6].nethwlink", "br0")
btdb.set_string (db,"vm.cfg[6].nettype", "veth")
btdb.set_uint32 (db,"vm.cfg.size", 8)
btdb.set_boolean (db,"vm.cfg[7].autostart", 0)
btdb.set_string (db,"vm.cfg[7].base_path", "")
btdb.set_string (db,"vm.cfg[7].name", "vm007")
btdb.set_string (db,"vm.cfg[7].nethwaddr", btdb.generate_mac(platform_name, 7))
btdb.set_string (db,"vm.cfg[7].nethwlink", "br0")
btdb.set_string (db,"vm.cfg[7].nettype", "veth")
btdb.set_uint32 (db,"vm.cfg.size", 9)
btdb.set_boolean (db,"vm.cfg[8].autostart", 0)
btdb.set_string (db,"vm.cfg[8].base_path", "")
btdb.set_string (db,"vm.cfg[8].name", "vm008")
btdb.set_string (db,"vm.cfg[8].nethwaddr", btdb.generate_mac(platform_name, 8))
btdb.set_string (db,"vm.cfg[8].nethwlink", "br0")
btdb.set_string (db,"vm.cfg[8].nettype", "veth")
btdb.set_uint32 (db,"vm.cfg.size", 10)
btdb.set_boolean (db,"vm.cfg[9].autostart", 0)
btdb.set_string (db,"vm.cfg[9].base_path", "")
btdb.set_string (db,"vm.cfg[9].name", "vm009")
btdb.set_string (db,"vm.cfg[9].nethwaddr", btdb.generate_mac(platform_name, 9))
btdb.set_string (db,"vm.cfg[9].nethwlink", "br0")
btdb.set_string (db,"vm.cfg[9].nettype", "veth")
def gen_cfg_network(db):
btdb.set_uint32 (db,"network.cfg.size", 1)
btdb.set_string (db,"network.cfg[0].type", "generic")
btdb.set_string (db,"network.cfg[0].interface_name", "lo")
btdb.set_boolean (db,"network.cfg[0].is_up", 1)
btdb.set_boolean (db,"network.cfg[0].is_dhcp", 0)
btdb.set_boolean (db,"network.cfg[0].is_setup_ipaddress", 0)
btdb.set_boolean (db,"network.cfg[0].is_setup_hwaddress", 0)
btdb.set_string (db,"network.cfg[0].hwaddress", "")
btdb.set_uint32 (db,"network.cfg[0].interfaces.size", 0)
btdb.set_uint32 (db,"network.cfg.size", 2)
btdb.set_string (db,"network.cfg[1].type", "generic")
btdb.set_string (db,"network.cfg[1].interface_name", "eth0")
btdb.set_boolean (db,"network.cfg[1].is_up", 1)
btdb.set_boolean (db,"network.cfg[1].is_dhcp", 0)
btdb.set_boolean (db,"network.cfg[1].is_setup_ipaddress", 0)
btdb.set_boolean (db,"network.cfg[1].is_setup_hwaddress", 0)
btdb.set_string (db,"network.cfg[1].hwaddress", "")
btdb.set_uint32 (db,"network.cfg[1].interfaces.size", 0)
btdb.set_uint32 (db,"network.cfg.size", 3)
btdb.set_string (db,"network.cfg[2].type", "bridge")
btdb.set_string (db,"network.cfg[2].interface_name", "br0")
btdb.set_boolean (db,"network.cfg[2].is_up", 1)
btdb.set_boolean (db,"network.cfg[2].is_dhcp", 1)
btdb.set_boolean (db,"network.cfg[2].is_setup_ipaddress", 0)
btdb.set_boolean (db,"network.cfg[2].is_setup_hwaddress", 1)
btdb.set_string (db,"network.cfg[2].hwaddress", btdb.generate_mac(platform_name, 250))
btdb.set_uint32 (db,"network.cfg[2].interfaces.size", 1)
btdb.set_string (db,"network.cfg[2].interfaces[0].name", "eth0")
btdb.set_uint32 (db,"network.cfg.size", 4)
btdb.set_string (db,"network.cfg[3].type", "vlan")
btdb.set_string (db,"network.cfg[3].interface_name", "eth0.100")
btdb.set_boolean (db,"network.cfg[3].is_up", 1)
btdb.set_boolean (db,"network.cfg[3].is_dhcp", 0)
btdb.set_boolean (db,"network.cfg[3].is_setup_ipaddress", 0)
btdb.set_boolean (db,"network.cfg[3].is_setup_hwaddress", 0)
btdb.set_string (db,"network.cfg[3].hwaddress", "")
btdb.set_uint32 (db,"network.cfg[3].interfaces.size", 0)
btdb.set_uint32 (db,"network.cfg.size", 5)
btdb.set_string (db,"network.cfg[4].type", "bridge")
btdb.set_string (db,"network.cfg[4].interface_name", "br1")
btdb.set_boolean (db,"network.cfg[4].is_up", 1)
btdb.set_boolean (db,"network.cfg[4].is_dhcp", 0)
btdb.set_boolean (db,"network.cfg[4].is_setup_ipaddress", 1)
btdb.set_boolean (db,"network.cfg[4].is_setup_hwaddress", 1)
btdb.set_string (db,"network.cfg[4].hwaddress", btdb.generate_mac(platform_name, 251))
btdb.set_uint32 (db,"network.cfg[4].interfaces.size", 1)
btdb.set_string (db,"network.cfg[4].interfaces[0].name", "eth0.100")
btdb.set_string (db,"network.cfg[4].interface_address", "192.168.200.254")
btdb.set_string (db,"network.cfg[4].interface_netmask", "255.255.255.0")
def gen_cfg_plugincmd(db):
btdb.set_uint32 (db,"plugincmd.cfg.size", 1024)
btdb.set_boolean (db,"plugincmd.cfg[1].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[1].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[1].name", "raiddev")
btdb.set_boolean (db,"plugincmd.cfg[2].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[2].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[2].name", "mntbase")
btdb.set_boolean (db,"plugincmd.cfg[3].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[3].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[3].name", "netdev")
btdb.set_boolean (db,"plugincmd.cfg[4].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[4].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[4].name", "netssh")
btdb.set_boolean (db,"plugincmd.cfg[5].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[5].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[5].name", "netntp")
btdb.set_boolean (db,"plugincmd.cfg[6].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[6].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[6].name", "nethttp")
btdb.set_boolean (db,"plugincmd.cfg[7].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[7].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[7].name", "vmcontainer")
btdb.set_boolean (db,"plugincmd.cfg[8].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[8].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[8].name", "mntbasecount")
btdb.set_boolean (db,"plugincmd.cfg[9].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[9].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[9].name", "mntbaseget")
btdb.set_boolean (db,"plugincmd.cfg[10].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[10].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[10].name", "mntbaseset")
btdb.set_boolean (db,"plugincmd.cfg[11].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[11].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[11].name", "vmcount")
btdb.set_boolean (db,"plugincmd.cfg[12].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[12].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[12].name", "vmget")
btdb.set_boolean (db,"plugincmd.cfg[13].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[13].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[13].name", "vmset")
btdb.set_boolean (db,"plugincmd.cfg[14].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[14].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[14].name", "vmadd")
btdb.set_boolean (db,"plugincmd.cfg[15].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[15].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[15].name", "raiddevcount")
btdb.set_boolean (db,"plugincmd.cfg[16].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[16].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[16].name", "raiddevget")
btdb.set_boolean (db,"plugincmd.cfg[17].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[17].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[17].name", "raiddevset")
btdb.set_boolean (db,"plugincmd.cfg[18].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[18].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[18].name", "mkbtrfs")
btdb.set_boolean (db,"plugincmd.cfg[19].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[19].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[19].name", "mkbtrfs_status")
btdb.set_boolean (db,"plugincmd.cfg[20].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[20].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[20].name", "db_setbool_f")
btdb.set_boolean (db,"plugincmd.cfg[21].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[21].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[21].name", "db_getbool_f")
btdb.set_boolean (db,"plugincmd.cfg[22].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[22].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[22].name", "db_setuint32_f")
btdb.set_boolean (db,"plugincmd.cfg[23].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[23].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[23].name", "db_getuint32_f")
btdb.set_boolean (db,"plugincmd.cfg[24].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[24].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[24].name", "db_setstring_f")
btdb.set_boolean (db,"plugincmd.cfg[25].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[25].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[25].name", "db_getstring_f")
btdb.set_boolean (db,"plugincmd.cfg[26].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[26].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[26].name", "db_setbool_r")
btdb.set_boolean (db,"plugincmd.cfg[27].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[27].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[27].name", "db_getbool_r")
btdb.set_boolean (db,"plugincmd.cfg[28].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[28].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[28].name", "db_setuint32_r")
btdb.set_boolean (db,"plugincmd.cfg[29].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[29].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[29].name", "db_getuint32_r")
btdb.set_boolean (db,"plugincmd.cfg[30].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[30].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[30].name", "db_setstring_r")
btdb.set_boolean (db,"plugincmd.cfg[31].enabled", 1)
btdb.set_boolean (db,"plugincmd.cfg[31].fixed", 0)
btdb.set_string (db,"plugincmd.cfg[31].name", "db_getstring_r")
if __name__ == "__main__":
db_name = platform_name + '.db'
db = btdb.open(db_name)
gen_cfg_platform(db)
'''gen_cfg_mountfs(db)'''
gen_cfg_network(db)
gen_cfg_vm_base_image(db)
gen_cfg_vm(db)
gen_cfg_plugincmd(db)
btdb.close(db)
| [
"[email protected]"
] | |
69dc9b2fe646f35c01edb5ff5eb318b3291f0fa9 | f125a883dbcc1912dacb3bf13e0f9263a42e57fe | /tsis5/part1/21.py | 1fc47ed9b0a9a65ab42e5e8b5dd618f9a234fcfe | [] | no_license | AruzhanBazarbai/pp2 | 1f28b9439d1b55499dec4158e8906954b507f04a | 9d7f1203b6735b27bb54dfda73b3d2c6b90524c3 | refs/heads/master | 2023-07-13T05:26:02.154105 | 2021-08-27T10:20:34 | 2021-08-27T10:20:34 | 335,332,307 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 382 | py | #Write a Python program to create a file where all letters of English alphabet are listed by specified number of letters on each line
import string
def letters_file_line(n):
with open("words1.txt", "w") as f:
alphabet = string.ascii_uppercase
letters = [alphabet[i:i + n] + "\n" for i in range(0, len(alphabet), n)]
f.writelines(letters)
letters_file_line(3) | [
"[email protected]"
] | |
04c4f07bd5698c3866128a445148f52291cad0de | eef9afdc9ab5ee6ebbfa23c3162b978f137951a8 | /oops_concept/encapsulation/encapsul3.py | 0804609b0c00d8bb1f7947f4a6266df30c65c544 | [] | no_license | krishnadhara/programs-venky | 2b679dca2a6158ecd6a5c28e86c8ed0c3bab43d4 | 0f4fd0972dec47e273b6677bbd32e2d0742789ae | refs/heads/master | 2020-06-05T04:48:45.792427 | 2019-06-17T09:59:45 | 2019-06-17T09:59:45 | 192,318,337 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 210 | py | class SeeMee:
def youcanseemee(self):
return "you can see mee"
def __youcantseemee(self):
return "you cant see mee"
p = SeeMee()
print(p.youcanseemee())
print(p._SeeMee__youcantseemee()) | [
"[email protected]"
] | |
3ff2138e33c5184658a9ea4eb2200b7f23f05ad5 | df01d62513cd03c0b794dcebcd5d3de28084e909 | /djbShop/djbShop/urls.py | 8005492bfc9e6511dbaa843d4b98e9dc8374289a | [] | no_license | codingEzio/code_py_bookreview_django2_by_example | 32206fc30b7aab6f0a613d481089bf8bffd1380c | 9c2d022364e1b69063bd7a0b741ebeeb5b7d4e13 | refs/heads/master | 2022-12-23T20:32:42.899128 | 2022-12-20T07:40:11 | 2022-12-20T07:40:11 | 207,786,302 | 1 | 0 | null | 2019-12-28T04:59:41 | 2019-09-11T10:35:44 | Python | UTF-8 | Python | false | false | 644 | py | from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('cart/', include('cart.urls', namespace='cart')),
path('orders/', include('orders.urls', namespace='orders')),
path('', include('shop.urls', namespace='shop')),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
path('__debug__/', include(debug_toolbar.urls)),
]
if settings.DEBUG:
urlpatterns += static(prefix=settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
| [
"[email protected]"
] | |
69370efa4a456f47d0ca107e5eee7219d752893c | b641e56db0f49dee6d27bea933255bff5caa6058 | /app/__init__.py | 2e99a6f67bb73c23a1950f7a7efd484e4990a7b7 | [
"BSD-2-Clause"
] | permissive | uniphil/kibera-school-project | ed2bffdc938878f2370ff458aef0582b48c1ba1f | 4e77538af66065ea00d7a7559129026a72aa4353 | refs/heads/master | 2016-09-03T01:44:43.809992 | 2014-05-20T21:23:15 | 2014-05-20T21:23:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 540 | py | # -*- coding: utf-8 -*-
"""
app
~~~
Static site generator for the Kibera School Project by Feedback Labs
This file initializes the app and manages configuration before importing
the other modules to do all the work.
"""
# from flask import Flask
# app = Flask('app')
# app.config['FREEZER_DESTINATION'] = app.config['BUILD_OUTPUT'] = '../output'
# app.config['CONTENT_FOLDER'] = '../content'
# app.config['CNAME'] = 'kibera-staging.precomp.ca'
# from . import content
# from . import views
# from . import static
| [
"[email protected]"
] | |
8145d3a3343b5e652288a7d273365a1643b1d1da | 9906dfd3d059afdf3841a883cd1c75018f0f3b67 | /Midterm programs/redo of Midterm program 1.py | 0aa0b6db058b8d883cba5200e85fa3742a7ba558 | [] | no_license | ThomasMGilman/ETGG1801_GameProgrammingFoundations | 73ebc4ef6833b0a7ed4cdab8416bee3da91f0018 | 4d7e412507b9c812b026717514bd5c5f121a8f31 | refs/heads/master | 2020-03-29T23:11:08.620415 | 2018-09-26T16:56:33 | 2018-09-26T16:56:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 57 | py | i=1
while i<=41:
print(i)
i+=2
print("all done")
| [
"[email protected]"
] | |
30ce2874708c452ce8a921d0df7df203cd619871 | 34d88082307281333ef4aeeec012a3ff5f8ec06e | /w3resource/List_/Q058.py | 02e569e86ae9c120564deb6898a1645490b175de | [] | no_license | JKChang2015/Python | a6f8b56fa3f9943682470ae57e5ad3266feb47a7 | adf3173263418aee5d32f96b9ea3bf416c43cc7b | refs/heads/master | 2022-12-12T12:24:48.682712 | 2021-07-30T22:27:41 | 2021-07-30T22:27:41 | 80,747,432 | 1 | 8 | null | 2022-12-08T04:32:06 | 2017-02-02T17:05:19 | HTML | UTF-8 | Python | false | false | 285 | py | # -*- coding: UTF-8 -*-
# Q058
# Created by JKChang
# Thu, 31/08/2017, 16:35
# Tag:
# Description: 58. Write a Python program to replace the last element in a list with another list.
# Sample data : [1, 3, 5, 7, 9, 10], [2, 4, 6, 8]
# Expected Output: [1, 3, 5, 7, 9, 2, 4, 6, 8]
| [
"[email protected]"
] | |
e1f81e46b0c455bb596d317beacc49baf9d411d6 | e4066b34668bbf7fccd2ff20deb0d53392350982 | /project_scrapy/spiders/dshop.py | be32858a472c5b199e95d1d6197ee401499faebd | [] | no_license | sushma535/WebSites | 24a688b86e1c6571110f20421533f0e7fdf6e1a8 | 16a3bfa44e6c7e22ae230f5b336a059817871a97 | refs/heads/master | 2023-08-18T09:09:16.052555 | 2021-10-11T00:41:50 | 2021-10-11T00:41:50 | 415,621,279 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,539 | py | import scrapy
from scrapy.crawler import CrawlerProcess
import os
import csv
from csv import reader
import re
total_data = {}
class SimilarWeb(scrapy.Spider):
name = 'SW'
user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
start_urls = ['https://www.dshop.com.au/', 'https://www.similarsites.com/site/dshop.com.au/']
csv_columns = ['Category', 'Description', 'Name', 'Url']
csv_file = 'websites1_data.csv'
count = 0
def parse(self, response):
data, desc, cat = '', '', ''
print('response url:', response.url)
if response.url == self.start_urls[0]:
data = response.css('title::text').get()
if data:
data = re.sub("\n\t\t", '', data)
total_data['Name'] = data
self.count += 1
elif response.url == self.start_urls[1]:
cat = response.css(
'div[class="StatisticsCategoriesDistribution__CategoryTitle-fnuckk-6 jsMDeK"]::text').getall()
desc = response.css('div[class="SiteHeader__Description-sc-1ybnx66-8 hhZNQm"]::text').get()
if cat:
cat = ": ".join(cat[:])
total_data['Category'] = cat
total_data['Description'] = desc
total_data['Url'] = self.start_urls[0]
self.count += 1
if self.count == 2:
print("total data", total_data)
new_data = [total_data['Category'], total_data['Description'], total_data['Name'],
total_data['Url']]
print("new data", new_data)
self.row_appending_to_csv_file(new_data)
def row_appending_to_csv_file(self, data):
if os.path.exists(self.csv_file):
need_to_add_headers = False
with open(self.csv_file, 'a+', newline='') as file:
file.seek(0)
csv_reader = reader(file)
if len(list(csv_reader)) == 0:
need_to_add_headers = True
csv_writer = csv.writer(file)
if need_to_add_headers:
csv_writer.writerow(self.csv_columns)
csv_writer.writerow(data)
else:
with open(self.csv_file, 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerow(self.csv_columns) # header
csv_writer.writerow(data)
process = CrawlerProcess()
process.crawl(SimilarWeb)
process.start()
| [
"[email protected]"
] | |
98aac32f8002f1242c4200d8fc88f6918443821c | 3560a70fefb3f32a85206b66704e473e1dec8761 | /docs/conf.py | 42236bc483f2519db436abdd4f9966ec17483ca0 | [
"MIT"
] | permissive | francispoulin/hankel | 626c0e7e38934217ff274ea5a012023bb3b983d8 | 0dc05b37df16ac3ff1df5ebdd87b9107bf0197b0 | refs/heads/master | 2021-01-11T14:37:12.944019 | 2017-02-13T08:07:42 | 2017-02-13T08:07:42 | 80,174,672 | 0 | 0 | null | 2017-01-27T02:13:41 | 2017-01-27T02:13:41 | null | UTF-8 | Python | false | false | 5,915 | py | # -*- coding: utf-8 -*-
#
# hankel documentation build configuration file, created by
# sphinx-quickstart on Mon Feb 13 10:17:24 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
#'sphinx.ext.githubpages',
'numpydoc',
'sphinx.ext.autosummary',
'nbsphinx',
'IPython.sphinxext.ipython_console_highlighting' # Ensures syntax highlighting works in notebooks (workaround)
]
autosummary_generate = True
numpydoc_show_class_members=False
# Add any paths that contain templates here, relative to this directory.
templates_path = ['templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'hankel'
copyright = u'2017, Steven Murray'
author = u'Steven Murray'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
import re, io,os
def read(*names, **kwargs):
with io.open(
os.path.join(os.path.dirname(__file__), *names),
encoding=kwargs.get("encoding", "utf8")
) as fp:
return fp.read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
# The short X.Y version.
version = find_version("..","hankel", "__init__.py")
# The full version, including alpha/beta/rc tags.
release = find_version("..","hankel", "__init__.py")
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store','templates','**.ipynb_checkpoints']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'hankeldoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'hankel.tex', u'hankel Documentation',
u'Steven Murray', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'hankel', u'hankel Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'hankel', u'hankel Documentation',
author, 'hankel', 'One line description of project.',
'Miscellaneous'),
]
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
| [
"[email protected]"
] | |
ae01ef1517dbf0dea633d118236da9dfb2265530 | 69a327a2af65d7252b624fe7cadd537eb51ca6d6 | /String/BOJ_1259.py | d717f4cfec4f6568eee7fb4837c2ffb29c2ca38d | [] | no_license | enriver/algorithm_python | 45b742bd17c6a2991ac8095d13272ec4f88d9bf5 | 77897f2bf0241756ba6fd07c052424a6f4991090 | refs/heads/master | 2023-09-03T23:28:23.975609 | 2021-10-29T09:25:32 | 2021-10-29T09:25:32 | 278,907,031 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 520 | py | # 팰린드롬수
import sys
for _ in range(100):
n=sys.stdin.readline()
isP=True
if int(n)==0:
break
else:
val=list()
re_val=list()
for i in n:
val.append(i)
re_val.append(i)
re_val.reverse()
val.pop(-1)
re_val.pop(0)
for i in range(len(val)):
if val[i]!=re_val[i]:
isP=False
if isP==False:
print('no')
else:
print('yes')
| [
"[email protected]"
] | |
018beb2cab77071fe797d905f21a3473c8bffbd0 | 4e07727db834a45b2d77f0d9e54ed57796dc986d | /demo/picoalu.py | fc9ba7c3281dbd67618b12758831aa03c88c67b5 | [] | no_license | phanrahan/pico40 | 278447961d9d115f94b02e5322ba452442808e30 | 26cf9f6130666cc981ca27324bc4c1137eaf3252 | refs/heads/master | 2021-01-22T08:05:56.855776 | 2017-10-20T20:03:52 | 2017-10-20T20:03:52 | 81,874,575 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 2,897 | py | import sys
from magma import *
from mantle import *
from parts.lattice.ice40.primitives.RAMB import ROMB
from pico.asm import *
from pico.cpu.seq import Sequencer
from pico.cpu.alu import Arith, Logic
from pico.cpu.ram import DualRAM
from boards.icestick import IceStick
icestick = IceStick()
icestick.Clock.on()
for i in range(8):
icestick.J1[i].input().on()
for i in range(8):
icestick.J3[i].output().on()
main = icestick.main()
ADDRN = 8
INSTN = 16
N = 8
def instructiondecode(insttype):
# alu instructions
logicinst = ROM2((1 << 0))(insttype)
arithinst = ROM2((1 << 1))(insttype)
aluinst = ROM2((1 << 0) | (1 << 1))(insttype)
# ld and st (immediate)
ldloinst = ROM4(1 << 8)(inst[12:16])
ldinst = ROM4(1 << 10)(inst[12:16])
stinst = ROM4(1 << 11)(inst[12:16])
# control flow instructions
jumpinst = ROM4(1 << 12)(inst[12:16])
#callinst = ROM4(1 << 13)(inst[12:16])
return logicinst, arithinst, aluinst, \
ldloinst, ldinst, stinst, \
jumpinst
# mov.py
# and.py
# or.py
# xor.py
# add.py
# sub.py
# and.py
#def prog():
# ldlo(r0, 0x55)
# ldlo(r1, 0x0f)
# and_(r1, r0)
# st(r1, 0)
# jmp(0)
# count.py
def prog():
ldlo(r0,0)
ldlo(r1,1)
loop = label()
add(r0,r1)
st(r0, 0)
jmp(loop)
mem = assemble(prog, 1<<ADDRN)
# program memory
romb = ROMB(mem)
wire( 1, romb.RCLKE )
wire( 1, romb.RE )
inst = romb.RDATA
# instruction decode
addr = inst[0:ADDRN]
imm = inst[0:N]
rb = inst[4:8]
ra = inst[8:12]
cc = inst[8:12]
op = inst[12:14]
insttype = inst[14:16]
logicinst, arithinst, aluinst, ldloinst, ldinst, stinst, jumpinst =\
instructiondecode(insttype)
jump = jumpinst
# romb's output is registered
# phase=0
# fetch()
# phase=1
# execute()
phase = TFF()(1)
# register write
regwr = LUT4((I0|I1|I2)&I3)(aluinst, ldloinst, ldinst, phase)
# sequencer
print 'Building sequencer'
seq = Sequencer(ADDRN)
pc = seq(addr, jump, phase)
wire(pc, romb.RADDR)
print 'Building input'
input = main.J1
print 'Building input mux'
regiomux = Mux(2, N)
regiomux(imm, input, ldinst)
print 'Building register input mux'
regimux = Mux(2, N)
print 'Building registers'
raval, rbval = DualRAM(4, ra, rb, ra, regimux, regwr)
# alu
print 'Building logic unit'
logicunit = Logic(N)
print 'Building arith unit'
arithunit = Arith(N)
print 'Building alu mux'
alumux = Mux(2, N)
print 'Wiring logic unit'
logicres = logicunit(raval, rbval, op[0], op[1])
print 'Wiring arith unit'
arithres = arithunit(raval, rbval, op[0], op[1])
wire(0, arithunit.CIN)
print 'Wiring alumux'
res = alumux(logicres, arithres, arithinst)
print 'Wiring register input mux'
ld = Or2()(ldinst, ldloinst)
regimux(res, regiomux, ld) # full io
print 'Wiring output'
output = Register(N, ce=True)
owr = And2()(stinst, phase)
output(raval, CE=owr)
wire(output, main.J3)
compile(sys.argv[1], main)
| [
"[email protected]"
] | |
f7b6b12562a778214d8a22df2c85123c9eb66bad | 53edf6b0f4262ee76bb4e3b943394cfeafe54865 | /simulation_codes/_archived/PREDCORR_1D_TSC/py2/save_routines.py | 266faaaf7eebc39daea92fce756fa412c992f8b1 | [] | no_license | Yoshi2112/hybrid | f86265a2d35cb0a402ba6ab5f718717d8eeb740c | 85f3051be9368bced41af7d73b4ede9c3e15ff16 | refs/heads/master | 2023-07-07T21:47:59.791167 | 2023-06-27T23:09:23 | 2023-06-27T23:09:23 | 82,878,960 | 0 | 1 | null | 2020-04-16T18:03:59 | 2017-02-23T03:14:49 | Python | UTF-8 | Python | false | false | 4,135 | py | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 22 10:44:46 2017
@author: iarey
"""
import numpy as np
import pickle
import os
import sys
from shutil import rmtree
import simulation_parameters_1D as const
from simulation_parameters_1D import generate_data, generate_plots, drive, save_path, NX, ne, density
from simulation_parameters_1D import idx_bounds, Nj, species_lbl, temp_type, dist_type, mass, charge, velocity, sim_repr, Tpar, Tper, temp_color
def manage_directories():
print 'Checking directories...'
if (generate_data == 1 or generate_plots == 1) == True:
if os.path.exists('%s/%s' % (drive, save_path)) == False:
os.makedirs('%s/%s' % (drive, save_path)) # Create master test series directory
print 'Master directory created'
path = ('%s/%s/run_%d' % (drive, save_path, const.run_num)) # Set root run path (for images)
if os.path.exists(path) == False:
os.makedirs(path)
print 'Run directory created'
else:
print 'Run directory already exists'
overwrite_flag = raw_input('Overwrite? (Y/N) \n')
if overwrite_flag.lower() == 'y':
rmtree(path)
os.makedirs(path)
elif overwrite_flag.lower() == 'n':
sys.exit('Program Terminated: Change run_num in simulation_parameters_1D')
else:
sys.exit('Unfamiliar input: Run terminated for safety')
return
def store_run_parameters(dt, data_dump_iter):
d_path = ('%s/%s/run_%d/data' % (drive, save_path, const.run_num)) # Set path for data
manage_directories()
if os.path.exists(d_path) == False: # Create data directory
os.makedirs(d_path)
# Single parameters
params = dict([('seed', const.seed),
('Nj', Nj),
('dt', dt),
('NX', NX),
('dxm', const.dxm),
('dx', const.dx),
('cellpart', const.cellpart),
('B0', const.B0),
('ne', ne),
('Te0', const.Te0),
('ie', const.ie),
('theta', const.theta),
('data_dump_iter', data_dump_iter),
('max_rev', const.max_rev),
('orbit_res', const.orbit_res),
('freq_res', const.freq_res),
('run_desc', const.run_description),
('method_type', 'PREDCORR'),
('particle_shape', 'TSC')
])
h_name = os.path.join(d_path, 'Header.pckl') # Data file containing dictionary of variables used in run
with open(h_name, 'wb') as f:
pickle.dump(params, f)
f.close()
print 'Header file saved'
# Particle values: Array parameters
p_file = os.path.join(d_path, 'p_data')
np.savez(p_file, idx_bounds = idx_bounds,
species_lbl = species_lbl,
temp_color = temp_color,
temp_type = temp_type,
dist_type = dist_type,
mass = mass,
charge = charge,
velocity = velocity,
density = density,
sim_repr = sim_repr,
Tpar = Tpar,
Tper = Tper)
print 'Particle data saved'
return
def save_data(dt, data_iter, qq, pos, vel, Ji, E, B, Ve, Te, dns):
d_path = ('%s/%s/run_%d/data' % (drive, save_path, const.run_num)) # Set path for data
r = qq / data_iter # Capture number
d_filename = 'data%05d' % r
d_fullpath = os.path.join(d_path, d_filename)
np.savez(d_fullpath, pos = pos, vel = vel, E = E[1:NX+1, 0:3], B = B[1:NX+2, 0:3], J = Ji[1:NX+1],
dns = dns[1:NX+1], Ve = Ve[1:NX+1], Te = Te[1:NX+1]) # Data file for each iteration
print 'Data saved'.format(qq)
| [
"[email protected]"
] | |
1ea83f90ea8db170062f45f51f1716794d7d0fc5 | f0a5ad7b8aa39f51f233391fead0da3eabecc4ee | /.history/toolbox/sheets_20191128120456.py | 54667dc8f469a984db42e907ae4f73a38cf6d539 | [] | no_license | OseiasBeu/webScrapping | e0a524847e55b24dbbd3d57bbe7fa43b4e101f48 | 1e72c7551aea355a891043baecfcbab8a89e719a | refs/heads/master | 2022-10-25T18:12:50.858653 | 2020-06-18T01:29:24 | 2020-06-18T01:29:24 | 224,681,550 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,501 | py | from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import numpy as np
# import gspread
def insertPlanMiddleware(rows):
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SAMPLE_SPREADSHEET_ID = '1QSGAY_WyamEQBZ4ITdAGCVAbavR9t-D-4gPQx4Sbf7g'
SAMPLE_RANGE_NAME = 'middleware'
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'C:\\Users\\beuo\\Documents\\Demandas\\AtualizaMiddleIntegrationVtex\\toolbox\\credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
# gs= gspread.authorize(service)
# gs
sheet = service.spreadsheets()
# result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
# range=SAMPLE_RANGE_NAME).execute()
# values = result.get('values', [])
# print(values)
rows = rows[['timeStamp','clienteEstado','warehouseId','Pendentes de integração']]
rows = np.asarray(rows)
# range_ = 'my-range' # TODO: Update placeholder value.
# How the input data should be interpreted.
for row in rows:
value_input_option = 'RAW' # TODO: Update placeholder value.
value_range_body = {"1","3","4","5"}
request = service.spreadsheets().values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME, valueInputOption=value_input_option, body=value_range_body)
response = request.execute()
print(response)
| [
"[email protected]"
] | |
b7525b3c4b2ee07bfaef0438826a3266ea1bfd5c | b2c6833c5b2317ea81236c15ab730b8609b60043 | /gyp/public_headers.gypi | adef01260d88ef675d6f400829a1fb2bbbc9c106 | [
"BSD-3-Clause"
] | permissive | Axure/skia | 340531c240bb30677e75da52bbb859db81ebe3d1 | c4f30b1074e1068d6fc0f368428f410ed6d4b2b5 | refs/heads/master | 2021-01-17T22:06:37.416598 | 2014-07-13T17:09:42 | 2014-07-13T17:09:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,782 | gypi | # Include this gypi to include all public header files that exist in the
# include directory.
#
# The list is computed by running 'find include -name *.h' in the root dir of
# the project.
#
{
'variables': {
'header_filenames': [
'pdf/SkPDFDevice.h',
'pdf/SkPDFDocument.h',
'svg/SkSVGTypes.h',
'svg/SkSVGBase.h',
'svg/SkSVGAttribute.h',
'svg/SkSVGParser.h',
'svg/SkSVGPaintState.h',
'animator/SkAnimator.h',
'animator/SkAnimatorView.h',
'gpu/GrTexture.h',
'gpu/SkGr.h',
'gpu/GrContext.h',
'gpu/gl/GrGLConfig_chrome.h',
'gpu/gl/SkNativeGLContext.h',
'gpu/gl/SkMesaGLContext.h',
'gpu/gl/SkDebugGLContext.h',
'gpu/gl/SkANGLEGLContext.h',
'gpu/gl/GrGLConfig.h',
'gpu/gl/GrGLInterface.h',
'gpu/gl/SkNullGLContext.h',
'gpu/gl/GrGLFunctions.h',
'gpu/gl/SkGLContextHelper.h',
'gpu/gl/GrGLExtensions.h',
'gpu/SkGpuDevice.h',
'gpu/GrTypes.h',
'gpu/GrFontScaler.h',
'gpu/GrResource.h',
'gpu/GrKey.h',
'gpu/GrOvalRenderer.h',
'gpu/GrEffectUnitTest.h',
'gpu/GrConfig.h',
'gpu/GrPaint.h',
'gpu/GrPathRendererChain.h',
'gpu/GrTBackendEffectFactory.h',
'gpu/GrDrawEffect.h',
'gpu/GrTextContext.h',
'gpu/GrEffect.h',
'gpu/SkGrTexturePixelRef.h',
'gpu/GrTextureAccess.h',
'gpu/GrRect.h',
'gpu/GrEffectStage.h',
'gpu/GrClipData.h',
'gpu/GrUserConfig.h',
'gpu/SkGrPixelRef.h',
'gpu/GrAARectRenderer.h',
'gpu/GrColor.h',
'gpu/GrGlyph.h',
'gpu/GrBackendEffectFactory.h',
'gpu/GrContextFactory.h',
'gpu/GrRenderTarget.h',
'gpu/GrSurface.h',
'gpu/GrTypesPriv.h',
'config/sk_stdint.h',
'config/SkUserConfig.h',
'pipe/SkGPipe.h',
'images/SkMovie.h',
'images/SkPageFlipper.h',
'images/SkForceLinking.h',
'effects/SkMorphologyImageFilter.h',
'effects/Sk2DPathEffect.h',
'effects/SkXfermodeImageFilter.h',
'effects/SkAlphaThresholdFilter.h',
'effects/SkArithmeticMode.h',
'effects/SkMergeImageFilter.h',
'effects/SkPerlinNoiseShader.h',
'effects/SkLerpXfermode.h',
'effects/SkLumaColorFilter.h',
'effects/SkRectShaderImageFilter.h',
'effects/SkMagnifierImageFilter.h',
'effects/SkPorterDuff.h',
'effects/SkBlurImageFilter.h',
'effects/SkTableMaskFilter.h',
'effects/SkAvoidXfermode.h',
'effects/SkBitmapSource.h',
'effects/SkCornerPathEffect.h',
'effects/SkTransparentShader.h',
'effects/SkStippleMaskFilter.h',
'effects/SkPaintFlagsDrawFilter.h',
'effects/SkOffsetImageFilter.h',
'effects/SkDiscretePathEffect.h',
'effects/SkTableColorFilter.h',
'effects/SkGradientShader.h',
'effects/SkEmbossMaskFilter.h',
'effects/SkComposeImageFilter.h',
'effects/SkTestImageFilters.h',
'effects/SkLayerRasterizer.h',
'effects/SkDashPathEffect.h',
'effects/Sk1DPathEffect.h',
'effects/SkBlurMaskFilter.h',
'effects/SkDrawExtraPathEffect.h',
'effects/SkDisplacementMapEffect.h',
'effects/SkPixelXorXfermode.h',
'effects/SkColorMatrixFilter.h',
'effects/SkColorMatrix.h',
'effects/SkBlurDrawLooper.h',
'effects/SkColorFilterImageFilter.h',
'effects/SkLayerDrawLooper.h',
'effects/SkLightingImageFilter.h',
'effects/SkDropShadowImageFilter.h',
'effects/SkMatrixConvolutionImageFilter.h',
'utils/SkBoundaryPatch.h',
'utils/SkCamera.h',
'utils/SkCubicInterval.h',
'utils/SkCullPoints.h',
'utils/SkDebugUtils.h',
'utils/SkDeferredCanvas.h',
'utils/SkDumpCanvas.h',
'utils/SkDumpCanvas.h',
'utils/SkInterpolator.h',
'utils/SkInterpolator.h',
'utils/SkLayer.h',
'utils/SkLua.h',
'utils/SkLua.h',
'utils/SkLuaCanvas.h',
'utils/SkMatrix44.h',
'utils/SkMatrix44.h',
'utils/SkMeshUtils.h',
'utils/SkNWayCanvas.h',
'utils/SkNinePatch.h',
'utils/SkNullCanvas.h',
'utils/SkParse.h',
'utils/SkParse.h',
'utils/SkParsePaint.h',
'utils/SkParsePaint.h',
'utils/SkParsePath.h',
'utils/SkPathUtils.h',
'utils/SkPictureUtils.h',
'utils/SkProxyCanvas.h',
'utils/SkRTConf.h',
'utils/SkRTConf.h',
'utils/SkRandom.h',
'utils/SkRunnable.h',
'utils/SkRunnable.h',
'utils/SkThreadPool.h',
'utils/SkThreadPool.h',
'utils/SkWGL.h',
'utils/SkWGL.h',
'utils/ios/SkStream_NSData.h',
'utils/mac/SkCGUtils.h',
'utils/win/SkAutoCoInitialize.h',
'utils/win/SkHRESULT.h',
'utils/win/SkIStream.h',
'utils/win/SkTScopedComPtr.h',
'xml/SkDOM.h',
'xml/SkJS.h',
'xml/SkXMLParser.h',
'xml/SkBML_XMLParser.h',
'xml/SkBML_WXMLParser.h',
'xml/SkXMLWriter.h',
'device/xps/SkXPSDevice.h',
'device/xps/SkConstexprMath.h',
'ports/SkTypeface_win.h',
'ports/SkFontConfigInterface.h',
'ports/SkTypeface_mac.h',
'ports/SkTypeface_android.h',
'ports/SkFontStyle.h',
'ports/SkFontMgr.h',
'text/SkTextLayout.h',
'core/SkColor.h',
'core/SkFontHost.h',
'core/SkMetaData.h',
'core/SkRRect.h',
'core/SkMatrix.h',
'core/SkDataTable.h',
'core/SkScalar.h',
'core/SkFlattenableSerialization.h',
'core/SkTypeface.h',
'core/SkImageEncoder.h',
'core/SkDrawFilter.h',
'core/SkTDict.h',
'core/SkRasterizer.h',
'core/SkColorPriv.h',
'core/SkFloatingPoint.h',
'core/SkOSFile.h',
'core/SkPaint.h',
'core/SkTDStack.h',
'core/SkDither.h',
'core/SkFixed.h',
'core/SkDocument.h',
'core/SkInstCnt.h',
'core/SkEndian.h',
'core/SkColorTable.h',
'core/SkBitmap.h',
'core/SkDraw.h',
'core/SkPackBits.h',
'core/SkFloatBits.h',
'core/SkDeque.h',
'core/SkTRegistry.h',
'core/SkTLazy.h',
'core/SkComposeShader.h',
'core/SkUtils.h',
'core/SkImage.h',
'core/SkPaintOptionsAndroid.h',
'core/SkDeviceProperties.h',
'core/SkGraphics.h',
'core/SkCanvas.h',
'core/SkPicture.h',
'core/SkClipStack.h',
'core/SkXfermode.h',
'core/SkColorFilter.h',
'core/SkRegion.h',
'core/SkRefCnt.h',
'core/SkStream.h',
'core/SkFontLCDConfig.h',
'core/SkBlitRow.h',
'core/SkGeometry.h',
'core/SkStrokeRec.h',
'core/SkImageDecoder.h',
'core/SkTime.h',
'core/SkPathMeasure.h',
'core/SkMaskFilter.h',
'core/SkFlate.h',
'core/SkTDArray.h',
'core/SkAnnotation.h',
'core/SkMath.h',
'core/SkDrawLooper.h',
'core/SkFlattenableBuffers.h',
'core/SkTemplates.h',
'core/SkMask.h',
'core/SkMallocPixelRef.h',
'core/SkWeakRefCnt.h',
'core/SkTypes.h',
'core/SkThread.h',
'core/SkData.h',
'core/SkPoint.h',
'core/SkColorShader.h',
'core/SkChunkAlloc.h',
'core/SkUnPreMultiply.h',
'core/SkReader32.h',
'core/SkDevice.h',
'core/SkImageFilter.h',
'core/SkAdvancedTypefaceMetrics.h',
'core/SkTInternalLList.h',
'core/SkTArray.h',
'core/SkStringUtils.h',
'core/SkPreConfig.h',
'core/SkLineClipper.h',
'core/SkPathEffect.h',
'core/SkString.h',
'core/SkPixelRef.h',
'core/SkSize.h',
'core/SkSurface.h',
'core/SkPostConfig.h',
'core/SkShader.h',
'core/SkWriter32.h',
'core/SkError.h',
'core/SkPath.h',
'core/SkFlattenable.h',
'core/SkTSearch.h',
'core/SkRect.h',
'pathops/SkPathOps.h',
'views/SkTouchGesture.h',
'views/SkEvent.h',
'views/SkOSWindow_NaCl.h',
'views/SkTextBox.h',
'views/SkViewInflate.h',
'views/SkOSWindow_iOS.h',
'views/SkBGViewArtist.h',
'views/SkOSWindow_SDL.h',
'views/SkWindow.h',
'views/SkSystemEventTypes.h',
'views/SkOSWindow_Android.h',
'views/SkOSWindow_Mac.h',
'views/android/AndroidKeyToSkKey.h',
'views/SkEventSink.h',
'views/animated/SkImageView.h',
'views/animated/SkWidgetViews.h',
'views/animated/SkProgressBarView.h',
'views/animated/SkBorderView.h',
'views/animated/SkScrollBarView.h',
'views/SkStackViewLayout.h',
'views/SkApplication.h',
'views/unix/keysym2ucs.h',
'views/unix/XkeysToSkKeys.h',
'views/SkKey.h',
'views/SkView.h',
'views/SkOSMenu.h',
'views/SkOSWindow_Unix.h',
'views/SkWidget.h',
'views/SkOSWindow_Win.h',
],
},
}
| [
"[email protected]"
] | |
9b1b03442cc1fc5f738453149dd093c7e29e3127 | 3f5c0e166f8d88ce9aa9170dc4a80a5b64c64c6a | /melange-testing/tests/app/soc/modules/gsoc/views/test_accepted_orgs.py | aad371c70d5f7d5208def2a91af8f8303e948b7e | [] | no_license | praveen97uma/GSoC-Docs | a006538b1d05ecab1a105139e4eb2f2cff36b07f | 40c97239887a5c430be28a76cc2cd7a968511ce0 | refs/heads/master | 2021-01-23T16:26:56.949299 | 2012-06-14T19:31:30 | 2012-06-14T19:31:30 | 1,505,012 | 1 | 1 | null | 2020-02-08T05:17:26 | 2011-03-21T01:39:34 | Python | UTF-8 | Python | false | false | 3,478 | py | #!/usr/bin/env python2.5
#
# Copyright 2011 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests the view for GSoC accepted orgs.
"""
from soc.modules.gsoc.models.organization import GSoCOrganization
from soc.modules.seeder.logic.seeder import logic as seeder_logic
from tests.test_utils import GSoCDjangoTestCase
class AcceptedOrgsPageTest(GSoCDjangoTestCase):
"""Tests the page to display accepted organization.
"""
def setUp(self):
self.init()
self.url1 = '/gsoc/accepted_orgs/' + self.gsoc.key().name()
self.url2 = '/gsoc/program/accepted_orgs/' + self.gsoc.key().name()
self.url3 = '/program/accepted_orgs/' + self.gsoc.key().name()
def assertAcceptedOrgsPageTemplatesUsed(self, response):
"""Asserts that all the required templates to render the page were used.
"""
self.assertGSoCTemplatesUsed(response)
self.assertTemplateUsed(response, 'v2/modules/gsoc/accepted_orgs/base.html')
self.assertTemplateUsed(response,
'v2/modules/gsoc/accepted_orgs/_project_list.html')
self.assertTemplateUsed(response, 'v2/soc/_program_select.html')
self.assertTemplateUsed(response,
'v2/modules/gsoc/accepted_orgs/_project_list.html')
self.assertTemplateUsed(response, 'v2/soc/list/lists.html')
self.assertTemplateUsed(response, 'v2/soc/list/list.html')
def testAcceptedOrgsAreDisplayedOnlyAfterTheyAreAnnounced(self):
"""Tests that the list of accepted organizations can be accessed only after
the organizations have been announced.
"""
self.timeline.orgSignup()
response = self.get(self.url3)
self.assertResponseForbidden(response)
response = self.get(self.url2)
self.assertResponseForbidden(response)
response = self.get(self.url1)
self.assertResponseForbidden(response)
def testAcceptedOrgsAreDisplayedAfterOrganizationsHaveBeenAnnounced(self):
"""Tests that the list of the organizations can not be accessed before
organizations have been announced.
"""
org_properties = {'scope': self.gsoc, 'status': 'active'}
seeder_logic.seed(GSoCOrganization, org_properties)
seeder_logic.seed(GSoCOrganization, org_properties)
self.timeline.orgsAnnounced()
response = self.get(self.url1)
self.assertResponseOK(response)
self.assertAcceptedOrgsPageTemplatesUsed(response)
list_data = self.getListData(self.url1, 0)
#Third organization is self.gsoc
self.assertEqual(len(list_data), 3)
response = self.get(self.url2)
self.assertResponseOK(response)
self.assertAcceptedOrgsPageTemplatesUsed(response)
list_data = self.getListData(self.url2, 0)
self.assertEqual(len(list_data), 3)
response = self.get(self.url3)
self.assertResponseOK(response)
self.assertAcceptedOrgsPageTemplatesUsed(response)
list_data = self.getListData(self.url3, 0)
self.assertEqual(len(list_data), 3)
| [
"[email protected]"
] | |
89fda3fd3aa06a78e69f6ff23728534a1850dea0 | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /nb836onw9bek4FPDt_4.py | 00c57b5b188d38dbf5b5076fa134b394a85da9e9 | [] | no_license | daniel-reich/turbo-robot | feda6c0523bb83ab8954b6d06302bfec5b16ebdf | a7a25c63097674c0a81675eed7e6b763785f1c41 | refs/heads/main | 2023-03-26T01:55:14.210264 | 2021-03-23T16:08:01 | 2021-03-23T16:08:01 | 350,773,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 765 | py | """
Given a sentence, return the number of words which have the **same first and
last letter**.
### Examples
count_same_ends("Pop! goes the balloon") ➞ 1
count_same_ends("And the crowd goes wild!") ➞ 0
count_same_ends("No I am not in a gang.") ➞ 1
### Notes
* Don't count single character words (such as "I" and "A" in example #3).
* The function should not be case sensitive, meaning a capital "P" should match with a lowercase one.
* Mind the punctuation!
* Bonus points indeed for using regex!
"""
def count_same_ends(txt):
count = 0
a = "".join([i.lower() for i in txt if i.isalpha() or i.isspace()]).split()
for i in a:
if len(i) > 1 and i[0] == i[-1]:
count += 1
return count
| [
"[email protected]"
] | |
5003a32bcda2bbd12438f4b9346f880068dfb407 | bc108434d5f485a5ca593942b0fbe2f4d044ebda | /pp/grpc/helloworld_protobuf.py | f7a1dedccb7a472def9fed97b93e26e7b8db1fb7 | [] | no_license | js-ts/AI | 746a34493a772fb88aee296f463122b68f3b299d | 353e7abfa7b02b45d2b7fec096b58e07651eb71d | refs/heads/master | 2023-05-29T16:19:03.463999 | 2021-06-22T05:49:44 | 2021-06-22T05:49:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 921 | py | import numpy as np
import base64
import json
import helloworld_pb2
data = np.random.rand(2, 2)
tmp = helloworld_pb2.ModelRequest()
tmp.a = 1
tmp.b = 2
tmp.data = base64.b64encode(data)
print(str(tmp))
tmp1 = helloworld_pb2.ModelRequest()
tmp1.ParseFromString(tmp.SerializeToString())
print('tmp1', str(tmp1))
tmp2 = helloworld_pb2.ModelRequest(data=base64.b64encode(data), a=2, b=2)
print('tmp2', str(tmp2))
# tmp3 = {'a': 1, 'b': 2, 'data': 'data'}
# print(json.dumps(tmp3))
data = helloworld_pb2.DataExample()
Blob = helloworld_pb2.DataExample.Blob
data.data = base64.b64encode(np.random.rand(1,2))
data.c = 10
data.d = 10
blob1 = data.blobs.add()
# blob1 = Blob(info='123', data=123) # wrong
blob1.info = str(123)
blob1.data = 123
data.blobs.append(Blob(info='234', data=234))
data.blobs.extend([Blob(info=str(i), data=i) for i in range(5)])
print(str(data)) | [
"[email protected]"
] | |
bdb2f40d0e4ed3f865fd7791907e585cf87f8f5a | 7d096568677660790479d87c22b47aae838ef96b | /stubs-legacy/System/Windows/Controls/Primitives_parts/StatusBarItem.py | b752a6eb9a82136cb4262f6c7ca0784f7645d7de | [
"MIT"
] | permissive | NISystemsEngineering/rfmx-pythonnet | 30adbdd5660b0d755957f35b68a4c2f60065800c | cd4f90a88a37ed043df880972cb55dfe18883bb7 | refs/heads/master | 2023-02-04T00:39:41.107043 | 2023-02-01T21:58:50 | 2023-02-01T21:58:50 | 191,603,578 | 7 | 5 | MIT | 2023-02-01T21:58:52 | 2019-06-12T16:02:32 | Python | UTF-8 | Python | false | false | 60,382 | py | class StatusBarItem(ContentControl,IResource,IAnimatable,IInputElement,IFrameworkInputElement,ISupportInitialize,IHaveResources,IQueryAmbient,IAddChild):
"""
Represents an item of a System.Windows.Controls.Primitives.StatusBar control.
StatusBarItem()
"""
def AddChild(self,*args):
"""
AddChild(self: ContentControl,value: object)
Adds a specified object as the child of a System.Windows.Controls.ContentControl.
value: The object to add.
"""
pass
def AddLogicalChild(self,*args):
"""
AddLogicalChild(self: FrameworkElement,child: object)
Adds the provided object to the logical tree of this element.
child: Child element to be added.
"""
pass
def AddText(self,*args):
"""
AddText(self: ContentControl,text: str)
Adds a specified text string to a System.Windows.Controls.ContentControl.
text: The string to add.
"""
pass
def AddVisualChild(self,*args):
"""
AddVisualChild(self: Visual,child: Visual)
Defines the parent-child relationship between two visuals.
child: The child visual object to add to parent visual.
"""
pass
def ArrangeCore(self,*args):
"""
ArrangeCore(self: FrameworkElement,finalRect: Rect)
Implements System.Windows.UIElement.ArrangeCore(System.Windows.Rect) (defined as virtual in
System.Windows.UIElement) and seals the implementation.
finalRect: The final area within the parent that this element should use to arrange itself and its children.
"""
pass
def ArrangeOverride(self,*args):
"""
ArrangeOverride(self: Control,arrangeBounds: Size) -> Size
Called to arrange and size the content of a System.Windows.Controls.Control object.
arrangeBounds: The computed size that is used to arrange the content.
Returns: The size of the control.
"""
pass
def GetLayoutClip(self,*args):
"""
GetLayoutClip(self: FrameworkElement,layoutSlotSize: Size) -> Geometry
Returns a geometry for a clipping mask. The mask applies if the layout system attempts to
arrange an element that is larger than the available display space.
layoutSlotSize: The size of the part of the element that does visual presentation.
Returns: The clipping geometry.
"""
pass
def GetTemplateChild(self,*args):
"""
GetTemplateChild(self: FrameworkElement,childName: str) -> DependencyObject
Returns the named element in the visual tree of an instantiated
System.Windows.Controls.ControlTemplate.
childName: Name of the child to find.
Returns: The requested element. May be null if no element of the requested name exists.
"""
pass
def GetUIParentCore(self,*args):
"""
GetUIParentCore(self: FrameworkElement) -> DependencyObject
Returns an alternative logical parent for this element if there is no visual parent.
Returns: Returns something other than null whenever a WPF framework-level implementation of this method
has a non-visual parent connection.
"""
pass
def GetVisualChild(self,*args):
"""
GetVisualChild(self: FrameworkElement,index: int) -> Visual
Overrides System.Windows.Media.Visual.GetVisualChild(System.Int32),and returns a child at the
specified index from a collection of child elements.
index: The zero-based index of the requested child element in the collection.
Returns: The requested child element. This should not return null; if the provided index is out of range,
an exception is thrown.
"""
pass
def HitTestCore(self,*args):
"""
HitTestCore(self: UIElement,hitTestParameters: GeometryHitTestParameters) -> GeometryHitTestResult
Implements
System.Windows.Media.Visual.HitTestCore(System.Windows.Media.GeometryHitTestParameters) to
supply base element hit testing behavior (returning System.Windows.Media.GeometryHitTestResult).
hitTestParameters: Describes the hit test to perform,including the initial hit point.
Returns: Results of the test,including the evaluated geometry.
HitTestCore(self: UIElement,hitTestParameters: PointHitTestParameters) -> HitTestResult
Implements System.Windows.Media.Visual.HitTestCore(System.Windows.Media.PointHitTestParameters)
to supply base element hit testing behavior (returning System.Windows.Media.HitTestResult).
hitTestParameters: Describes the hit test to perform,including the initial hit point.
Returns: Results of the test,including the evaluated point.
"""
pass
def MeasureCore(self,*args):
"""
MeasureCore(self: FrameworkElement,availableSize: Size) -> Size
Implements basic measure-pass layout system behavior for System.Windows.FrameworkElement.
availableSize: The available size that the parent element can give to the child elements.
Returns: The desired size of this element in layout.
"""
pass
def MeasureOverride(self,*args):
"""
MeasureOverride(self: Control,constraint: Size) -> Size
Called to remeasure a control.
constraint: The maximum size that the method can return.
Returns: The size of the control,up to the maximum specified by constraint.
"""
pass
def OnAccessKey(self,*args):
"""
OnAccessKey(self: UIElement,e: AccessKeyEventArgs)
Provides class handling for when an access key that is meaningful for this element is invoked.
e: The event data to the access key event. The event data reports which key was invoked,and
indicate whether the System.Windows.Input.AccessKeyManager object that controls the sending of
these events also sent this access key invocation to other elements.
"""
pass
def OnChildDesiredSizeChanged(self,*args):
"""
OnChildDesiredSizeChanged(self: UIElement,child: UIElement)
Supports layout behavior when a child element is resized.
child: The child element that is being resized.
"""
pass
def OnContentChanged(self,*args):
"""
OnContentChanged(self: ContentControl,oldContent: object,newContent: object)
Called when the System.Windows.Controls.ContentControl.Content property changes.
oldContent: The old value of the System.Windows.Controls.ContentControl.Content property.
newContent: The new value of the System.Windows.Controls.ContentControl.Content property.
"""
pass
def OnContentStringFormatChanged(self,*args):
"""
OnContentStringFormatChanged(self: ContentControl,oldContentStringFormat: str,newContentStringFormat: str)
Occurs when the System.Windows.Controls.ContentControl.ContentStringFormat property changes.
oldContentStringFormat: The old value of System.Windows.Controls.ContentControl.ContentStringFormat.
newContentStringFormat: The new value of System.Windows.Controls.ContentControl.ContentStringFormat.
"""
pass
def OnContentTemplateChanged(self,*args):
"""
OnContentTemplateChanged(self: ContentControl,oldContentTemplate: DataTemplate,newContentTemplate: DataTemplate)
Called when the System.Windows.Controls.ContentControl.ContentTemplate property changes.
oldContentTemplate: The old value of the System.Windows.Controls.ContentControl.ContentTemplate property.
newContentTemplate: The new value of the System.Windows.Controls.ContentControl.ContentTemplate property.
"""
pass
def OnContentTemplateSelectorChanged(self,*args):
"""
OnContentTemplateSelectorChanged(self: ContentControl,oldContentTemplateSelector: DataTemplateSelector,newContentTemplateSelector: DataTemplateSelector)
Called when the System.Windows.Controls.ContentControl.ContentTemplateSelector property changes.
oldContentTemplateSelector: The old value of the System.Windows.Controls.ContentControl.ContentTemplateSelector property.
newContentTemplateSelector: The new value of the System.Windows.Controls.ContentControl.ContentTemplateSelector property.
"""
pass
def OnContextMenuClosing(self,*args):
"""
OnContextMenuClosing(self: FrameworkElement,e: ContextMenuEventArgs)
Invoked whenever an unhandled System.Windows.FrameworkElement.ContextMenuClosing routed event
reaches this class in its route. Implement this method to add class handling for this event.
e: Provides data about the event.
"""
pass
def OnContextMenuOpening(self,*args):
"""
OnContextMenuOpening(self: FrameworkElement,e: ContextMenuEventArgs)
Invoked whenever an unhandled System.Windows.FrameworkElement.ContextMenuOpening routed event
reaches this class in its route. Implement this method to add class handling for this event.
e: The System.Windows.RoutedEventArgs that contains the event data.
"""
pass
def OnCreateAutomationPeer(self,*args):
"""
OnCreateAutomationPeer(self: StatusBarItem) -> AutomationPeer
Specifies an System.Windows.Automation.Peers.AutomationPeer for the
System.Windows.Controls.Primitives.StatusBarItem.
Returns: A System.Windows.Automation.Peers.StatusBarItemAutomationPeer for this
System.Windows.Controls.Primitives.StatusBarItem.
"""
pass
def OnDpiChanged(self,*args):
""" OnDpiChanged(self: Visual,oldDpi: DpiScale,newDpi: DpiScale) """
pass
def OnDragEnter(self,*args):
"""
OnDragEnter(self: UIElement,e: DragEventArgs)
Invoked when an unhandled System.Windows.DragDrop.DragEnter�attached event reaches an element in
its route that is derived from this class. Implement this method to add class handling for this
event.
e: The System.Windows.DragEventArgs that contains the event data.
"""
pass
def OnDragLeave(self,*args):
"""
OnDragLeave(self: UIElement,e: DragEventArgs)
Invoked when an unhandled System.Windows.DragDrop.DragLeave�attached event reaches an element in
its route that is derived from this class. Implement this method to add class handling for this
event.
e: The System.Windows.DragEventArgs that contains the event data.
"""
pass
def OnDragOver(self,*args):
"""
OnDragOver(self: UIElement,e: DragEventArgs)
Invoked when an unhandled System.Windows.DragDrop.DragOver�attached event reaches an element in
its route that is derived from this class. Implement this method to add class handling for this
event.
e: The System.Windows.DragEventArgs that contains the event data.
"""
pass
def OnDrop(self,*args):
"""
OnDrop(self: UIElement,e: DragEventArgs)
Invoked when an unhandled System.Windows.DragDrop.DragEnter�attached event reaches an element in
its route that is derived from this class. Implement this method to add class handling for this
event.
e: The System.Windows.DragEventArgs that contains the event data.
"""
pass
def OnGiveFeedback(self,*args):
"""
OnGiveFeedback(self: UIElement,e: GiveFeedbackEventArgs)
Invoked when an unhandled System.Windows.DragDrop.GiveFeedback�attached event reaches an element
in its route that is derived from this class. Implement this method to add class handling for
this event.
e: The System.Windows.GiveFeedbackEventArgs that contains the event data.
"""
pass
def OnGotFocus(self,*args):
"""
OnGotFocus(self: FrameworkElement,e: RoutedEventArgs)
Invoked whenever an unhandled System.Windows.UIElement.GotFocus event reaches this element in
its route.
e: The System.Windows.RoutedEventArgs that contains the event data.
"""
pass
def OnGotKeyboardFocus(self,*args):
"""
OnGotKeyboardFocus(self: UIElement,e: KeyboardFocusChangedEventArgs)
Invoked when an unhandled System.Windows.Input.Keyboard.GotKeyboardFocus�attached event reaches
an element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.KeyboardFocusChangedEventArgs that contains the event data.
"""
pass
def OnGotMouseCapture(self,*args):
"""
OnGotMouseCapture(self: UIElement,e: MouseEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.GotMouseCapture�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.MouseEventArgs that contains the event data.
"""
pass
def OnGotStylusCapture(self,*args):
"""
OnGotStylusCapture(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.GotStylusCapture�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnGotTouchCapture(self,*args):
"""
OnGotTouchCapture(self: UIElement,e: TouchEventArgs)
Provides class handling for the System.Windows.UIElement.GotTouchCapture routed event that
occurs when a touch is captured to this element.
e: A System.Windows.Input.TouchEventArgs that contains the event data.
"""
pass
def OnInitialized(self,*args):
"""
OnInitialized(self: FrameworkElement,e: EventArgs)
Raises the System.Windows.FrameworkElement.Initialized event. This method is invoked whenever
System.Windows.FrameworkElement.IsInitialized is set to true internally.
e: The System.Windows.RoutedEventArgs that contains the event data.
"""
pass
def OnIsKeyboardFocusedChanged(self,*args):
"""
OnIsKeyboardFocusedChanged(self: UIElement,e: DependencyPropertyChangedEventArgs)
Invoked when an unhandled System.Windows.UIElement.IsKeyboardFocusedChanged event is raised on
this element. Implement this method to add class handling for this event.
e: The System.Windows.DependencyPropertyChangedEventArgs that contains the event data.
"""
pass
def OnIsKeyboardFocusWithinChanged(self,*args):
"""
OnIsKeyboardFocusWithinChanged(self: UIElement,e: DependencyPropertyChangedEventArgs)
Invoked just before the System.Windows.UIElement.IsKeyboardFocusWithinChanged event is raised by
this element. Implement this method to add class handling for this event.
e: A System.Windows.DependencyPropertyChangedEventArgs that contains the event data.
"""
pass
def OnIsMouseCapturedChanged(self,*args):
"""
OnIsMouseCapturedChanged(self: UIElement,e: DependencyPropertyChangedEventArgs)
Invoked when an unhandled System.Windows.UIElement.IsMouseCapturedChanged event is raised on
this element. Implement this method to add class handling for this event.
e: The System.Windows.DependencyPropertyChangedEventArgs that contains the event data.
"""
pass
def OnIsMouseCaptureWithinChanged(self,*args):
"""
OnIsMouseCaptureWithinChanged(self: UIElement,e: DependencyPropertyChangedEventArgs)
Invoked when an unhandled System.Windows.UIElement.IsMouseCaptureWithinChanged event is raised
on this element. Implement this method to add class handling for this event.
e: A System.Windows.DependencyPropertyChangedEventArgs that contains the event data.
"""
pass
def OnIsMouseDirectlyOverChanged(self,*args):
"""
OnIsMouseDirectlyOverChanged(self: UIElement,e: DependencyPropertyChangedEventArgs)
Invoked when an unhandled System.Windows.UIElement.IsMouseDirectlyOverChanged event is raised on
this element. Implement this method to add class handling for this event.
e: The System.Windows.DependencyPropertyChangedEventArgs that contains the event data.
"""
pass
def OnIsStylusCapturedChanged(self,*args):
"""
OnIsStylusCapturedChanged(self: UIElement,e: DependencyPropertyChangedEventArgs)
Invoked when an unhandled System.Windows.UIElement.IsStylusCapturedChanged event is raised on
this element. Implement this method to add class handling for this event.
e: A System.Windows.DependencyPropertyChangedEventArgs that contains the event data.
"""
pass
def OnIsStylusCaptureWithinChanged(self,*args):
"""
OnIsStylusCaptureWithinChanged(self: UIElement,e: DependencyPropertyChangedEventArgs)
Invoked when an unhandled System.Windows.UIElement.IsStylusCaptureWithinChanged event is raised
on this element. Implement this method to add class handling for this event.
e: The System.Windows.DependencyPropertyChangedEventArgs that contains the event data.
"""
pass
def OnIsStylusDirectlyOverChanged(self,*args):
"""
OnIsStylusDirectlyOverChanged(self: UIElement,e: DependencyPropertyChangedEventArgs)
Invoked when an unhandled System.Windows.UIElement.IsStylusDirectlyOverChanged event is raised
on this element. Implement this method to add class handling for this event.
e: The System.Windows.DependencyPropertyChangedEventArgs that contains the event data.
"""
pass
def OnKeyDown(self,*args):
"""
OnKeyDown(self: UIElement,e: KeyEventArgs)
Invoked when an unhandled System.Windows.Input.Keyboard.KeyDown�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.KeyEventArgs that contains the event data.
"""
pass
def OnKeyUp(self,*args):
"""
OnKeyUp(self: UIElement,e: KeyEventArgs)
Invoked when an unhandled System.Windows.Input.Keyboard.KeyUp�attached event reaches an element
in its route that is derived from this class. Implement this method to add class handling for
this event.
e: The System.Windows.Input.KeyEventArgs that contains the event data.
"""
pass
def OnLostFocus(self,*args):
"""
OnLostFocus(self: UIElement,e: RoutedEventArgs)
Raises the System.Windows.UIElement.LostFocus�routed event by using the event data that is
provided.
e: A System.Windows.RoutedEventArgs that contains event data. This event data must contain the
identifier for the System.Windows.UIElement.LostFocus event.
"""
pass
def OnLostKeyboardFocus(self,*args):
"""
OnLostKeyboardFocus(self: UIElement,e: KeyboardFocusChangedEventArgs)
Invoked when an unhandled System.Windows.Input.Keyboard.LostKeyboardFocus�attached event reaches
an element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.KeyboardFocusChangedEventArgs that contains event data.
"""
pass
def OnLostMouseCapture(self,*args):
"""
OnLostMouseCapture(self: UIElement,e: MouseEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.LostMouseCapture�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.MouseEventArgs that contains event data.
"""
pass
def OnLostStylusCapture(self,*args):
"""
OnLostStylusCapture(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.LostStylusCapture�attached event reaches
an element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains event data.
"""
pass
def OnLostTouchCapture(self,*args):
"""
OnLostTouchCapture(self: UIElement,e: TouchEventArgs)
Provides class handling for the System.Windows.UIElement.LostTouchCapture routed event that
occurs when this element loses a touch capture.
e: A System.Windows.Input.TouchEventArgs that contains the event data.
"""
pass
def OnManipulationBoundaryFeedback(self,*args):
"""
OnManipulationBoundaryFeedback(self: UIElement,e: ManipulationBoundaryFeedbackEventArgs)
Called when the System.Windows.UIElement.ManipulationBoundaryFeedback event occurs.
e: The data for the event.
"""
pass
def OnManipulationCompleted(self,*args):
"""
OnManipulationCompleted(self: UIElement,e: ManipulationCompletedEventArgs)
Called when the System.Windows.UIElement.ManipulationCompleted event occurs.
e: The data for the event.
"""
pass
def OnManipulationDelta(self,*args):
"""
OnManipulationDelta(self: UIElement,e: ManipulationDeltaEventArgs)
Called when the System.Windows.UIElement.ManipulationDelta event occurs.
e: The data for the event.
"""
pass
def OnManipulationInertiaStarting(self,*args):
"""
OnManipulationInertiaStarting(self: UIElement,e: ManipulationInertiaStartingEventArgs)
Called when the System.Windows.UIElement.ManipulationInertiaStarting event occurs.
e: The data for the event.
"""
pass
def OnManipulationStarted(self,*args):
"""
OnManipulationStarted(self: UIElement,e: ManipulationStartedEventArgs)
Called when the System.Windows.UIElement.ManipulationStarted event occurs.
e: The data for the event.
"""
pass
def OnManipulationStarting(self,*args):
"""
OnManipulationStarting(self: UIElement,e: ManipulationStartingEventArgs)
Provides class handling for the System.Windows.UIElement.ManipulationStarting routed event that
occurs when the manipulation processor is first created.
e: A System.Windows.Input.ManipulationStartingEventArgs that contains the event data.
"""
pass
def OnMouseDoubleClick(self,*args):
"""
OnMouseDoubleClick(self: Control,e: MouseButtonEventArgs)
Raises the System.Windows.Controls.Control.MouseDoubleClick routed event.
e: The event data.
"""
pass
def OnMouseDown(self,*args):
"""
OnMouseDown(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.MouseDown�attached event reaches an element
in its route that is derived from this class. Implement this method to add class handling for
this event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. This event data
reports details about the mouse button that was pressed and the handled state.
"""
pass
def OnMouseEnter(self,*args):
"""
OnMouseEnter(self: UIElement,e: MouseEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.MouseEnter�attached event is raised on this
element. Implement this method to add class handling for this event.
e: The System.Windows.Input.MouseEventArgs that contains the event data.
"""
pass
def OnMouseLeave(self,*args):
"""
OnMouseLeave(self: UIElement,e: MouseEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.MouseLeave�attached event is raised on this
element. Implement this method to add class handling for this event.
e: The System.Windows.Input.MouseEventArgs that contains the event data.
"""
pass
def OnMouseLeftButtonDown(self,*args):
"""
OnMouseLeftButtonDown(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.UIElement.MouseLeftButtonDown�routed event is raised on
this element. Implement this method to add class handling for this event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. The event data
reports that the left mouse button was pressed.
"""
pass
def OnMouseLeftButtonUp(self,*args):
"""
OnMouseLeftButtonUp(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.UIElement.MouseLeftButtonUp�routed event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. The event data
reports that the left mouse button was released.
"""
pass
def OnMouseMove(self,*args):
"""
OnMouseMove(self: UIElement,e: MouseEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.MouseMove�attached event reaches an element
in its route that is derived from this class. Implement this method to add class handling for
this event.
e: The System.Windows.Input.MouseEventArgs that contains the event data.
"""
pass
def OnMouseRightButtonDown(self,*args):
"""
OnMouseRightButtonDown(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.UIElement.MouseRightButtonDown�routed event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. The event data
reports that the right mouse button was pressed.
"""
pass
def OnMouseRightButtonUp(self,*args):
"""
OnMouseRightButtonUp(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.UIElement.MouseRightButtonUp�routed event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. The event data
reports that the right mouse button was released.
"""
pass
def OnMouseUp(self,*args):
"""
OnMouseUp(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.MouseUp�routed event reaches an element in
its route that is derived from this class. Implement this method to add class handling for this
event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. The event data
reports that the mouse button was released.
"""
pass
def OnMouseWheel(self,*args):
"""
OnMouseWheel(self: UIElement,e: MouseWheelEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.MouseWheel�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.MouseWheelEventArgs that contains the event data.
"""
pass
def OnPreviewDragEnter(self,*args):
"""
OnPreviewDragEnter(self: UIElement,e: DragEventArgs)
Invoked when an unhandled System.Windows.DragDrop.PreviewDragEnter�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.DragEventArgs that contains the event data.
"""
pass
def OnPreviewDragLeave(self,*args):
"""
OnPreviewDragLeave(self: UIElement,e: DragEventArgs)
Invoked when an unhandled System.Windows.DragDrop.PreviewDragLeave�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.DragEventArgs that contains the event data.
"""
pass
def OnPreviewDragOver(self,*args):
"""
OnPreviewDragOver(self: UIElement,e: DragEventArgs)
Invoked when an unhandled System.Windows.DragDrop.PreviewDragOver�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.DragEventArgs that contains the event data.
"""
pass
def OnPreviewDrop(self,*args):
"""
OnPreviewDrop(self: UIElement,e: DragEventArgs)
Invoked when an unhandled System.Windows.DragDrop.PreviewDrop�attached event reaches an element
in its route that is derived from this class. Implement this method to add class handling for
this event.
e: The System.Windows.DragEventArgs that contains the event data.
"""
pass
def OnPreviewGiveFeedback(self,*args):
"""
OnPreviewGiveFeedback(self: UIElement,e: GiveFeedbackEventArgs)
Invoked when an unhandled System.Windows.DragDrop.PreviewGiveFeedback�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.GiveFeedbackEventArgs that contains the event data.
"""
pass
def OnPreviewGotKeyboardFocus(self,*args):
"""
OnPreviewGotKeyboardFocus(self: UIElement,e: KeyboardFocusChangedEventArgs)
Invoked when an unhandled System.Windows.Input.Keyboard.PreviewGotKeyboardFocus�attached event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.KeyboardFocusChangedEventArgs that contains the event data.
"""
pass
def OnPreviewKeyDown(self,*args):
"""
OnPreviewKeyDown(self: UIElement,e: KeyEventArgs)
Invoked when an unhandled System.Windows.Input.Keyboard.PreviewKeyDown�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.KeyEventArgs that contains the event data.
"""
pass
def OnPreviewKeyUp(self,*args):
"""
OnPreviewKeyUp(self: UIElement,e: KeyEventArgs)
Invoked when an unhandled System.Windows.Input.Keyboard.PreviewKeyUp�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.KeyEventArgs that contains the event data.
"""
pass
def OnPreviewLostKeyboardFocus(self,*args):
"""
OnPreviewLostKeyboardFocus(self: UIElement,e: KeyboardFocusChangedEventArgs)
Invoked when an unhandled System.Windows.Input.Keyboard.PreviewKeyDown�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.KeyboardFocusChangedEventArgs that contains the event data.
"""
pass
def OnPreviewMouseDoubleClick(self,*args):
"""
OnPreviewMouseDoubleClick(self: Control,e: MouseButtonEventArgs)
Raises the System.Windows.Controls.Control.PreviewMouseDoubleClick routed event.
e: The event data.
"""
pass
def OnPreviewMouseDown(self,*args):
"""
OnPreviewMouseDown(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.PreviewMouseDown attached�routed event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. The event data
reports that one or more mouse buttons were pressed.
"""
pass
def OnPreviewMouseLeftButtonDown(self,*args):
"""
OnPreviewMouseLeftButtonDown(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.UIElement.PreviewMouseLeftButtonDown�routed event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. The event data
reports that the left mouse button was pressed.
"""
pass
def OnPreviewMouseLeftButtonUp(self,*args):
"""
OnPreviewMouseLeftButtonUp(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.UIElement.PreviewMouseLeftButtonUp�routed event reaches
an element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. The event data
reports that the left mouse button was released.
"""
pass
def OnPreviewMouseMove(self,*args):
"""
OnPreviewMouseMove(self: UIElement,e: MouseEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.PreviewMouseMove�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.MouseEventArgs that contains the event data.
"""
pass
def OnPreviewMouseRightButtonDown(self,*args):
"""
OnPreviewMouseRightButtonDown(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.UIElement.PreviewMouseRightButtonDown�routed event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. The event data
reports that the right mouse button was pressed.
"""
pass
def OnPreviewMouseRightButtonUp(self,*args):
"""
OnPreviewMouseRightButtonUp(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.UIElement.PreviewMouseRightButtonUp�routed event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. The event data
reports that the right mouse button was released.
"""
pass
def OnPreviewMouseUp(self,*args):
"""
OnPreviewMouseUp(self: UIElement,e: MouseButtonEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.PreviewMouseUp�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.MouseButtonEventArgs that contains the event data. The event data
reports that one or more mouse buttons were released.
"""
pass
def OnPreviewMouseWheel(self,*args):
"""
OnPreviewMouseWheel(self: UIElement,e: MouseWheelEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.PreviewMouseWheel�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.MouseWheelEventArgs that contains the event data.
"""
pass
def OnPreviewQueryContinueDrag(self,*args):
"""
OnPreviewQueryContinueDrag(self: UIElement,e: QueryContinueDragEventArgs)
Invoked when an unhandled System.Windows.DragDrop.PreviewQueryContinueDrag�attached event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.QueryContinueDragEventArgs that contains the event data.
"""
pass
def OnPreviewStylusButtonDown(self,*args):
"""
OnPreviewStylusButtonDown(self: UIElement,e: StylusButtonEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.PreviewStylusButtonDown�attached event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.StylusButtonEventArgs that contains the event data.
"""
pass
def OnPreviewStylusButtonUp(self,*args):
"""
OnPreviewStylusButtonUp(self: UIElement,e: StylusButtonEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.PreviewStylusButtonUp�attached event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.StylusButtonEventArgs that contains the event data.
"""
pass
def OnPreviewStylusDown(self,*args):
"""
OnPreviewStylusDown(self: UIElement,e: StylusDownEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.PreviewStylusDown�attached event reaches
an element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusDownEventArgs that contains the event data.
"""
pass
def OnPreviewStylusInAirMove(self,*args):
"""
OnPreviewStylusInAirMove(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.PreviewStylusInAirMove�attached event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnPreviewStylusInRange(self,*args):
"""
OnPreviewStylusInRange(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.PreviewStylusInRange�attached event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnPreviewStylusMove(self,*args):
"""
OnPreviewStylusMove(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.PreviewStylusMove�attached event reaches
an element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnPreviewStylusOutOfRange(self,*args):
"""
OnPreviewStylusOutOfRange(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.PreviewStylusOutOfRange�attached event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnPreviewStylusSystemGesture(self,*args):
"""
OnPreviewStylusSystemGesture(self: UIElement,e: StylusSystemGestureEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.PreviewStylusSystemGesture�attached event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.StylusSystemGestureEventArgs that contains the event data.
"""
pass
def OnPreviewStylusUp(self,*args):
"""
OnPreviewStylusUp(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.PreviewStylusUp�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnPreviewTextInput(self,*args):
"""
OnPreviewTextInput(self: UIElement,e: TextCompositionEventArgs)
Invoked when an unhandled System.Windows.Input.TextCompositionManager.PreviewTextInput�attached
event reaches an element in its route that is derived from this class. Implement this method to
add class handling for this event.
e: The System.Windows.Input.TextCompositionEventArgs that contains the event data.
"""
pass
def OnPreviewTouchDown(self,*args):
"""
OnPreviewTouchDown(self: UIElement,e: TouchEventArgs)
Provides class handling for the System.Windows.UIElement.PreviewTouchDown routed event that
occurs when a touch presses this element.
e: A System.Windows.Input.TouchEventArgs that contains the event data.
"""
pass
def OnPreviewTouchMove(self,*args):
"""
OnPreviewTouchMove(self: UIElement,e: TouchEventArgs)
Provides class handling for the System.Windows.UIElement.PreviewTouchMove routed event that
occurs when a touch moves while inside this element.
e: A System.Windows.Input.TouchEventArgs that contains the event data.
"""
pass
def OnPreviewTouchUp(self,*args):
"""
OnPreviewTouchUp(self: UIElement,e: TouchEventArgs)
Provides class handling for the System.Windows.UIElement.PreviewTouchUp routed event that occurs
when a touch is released inside this element.
e: A System.Windows.Input.TouchEventArgs that contains the event data.
"""
pass
def OnPropertyChanged(self,*args):
"""
OnPropertyChanged(self: FrameworkElement,e: DependencyPropertyChangedEventArgs)
Invoked whenever the effective value of any dependency property on this
System.Windows.FrameworkElement has been updated. The specific dependency property that changed
is reported in the arguments parameter. Overrides
System.Windows.DependencyObject.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventAr
gs).
e: The event data that describes the property that changed,as well as old and new values.
"""
pass
def OnQueryContinueDrag(self,*args):
"""
OnQueryContinueDrag(self: UIElement,e: QueryContinueDragEventArgs)
Invoked when an unhandled System.Windows.DragDrop.QueryContinueDrag�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.QueryContinueDragEventArgs that contains the event data.
"""
pass
def OnQueryCursor(self,*args):
"""
OnQueryCursor(self: UIElement,e: QueryCursorEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.QueryCursor�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.QueryCursorEventArgs that contains the event data.
"""
pass
def OnRender(self,*args):
"""
OnRender(self: UIElement,drawingContext: DrawingContext)
When overridden in a derived class,participates in rendering operations that are directed by
the layout system. The rendering instructions for this element are not used directly when this
method is invoked,and are instead preserved for later asynchronous use by layout and drawing.
drawingContext: The drawing instructions for a specific element. This context is provided to the layout system.
"""
pass
def OnRenderSizeChanged(self,*args):
"""
OnRenderSizeChanged(self: FrameworkElement,sizeInfo: SizeChangedInfo)
Raises the System.Windows.FrameworkElement.SizeChanged event,using the specified information as
part of the eventual event data.
sizeInfo: Details of the old and new size involved in the change.
"""
pass
def OnStyleChanged(self,*args):
"""
OnStyleChanged(self: FrameworkElement,oldStyle: Style,newStyle: Style)
Invoked when the style in use on this element changes,which will invalidate the layout.
oldStyle: The old style.
newStyle: The new style.
"""
pass
def OnStylusButtonDown(self,*args):
"""
OnStylusButtonDown(self: UIElement,e: StylusButtonEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusButtonDown�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusButtonEventArgs that contains the event data.
"""
pass
def OnStylusButtonUp(self,*args):
"""
OnStylusButtonUp(self: UIElement,e: StylusButtonEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusButtonUp�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusButtonEventArgs that contains the event data.
"""
pass
def OnStylusDown(self,*args):
"""
OnStylusDown(self: UIElement,e: StylusDownEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusDown�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusDownEventArgs that contains the event data.
"""
pass
def OnStylusEnter(self,*args):
"""
OnStylusEnter(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusEnter�attached event is raised by
this element. Implement this method to add class handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnStylusInAirMove(self,*args):
"""
OnStylusInAirMove(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusInAirMove�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnStylusInRange(self,*args):
"""
OnStylusInRange(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusInRange�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnStylusLeave(self,*args):
"""
OnStylusLeave(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusLeave�attached event is raised by
this element. Implement this method to add class handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnStylusMove(self,*args):
"""
OnStylusMove(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusMove�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnStylusOutOfRange(self,*args):
"""
OnStylusOutOfRange(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusOutOfRange�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnStylusSystemGesture(self,*args):
"""
OnStylusSystemGesture(self: UIElement,e: StylusSystemGestureEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusSystemGesture�attached event reaches
an element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.StylusSystemGestureEventArgs that contains the event data.
"""
pass
def OnStylusUp(self,*args):
"""
OnStylusUp(self: UIElement,e: StylusEventArgs)
Invoked when an unhandled System.Windows.Input.Stylus.StylusUp�attached event reaches an element
in its route that is derived from this class. Implement this method to add class handling for
this event.
e: The System.Windows.Input.StylusEventArgs that contains the event data.
"""
pass
def OnTemplateChanged(self,*args):
"""
OnTemplateChanged(self: Control,oldTemplate: ControlTemplate,newTemplate: ControlTemplate)
Called whenever the control's template changes.
oldTemplate: The old template.
newTemplate: The new template.
"""
pass
def OnTextInput(self,*args):
"""
OnTextInput(self: UIElement,e: TextCompositionEventArgs)
Invoked when an unhandled System.Windows.Input.TextCompositionManager.TextInput�attached event
reaches an element in its route that is derived from this class. Implement this method to add
class handling for this event.
e: The System.Windows.Input.TextCompositionEventArgs that contains the event data.
"""
pass
def OnToolTipClosing(self,*args):
"""
OnToolTipClosing(self: FrameworkElement,e: ToolTipEventArgs)
Invoked whenever an unhandled System.Windows.FrameworkElement.ToolTipClosing routed event
reaches this class in its route. Implement this method to add class handling for this event.
e: Provides data about the event.
"""
pass
def OnToolTipOpening(self,*args):
"""
OnToolTipOpening(self: FrameworkElement,e: ToolTipEventArgs)
Invoked whenever the System.Windows.FrameworkElement.ToolTipOpening routed event reaches this
class in its route. Implement this method to add class handling for this event.
e: Provides data about the event.
"""
pass
def OnTouchDown(self,*args):
"""
OnTouchDown(self: UIElement,e: TouchEventArgs)
Provides class handling for the System.Windows.UIElement.TouchDown routed event that occurs when
a touch presses inside this element.
e: A System.Windows.Input.TouchEventArgs that contains the event data.
"""
pass
def OnTouchEnter(self,*args):
"""
OnTouchEnter(self: UIElement,e: TouchEventArgs)
Provides class handling for the System.Windows.UIElement.TouchEnter routed event that occurs
when a touch moves from outside to inside the bounds of this element.
e: A System.Windows.Input.TouchEventArgs that contains the event data.
"""
pass
def OnTouchLeave(self,*args):
"""
OnTouchLeave(self: UIElement,e: TouchEventArgs)
Provides class handling for the System.Windows.UIElement.TouchLeave routed event that occurs
when a touch moves from inside to outside the bounds of this System.Windows.UIElement.
e: A System.Windows.Input.TouchEventArgs that contains the event data.
"""
pass
def OnTouchMove(self,*args):
"""
OnTouchMove(self: UIElement,e: TouchEventArgs)
Provides class handling for the System.Windows.UIElement.TouchMove routed event that occurs when
a touch moves while inside this element.
e: A System.Windows.Input.TouchEventArgs that contains the event data.
"""
pass
def OnTouchUp(self,*args):
"""
OnTouchUp(self: UIElement,e: TouchEventArgs)
Provides class handling for the System.Windows.UIElement.TouchUp routed event that occurs when a
touch is released inside this element.
e: A System.Windows.Input.TouchEventArgs that contains the event data.
"""
pass
def OnVisualChildrenChanged(self,*args):
"""
OnVisualChildrenChanged(self: Visual,visualAdded: DependencyObject,visualRemoved: DependencyObject)
Called when the System.Windows.Media.VisualCollection of the visual object is modified.
visualAdded: The System.Windows.Media.Visual that was added to the collection
visualRemoved: The System.Windows.Media.Visual that was removed from the collection
"""
pass
def OnVisualParentChanged(self,*args):
"""
OnVisualParentChanged(self: FrameworkElement,oldParent: DependencyObject)
Invoked when the parent of this element in the visual tree is changed. Overrides
System.Windows.UIElement.OnVisualParentChanged(System.Windows.DependencyObject).
oldParent: The old parent element. May be null to indicate that the element did not have a visual parent
previously.
"""
pass
def ParentLayoutInvalidated(self,*args):
"""
ParentLayoutInvalidated(self: FrameworkElement,child: UIElement)
Supports incremental layout implementations in specialized subclasses of
System.Windows.FrameworkElement.
System.Windows.FrameworkElement.ParentLayoutInvalidated(System.Windows.UIElement) is invoked
when a child element has invalidated a property that is marked in metadata as affecting the
parent's measure or arrange passes during layout.
child: The child element reporting the change.
"""
pass
def RemoveLogicalChild(self,*args):
"""
RemoveLogicalChild(self: FrameworkElement,child: object)
Removes the provided object from this element's logical tree. System.Windows.FrameworkElement
updates the affected logical tree parent pointers to keep in sync with this deletion.
child: The element to remove.
"""
pass
def RemoveVisualChild(self,*args):
"""
RemoveVisualChild(self: Visual,child: Visual)
Removes the parent-child relationship between two visuals.
child: The child visual object to remove from the parent visual.
"""
pass
def ShouldSerializeProperty(self,*args):
"""
ShouldSerializeProperty(self: DependencyObject,dp: DependencyProperty) -> bool
Returns a value that indicates whether serialization processes should serialize the value for
the provided dependency property.
dp: The identifier for the dependency property that should be serialized.
Returns: true if the dependency property that is supplied should be value-serialized; otherwise,false.
"""
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __str__(self,*args):
pass
DefaultStyleKey=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the key to use to reference the style for this control,when theme styles are used or defined.
"""
HandlesScrolling=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value that indicates whether a control supports scrolling.
"""
HasEffectiveKeyboardFocus=property(lambda self: object(),lambda self,v: None,lambda self: None)
InheritanceBehavior=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the scope limits for property value inheritance,resource key lookup,and RelativeSource FindAncestor lookup.
"""
IsEnabledCore=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value that becomes the return value of System.Windows.UIElement.IsEnabled in derived classes.
"""
LogicalChildren=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets an enumerator to the content control's logical child elements.
"""
StylusPlugIns=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a collection of all stylus plug-in (customization) objects associated with this element.
"""
VisualBitmapEffect=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.Effects.BitmapEffect value for the System.Windows.Media.Visual.
"""
VisualBitmapEffectInput=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.Effects.BitmapEffectInput value for the System.Windows.Media.Visual.
"""
VisualBitmapScalingMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.BitmapScalingMode for the System.Windows.Media.Visual.
"""
VisualCacheMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a cached representation of the System.Windows.Media.Visual.
"""
VisualChildrenCount=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the number of visual child elements within this element.
"""
VisualClearTypeHint=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.ClearTypeHint that determines how ClearType is rendered in the System.Windows.Media.Visual.
"""
VisualClip=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the clip region of the System.Windows.Media.Visual as a System.Windows.Media.Geometry value.
"""
VisualEdgeMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the edge mode of the System.Windows.Media.Visual as an System.Windows.Media.EdgeMode value.
"""
VisualEffect=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the bitmap effect to apply to the System.Windows.Media.Visual.
"""
VisualOffset=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the offset value of the visual object.
"""
VisualOpacity=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the opacity of the System.Windows.Media.Visual.
"""
VisualOpacityMask=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.Brush value that represents the opacity mask of the System.Windows.Media.Visual.
"""
VisualParent=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the visual tree parent of the visual object.
"""
VisualScrollableAreaClip=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a clipped scrollable area for the System.Windows.Media.Visual.
"""
VisualTextHintingMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.TextHintingMode of the System.Windows.Media.Visual.
"""
VisualTextRenderingMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.TextRenderingMode of the System.Windows.Media.Visual.
"""
VisualTransform=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the System.Windows.Media.Transform value for the System.Windows.Media.Visual.
"""
VisualXSnappingGuidelines=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the x-coordinate (vertical) guideline collection.
"""
VisualYSnappingGuidelines=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the y-coordinate (horizontal) guideline collection.
"""
| [
"[email protected]"
] | |
1dfe400c08503f5360301196fafbd7c95bf1a7d4 | d5e94042ac2b248b7701117a6ea941bcc862067a | /upvote/gae/modules/bit9_api/api/api.py | ae03d52d4f13cf2e52982357e0e217325cd19a3f | [
"Apache-2.0"
] | permissive | codegrande/upvote | f373105203a0595f76c29e138a18a95dc24a63df | e05d477bb13e470127b109eb8905a66a06eed5ac | refs/heads/master | 2020-03-07T19:40:47.185833 | 2019-06-20T14:35:20 | 2019-06-20T14:35:20 | 127,677,753 | 0 | 0 | null | 2018-04-01T22:49:28 | 2018-04-01T22:49:27 | null | UTF-8 | Python | false | false | 19,026 | py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module for interacting with the Bit9 REST API ORM."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from upvote.gae.modules.bit9_api.api import constants
from upvote.gae.modules.bit9_api.api import context
from upvote.gae.modules.bit9_api.api import exceptions
from upvote.gae.modules.bit9_api.api import model # pylint: disable=unused-import
# Import only the externally relevant names into the modules's namespace.
# pylint: disable=invalid-name
METHOD = constants.METHOD
VERSION = constants.VERSION
BaseContext = context.BaseContext
Context = context.Context
Error = exceptions.Error
NotFoundError = exceptions.NotFoundError
QueryError = exceptions.QueryError
RequestError = exceptions.RequestError
PropertyError = exceptions.PropertyError
# pylint: enable=invalid-name
# NOTE: This API is automatically generated by the build_from_docs.py script.
# Updates can be implemented there and regenerated from the docs.
# pylint: disable=missing-docstring,line-too-long
################################################################################
####################### Generated by build_from_docs.py ########################
################################################################################
class ApprovalRequest(model.Model):
ROUTE = 'approvalRequest'
id = model.Int32Property('id')
file_catalog_id = model.Int32Property('fileCatalogId', expands_to='FileCatalog')
installer_file_catalog_id = model.Int32Property('installerFileCatalogId', expands_to='FileCatalog')
process_file_catalog_id = model.Int32Property('processFileCatalogId', expands_to='FileCatalog')
computer_id = model.Int32Property('computerId', expands_to='Computer')
computer_name = model.StringProperty('computerName')
date_created = model.DateTimeProperty('dateCreated')
created_by = model.StringProperty('createdBy')
created_by_user_id = model.Int32Property('createdByUserId')
date_modified = model.DateTimeProperty('dateModified')
modified_by = model.StringProperty('modifiedBy')
modified_by_user_id = model.Int32Property('modifiedByUserId')
enforcement_level = model.Int32Property('enforcementLevel')
resolution = model.Int32Property('resolution', allow_update=True)
request_type = model.Int32Property('requestType')
requestor_comments = model.StringProperty('requestorComments')
requestor_email = model.StringProperty('requestorEmail', allow_update=True)
priority = model.Int32Property('priority')
resolution_comments = model.StringProperty('resolutionComments', allow_update=True)
status = model.Int32Property('status', allow_update=True)
policy_id = model.Int32Property('policyId', expands_to='Policy')
multiple_blocks = model.BooleanProperty('multipleBlocks')
file_name = model.StringProperty('fileName')
path_name = model.StringProperty('pathName')
process = model.StringProperty('process')
custom_rule_id = model.Int32Property('customRuleId')
class Certificate(model.Model):
ROUTE = 'certificate'
id = model.Int32Property('id')
parent_certificate_id = model.Int32Property(
'parentCertificateId', expands_to='Certificate')
publisher_id = model.Int32Property('publisherId', expands_to='Publisher')
thumbprint = model.StringProperty('thumbprint')
thumbprint_algorithm = model.StringProperty('thumbprintAlgorithm')
subject_name = model.StringProperty('subjectName')
signature_algorithm = model.StringProperty('signatureAlgorithm')
serial_number = model.StringProperty('serialNumber')
valid_from = model.DateTimeProperty('validFrom')
valid_to = model.DateTimeProperty('validTo')
public_key_algorithm = model.StringProperty('publicKeyAlgorithm')
public_key_size = model.Int32Property('publicKeySize')
first_seen_computer_id = model.Int32Property(
'firstSeenComputerId', expands_to='Computer')
description = model.StringProperty('description', allow_update=True)
source_type = model.Int32Property('sourceType')
date_created = model.DateTimeProperty('dateCreated')
date_modified = model.DateTimeProperty('dateModified')
modified_by_user = model.StringProperty('modifiedByUser')
modified_by_user_id = model.Int32Property('modifiedByUserId')
intermediary = model.BooleanProperty('intermediary')
valid = model.BooleanProperty('valid')
embedded = model.BooleanProperty('embedded')
detached = model.BooleanProperty('detached')
signer = model.BooleanProperty('signer')
cosigner = model.BooleanProperty('cosigner')
certificate_state = model.Int32Property('certificateState', allow_update=True)
certificate_effective_state = model.Int32Property('certificateEffectiveState')
cl_version = model.Int64Property('clVersion')
class Computer(model.Model):
ROUTE = 'computer'
id = model.Int32Property('id')
name = model.StringProperty('name', allow_update=True)
computer_tag = model.StringProperty('computerTag', allow_update=True)
description = model.StringProperty('description', allow_update=True)
policy_id = model.Int32Property('policyId', allow_update=True, expands_to='Policy')
previous_policy_id = model.Int32Property('previousPolicyId', expands_to='Policy')
policy_name = model.StringProperty('policyName')
automatic_policy = model.BooleanProperty('automaticPolicy', allow_update=True)
local_approval = model.BooleanProperty('localApproval', allow_update=True)
users = model.StringProperty('users')
ip_address = model.StringProperty('ipAddress')
connected = model.BooleanProperty('connected')
enforcement_level = model.Int32Property('enforcementLevel')
disconnected_enforcement_level = model.Int32Property('disconnectedEnforcementLevel')
cli_password = model.StringProperty('CLIPassword')
last_register_date = model.DateTimeProperty('lastRegisterDate')
last_poll_date = model.DateTimeProperty('lastPollDate')
os_short_name = model.StringProperty('osShortName')
os_name = model.StringProperty('osName')
platform_id = model.Int32Property('platformId')
virtualized = model.StringProperty('virtualized')
virtual_platform = model.StringProperty('virtualPlatform')
date_created = model.DateTimeProperty('dateCreated')
agent_version = model.StringProperty('agentVersion')
days_offline = model.Int32Property('daysOffline')
uninstalled = model.BooleanProperty('uninstalled')
deleted = model.BooleanProperty('deleted')
processor_count = model.Int32Property('processorCount')
processor_speed = model.DoubleProperty('processorSpeed')
processor_model = model.StringProperty('processorModel')
machine_model = model.StringProperty('machineModel')
memory_size = model.Int32Property('memorySize')
upgrade_status = model.StringProperty('upgradeStatus')
upgrade_error = model.StringProperty('upgradeError')
upgrade_error_time = model.DateTimeProperty('upgradeErrorTime')
upgrade_error_count = model.Int32Property('upgradeErrorCount')
sync_flags = model.Int32Property('syncFlags')
refresh_flags = model.Int32Property('refreshFlags', allow_update=True)
policy_status = model.StringProperty('policyStatus')
policy_status_details = model.StringProperty('policyStatusDetails')
prioritized = model.BooleanProperty('prioritized', allow_update=True)
mac_address = model.StringProperty('macAddress')
debug_level = model.Int32Property('debugLevel', allow_update=True)
kernel_debug_level = model.Int32Property('kernelDebugLevel', allow_update=True)
debug_flags = model.Int32Property('debugFlags', allow_update=True)
debug_duration = model.Int32Property('debugDuration', allow_update=True)
active_debug_level = model.Int32Property('activeDebugLevel')
active_kernel_debug_level = model.Int32Property('activeKernelDebugLevel')
active_debug_flags = model.Int32Property('activeDebugFlags')
cc_level = model.Int32Property('ccLevel', allow_update=True)
cc_flags = model.Int32Property('ccFlags', allow_update=True)
supported_kernel = model.BooleanProperty('supportedKernel')
force_upgrade = model.BooleanProperty('forceUpgrade', allow_update=True)
has_health_check_errors = model.BooleanProperty('hasHealthCheckErrors')
cl_version = model.Int32Property('clVersion')
agent_memory_dumps = model.Int32Property('agentMemoryDumps')
system_memory_dumps = model.Int32Property('systemMemoryDumps')
initializing = model.BooleanProperty('initializing')
is_active = model.BooleanProperty('isActive')
tamper_protection_active = model.BooleanProperty('tamperProtectionActive')
agent_cache_size = model.Int32Property('agentCacheSize')
agent_queue_size = model.Int32Property('agentQueueSize')
sync_percent = model.Int32Property('syncPercent')
init_percent = model.Int32Property('initPercent')
td_count = model.Int32Property('tdCount')
template = model.BooleanProperty('template', allow_update=True)
template_computer_id = model.Int32Property('templateComputerId', expands_to='Computer')
template_date = model.DateTimeProperty('templateDate')
template_clone_cleanup_mode = model.Int32Property('templateCloneCleanupMode', allow_update=True)
template_clone_cleanup_time = model.Int32Property('templateCloneCleanupTime', allow_update=True)
template_clone_cleanup_time_scale = model.Int32Property('templateCloneCleanupTimeScale', allow_update=True)
template_track_mods_only = model.BooleanProperty('templateTrackModsOnly', allow_update=True)
cb_sensor_id = model.Int32Property('cbSensorId')
cb_sensor_version = model.StringProperty('cbSensorVersion')
cb_sensor_flags = model.Int32Property('cbSensorFlags')
has_duplicates = model.BooleanProperty('hasDuplicates')
scep_status = model.Int32Property('SCEPStatus')
class Event(model.Model):
ROUTE = 'event'
id = model.Int64Property('id')
timestamp = model.DateTimeProperty('timestamp')
received_timestamp = model.DateTimeProperty('receivedTimestamp')
description = model.StringProperty('description')
type = model.Int32Property('type')
subtype = model.Int32Property('subtype')
subtype_name = model.StringProperty('subtypeName')
ip_address = model.StringProperty('ipAddress')
computer_id = model.Int32Property('computerId', expands_to='Computer')
computer_name = model.StringProperty('computerName')
policy_id = model.Int32Property('policyId', expands_to='Policy')
policy_name = model.StringProperty('policyName')
file_catalog_id = model.Int32Property('fileCatalogId', expands_to='FileCatalog')
installer_file_catalog_id = model.Int32Property('installerFileCatalogId', expands_to='FileCatalog')
process_file_catalog_id = model.Int32Property('processFileCatalogId', expands_to='FileCatalog')
file_name = model.StringProperty('fileName')
path_name = model.StringProperty('pathName')
command_line = model.StringProperty('commandLine')
process_path_name = model.StringProperty('processPathName')
process_file_name = model.StringProperty('processFileName')
installer_file_name = model.StringProperty('installerFileName')
process_key = model.StringProperty('processKey')
severity = model.Int32Property('severity')
user_name = model.StringProperty('userName')
rule_name = model.StringProperty('ruleName')
ban_name = model.StringProperty('banName')
updater_name = model.StringProperty('updaterName')
indicator_name = model.StringProperty('indicatorName')
param1 = model.StringProperty('param1')
param2 = model.StringProperty('param2')
param3 = model.StringProperty('param3')
string_id = model.Int32Property('stringId')
class FileCatalog(model.Model):
ROUTE = 'fileCatalog'
id = model.Int32Property('id')
date_created = model.DateTimeProperty('dateCreated')
path_name = model.StringProperty('pathName')
file_name = model.StringProperty('fileName')
file_extension = model.StringProperty('fileExtension')
computer_id = model.Int32Property('computerId', expands_to='Computer')
md5 = model.StringProperty('md5')
sha1 = model.StringProperty('sha1')
sha256 = model.StringProperty('sha256')
sha256_hash_type = model.Int32Property('sha256HashType')
file_type = model.StringProperty('fileType')
file_size = model.Int64Property('fileSize')
product_name = model.StringProperty('productName')
publisher = model.StringProperty('publisher')
company = model.StringProperty('company')
publisher_or_company = model.StringProperty('publisherOrCompany')
product_version = model.StringProperty('productVersion')
installed_program_name = model.StringProperty('installedProgramName')
reputation_available = model.BooleanProperty('reputationAvailable')
trust = model.Int32Property('trust')
trust_messages = model.StringProperty('trustMessages')
threat = model.Int16Property('threat')
category = model.StringProperty('category')
file_state = model.Int32Property('fileState')
publisher_state = model.Int32Property('publisherState')
certificate_state = model.Int32Property('certificateState')
effective_state = model.StringProperty('effectiveState')
approved_by_reputation = model.BooleanProperty('approvedByReputation')
reputation_enabled = model.BooleanProperty('reputationEnabled')
prevalence = model.Int32Property('prevalence')
file_flags = model.Int32Property('fileFlags')
publisher_id = model.Int32Property('publisherId', expands_to='Publisher')
certificate_id = model.Int32Property('certificateId', expands_to='Certificate')
class FileInstance(model.Model):
ROUTE = 'fileInstance'
id = model.Int64Property('id')
file_catalog_id = model.Int32Property('fileCatalogId', expands_to='FileCatalog')
file_instance_group_id = model.Int64Property('fileInstanceGroupId')
computer_id = model.Int32Property('computerId', expands_to='Computer')
date_created = model.DateTimeProperty('dateCreated')
file_name = model.StringProperty('fileName')
path_name = model.StringProperty('pathName')
executed = model.BooleanProperty('executed')
local_state = model.Int32Property('localState', allow_update=True)
detailed_local_state = model.Int32Property('detailedLocalState')
detached_publisher_id = model.Int32Property('detachedPublisherId', expands_to='Publisher')
detached_certificate_id = model.Int32Property('detachedCertificateId', expands_to='Certificate')
class FileRule(model.Model):
ROUTE = 'fileRule'
id = model.Int64Property('id')
file_catalog_id = model.Int32Property('fileCatalogId', allow_update=True, expands_to='FileCatalog')
name = model.StringProperty('name', allow_update=True)
description = model.StringProperty('description', allow_update=True)
file_state = model.Int32Property('fileState', allow_update=True)
source_type = model.Int32Property('sourceType')
source_id = model.Int32Property('sourceId')
report_only = model.BooleanProperty('reportOnly', allow_update=True)
reputation_approvals_enabled = model.BooleanProperty('reputationApprovalsEnabled', allow_update=True)
force_installer = model.BooleanProperty('forceInstaller', allow_update=True)
force_not_installer = model.BooleanProperty('forceNotInstaller', allow_update=True)
policy_ids = model.StringProperty('policyIds', allow_update=True)
hash = model.StringProperty('hash', allow_update=True)
platform_flags = model.Int32Property('platformFlags', allow_update=True)
date_created = model.DateTimeProperty('dateCreated')
created_by = model.StringProperty('createdBy')
created_by_user_id = model.Int32Property('createdByUserId')
date_modified = model.DateTimeProperty('dateModified')
modified_by = model.StringProperty('modifiedBy')
modified_by_user_id = model.Int32Property('modifiedByUserId')
cl_version = model.Int64Property('clVersion')
class Policy(model.Model):
ROUTE = 'policy'
id = model.Int32Property('id')
name = model.StringProperty('name', allow_update=True)
description = model.StringProperty('description', allow_update=True)
package_name = model.StringProperty('packageName')
enforcement_level = model.Int32Property('enforcementLevel', allow_update=True)
disconnected_enforcement_level = model.Int32Property('disconnectedEnforcementLevel', allow_update=True)
help_desk_url = model.StringProperty('helpDeskUrl')
image_url = model.StringProperty('imageUrl')
date_created = model.DateTimeProperty('dateCreated')
created_by_user_id = model.Int32Property('createdByUserId')
date_modified = model.DateTimeProperty('dateModified')
modified_by_user_id = model.Int32Property('modifiedByUserId')
read_only = model.BooleanProperty('readOnly')
hidden = model.BooleanProperty('hidden')
automatic = model.BooleanProperty('automatic', allow_update=True)
load_agent_in_safe_mode = model.BooleanProperty('loadAgentInSafeMode', allow_update=True)
reputation_enabled = model.BooleanProperty('reputationEnabled', allow_update=True)
file_tracking_enabled = model.BooleanProperty('fileTrackingEnabled', allow_update=True)
custom_logo = model.BooleanProperty('customLogo', allow_update=True)
automatic_approvals_on_transition = model.BooleanProperty('automaticApprovalsOnTransition', allow_update=True)
allow_agent_upgrades = model.BooleanProperty('allowAgentUpgrades', allow_update=True)
total_computers = model.Int32Property('totalComputers')
connected_computers = model.Int32Property('connectedComputers')
at_enforcement_computers = model.Int32Property('atEnforcementComputers')
cl_version_max = model.Int32Property('clVersionMax')
class Publisher(model.Model):
ROUTE = 'publisher'
id = model.Int32Property('id')
name = model.StringProperty('name')
description = model.StringProperty('description', allow_update=True)
date_created = model.DateTimeProperty('dateCreated')
modified_by = model.StringProperty('modifiedBy')
modified_by_user_id = model.Int32Property('modifiedByUserId')
date_modified = model.DateTimeProperty('dateModified')
publisher_reputation = model.Int32Property('publisherReputation')
publisher_state = model.Int32Property('publisherState', allow_update=True)
policy_ids = model.StringProperty('policyIds', allow_update=True)
reputation_approvals_enabled = model.BooleanProperty('reputationApprovalsEnabled', allow_update=True)
source_type = model.Int32Property('sourceType')
first_seen_computer_id = model.Int32Property('firstSeenComputerId', expands_to='Computer')
platform_flags = model.Int32Property('platformFlags')
signed_files_count = model.Int32Property('signedFilesCount')
signed_certificate_count = model.Int32Property('signedCertificateCount')
hidden = model.BooleanProperty('hidden')
cl_version = model.Int64Property('clVersion')
| [
"[email protected]"
] | |
8017fb462a269f73fa8c9ffa3fee73675aa70275 | d37a19ab3bcaba6e808a18df411c653c644d27db | /Year1/ca117/Lab11.1/triathlon_v3_111.py | 448776ad2f5a0f4641f48466df4f272a8bdccb60 | [] | no_license | Andrew-Finn/DCU | 9e7009dac9a543aaade17e9e94116259dcc1de20 | 013789e8150d80d3b3ce2c0c7ba968b2c69a7ce0 | refs/heads/master | 2023-02-21T05:13:42.731828 | 2022-02-14T12:39:20 | 2022-02-14T12:39:20 | 157,438,470 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,261 | py | class Triathlete:
def __init__(self, name, tid):
self.name = name
self.tid = tid
self.times = {}
def __str__(self):
return "Name: {}\nID: {}\nRace time: {}".format(
self.name, self.tid, self.race_time())
def add_time(self, sport, time):
self.times[sport] = time
def get_time(self, sport):
return self.times[sport]
def race_time(self):
return sum(self.times.values())
def __lt__(self, other):
return self.race_time() < other.race_time()
def __eq__(self, other):
return self.race_time() == other.race_time()
class Triathlon:
def __init__(self):
self.athletes = []
def __str__(self):
return "\n".join(str(a) for a in sorted(self.athletes, key=lambda x: x.name))
def add(self, athlete):
self.athletes.append(athlete)
def remove(self, tid):
ind = next(a for a in self.athletes if a.tid == tid)
self.athletes.remove(ind)
def lookup(self, tid):
return next((a for a in self.athletes if a.tid == tid), None)
def best(self):
return min(self.athletes, key=lambda a: a.race_time())
def worst(self):
return max(self.athletes, key=lambda a: a.race_time())
| [
"[email protected]"
] | |
194840074149cc1c77f461d43ac7f0f971bea662 | 7698a74a06e10dd5e1f27e6bd9f9b2a5cda1c5fb | /pdb_search/quire_pdb_2014_mw70to250_tversky/postprocess_uniprot_pdb_lig_links_lists_max_num.py | e4cdbb9594d067e9ee24a33569e8d5f303c8e0d5 | [] | no_license | kingbo2008/teb_scripts_programs | ef20b24fe8982046397d3659b68f0ad70e9b6b8b | 5fd9d60c28ceb5c7827f1bd94b1b8fdecf74944e | refs/heads/master | 2023-02-11T00:57:59.347144 | 2021-01-07T17:42:11 | 2021-01-07T17:42:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,580 | py | ## Trent Balius, Shoichet group, UCSF, 2014.08.08
import urllib, urllib2, math
import scrape_pdb_for_uniprot as spfu
import scrape_pdb_for_lig_mod as spfl
import scrape_zinc_zincid as szzi
import tanimoto_cal_axon as tancal
def find_linked_list_count(lines):
list = []
sublist = []
#sublist.append(lig1)
#sublist.append(lig2)
#print "lines = ", lines
while (len(lines)>0):
#print "sublist = ",sublist
num = len(lines)
for i in range(len(lines)):
#print lines[i]
splitline = lines[i].split()
lig1 = splitline[0]
lig2 = splitline[1]
if (lig1 in sublist) and not (lig2 in sublist):
sublist.append(lig2)
del lines[i]
break
elif (lig2 in sublist) and not (lig1 in sublist):
sublist.append(lig1)
del lines[i]
break
elif ((lig2 in sublist) and (lig1 in sublist)):
del lines[i]
break
elif (len(sublist) == 0):
sublist.append(lig1)
sublist.append(lig2)
del lines[i]
break
#print num, len(lines)
if (num == len(lines) or len(lines) == 0):
#print "I AM HERE ", sublist
list.append(sublist)
sublist = []
#sublist.append(lig1)
#sublist.append(lig2)
#print "list = ",list
max = 0
for sublist in list:
#print len(sublist)
#print sublist
if (max < len(sublist)):
max = len(sublist)
return max
print " stuff that matters::::::::::"
#filein = open("uniprot_lig_tanamoto_mwdiff_formula_diff.txt",'r')
filein = open("uniprot_lig_tversky_mwdiff_formula_diff_new.txt",'r')
fileout = open("uniprot_max_linked_list_size.txt",'w')
fileout2 = open("uniprot_lig_tversky_mwdiff_formula_diff_reduced.txt",'w')
uniprot_old = ''
sublist = []
lines = []
writelines = ''
for line in filein:
if "This" in line:
continue
print line
splitline = line.split()
uniprot = splitline[0].strip(',')
lig1 = splitline[2].strip(',')
lig2 = splitline[3].strip(',')
#mfd = float(splitline[13])
mfd = float(splitline[16])
tc = float(splitline[6])
#if (mfd>4.0): # if the molecular formula difference is grater than 4 then skip the line (pair)
if (mfd>1.0): # if the molecular formula difference heavy atoms is grater than 1 then skip the line (pair)
print "skiped"
continue
#if (mfd == 0.0 and tc == 1.0):
# print "skiped because ligs are isomers"
# continue
if uniprot_old != uniprot:
max = find_linked_list_count(lines)
print uniprot_old, max
if (max > 5):
fileout.write(uniprot_old+" "+str(max)+'\n')
fileout2.write(writelines) # will right out all line the for uniprot that pass (max>5) and the mfd>4.0
lines = []
writelines = ''
uniprot_old = uniprot
lines.append(lig1+' '+lig2)
writelines=writelines+line # this will
max = find_linked_list_count(lines)
print uniprot_old, max
if (max > 5):
fileout.write(uniprot_old+" "+str(max)+'\n')
fileout2.write(writelines) # will right out all line the for uniprot that pass (max>5) and the mfd>4.0
filein.close()
fileout.close()
fileout2.close()
| [
"[email protected]"
] | |
18b0e53eac6e5967a1b4c546a35303373af7f399 | 65329299fca8dcf2e204132624d9b0f8f8f39af7 | /napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/neighbors/neighbor/state/messages/__init__.py | 2d44d9f348472cccab1a16ac19e4b20bb30b57ee | [
"Apache-2.0"
] | permissive | darylturner/napalm-yang | bf30420e22d8926efdc0705165ed0441545cdacf | b14946b884ad2019b896ee151285900c89653f44 | refs/heads/master | 2021-05-14T12:17:37.424659 | 2017-11-17T07:32:49 | 2017-11-17T07:32:49 | 116,404,171 | 0 | 0 | null | 2018-01-05T16:21:37 | 2018-01-05T16:21:36 | null | UTF-8 | Python | false | false | 14,654 | py |
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
import sent
import received
class messages(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/protocols/protocol/bgp/neighbors/neighbor/state/messages. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Counters for BGP messages sent and received from the
neighbor
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_extmethods', '__sent','__received',)
_yang_name = 'messages'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__received = YANGDynClass(base=received.received, is_container='container', yang_name="received", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
self.__sent = YANGDynClass(base=sent.sent, is_container='container', yang_name="sent", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'network-instances', u'network-instance', u'protocols', u'protocol', u'bgp', u'neighbors', u'neighbor', u'state', u'messages']
def _get_sent(self):
"""
Getter method for sent, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/neighbors/neighbor/state/messages/sent (container)
YANG Description: Counters relating to BGP messages sent to the neighbor
"""
return self.__sent
def _set_sent(self, v, load=False):
"""
Setter method for sent, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/neighbors/neighbor/state/messages/sent (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_sent is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sent() directly.
YANG Description: Counters relating to BGP messages sent to the neighbor
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=sent.sent, is_container='container', yang_name="sent", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sent must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=sent.sent, is_container='container', yang_name="sent", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)""",
})
self.__sent = t
if hasattr(self, '_set'):
self._set()
def _unset_sent(self):
self.__sent = YANGDynClass(base=sent.sent, is_container='container', yang_name="sent", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
def _get_received(self):
"""
Getter method for received, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/neighbors/neighbor/state/messages/received (container)
YANG Description: Counters for BGP messages received from the neighbor
"""
return self.__received
def _set_received(self, v, load=False):
"""
Setter method for received, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/neighbors/neighbor/state/messages/received (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_received is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_received() directly.
YANG Description: Counters for BGP messages received from the neighbor
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=received.received, is_container='container', yang_name="received", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """received must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=received.received, is_container='container', yang_name="received", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)""",
})
self.__received = t
if hasattr(self, '_set'):
self._set()
def _unset_received(self):
self.__received = YANGDynClass(base=received.received, is_container='container', yang_name="received", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
sent = __builtin__.property(_get_sent)
received = __builtin__.property(_get_received)
_pyangbind_elements = {'sent': sent, 'received': received, }
import sent
import received
class messages(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance-l2 - based on the path /network-instances/network-instance/protocols/protocol/bgp/neighbors/neighbor/state/messages. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Counters for BGP messages sent and received from the
neighbor
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_extmethods', '__sent','__received',)
_yang_name = 'messages'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__received = YANGDynClass(base=received.received, is_container='container', yang_name="received", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
self.__sent = YANGDynClass(base=sent.sent, is_container='container', yang_name="sent", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'network-instances', u'network-instance', u'protocols', u'protocol', u'bgp', u'neighbors', u'neighbor', u'state', u'messages']
def _get_sent(self):
"""
Getter method for sent, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/neighbors/neighbor/state/messages/sent (container)
YANG Description: Counters relating to BGP messages sent to the neighbor
"""
return self.__sent
def _set_sent(self, v, load=False):
"""
Setter method for sent, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/neighbors/neighbor/state/messages/sent (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_sent is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sent() directly.
YANG Description: Counters relating to BGP messages sent to the neighbor
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=sent.sent, is_container='container', yang_name="sent", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sent must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=sent.sent, is_container='container', yang_name="sent", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)""",
})
self.__sent = t
if hasattr(self, '_set'):
self._set()
def _unset_sent(self):
self.__sent = YANGDynClass(base=sent.sent, is_container='container', yang_name="sent", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
def _get_received(self):
"""
Getter method for received, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/neighbors/neighbor/state/messages/received (container)
YANG Description: Counters for BGP messages received from the neighbor
"""
return self.__received
def _set_received(self, v, load=False):
"""
Setter method for received, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/neighbors/neighbor/state/messages/received (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_received is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_received() directly.
YANG Description: Counters for BGP messages received from the neighbor
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=received.received, is_container='container', yang_name="received", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """received must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=received.received, is_container='container', yang_name="received", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)""",
})
self.__received = t
if hasattr(self, '_set'):
self._set()
def _unset_received(self):
self.__received = YANGDynClass(base=received.received, is_container='container', yang_name="received", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)
sent = __builtin__.property(_get_sent)
received = __builtin__.property(_get_received)
_pyangbind_elements = {'sent': sent, 'received': received, }
| [
"[email protected]"
] | |
8daa3a2822a6f1ca6fea3e85851a2bdb5803592e | c053101986b0c9884c2003ec1c86bdf69c41d225 | /normal-tips/WordCloud/CN_cloud.py | 9bb43bd4f2992c1810594970824ab5e29931011d | [] | no_license | JZDBB/Python-ZeroToAll | 4c32a43044a581941943f822e81fa37df6ef8dd4 | 67a1e9db0775d897dcc5c0d90f663de9788221a3 | refs/heads/master | 2021-05-09T18:36:45.358508 | 2019-11-01T08:15:54 | 2019-11-01T08:15:54 | 119,166,874 | 0 | 0 | null | 2019-10-29T20:59:04 | 2018-01-27T13:29:59 | HTML | UTF-8 | Python | false | false | 4,430 | py | # # -*- coding: utf-8 -*-
# import jieba
# import os
# import codecs
# from scipy.misc import imread
# import matplotlib as mpl
# import matplotlib.pyplot as plt
# from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
#
#
# class GetWords(object):
# def __init__(self, dict_name, file_list, dic_list):
# self.dict_name = dict_name
# self.file_list = file_list
# self.dic_list = dic_list
#
# # 获取自定义词典
# def get_dic(self):
# dic = open(self.dict_name, 'r')
# while 1:
# line = dic.readline().strip()
# self.dic_list.append(line)
# if not line:
# break
# pass
#
# def get_word_to_cloud(self):
# for file in self.file_list:
# with codecs.open('../spider/' + file, "r", encoding='utf-8', errors='ignore') as string:
# string = string.read().upper()
# res = jieba.cut(string, HMM=False)
# reslist = list(res)
# wordDict = {}
# for i in reslist:
# if i not in self.dic_list:
# continue
# if i in wordDict:
# wordDict[i] = wordDict[i] + 1
# else:
# wordDict[i] = 1
#
# coloring = imread('test.jpeg')
#
# wc = WordCloud(font_path='msyh.ttf', mask=coloring,
# background_color="white", max_words=50,
# max_font_size=40, random_state=42)
#
# wc.generate_from_frequencies(wordDict)
#
# wc.to_file("%s.png" % (file))
#
#
# def set_dic():
# _curpath = os.path.normpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
# settings_path = os.environ.get('dict.txt')
# if settings_path and os.path.exists(settings_path):
# jieba.set_dictionary(settings_path)
# elif os.path.exists(os.path.join(_curpath, 'data/dict.txt.big')):
# jieba.set_dictionary('data/dict.txt.big')
# else:
# print("Using traditional dictionary!")
#
#
# if __name__ == '__main__':
# set_dic()
# file_list = ['data_visualize.txt', 'data_dev.txt', 'data_mining.txt', 'data_arc.txt', 'data_analysis.txt']
# dic_name = 'dict.txt'
# dic_list = []
# getwords = GetWords(dic_name, file_list, dic_list)
# getwords.get_dic()
# getwords.get_word_to_cloud()
# -*-coding:utf-8-*-
###生成txt文件的词云
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import jieba
from PIL import Image
import numpy as np
import os
from os import path
text = open("fenciHou1.txt", "rb").read().decode('utf-8')
# text = open("cv.txt", "rb").read()
# 结巴分词
# wordlist = jieba.cut(text, cut_all=True)
# wl = " ".join(wordlist)
# print(wl)#输出分词之后的txt
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
background_Image = np.array(Image.open(path.join(d, "1545566997_781739.png")))
# or
# background_Image = imread(path.join(d, "mask1900.jpg"))
# 提取背景图片颜色
img_colors = ImageColorGenerator(background_Image)
# 把分词后的txt写入文本文件
# fenciTxt = open("fenciHou.txt","w+", encoding='utf-8')
# fenciTxt.writelines(wl)
# fenciTxt.close()
# 设置词云
wc = WordCloud(background_color="black", # 设置背景颜色
margin = 2, # 设置页面边缘
mask=background_Image,# mask = "图片", #设置背景图片
max_words=500, # 设置最大显示的字数
# stopwords = "", #设置停用词
font_path="fangsong_GB2312.ttf",
# 设置中文字体,使得词云可以显示(词云默认字体是“DroidSansMono.ttf字体库”,不支持中文)
max_font_size=200, # 设置字体最大值
min_font_size=5, # 最小字号
collocations=False, # 不重复显示词语
colormap='viridis', # matplotlib 色图,可更改名称进而更改整体风格
random_state=30, # 设置有多少种随机生成状态,即有多少种配色方案
mode='RGB'
)
myword = wc.generate(text) # 生成词云
wc.recolor(color_func=img_colors)
#存储图像
wc.to_file('12.png')
# 展示词云图
plt.imshow(myword)
plt.axis("off")
plt.show()
| [
"[email protected]"
] | |
6e56f5fe3ef0c5ddaeeabc6fa8213b24e7c6e253 | 6b7ff6d09f1da2793f4cc2d3f319256580fbae0c | /astroquery/vo_conesearch/async.py | 571c6d6d91008c9db5a4f15c4ef5f22b917ec926 | [] | no_license | AyushYadav/astroquery | 39e4e696441fdfe84e9e66cf905f6febde3080a3 | 4645d11f56f96404870d284603c024a3de0d8198 | refs/heads/master | 2020-05-18T13:02:06.068072 | 2017-05-21T17:16:15 | 2017-05-21T17:16:15 | 86,921,243 | 1 | 0 | null | 2017-04-01T15:05:25 | 2017-04-01T15:05:25 | null | UTF-8 | Python | false | false | 2,323 | py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Asynchronous VO service requests."""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# ASTROPY
from astropy.utils.compat.futures import ThreadPoolExecutor
__all__ = ['AsyncBase']
class AsyncBase(object):
"""Base class for asynchronous VO service requests
using :py:class:`concurrent.futures.ThreadPoolExecutor`.
Service request will be forced to run in silent
mode by setting ``verbose=False``. Warnings are controlled
by :py:mod:`warnings` module.
.. note::
Methods of the attributes can be accessed directly,
with priority given to ``executor``.
Parameters
----------
func : function
The function to run.
args, kwargs
Arguments and keywords accepted by the service request
function to be called asynchronously.
Attributes
----------
executor : :py:class:`concurrent.futures.ThreadPoolExecutor`
Executor running the function on single thread.
future : :py:class:`concurrent.futures.Future`
Asynchronous execution created by ``executor``.
"""
def __init__(self, func, *args, **kwargs):
kwargs['verbose'] = False
self.executor = ThreadPoolExecutor(1)
self.future = self.executor.submit(func, *args, **kwargs)
def __getattr__(self, what):
"""Expose ``executor`` and ``future`` methods."""
try:
return getattr(self.executor, what)
except AttributeError:
return getattr(self.future, what)
def get(self, timeout=None):
"""Get result, if available, then shut down thread.
Parameters
----------
timeout : int or float
Wait the given amount of time in seconds before
obtaining result. If not given, wait indefinitely
until function is done.
Returns
-------
result
Result returned by the function.
Raises
------
Exception
Errors raised by :py:class:`concurrent.futures.Future`.
"""
try:
result = self.future.result(timeout=timeout)
finally:
self.executor.shutdown(wait=False)
return result
| [
"[email protected]"
] | |
72e68a94ce144b60b07b3ec9392dddb8e4c927c4 | 3a02ec695af95e5d5f5c4f14ab393cd2ad709be3 | /kochat/model/fallback/__init__.py | 748d571c72c6d0720a72f9bead1e08855a573784 | [
"Apache-2.0"
] | permissive | seunghyunmoon2/kochat | 50f0db168ca5163e6926331d8d81ebf3a26e4f7e | f5a5df38c7c24080855f9279450195bc0a8eae74 | refs/heads/master | 2022-12-23T17:07:49.856243 | 2020-10-02T06:01:06 | 2020-10-02T06:01:06 | 278,004,648 | 0 | 0 | Apache-2.0 | 2020-07-08T06:08:38 | 2020-07-08T06:08:38 | null | UTF-8 | Python | false | false | 183 | py | """
@auther Hyunwoong
@since 6/28/2020
@see https://github.com/gusdnd852
"""
from kochat.model.intent.cnn import CNN
from kochat.model.intent.lstm import LSTM
__ALL__ = [CNN, LSTM]
| [
"[email protected]"
] | |
33ea27c8dee8244bf11dc728aa76c3f6757fe576 | b1aa3c599c5d831444e0ae4e434f35f57b4c6c45 | /month1/week4/python_class11/main_operate.py | 984d84fa3373dc4dd1f9d5a380f1fe28a39feca9 | [] | no_license | yunyusha/xunxibiji | 2346d7f2406312363216c5bddbf97f35c1e2c238 | f6c3ffb4df2387b8359b67d5e15e5e33e81e3f7d | refs/heads/master | 2020-03-28T12:31:17.429159 | 2018-09-11T11:35:19 | 2018-09-11T11:35:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,620 | py | """Main Operate
Usage:
main_operate.py [-gkdtz] <from> <to> <time>
main_operate.py [-GDKTZ] <from> <to> <time>
Options:
"""
from docopt import docopt
from tickets import Ticket
import time
if __name__ == "__main__":
arguments = docopt(__doc__)
# 根据用户输入的选择项完成对应类别列车的信息查询
kinds = []
if arguments.get("-g") is True or arguments.get("-G") is True:
kinds.append('G')
if arguments.get("-k") is True or arguments.get("-K") is True:
kinds.append("K")
if arguments.get("-d") is True or arguments.get("-D") is True:
kinds.append("D")
if arguments.get("-t") is True or arguments.get("-T") is True:
kinds.append("T")
if arguments.get("-z") is True or arguments.get("-Z") is True:
kinds.append("Z")
if len(kinds) == 0:
kinds = ["K","G", "D", "T", "Z"]
# 获取当前程序运行时的时间
time_date = time.strftime("%Y-%m-%d", time.localtime())
# 获取用户通过终端输入的时间
time_input = arguments.get("<time>").split('-')
# 将用户输入的日期变成两位表示
time_input = list(map(lambda x: ("0"+x) if len(x) == 1 else x, time_input))
time_input = "-".join(time_input)
# 判断用户输入的时间是否超出12306查询时间
if time_input >= time_date:
dic = {'from':arguments.get('<from>'), "to":arguments.get('<to>'),'time':time_input}
ticket = Ticket(**dic)
ticket.check_ticket()
ticket.check_train(kinds)
else:
print('对不起您所查询的列车时间不在规定时间之内')
| [
"[email protected]"
] | |
a8266a0805a71be951a9468186ac375deefcf2a6 | ce6f8510f6a2fd48b7037c1c8448f719fd54f8b4 | /piecrust/admin/scm/git.py | b5ae5a0695d49f6903c42acf33f94be881e9eef4 | [
"Apache-2.0"
] | permissive | ludovicchabant/PieCrust2 | bd014f8aa880ec2b2360a298263d2de279d4252f | ebb567b577cbd2efb018183b73eff05c7a12c318 | refs/heads/master | 2023-01-09T17:09:56.991209 | 2022-12-31T00:48:04 | 2022-12-31T00:48:04 | 23,298,052 | 46 | 9 | NOASSERTION | 2022-12-31T01:05:07 | 2014-08-25T01:29:18 | Python | UTF-8 | Python | false | false | 1,872 | py | import os
import logging
import tempfile
import subprocess
from .base import SourceControl, RepoStatus, _s
logger = logging.getLogger(__name__)
class GitSourceControl(SourceControl):
def __init__(self, root_dir, cfg):
super(GitSourceControl, self).__init__(root_dir, cfg)
self.git = cfg.get('exe', 'git')
def getStatus(self):
res = RepoStatus()
st_out = self._run('status', '-s')
for line in st_out.split('\n'):
if not line:
continue
if line.startswith('?? '):
path = line[3:].strip()
if path[-1] == '/':
import glob
res.new_files += [
f for f in glob.glob(path + '**', recursive=True)
if f[-1] != '/']
else:
res.new_files.append(path)
elif line.startswith(' M '):
res.edited_files.append(line[3:])
return res
def _doCommit(self, paths, message, author):
self._run('add', *paths)
# Create a temp file with the commit message.
f, temp = tempfile.mkstemp()
with os.fdopen(f, 'w') as fd:
fd.write(message)
# Commit and clean up the temp file.
try:
commit_args = list(paths) + ['-F', temp]
if author:
commit_args += ['--author="%s"' % author]
self._run('commit', *commit_args)
finally:
os.remove(temp)
def _run(self, cmd, *args, **kwargs):
exe = [self.git]
exe.append(cmd)
exe += args
logger.debug("Running Git: " + str(exe))
proc = subprocess.Popen(
exe, stdout=subprocess.PIPE, cwd=self.root_dir)
out, _ = proc.communicate()
encoded_out = _s(out)
return encoded_out
| [
"[email protected]"
] | |
07a22260c73200a52b1acc7292c2c3f9ba7a1175 | 11cd362cdd78c2fc48042ed203614b201ac94aa6 | /desktop/core/ext-py3/boto-2.49.0/boto/auth.py | df6dbf27be6de47416a5d03616db0dc190bbedf5 | [
"CC-BY-3.0",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"ZPL-2.0",
"Unlicense",
"LGPL-3.0-only",
"CC0-1.0",
"LicenseRef-scancode-other-permissive",
"CNRI-Python",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-or-later",
"Python-2.0",
"GPL-3.0-only",
"CC-BY-4.0",
"LicenseRef-scancode-jpython-1.1",
"AFL-2.1",
"JSON",
"WTFPL",
"MIT",
"LicenseRef-scancode-generic-exception",
"LicenseRef-scancode-jython",
"GPL-3.0-or-later",
"LicenseRef-scancode-python-cwi",
"BSD-3-Clause",
"LGPL-3.0-or-later",
"Zlib",
"LicenseRef-scancode-free-unknown",
"Classpath-exception-2.0",
"LicenseRef-scancode-proprietary-license",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"MPL-2.0",
"ISC",
"GPL-2.0-only",
"ZPL-2.1",
"BSL-1.0",
"Apache-2.0",
"LGPL-2.0-only",
"LicenseRef-scancode-public-domain",
"Xnet",
"BSD-2-Clause"
] | permissive | cloudera/hue | b42343d0e03d2936b5a9a32f8ddb3e9c5c80c908 | dccb9467675c67b9c3399fc76c5de6d31bfb8255 | refs/heads/master | 2023-08-31T06:49:25.724501 | 2023-08-28T20:45:00 | 2023-08-28T20:45:00 | 732,593 | 5,655 | 2,244 | Apache-2.0 | 2023-09-14T03:05:41 | 2010-06-21T19:46:51 | JavaScript | UTF-8 | Python | false | false | 41,839 | py | # Copyright 2010 Google Inc.
# Copyright (c) 2011 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2011, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Handles authentication required to AWS and GS
"""
import base64
import boto
import boto.auth_handler
import boto.exception
import boto.plugin
import boto.utils
import copy
import datetime
from email.utils import formatdate
import hmac
import os
import posixpath
from boto.compat import urllib, encodebytes, parse_qs_safe, urlparse
from boto.auth_handler import AuthHandler
from boto.exception import BotoClientError
try:
from hashlib import sha1 as sha
from hashlib import sha256 as sha256
except ImportError:
import sha
sha256 = None
# Region detection strings to determine if SigV2 should be used
# by default
S3_AUTH_DETECT = [
'-ap-northeast-1',
'.ap-northeast-1',
'-ap-southeast-1',
'.ap-southeast-1',
'-ap-southeast-2',
'.ap-southeast-2',
'-eu-west-1',
'.eu-west-1',
'-external-1',
'.external-1',
'-sa-east-1',
'.sa-east-1',
'-us-east-1',
'.us-east-1',
'-us-gov-west-1',
'.us-gov-west-1',
'-us-west-1',
'.us-west-1',
'-us-west-2',
'.us-west-2'
]
SIGV4_DETECT = [
'.cn-',
# In eu-central and ap-northeast-2 we support both host styles for S3
'.eu-central',
'-eu-central',
'.ap-northeast-2',
'-ap-northeast-2',
'.ap-south-1',
'-ap-south-1',
'.us-east-2',
'-us-east-2',
'-ca-central',
'.ca-central',
'.eu-west-2',
'-eu-west-2',
]
class HmacKeys(object):
"""Key based Auth handler helper."""
def __init__(self, host, config, provider):
if provider.access_key is None or provider.secret_key is None:
raise boto.auth_handler.NotReadyToAuthenticate()
self.host = host
self.update_provider(provider)
def update_provider(self, provider):
self._provider = provider
self._hmac = hmac.new(self._provider.secret_key.encode('utf-8'),
digestmod=sha)
if sha256:
self._hmac_256 = hmac.new(self._provider.secret_key.encode('utf-8'),
digestmod=sha256)
else:
self._hmac_256 = None
def algorithm(self):
if self._hmac_256:
return 'HmacSHA256'
else:
return 'HmacSHA1'
def _get_hmac(self):
if self._hmac_256:
digestmod = sha256
else:
digestmod = sha
return hmac.new(self._provider.secret_key.encode('utf-8'),
digestmod=digestmod)
def sign_string(self, string_to_sign):
new_hmac = self._get_hmac()
new_hmac.update(string_to_sign.encode('utf-8'))
return encodebytes(new_hmac.digest()).decode('utf-8').strip()
def __getstate__(self):
pickled_dict = copy.copy(self.__dict__)
del pickled_dict['_hmac']
del pickled_dict['_hmac_256']
return pickled_dict
def __setstate__(self, dct):
self.__dict__ = dct
self.update_provider(self._provider)
class AnonAuthHandler(AuthHandler, HmacKeys):
"""
Implements Anonymous requests.
"""
capability = ['anon']
def __init__(self, host, config, provider):
super(AnonAuthHandler, self).__init__(host, config, provider)
def add_auth(self, http_request, **kwargs):
pass
class HmacAuthV1Handler(AuthHandler, HmacKeys):
""" Implements the HMAC request signing used by S3 and GS."""
capability = ['hmac-v1', 's3']
def __init__(self, host, config, provider):
AuthHandler.__init__(self, host, config, provider)
HmacKeys.__init__(self, host, config, provider)
self._hmac_256 = None
def update_provider(self, provider):
super(HmacAuthV1Handler, self).update_provider(provider)
self._hmac_256 = None
def add_auth(self, http_request, **kwargs):
headers = http_request.headers
method = http_request.method
auth_path = http_request.auth_path
if 'Date' not in headers:
headers['Date'] = formatdate(usegmt=True)
if self._provider.security_token:
key = self._provider.security_token_header
headers[key] = self._provider.security_token
string_to_sign = boto.utils.canonical_string(method, auth_path,
headers, None,
self._provider)
boto.log.debug('StringToSign:\n%s' % string_to_sign)
b64_hmac = self.sign_string(string_to_sign)
auth_hdr = self._provider.auth_header
auth = ("%s %s:%s" % (auth_hdr, self._provider.access_key, b64_hmac))
boto.log.debug('Signature:\n%s' % auth)
headers['Authorization'] = auth
class HmacAuthV2Handler(AuthHandler, HmacKeys):
"""
Implements the simplified HMAC authorization used by CloudFront.
"""
capability = ['hmac-v2', 'cloudfront']
def __init__(self, host, config, provider):
AuthHandler.__init__(self, host, config, provider)
HmacKeys.__init__(self, host, config, provider)
self._hmac_256 = None
def update_provider(self, provider):
super(HmacAuthV2Handler, self).update_provider(provider)
self._hmac_256 = None
def add_auth(self, http_request, **kwargs):
headers = http_request.headers
if 'Date' not in headers:
headers['Date'] = formatdate(usegmt=True)
if self._provider.security_token:
key = self._provider.security_token_header
headers[key] = self._provider.security_token
b64_hmac = self.sign_string(headers['Date'])
auth_hdr = self._provider.auth_header
headers['Authorization'] = ("%s %s:%s" %
(auth_hdr,
self._provider.access_key, b64_hmac))
class HmacAuthV3Handler(AuthHandler, HmacKeys):
"""Implements the new Version 3 HMAC authorization used by Route53."""
capability = ['hmac-v3', 'route53', 'ses']
def __init__(self, host, config, provider):
AuthHandler.__init__(self, host, config, provider)
HmacKeys.__init__(self, host, config, provider)
def add_auth(self, http_request, **kwargs):
headers = http_request.headers
if 'Date' not in headers:
headers['Date'] = formatdate(usegmt=True)
if self._provider.security_token:
key = self._provider.security_token_header
headers[key] = self._provider.security_token
b64_hmac = self.sign_string(headers['Date'])
s = "AWS3-HTTPS AWSAccessKeyId=%s," % self._provider.access_key
s += "Algorithm=%s,Signature=%s" % (self.algorithm(), b64_hmac)
headers['X-Amzn-Authorization'] = s
class HmacAuthV3HTTPHandler(AuthHandler, HmacKeys):
"""
Implements the new Version 3 HMAC authorization used by DynamoDB.
"""
capability = ['hmac-v3-http']
def __init__(self, host, config, provider):
AuthHandler.__init__(self, host, config, provider)
HmacKeys.__init__(self, host, config, provider)
def headers_to_sign(self, http_request):
"""
Select the headers from the request that need to be included
in the StringToSign.
"""
headers_to_sign = {'Host': self.host}
for name, value in http_request.headers.items():
lname = name.lower()
if lname.startswith('x-amz'):
headers_to_sign[name] = value
return headers_to_sign
def canonical_headers(self, headers_to_sign):
"""
Return the headers that need to be included in the StringToSign
in their canonical form by converting all header keys to lower
case, sorting them in alphabetical order and then joining
them into a string, separated by newlines.
"""
l = sorted(['%s:%s' % (n.lower().strip(),
headers_to_sign[n].strip()) for n in headers_to_sign])
return '\n'.join(l)
def string_to_sign(self, http_request):
"""
Return the canonical StringToSign as well as a dict
containing the original version of all headers that
were included in the StringToSign.
"""
headers_to_sign = self.headers_to_sign(http_request)
canonical_headers = self.canonical_headers(headers_to_sign)
string_to_sign = '\n'.join([http_request.method,
http_request.auth_path,
'',
canonical_headers,
'',
http_request.body])
return string_to_sign, headers_to_sign
def add_auth(self, req, **kwargs):
"""
Add AWS3 authentication to a request.
:type req: :class`boto.connection.HTTPRequest`
:param req: The HTTPRequest object.
"""
# This could be a retry. Make sure the previous
# authorization header is removed first.
if 'X-Amzn-Authorization' in req.headers:
del req.headers['X-Amzn-Authorization']
req.headers['X-Amz-Date'] = formatdate(usegmt=True)
if self._provider.security_token:
req.headers['X-Amz-Security-Token'] = self._provider.security_token
string_to_sign, headers_to_sign = self.string_to_sign(req)
boto.log.debug('StringToSign:\n%s' % string_to_sign)
hash_value = sha256(string_to_sign.encode('utf-8')).digest()
b64_hmac = self.sign_string(hash_value)
s = "AWS3 AWSAccessKeyId=%s," % self._provider.access_key
s += "Algorithm=%s," % self.algorithm()
s += "SignedHeaders=%s," % ';'.join(headers_to_sign)
s += "Signature=%s" % b64_hmac
req.headers['X-Amzn-Authorization'] = s
class HmacAuthV4Handler(AuthHandler, HmacKeys):
"""
Implements the new Version 4 HMAC authorization.
"""
capability = ['hmac-v4']
def __init__(self, host, config, provider,
service_name=None, region_name=None):
AuthHandler.__init__(self, host, config, provider)
HmacKeys.__init__(self, host, config, provider)
# You can set the service_name and region_name to override the
# values which would otherwise come from the endpoint, e.g.
# <service>.<region>.amazonaws.com.
self.service_name = service_name
self.region_name = region_name
def _sign(self, key, msg, hex=False):
if not isinstance(key, bytes):
key = key.encode('utf-8')
if hex:
sig = hmac.new(key, msg.encode('utf-8'), sha256).hexdigest()
else:
sig = hmac.new(key, msg.encode('utf-8'), sha256).digest()
return sig
def headers_to_sign(self, http_request):
"""
Select the headers from the request that need to be included
in the StringToSign.
"""
host_header_value = self.host_header(self.host, http_request)
if http_request.headers.get('Host'):
host_header_value = http_request.headers['Host']
headers_to_sign = {'Host': host_header_value}
for name, value in http_request.headers.items():
lname = name.lower()
if lname.startswith('x-amz'):
if isinstance(value, bytes):
value = value.decode('utf-8')
headers_to_sign[name] = value
return headers_to_sign
def host_header(self, host, http_request):
port = http_request.port
secure = http_request.protocol == 'https'
if ((port == 80 and not secure) or (port == 443 and secure)):
return host
return '%s:%s' % (host, port)
def query_string(self, http_request):
parameter_names = sorted(http_request.params.keys())
pairs = []
for pname in parameter_names:
pval = boto.utils.get_utf8_value(http_request.params[pname])
pairs.append(urllib.parse.quote(pname, safe='') + '=' +
urllib.parse.quote(pval, safe='-_~'))
return '&'.join(pairs)
def canonical_query_string(self, http_request):
# POST requests pass parameters in through the
# http_request.body field.
if http_request.method == 'POST':
return ""
l = []
for param in sorted(http_request.params):
value = boto.utils.get_utf8_value(http_request.params[param])
l.append('%s=%s' % (urllib.parse.quote(param, safe='-_.~'),
urllib.parse.quote(value, safe='-_.~')))
return '&'.join(l)
def canonical_headers(self, headers_to_sign):
"""
Return the headers that need to be included in the StringToSign
in their canonical form by converting all header keys to lower
case, sorting them in alphabetical order and then joining
them into a string, separated by newlines.
"""
canonical = []
for header in headers_to_sign:
c_name = header.lower().strip()
raw_value = str(headers_to_sign[header])
if '"' in raw_value:
c_value = raw_value.strip()
else:
c_value = ' '.join(raw_value.strip().split())
canonical.append('%s:%s' % (c_name, c_value))
return '\n'.join(sorted(canonical))
def signed_headers(self, headers_to_sign):
l = ['%s' % n.lower().strip() for n in headers_to_sign]
l = sorted(l)
return ';'.join(l)
def canonical_uri(self, http_request):
path = http_request.auth_path
# Normalize the path
# in windows normpath('/') will be '\\' so we chane it back to '/'
normalized = posixpath.normpath(path).replace('\\', '/')
# Then urlencode whatever's left.
encoded = urllib.parse.quote(normalized)
if len(path) > 1 and path.endswith('/'):
encoded += '/'
return encoded
def payload(self, http_request):
body = http_request.body
# If the body is a file like object, we can use
# boto.utils.compute_hash, which will avoid reading
# the entire body into memory.
if hasattr(body, 'seek') and hasattr(body, 'read'):
return boto.utils.compute_hash(body, hash_algorithm=sha256)[0]
elif not isinstance(body, bytes):
body = body.encode('utf-8')
return sha256(body).hexdigest()
def canonical_request(self, http_request):
cr = [http_request.method.upper()]
cr.append(self.canonical_uri(http_request))
cr.append(self.canonical_query_string(http_request))
headers_to_sign = self.headers_to_sign(http_request)
cr.append(self.canonical_headers(headers_to_sign) + '\n')
cr.append(self.signed_headers(headers_to_sign))
cr.append(self.payload(http_request))
return '\n'.join(cr)
def scope(self, http_request):
scope = [self._provider.access_key]
scope.append(http_request.timestamp)
scope.append(http_request.region_name)
scope.append(http_request.service_name)
scope.append('aws4_request')
return '/'.join(scope)
def split_host_parts(self, host):
return host.split('.')
def determine_region_name(self, host):
parts = self.split_host_parts(host)
if self.region_name is not None:
region_name = self.region_name
elif len(parts) > 1:
if parts[1] == 'us-gov':
region_name = 'us-gov-west-1'
else:
if len(parts) == 3:
region_name = 'us-east-1'
else:
region_name = parts[1]
else:
region_name = parts[0]
return region_name
def determine_service_name(self, host):
parts = self.split_host_parts(host)
if self.service_name is not None:
service_name = self.service_name
else:
service_name = parts[0]
return service_name
def credential_scope(self, http_request):
scope = []
http_request.timestamp = http_request.headers['X-Amz-Date'][0:8]
scope.append(http_request.timestamp)
# The service_name and region_name either come from:
# * The service_name/region_name attrs or (if these values are None)
# * parsed from the endpoint <service>.<region>.amazonaws.com.
region_name = self.determine_region_name(http_request.host)
service_name = self.determine_service_name(http_request.host)
http_request.service_name = service_name
http_request.region_name = region_name
scope.append(http_request.region_name)
scope.append(http_request.service_name)
scope.append('aws4_request')
return '/'.join(scope)
def string_to_sign(self, http_request, canonical_request):
"""
Return the canonical StringToSign as well as a dict
containing the original version of all headers that
were included in the StringToSign.
"""
sts = ['AWS4-HMAC-SHA256']
sts.append(http_request.headers['X-Amz-Date'])
sts.append(self.credential_scope(http_request))
sts.append(sha256(canonical_request.encode('utf-8')).hexdigest())
return '\n'.join(sts)
def signature(self, http_request, string_to_sign):
key = self._provider.secret_key
k_date = self._sign(('AWS4' + key).encode('utf-8'),
http_request.timestamp)
k_region = self._sign(k_date, http_request.region_name)
k_service = self._sign(k_region, http_request.service_name)
k_signing = self._sign(k_service, 'aws4_request')
return self._sign(k_signing, string_to_sign, hex=True)
def add_auth(self, req, **kwargs):
"""
Add AWS4 authentication to a request.
:type req: :class`boto.connection.HTTPRequest`
:param req: The HTTPRequest object.
"""
# This could be a retry. Make sure the previous
# authorization header is removed first.
if 'X-Amzn-Authorization' in req.headers:
del req.headers['X-Amzn-Authorization']
now = datetime.datetime.utcnow()
req.headers['X-Amz-Date'] = now.strftime('%Y%m%dT%H%M%SZ')
if self._provider.security_token:
req.headers['X-Amz-Security-Token'] = self._provider.security_token
qs = self.query_string(req)
qs_to_post = qs
# We do not want to include any params that were mangled into
# the params if performing s3-sigv4 since it does not
# belong in the body of a post for some requests. Mangled
# refers to items in the query string URL being added to the
# http response params. However, these params get added to
# the body of the request, but the query string URL does not
# belong in the body of the request. ``unmangled_resp`` is the
# response that happened prior to the mangling. This ``unmangled_req``
# kwarg will only appear for s3-sigv4.
if 'unmangled_req' in kwargs:
qs_to_post = self.query_string(kwargs['unmangled_req'])
if qs_to_post and req.method == 'POST':
# Stash request parameters into post body
# before we generate the signature.
req.body = qs_to_post
req.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
req.headers['Content-Length'] = str(len(req.body))
else:
# Safe to modify req.path here since
# the signature will use req.auth_path.
req.path = req.path.split('?')[0]
if qs:
# Don't insert the '?' unless there's actually a query string
req.path = req.path + '?' + qs
canonical_request = self.canonical_request(req)
boto.log.debug('CanonicalRequest:\n%s' % canonical_request)
string_to_sign = self.string_to_sign(req, canonical_request)
boto.log.debug('StringToSign:\n%s' % string_to_sign)
signature = self.signature(req, string_to_sign)
boto.log.debug('Signature:\n%s' % signature)
headers_to_sign = self.headers_to_sign(req)
l = ['AWS4-HMAC-SHA256 Credential=%s' % self.scope(req)]
l.append('SignedHeaders=%s' % self.signed_headers(headers_to_sign))
l.append('Signature=%s' % signature)
req.headers['Authorization'] = ','.join(l)
class S3HmacAuthV4Handler(HmacAuthV4Handler, AuthHandler):
"""
Implements a variant of Version 4 HMAC authorization specific to S3.
"""
capability = ['hmac-v4-s3']
def __init__(self, *args, **kwargs):
super(S3HmacAuthV4Handler, self).__init__(*args, **kwargs)
if self.region_name:
self.region_name = self.clean_region_name(self.region_name)
def clean_region_name(self, region_name):
if region_name.startswith('s3-'):
return region_name[3:]
return region_name
def canonical_uri(self, http_request):
# S3 does **NOT** do path normalization that SigV4 typically does.
# Urlencode the path, **NOT** ``auth_path`` (because vhosting).
path = urllib.parse.urlparse(http_request.path)
# Because some quoting may have already been applied, let's back it out.
unquoted = urllib.parse.unquote(path.path)
# Requote, this time addressing all characters.
encoded = urllib.parse.quote(unquoted, safe='/~')
return encoded
def canonical_query_string(self, http_request):
# Note that we just do not return an empty string for
# POST request. Query strings in url are included in canonical
# query string.
l = []
for param in sorted(http_request.params):
value = boto.utils.get_utf8_value(http_request.params[param])
l.append('%s=%s' % (urllib.parse.quote(param, safe='-_.~'),
urllib.parse.quote(value, safe='-_.~')))
return '&'.join(l)
def host_header(self, host, http_request):
port = http_request.port
secure = http_request.protocol == 'https'
if ((port == 80 and not secure) or (port == 443 and secure)):
return http_request.host
return '%s:%s' % (http_request.host, port)
def headers_to_sign(self, http_request):
"""
Select the headers from the request that need to be included
in the StringToSign.
"""
host_header_value = self.host_header(self.host, http_request)
headers_to_sign = {'Host': host_header_value}
for name, value in http_request.headers.items():
lname = name.lower()
# Hooray for the only difference! The main SigV4 signer only does
# ``Host`` + ``x-amz-*``. But S3 wants pretty much everything
# signed, except for authorization itself.
if lname not in ['authorization']:
headers_to_sign[name] = value
return headers_to_sign
def determine_region_name(self, host):
# S3's different format(s) of representing region/service from the
# rest of AWS makes this hurt too.
#
# Possible domain formats:
# - s3.amazonaws.com (Classic)
# - s3-us-west-2.amazonaws.com (Specific region)
# - bukkit.s3.amazonaws.com (Vhosted Classic)
# - bukkit.s3-ap-northeast-1.amazonaws.com (Vhosted specific region)
# - s3.cn-north-1.amazonaws.com.cn - (Beijing region)
# - bukkit.s3.cn-north-1.amazonaws.com.cn - (Vhosted Beijing region)
parts = self.split_host_parts(host)
region_name = ''
if self.region_name is not None:
region_name = self.region_name
else:
# Classic URLs - s3-us-west-2.amazonaws.com
if len(parts) == 3:
region_name = self.clean_region_name(parts[0])
# Special-case for Classic.
if region_name == 's3':
region_name = 'us-east-1'
else:
# Iterate over the parts in reverse order.
for offset, part in enumerate(reversed(parts)):
part = part.lower()
# Look for the first thing starting with 's3'.
# Until there's a ``.s3`` TLD, we should be OK. :P
if part == 's3':
# If it's by itself, the region is the previous part.
region_name = parts[-offset]
# Unless it's Vhosted classic
if region_name == 'amazonaws':
region_name = 'us-east-1'
break
elif part.startswith('s3-'):
region_name = self.clean_region_name(part)
break
return region_name
def determine_service_name(self, host):
# Should this signing mechanism ever be used for anything else, this
# will fail. Consider utilizing the logic from the parent class should
# you find yourself here.
return 's3'
def mangle_path_and_params(self, req):
"""
Returns a copy of the request object with fixed ``auth_path/params``
attributes from the original.
"""
modified_req = copy.copy(req)
# Unlike the most other services, in S3, ``req.params`` isn't the only
# source of query string parameters.
# Because of the ``query_args``, we may already have a query string
# **ON** the ``path/auth_path``.
# Rip them apart, so the ``auth_path/params`` can be signed
# appropriately.
parsed_path = urllib.parse.urlparse(modified_req.auth_path)
modified_req.auth_path = parsed_path.path
if modified_req.params is None:
modified_req.params = {}
else:
# To keep the original request object untouched. We must make
# a copy of the params dictionary. Because the copy of the
# original request directly refers to the params dictionary
# of the original request.
copy_params = req.params.copy()
modified_req.params = copy_params
raw_qs = parsed_path.query
existing_qs = parse_qs_safe(
raw_qs,
keep_blank_values=True
)
# ``parse_qs`` will return lists. Don't do that unless there's a real,
# live list provided.
for key, value in existing_qs.items():
if isinstance(value, (list, tuple)):
if len(value) == 1:
existing_qs[key] = value[0]
modified_req.params.update(existing_qs)
return modified_req
def payload(self, http_request):
if http_request.headers.get('x-amz-content-sha256'):
return http_request.headers['x-amz-content-sha256']
return super(S3HmacAuthV4Handler, self).payload(http_request)
def add_auth(self, req, **kwargs):
if 'x-amz-content-sha256' not in req.headers:
if '_sha256' in req.headers:
req.headers['x-amz-content-sha256'] = req.headers.pop('_sha256')
else:
req.headers['x-amz-content-sha256'] = self.payload(req)
updated_req = self.mangle_path_and_params(req)
return super(S3HmacAuthV4Handler, self).add_auth(updated_req,
unmangled_req=req,
**kwargs)
def presign(self, req, expires, iso_date=None):
"""
Presign a request using SigV4 query params. Takes in an HTTP request
and an expiration time in seconds and returns a URL.
http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
"""
if iso_date is None:
iso_date = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
region = self.determine_region_name(req.host)
service = self.determine_service_name(req.host)
params = {
'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',
'X-Amz-Credential': '%s/%s/%s/%s/aws4_request' % (
self._provider.access_key,
iso_date[:8],
region,
service
),
'X-Amz-Date': iso_date,
'X-Amz-Expires': expires,
'X-Amz-SignedHeaders': 'host'
}
if self._provider.security_token:
params['X-Amz-Security-Token'] = self._provider.security_token
headers_to_sign = self.headers_to_sign(req)
l = sorted(['%s' % n.lower().strip() for n in headers_to_sign])
params['X-Amz-SignedHeaders'] = ';'.join(l)
req.params.update(params)
cr = self.canonical_request(req)
# We need to replace the payload SHA with a constant
cr = '\n'.join(cr.split('\n')[:-1]) + '\nUNSIGNED-PAYLOAD'
# Date header is expected for string_to_sign, but unused otherwise
req.headers['X-Amz-Date'] = iso_date
sts = self.string_to_sign(req, cr)
signature = self.signature(req, sts)
# Add signature to params now that we have it
req.params['X-Amz-Signature'] = signature
return '%s://%s%s?%s' % (req.protocol, req.host, req.path,
urllib.parse.urlencode(req.params))
class STSAnonHandler(AuthHandler):
"""
Provides pure query construction (no actual signing).
Used for making anonymous STS request for operations like
``assume_role_with_web_identity``.
"""
capability = ['sts-anon']
def _escape_value(self, value):
# This is changed from a previous version because this string is
# being passed to the query string and query strings must
# be url encoded. In particular STS requires the saml_response to
# be urlencoded when calling assume_role_with_saml.
return urllib.parse.quote(value)
def _build_query_string(self, params):
keys = list(params.keys())
keys.sort(key=lambda x: x.lower())
pairs = []
for key in keys:
val = boto.utils.get_utf8_value(params[key])
pairs.append(key + '=' + self._escape_value(val.decode('utf-8')))
return '&'.join(pairs)
def add_auth(self, http_request, **kwargs):
headers = http_request.headers
qs = self._build_query_string(
http_request.params
)
boto.log.debug('query_string in body: %s' % qs)
headers['Content-Type'] = 'application/x-www-form-urlencoded'
# This will be a POST so the query string should go into the body
# as opposed to being in the uri
http_request.body = qs
class QuerySignatureHelper(HmacKeys):
"""
Helper for Query signature based Auth handler.
Concrete sub class need to implement _calc_sigature method.
"""
def add_auth(self, http_request, **kwargs):
headers = http_request.headers
params = http_request.params
params['AWSAccessKeyId'] = self._provider.access_key
params['SignatureVersion'] = self.SignatureVersion
params['Timestamp'] = boto.utils.get_ts()
qs, signature = self._calc_signature(
http_request.params, http_request.method,
http_request.auth_path, http_request.host)
boto.log.debug('query_string: %s Signature: %s' % (qs, signature))
if http_request.method == 'POST':
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
http_request.body = qs + '&Signature=' + urllib.parse.quote_plus(signature)
http_request.headers['Content-Length'] = str(len(http_request.body))
else:
http_request.body = ''
# if this is a retried request, the qs from the previous try will
# already be there, we need to get rid of that and rebuild it
http_request.path = http_request.path.split('?')[0]
http_request.path = (http_request.path + '?' + qs +
'&Signature=' + urllib.parse.quote_plus(signature))
class QuerySignatureV0AuthHandler(QuerySignatureHelper, AuthHandler):
"""Provides Signature V0 Signing"""
SignatureVersion = 0
capability = ['sign-v0']
def _calc_signature(self, params, *args):
boto.log.debug('using _calc_signature_0')
hmac = self._get_hmac()
s = params['Action'] + params['Timestamp']
hmac.update(s.encode('utf-8'))
keys = params.keys()
keys.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
pairs = []
for key in keys:
val = boto.utils.get_utf8_value(params[key])
pairs.append(key + '=' + urllib.parse.quote(val))
qs = '&'.join(pairs)
return (qs, base64.b64encode(hmac.digest()))
class QuerySignatureV1AuthHandler(QuerySignatureHelper, AuthHandler):
"""
Provides Query Signature V1 Authentication.
"""
SignatureVersion = 1
capability = ['sign-v1', 'mturk']
def __init__(self, *args, **kw):
QuerySignatureHelper.__init__(self, *args, **kw)
AuthHandler.__init__(self, *args, **kw)
self._hmac_256 = None
def _calc_signature(self, params, *args):
boto.log.debug('using _calc_signature_1')
hmac = self._get_hmac()
keys = list(params.keys())
keys.sort(key=lambda x: x.lower())
pairs = []
for key in keys:
hmac.update(key.encode('utf-8'))
val = boto.utils.get_utf8_value(params[key])
hmac.update(val)
pairs.append(key + '=' + urllib.parse.quote(val))
qs = '&'.join(pairs)
return (qs, base64.b64encode(hmac.digest()))
class QuerySignatureV2AuthHandler(QuerySignatureHelper, AuthHandler):
"""Provides Query Signature V2 Authentication."""
SignatureVersion = 2
capability = ['sign-v2', 'ec2', 'ec2', 'emr', 'fps', 'ecs',
'sdb', 'iam', 'rds', 'sns', 'sqs', 'cloudformation']
def _calc_signature(self, params, verb, path, server_name):
boto.log.debug('using _calc_signature_2')
string_to_sign = '%s\n%s\n%s\n' % (verb, server_name.lower(), path)
hmac = self._get_hmac()
params['SignatureMethod'] = self.algorithm()
if self._provider.security_token:
params['SecurityToken'] = self._provider.security_token
keys = sorted(params.keys())
pairs = []
for key in keys:
val = boto.utils.get_utf8_value(params[key])
pairs.append(urllib.parse.quote(key, safe='') + '=' +
urllib.parse.quote(val, safe='-_~'))
qs = '&'.join(pairs)
boto.log.debug('query string: %s' % qs)
string_to_sign += qs
boto.log.debug('string_to_sign: %s' % string_to_sign)
hmac.update(string_to_sign.encode('utf-8'))
b64 = base64.b64encode(hmac.digest())
boto.log.debug('len(b64)=%d' % len(b64))
boto.log.debug('base64 encoded digest: %s' % b64)
return (qs, b64)
class POSTPathQSV2AuthHandler(QuerySignatureV2AuthHandler, AuthHandler):
"""
Query Signature V2 Authentication relocating signed query
into the path and allowing POST requests with Content-Types.
"""
capability = ['mws']
def add_auth(self, req, **kwargs):
req.params['AWSAccessKeyId'] = self._provider.access_key
req.params['SignatureVersion'] = self.SignatureVersion
req.params['Timestamp'] = boto.utils.get_ts()
qs, signature = self._calc_signature(req.params, req.method,
req.auth_path, req.host)
boto.log.debug('query_string: %s Signature: %s' % (qs, signature))
if req.method == 'POST':
req.headers['Content-Length'] = str(len(req.body))
req.headers['Content-Type'] = req.headers.get('Content-Type',
'text/plain')
else:
req.body = ''
# if this is a retried req, the qs from the previous try will
# already be there, we need to get rid of that and rebuild it
req.path = req.path.split('?')[0]
req.path = (req.path + '?' + qs +
'&Signature=' + urllib.parse.quote_plus(signature))
def get_auth_handler(host, config, provider, requested_capability=None):
"""Finds an AuthHandler that is ready to authenticate.
Lists through all the registered AuthHandlers to find one that is willing
to handle for the requested capabilities, config and provider.
:type host: string
:param host: The name of the host
:type config:
:param config:
:type provider:
:param provider:
Returns:
An implementation of AuthHandler.
Raises:
boto.exception.NoAuthHandlerFound
"""
ready_handlers = []
auth_handlers = boto.plugin.get_plugin(AuthHandler, requested_capability)
for handler in auth_handlers:
try:
ready_handlers.append(handler(host, config, provider))
except boto.auth_handler.NotReadyToAuthenticate:
pass
if not ready_handlers:
checked_handlers = auth_handlers
names = [handler.__name__ for handler in checked_handlers]
raise boto.exception.NoAuthHandlerFound(
'No handler was ready to authenticate. %d handlers were checked.'
' %s '
'Check your credentials' % (len(names), str(names)))
# We select the last ready auth handler that was loaded, to allow users to
# customize how auth works in environments where there are shared boto
# config files (e.g., /etc/boto.cfg and ~/.boto): The more general,
# system-wide shared configs should be loaded first, and the user's
# customizations loaded last. That way, for example, the system-wide
# config might include a plugin_directory that includes a service account
# auth plugin shared by all users of a Google Compute Engine instance
# (allowing sharing of non-user data between various services), and the
# user could override this with a .boto config that includes user-specific
# credentials (for access to user data).
return ready_handlers[-1]
def detect_potential_sigv4(func):
def _wrapper(self):
if os.environ.get('EC2_USE_SIGV4', False):
return ['hmac-v4']
if boto.config.get('ec2', 'use-sigv4', False):
return ['hmac-v4']
if hasattr(self, 'region'):
# If you're making changes here, you should also check
# ``boto/iam/connection.py``, as several things there are also
# endpoint-related.
if getattr(self.region, 'endpoint', ''):
for test in SIGV4_DETECT:
if test in self.region.endpoint:
return ['hmac-v4']
return func(self)
return _wrapper
def detect_potential_s3sigv4(func):
def _wrapper(self):
if os.environ.get('S3_USE_SIGV4', False):
return ['hmac-v4-s3']
if boto.config.get('s3', 'use-sigv4', False):
return ['hmac-v4-s3']
if not hasattr(self, 'host'):
return func(self)
# Keep the old explicit logic in case somebody was adding to the list.
for test in SIGV4_DETECT:
if test in self.host:
return ['hmac-v4-s3']
# Use default for non-aws hosts. Adding a url scheme is necessary if
# not present for urlparse to properly function.
host = self.host
if not self.host.startswith('http://') or \
self.host.startswith('https://'):
host = 'https://' + host
netloc = urlparse(host).netloc
if not (netloc.endswith('amazonaws.com') or
netloc.endswith('amazonaws.com.cn')):
return func(self)
# Use the default for the global endpoint
if netloc.endswith('s3.amazonaws.com'):
return func(self)
# Use the default for regions that support sigv4 and sigv2
if any(test in self.host for test in S3_AUTH_DETECT):
return func(self)
# Use anonymous if enabled.
if hasattr(self, 'anon') and self.anon:
return func(self)
# Default to sigv4 for aws hosts outside of regions that are known
# to support sigv2
return ['hmac-v4-s3']
return _wrapper
| [
"[email protected]"
] | |
e5ec008185718edf0ec86d4b41829b57366e0471 | e75751f44e1f38eede027143fd43b83606e4cb13 | /proyecto_final/apps/tasks/models.py | 51a4cd65c5845e55b67bf2ac51b036137c6e9f52 | [] | no_license | stephfz/exam_prep_cd-django | 8fef23c4ae1639c213b2d4a143fe1f5996d3b315 | 4633d65b4d86e29fff3f1c9fd09d690d9416f2f2 | refs/heads/master | 2023-05-10T14:55:15.249503 | 2021-05-25T16:11:38 | 2021-05-25T16:11:38 | 369,047,889 | 0 | 1 | null | 2021-06-15T00:31:31 | 2021-05-20T01:42:26 | Python | UTF-8 | Python | false | false | 2,168 | py | from django.db import models
import re
from django.core import validators
from django.core.exceptions import ValidationError
from django.contrib.auth.hashers import check_password, make_password
MIN_FIELD_LENGHT = 4
def ValidarLongitudMinima(cadena):
if len(cadena) < MIN_FIELD_LENGHT:
raise ValidationError(
f"{cadena} tiene deberia tener mas de {MIN_FIELD_LENGHT} caracteres"
)
def ValidarEmail(cadena):
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
if not EMAIL_REGEX.match(cadena):
raise ValidationError(
f'{cadena} no es un e-mail valido'
)
class User(models.Model):
name = models.CharField(max_length=45, blank = False, null =False, validators=[ValidarLongitudMinima])
lastname = models.CharField(max_length=45, blank = False, null = False , validators=[ValidarLongitudMinima])
email = models.CharField(max_length=50, validators=[ValidarEmail])
password = models.CharField(max_length=20, blank=False)
fecha_nacimiento = models.DateField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def save(self, *args, **kwargs):
self.password = make_password(self.password)
super(User, self).save(*args, **kwargs)
@staticmethod # User.authenticate('s', 'p')
#sin decorador, userObj = User() userObj.authenticate(s,s)
def authenticate(email, password):
results = User.objects.filter(email = email)
if len(results) == 1:
user = results[0]
bd_password = user.password
if check_password(password, bd_password):
return user
return None
class Task(models.Model):
name = models.CharField(max_length=45, blank = False, null =False, validators=[ValidarLongitudMinima])
due_date = models.DateField()
completed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, related_name="tasks", on_delete=models.CASCADE)
| [
"[email protected]"
] | |
4ad5a935680d32c5f47db945400a93b5d7813a54 | 7235051c8def972f3403bf10155e246c9c291c58 | /angola_erp/oficinas/doctype/ordem_de_reparacao/test_ordem_de_reparacao.py | 961f28830c5549ca52ea27afe99aed3a83b82258 | [
"MIT"
] | permissive | proenterprise/angola_erp | 8e79500ce7bcf499fc344948958ae8e8ab12f897 | 1c171362b132e567390cf702e6ebd72577297cdf | refs/heads/master | 2020-06-03T08:51:34.467041 | 2019-06-07T01:35:54 | 2019-06-07T01:35:54 | 191,514,859 | 1 | 0 | NOASSERTION | 2019-06-12T06:53:41 | 2019-06-12T06:53:41 | null | UTF-8 | Python | false | false | 221 | py | # -*- coding: utf-8 -*-
# Copyright (c) 2019, Helio de Jesus and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
class TestOrdemdeReparacao(unittest.TestCase):
pass
| [
"[email protected]"
] | |
73cd4fca469dc03c689a650f1c982b7519d64d32 | 7f8af0d2ffba9e8def7647afb5b070e9bfe20cf3 | /python/recoverVMjob/pyhesity.py | b3b62181e4b4dd6fa9cd78a1f94f59ccebd5d83e | [] | no_license | slasse/scripts | c47c4f86d347db35227c1869a85f01cf6b5af3f9 | 3de8ed983a4e7fbf9c9cea0bd3e05edf6fadc8b0 | refs/heads/master | 2023-03-19T15:15:27.751330 | 2021-03-15T12:48:36 | 2021-03-15T12:48:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,419 | py | #!/usr/bin/env python
"""Cohesity Python REST API Wrapper Module - v2.0.3 - Brian Seltzer - Jun 2019"""
##########################################################################################
# Change Log
# ==========
#
# 1.1 - added encrypted password storage - August 2017
# 1.2 - added date functions and private api access - April 2018
# 1.3 - simplified password encryption (weak!) to remove pycrypto dependency - April 2018
# 1.4 - improved error handling, added display function - May 2018
# 1.5 - added no content return - May 2018
# 1.6 - added dayDiff function - May 2018
# 1.7 - added password update feature - July 2018
# 1.8 - added support for None JSON returned - Jan 2019
# 1.9 - supressed HTTPS warning in Linux and PEP8 compliance - Feb 2019
# 1.9.1 - added support for interactive password prompt - Mar 2019
# 2.0 - python 3 compatibility - Mar 2019
# 2.0.1 - fixed date functions for pythion 3 - Mar 2019
# 2.0.2 - added file download - Jun 2019
# 2.0.3 - added silent error handling, apdrop(), apiconnected() - Jun 2019
#
##########################################################################################
# Install Notes
# =============
#
# Requires module: requests
# sudo easy_install requests
# - or -
# sudo yum install python-requests
#
##########################################################################################
from datetime import datetime
import time
import json
import requests
import getpass
import os
import urllib3
from os.path import expanduser
### ignore unsigned certificates
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
__all__ = ['apiauth', 'api', 'usecsToDate', 'dateToUsecs', 'timeAgo', 'dayDiff', 'display', 'fileDownload', 'apiconnected', 'apidrop']
APIROOT = ''
HEADER = ''
AUTHENTICATED = False
APIMETHODS = ['get', 'post', 'put', 'delete']
CONFIGDIR = expanduser("~") + '/.pyhesity'
### authentication
def apiauth(vip, username, domain='local', password=None, updatepw=None, prompt=None, quiet=None):
"""authentication function"""
global APIROOT
global HEADER
global AUTHENTICATED
APIROOT = 'https://' + vip + '/irisservices/api/v1'
creds = json.dumps({"domain": domain, "password": __getpassword(vip, username, password, domain, updatepw, prompt), "username": username})
HEADER = {'accept': 'application/json', 'content-type': 'application/json'}
url = APIROOT + '/public/accessTokens'
try:
response = requests.post(url, data=creds, headers=HEADER, verify=False)
if response != '':
if response.status_code == 201:
accessToken = response.json()['accessToken']
tokenType = response.json()['tokenType']
HEADER = {'accept': 'application/json',
'content-type': 'application/json',
'authorization': tokenType + ' ' + accessToken}
AUTHENTICATED = True
if(quiet is None):
print("Connected!")
else:
print(response.json()['message'])
except requests.exceptions.RequestException as e:
AUTHENTICATED = False
if quiet is None:
print(e)
def apiconnected():
return AUTHENTICATED
def apidrop():
global AUTHENTICATED
AUTHENTICATED = False
### api call function
def api(method, uri, data=None, quiet=None):
"""api call function"""
if AUTHENTICATED is False:
print 'Not Connected'
return None
response = ''
if uri[0] != '/':
uri = '/public/' + uri
if method in APIMETHODS:
try:
if method == 'get':
response = requests.get(APIROOT + uri, headers=HEADER, verify=False)
if method == 'post':
response = requests.post(APIROOT + uri, headers=HEADER, json=data, verify=False)
if method == 'put':
response = requests.put(APIROOT + uri, headers=HEADER, json=data, verify=False)
if method == 'delete':
response = requests.delete(APIROOT + uri, headers=HEADER, json=data, verify=False)
except requests.exceptions.RequestException as e:
if quiet is None:
print(e)
if isinstance(response, bool):
return ''
if response != '':
if response.status_code == 204:
return ''
if response.status_code == 404:
if quiet is None:
print('Invalid api call: ' + uri)
return None
responsejson = response.json()
if isinstance(responsejson, bool):
return ''
if responsejson is not None:
if 'errorCode' in responsejson:
if quiet is None:
if 'message' in responsejson:
print('\033[93m' + responsejson['errorCode'][1:] + ': ' + responsejson['message'] + '\033[0m')
else:
print(responsejson)
# return ''
# else:
return responsejson
else:
if quiet is None:
print("invalid api method")
### convert usecs to date
def usecsToDate(uedate):
"""Convert Unix Epoc Microseconds to Date String"""
uedate = int(uedate) / 1000000
return datetime.fromtimestamp(uedate).strftime('%Y-%m-%d %H:%M:%S')
### convert date to usecs
def dateToUsecs(datestring):
"""Convert Date String to Unix Epoc Microseconds"""
dt = datetime.strptime(datestring, "%Y-%m-%d %H:%M:%S")
# msecs = int(dt.strftime("%s"))
# usecs = msecs * 1000000
return int(time.mktime(dt.timetuple())) * 1000000
### convert date difference to usecs
def timeAgo(timedelta, timeunit):
"""Convert Date Difference to Unix Epoc Microseconds"""
nowsecs = int(time.mktime(datetime.now().timetuple())) * 1000000
secs = {'seconds': 1, 'sec': 1, 'secs': 1,
'minutes': 60, 'min': 60, 'mins': 60,
'hours': 3600, 'hour': 3600,
'days': 86400, 'day': 86400,
'weeks': 604800, 'week': 604800,
'months': 2628000, 'month': 2628000,
'years': 31536000, 'year': 31536000}
age = int(timedelta) * int(secs[timeunit.lower()]) * 1000000
return nowsecs - age
def dayDiff(newdate, olddate):
"""Return number of days between usec dates"""
return int(round((newdate - olddate) / float(86400000000)))
### get/store password for future runs
def __getpassword(vip, username, password, domain, updatepw, prompt):
"""get/set stored password"""
if password is not None:
return password
if prompt is not None:
pwd = getpass.getpass("Enter your password: ")
return pwd
pwpath = os.path.join(CONFIGDIR, 'lt.' + vip + '.' + username + '.' + domain)
if(updatepw is not None):
if(os.path.isfile(pwpath) is True):
os.remove(pwpath)
try:
pwdfile = open(pwpath, 'r')
pwd = ''.join(map(lambda num: chr(int(num) - 1), pwdfile.read().split(', ')))
pwdfile.close()
return pwd
except Exception:
pwd = getpass.getpass("Enter your password: ")
pwdfile = open(pwpath, 'w')
pwdfile.write(', '.join(str(char) for char in list(map(lambda char: ord(char) + 1, pwd))))
pwdfile.close()
return pwd
### display json/dictionary as formatted text
def display(myjson):
"""prettyprint dictionary"""
if(isinstance(myjson, list)):
# handle list of results
for result in myjson:
print(json.dumps(result, sort_keys=True, indent=4, separators=(', ', ': ')))
else:
# or handle single result
print(json.dumps(myjson, sort_keys=True, indent=4, separators=(', ', ': ')))
def fileDownload(uri, fileName):
"""download file"""
if AUTHENTICATED is False:
return "Not Connected"
if uri[0] != '/':
uri = '/public/' + uri
response = requests.get(APIROOT + uri, headers=HEADER, verify=False, stream=True)
f = open(fileName, 'wb')
for chunk in response.iter_content(chunk_size=1048576):
if chunk:
f.write(chunk)
f.close()
### create CONFIGDIR if it doesn't exist
if os.path.isdir(CONFIGDIR) is False:
os.mkdir(CONFIGDIR)
| [
"[email protected]"
] | |
6bf991a763e479c7e1cf1405735bd5a5b5bd5e30 | 14f455693213cae4506a01b7d0591e542c38de79 | /vendor/python-munin/plugins/aws_elb_requests | b846f9ba72903b7127b9edce58997a3bb6785c5e | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"X11-distribute-modifications-variant"
] | permissive | Cvalladares/Newsblur_Instrumented | f0b14d063759973330f202108a7eed3a29bcc033 | 4d6ee6aa9713879b1e2550ea5f2dbd819c73af12 | refs/heads/master | 2022-12-29T15:19:29.726455 | 2019-09-03T17:09:04 | 2019-09-03T17:09:04 | 206,130,022 | 0 | 0 | MIT | 2022-12-10T06:00:26 | 2019-09-03T17:07:04 | Python | UTF-8 | Python | false | false | 1,411 | #!/usr/bin/env python
import datetime
import os
import sys
import boto
from boto.ec2.cloudwatch import CloudWatchConnection
from vendor.munin import MuninPlugin
class AWSCloudWatchELBRequestsPlugin(MuninPlugin):
category = "AWS"
args = "-l 0 --base 1000"
vlabel = "Requests/sec"
info = "Show number of requests per second"
@property
def title(self):
return "Requests/sec for ELBs '%s'" % ",".join(self.elb_names)
@property
def fields(self):
return [
(n, dict(
label = "requests on ELB %s" % n,
type = "ABSOLUTE",
)) for n in self.elb_names
]
def __init__(self):
self.api_key = os.environ['AWS_KEY']
self.secret_key = os.environ['AWS_SECRET']
self.elb_names = (sys.argv[0].rsplit('_', 1)[-1] or os.environ['ELB_NAME']).split(',')
def execute(self):
minutes = 5
end_date = datetime.datetime.utcnow()
start_date = end_date - datetime.timedelta(minutes=minutes)
cw = CloudWatchConnection(self.api_key, self.secret_key)
return dict(
(n, sum(x['Sum'] for x in cw.get_metric_statistics(60, start_date, end_date, "RequestCount", "AWS/ELB", ["Sum"])))
for n in self.elb_names
)
if __name__ == "__main__":
AWSCloudWatchELBRequestsPlugin().run()
| [
"[email protected]"
] | ||
56912e1ee6caa7808dea0ddd13b2516f89961713 | 1c751c001357d23fe10e7a42490e3b76434dfa18 | /tools/py/ss.py | 06e26a8a47b602d63c9c69c1a72b29e584944444 | [] | no_license | pie-crust/etl | 995925199a71b299544bfac1ed8f504f16fbadc2 | 14b19b542eaa69b8679ce7df4d9a5d2720b3c5c7 | refs/heads/master | 2022-12-12T18:40:31.866907 | 2019-10-14T15:46:16 | 2019-10-14T15:46:16 | 215,082,544 | 0 | 0 | null | 2022-12-08T05:22:54 | 2019-10-14T15:43:04 | Python | UTF-8 | Python | false | false | 5,942 | py | import os, sys, io, csv, time, boto, gzip, math
import pyodbc
e=sys.exit
from pprint import pprint as pp
try:
from io import BytesIO as cStringIO
except:
try:
import cStringIO
except ImportError:
import io as cStringIO
def setKeytabCache(keyTabFile, keyTabPrincipal='',isVertica=True):
DEFAULT_DOMAIN = dbenvars.get('DEFAULT_DOMAIN'); assert DEFAULT_DOMAIN
if isVertica:
if keyTabFile != '':
verticakeyTabPrincipal = dbenvars.get('DB_SERVER') + '@' + DEFAULT_DOMAIN
os.system("kinit -k -t {} {}".format(keyTabFile, verticakeyTabPrincipal))
else:
message="keyTabFile {} not defined. Check environ variable KRB5_CLIENT_KTNAME".format(keyTabFile)
print 'ERROR', message
raise Exception(message)
else:
if keyTabFile != '' and keyTabPrincipal != '':
os.system("kinit -k -t {} {}".format(keyTabFile, keyTabPrincipal))
else:
message="keyTabFile {} or keyTabPrincipal not defined. Check environ variable KRB5_CLIENT_KTNAME".format(keyTabFile,keyTabPrincipal)
print 'ERROR', message
raise Exception(message)
encoding = 'utf-8'
write_file='_sqldata.csv'
stream = io.BytesIO()
#line_as_list = [line.encode(encoding) for line in line_as_list]
dbenvars={ 'DB_SERVER':'MDDATAMART1\MDDATAMART1', 'DEFAULT_DOMAIN':"homeGROUP.COM"}
def insert_data(data):
if 1:
stmt="INSERT INTO ACCOUNTINGBI.POSITION.DY_FiccDistribution (TransactionId,SettleDate,TransactionTypeCode,ClearedDate,CloseDate,CloseLeg, QuantityType,Quantity,AccountingDate,AsOfDateTime) values (?,?,?,?,?,?,?,?,?,?)"
#CAST(? AS DATE),CAST(? AS TIMESTAMP))
#tcur.setinputsizes([(pyodbc.SQL_WVARCHAR, 0, 0)])
tcur.fast_executemany = True
tcur.executemany(stmt, data)
e()
import datetime
def insert_data_2(data):
if 1:
stmt="INSERT INTO ACCOUNTINGBI.POSITION.DY_FiccDistribution (TransactionId,SettleDate,TransactionTypeCode,ClearedDate,CloseDate,CloseLeg, QuantityType,Quantity,AccountingDate,AsOfDateTime) values %s"
#tcur.setinputsizes([(pyodbc.SQL_WVARCHAR, 0, 0)])
#tcur.fast_executemany = True
out=[]
for row in data:
tmp=[str(x) if isinstance(x, datetime.date) else x for x in list(row)]
out.append('^'.join(["'1971-01-01'" if x==None else str(x) if isinstance(x, int) else "'%s'" % x for x in tmp]))
if out:
stmt="INSERT INTO ACCOUNTINGBI.POSITION.DY_FiccDistribution values (%s)" % '),\n('. join (out)
#print(stmt)
#e()
tcur.execute(stmt)
tcur.execute('commit')
print tcur.rowcount
def get_cnt(cur,tab):
cur.execute("SELECT count(1) from %s" % tab)
return cur.fetchone()[0]
rid=0
file_rows=25000 #16384
s3_rows=10000
def s3_upload_rows( bucket, s3_key, data, suffix='.gz' ):
rid=0
assert data
key = s3_key +suffix
use_rr=False
mpu = bucket.initiate_multipart_upload(key,reduced_redundancy=use_rr , metadata={'header':'test'})
stream = cStringIO()
compressor = gzip.GzipFile(fileobj=stream, mode='wb')
uploaded=0
#@timeit
def uploadPart(partCount=[0]):
global total_comp
partCount[0] += 1
stream.seek(0)
mpu.upload_part_from_file(stream, partCount[0])
total_comp +=stream.tell()
stream.seek(0)
stream.truncate()
#@timeit
def upload_to_s3():
global total_size,total_comp, rid
i=0
while True: # until EOF
i+=1
start_time = time.time()
chunk=''
#pp(data[0])
tmp=[]
if rid<len(data):
tmp= data[rid:][:s3_rows]
chunk=os.linesep.join(tmp)+os.linesep
#print rid, len(chunk), len(data)
rid +=len(tmp)
if not chunk: # EOF?
compressor.close()
uploadPart()
mpu.complete_upload()
break
else:
if sys.version_info[0] <3 and isinstance(chunk, unicode):
compressor.write(chunk.encode('utf-8'))
else:
compressor.write(chunk)
total_size +=len(chunk)
if stream.tell() > 10<<20: # min size for multipart upload is 5242880
uploadPart()
upload_to_s3()
return key
def convertSize( size):
if (size == 0):
return '0B'
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size,1024)))
p = math.pow(1024,i)
s = round(size/p,2)
return '%s %s' % (s,size_name[i])
tbl='DY_FICCDISTRIBUTION'
stg='POSITION_MODEL_STAGE_TEST_2'
sch='ACCOUNTINGBI.POSITION'
wrh='LOAD_WH'
def bulk_copy(cur, file_names):
global tbl, stg, sch, LOAD_WH
assert tbl and stg and sch and wrh
assert len(file_names)
files="','".join(file_names)
before=get_cnt(cur,tbl)
start_time=time.time()
if 1:
cmd="""
COPY INTO
%s
FROM '@%s/%s/'
FILES=('%s')
""" % (tbl,stg, 'DEMO', files)
if 1:
cur.execute("USE WAREHOUSE %s" % wrh)
cur.execute("USE SCHEMA %s" % sch)
try:
out=cur.execute(cmd)
except:
print(cmd)
raise
pp(out)
match=0
for id, row in enumerate(cur.fetchall()):
status, cnt = row[1:3]
print('%s: Insert #%d, status: [%s], row count: [%s]' % ('DEMO', id, status, cnt))
if status not in ['LOADED']:
match +=1
if match:
raise Exception('Unexpected load status')
cur.execute("commit")
after=get_cnt(cur,tbl)
print 'Rows inserted: ', after-before
sec=round((time.time() - start_time),2)
if __name__=="__main__":
if 1:
pyodbc.pooling = False
if 0:
keyTabFile=os.getenv('SSRSREPORTINGKEYTABFILE'); assert keyTabFile
keyTabPrincipal=os.getenv('DATASTAGINGSQLUSER'); assert keyTabPrincipal
#setKeytabCache(KEYTABFILE, os.getenv('DATASTAGINGSQLUSER'), None)
print ("kinit -k -t {} {}".format(keyTabFile, keyTabPrincipal))
#e()
os.system("kinit -k -t {} {}".format(keyTabFile, keyTabPrincipal))
connS='DSN=MDIR01;Database=DataStaging;Trusted_Connection=yes;POOL=0;App=FiccApi'
connS='DSN=MDDATAMART1;Database=Accounting;Trusted_Connection=yes;POOL=0;App=PositionReader'
sconn = pyodbc.connect(connS)
scur = sconn.cursor()
scur.arraysize=file_rows
#scur.setinputsizes([(pyodbc.SQL_WVARCHAR, 0, 0)])
if 1:
stmt="SELECT COUNT(*) from DY_FiccDistribution"
scur.execute(stmt)
| [
"[email protected]"
] | |
de2c57db3df051e2c71ce0c65bb11785838de827 | 51f6443116ef09aa91cca0ac91387c1ce9cb445a | /Curso_de_Python_ Curso_em_Video/PythonTeste/tuplasEx006.py | 7390994256a02018fcb186b5a803af55fff0bb07 | [
"MIT"
] | permissive | DanilooSilva/Cursos_de_Python | f449f75bc586f7cb5a7e43000583a83fff942e53 | 8f167a4c6e16f01601e23b6f107578aa1454472d | refs/heads/main | 2023-07-30T02:11:27.002831 | 2021-10-01T21:52:15 | 2021-10-01T21:52:15 | 331,683,041 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 266 | py | nomes = ('Danilo', 'Maria', 'Scarlett', 'Ohara', 'Allanys', 'Mel', 'Ze Russo')
for nome in nomes:
print(f'No nome {nome.upper()} temos as vogais', end=' ')
for vogais in nome:
if vogais in 'aAeEiIoOuU':
print(vogais, end=' ')
print() | [
"[email protected]"
] | |
16a554411b6c2550251a1231746f75bf6f984b71 | 7e806feae66ff77601a9f19dad4d4a4a8d774c88 | /server/api/migrations/0018_auto_20191110_1617.py | 4f9ad449149555622bb9070600a9cfa16d1eae8f | [] | no_license | admiralbolt/lorebook | bfc71fa39285a51bce70e0544aceca55db1132f4 | 6e5614796d4eccc696908053c5bc22950a8e6a8c | refs/heads/master | 2022-12-28T20:12:31.229136 | 2021-01-24T22:02:13 | 2021-01-24T22:02:13 | 215,921,497 | 1 | 0 | null | 2022-12-11T09:51:53 | 2019-10-18T02:03:34 | JavaScript | UTF-8 | Python | false | false | 588 | py | # Generated by Django 2.2.7 on 2019-11-10 16:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0017_auto_20191110_1610'),
]
operations = [
migrations.AlterField(
model_name='lore',
name='date_received',
field=models.DateField(blank=True, default=None, null=True),
),
migrations.AlterField(
model_name='lore',
name='date_written',
field=models.DateField(blank=True, default=None, null=True),
),
]
| [
"[email protected]"
] | |
ca8506bd95dca5bde283c3376e5c95788a982b55 | b7fab13642988c0e6535fb75ef6cb3548671d338 | /tools/ydk-py-master/openconfig/ydk/models/openconfig/ietf_diffserv_action.py | 293a2b138c9c7712e56f8bfd4726376e73af48fb | [
"Apache-2.0"
] | permissive | juancsosap/yangtraining | 6ad1b8cf89ecdebeef094e4238d1ee95f8eb0824 | 09d8bcc3827575a45cb8d5d27186042bf13ea451 | refs/heads/master | 2022-08-05T01:59:22.007845 | 2019-08-01T15:53:08 | 2019-08-01T15:53:08 | 200,079,665 | 0 | 1 | null | 2021-12-13T20:06:17 | 2019-08-01T15:54:15 | Python | UTF-8 | Python | false | false | 5,114 | py | """ ietf_diffserv_action
This module contains a collection of YANG definitions for configuring
diffserv specification implementations. Copyright (c) 2014 IETF
Trust and the persons identified as authors of the code. All rights
reserved. Redistribution and use in source and binary forms, with
or without modification, is permitted pursuant to, and subject
to the license terms contained in, the Simplified BSD License
set forth in Section 4.c of the IETF Trust's Legal Provisions
Relating to IETF Documents (http\://trustee.ietf.org/license\-info).
This version of this YANG module is part of RFC XXXX; see the
RFC itself for full legal notices.
"""
from ydk.entity_utils import get_relative_entity_path as _get_relative_entity_path
from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64
from ydk.filters import YFilter
from ydk.errors import YPYError, YPYModelError
from ydk.errors.error_handler import handle_type_error as _handle_type_error
class Meter(Identity):
"""
meter action type
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(Meter, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:meter")
class DropType(Identity):
"""
drop algorithm
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(DropType, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:drop-type")
class MinRate(Identity):
"""
min\-rate action type
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(MinRate, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:min-rate")
class Priority(Identity):
"""
priority action type
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(Priority, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:priority")
class MaxRate(Identity):
"""
max\-rate action type
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(MaxRate, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:max-rate")
class MeterActionType(Identity):
"""
action type in a meter
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(MeterActionType, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:meter-action-type")
class Marking(Identity):
"""
marking action type
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(Marking, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:marking")
class AlgorithmicDrop(Identity):
"""
algorithmic\-drop action type
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(AlgorithmicDrop, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:algorithmic-drop")
class MeterActionSet(Identity):
"""
mark action type in a meter
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(MeterActionSet, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:meter-action-set")
class RandomDetect(Identity):
"""
random detect algorithm
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(RandomDetect, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:random-detect")
class MeterActionDrop(Identity):
"""
drop action type in a meter
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(MeterActionDrop, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:meter-action-drop")
class AlwaysDrop(Identity):
"""
always drop algorithm
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(AlwaysDrop, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:always-drop")
class TailDrop(Identity):
"""
tail drop algorithm
"""
_prefix = 'action'
_revision = '2015-04-07'
def __init__(self):
super(TailDrop, self).__init__("urn:ietf:params:xml:ns:yang:ietf-diffserv-action", "ietf-diffserv-action", "ietf-diffserv-action:tail-drop")
| [
"[email protected]"
] | |
bbb370b912be9dd1d301c91a2df51194eab247b0 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02647/s288463755.py | 23233f7ddad32a580359992f962a8751dd84649d | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 458 | py | n, k = map(int, input().split())
alst = list(map(int, input().split()))
for _ in range(k):
tmp = [0 for _ in range(n + 1)]
for i, num in enumerate(alst):
min_ind = max(i - num, 0)
max_ind = min(i + num + 1, n)
tmp[min_ind] += 1
tmp[max_ind] -= 1
next_num = 0
for i, num in enumerate(tmp[:-1]):
next_num += num
alst[i] = next_num
if tmp[0] == n and tmp[-1] == -n:
break
print(*alst) | [
"[email protected]"
] | |
80423bb24b65dcb3c53ed7198486ab73d0f22546 | dce4a52986ddccea91fbf937bd89e0ae00b9d046 | /jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/dnn.py | 91eb3a57ac422be745273f7600e4e975db03d00b | [
"MIT"
] | permissive | Lab603/PicEncyclopedias | 54a641b106b7bb2d2f71b2dacef1e5dbeaf773a6 | 6d39eeb66c63a6f0f7895befc588c9eb1dd105f9 | refs/heads/master | 2022-11-11T13:35:32.781340 | 2018-03-15T05:53:07 | 2018-03-15T05:53:07 | 103,941,664 | 6 | 3 | MIT | 2022-10-28T05:31:37 | 2017-09-18T13:20:47 | C++ | UTF-8 | Python | false | false | 14,572 | py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Deep Neural Network estimators."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib import layers
from tensorflow.contrib.learn.python.learn.estimators import _sklearn
from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined
from tensorflow.contrib.learn.python.learn.estimators.base import DeprecatedMixin
from tensorflow.python.ops import nn
from tensorflow.python.platform import tf_logging as logging
# TODO(b/29580537): Replace with @changing decorator.
def _changing(feature_columns):
if feature_columns is not None:
return
logging.warn(
"Change warning: `feature_columns` will be required after 2016-08-01.\n"
"Instructions for updating:\n"
"Pass `tf.contrib.learn.infer_real_valued_columns_from_input(x)` or"
" `tf.contrib.learn.infer_real_valued_columns_from_input_fn(input_fn)`"
" as `feature_columns`, where `x` or `input_fn` is your argument to"
" `fit`, `evaluate`, or `predict`.")
class DNNClassifier(dnn_linear_combined.DNNLinearCombinedClassifier):
"""A classifier for TensorFlow DNN models.
Example:
```python
education = sparse_column_with_hash_bucket(column_name="education",
hash_bucket_size=1000)
occupation = sparse_column_with_hash_bucket(column_name="occupation",
hash_bucket_size=1000)
education_emb = embedding_column(sparse_id_column=education, dimension=16,
combiner="sum")
occupation_emb = embedding_column(sparse_id_column=occupation, dimension=16,
combiner="sum")
estimator = DNNClassifier(
feature_columns=[education_emb, occupation_emb],
hidden_units=[1024, 512, 256])
# Or estimator using the ProximalAdagradOptimizer optimizer with
# regularization.
estimator = DNNClassifier(
feature_columns=[education_emb, occupation_emb],
hidden_units=[1024, 512, 256],
optimizer=tf.train.ProximalAdagradOptimizer(
learning_rate=0.1,
l1_regularization_strength=0.001
))
# Input builders
def input_fn_train: # returns x, Y
pass
estimator.fit(input_fn=input_fn_train)
def input_fn_eval: # returns x, Y
pass
estimator.evaluate(input_fn=input_fn_eval)
estimator.predict(x=x)
```
Input of `fit` and `evaluate` should have following features,
otherwise there will be a `KeyError`:
* if `weight_column_name` is not `None`, a feature with
`key=weight_column_name` whose value is a `Tensor`.
* for each `column` in `feature_columns`:
- if `column` is a `SparseColumn`, a feature with `key=column.name`
whose `value` is a `SparseTensor`.
- if `column` is a `WeightedSparseColumn`, two features: the first with
`key` the id column name, the second with `key` the weight column name.
Both features' `value` must be a `SparseTensor`.
- if `column` is a `RealValuedColumn`, a feature with `key=column.name`
whose `value` is a `Tensor`.
- if `feature_columns` is `None`, then `input` must contain only real
valued `Tensor`.
"""
def __init__(self,
hidden_units,
feature_columns=None,
model_dir=None,
n_classes=2,
weight_column_name=None,
optimizer=None,
activation_fn=nn.relu,
dropout=None,
gradient_clip_norm=None,
enable_centered_bias=True,
config=None):
"""Initializes a DNNClassifier instance.
Args:
hidden_units: List of hidden units per layer. All layers are fully
connected. Ex. `[64, 32]` means first layer has 64 nodes and second one
has 32.
feature_columns: An iterable containing all the feature columns used by
the model. All items in the set should be instances of classes derived
from `FeatureColumn`.
model_dir: Directory to save model parameters, graph and etc. This can also
be used to load checkpoints from the directory into a estimator to continue
training a previously saved model.
n_classes: number of target classes. Default is binary classification.
It must be greater than 1.
weight_column_name: A string defining feature column name representing
weights. It is used to down weight or boost examples during training. It
will be multiplied by the loss of the example.
optimizer: An instance of `tf.Optimizer` used to train the model. If
`None`, will use an Adagrad optimizer.
activation_fn: Activation function applied to each layer. If `None`, will
use `tf.nn.relu`.
dropout: When not `None`, the probability we will drop out a given
coordinate.
gradient_clip_norm: A float > 0. If provided, gradients are
clipped to their global norm with this clipping ratio. See
tf.clip_by_global_norm for more details.
enable_centered_bias: A bool. If True, estimator will learn a centered
bias variable for each class. Rest of the model structure learns the
residual after centered bias.
config: `RunConfig` object to configure the runtime settings.
Returns:
A `DNNClassifier` estimator.
"""
_changing(feature_columns)
super(DNNClassifier, self).__init__(
model_dir=model_dir,
n_classes=n_classes,
weight_column_name=weight_column_name,
dnn_feature_columns=feature_columns,
dnn_optimizer=optimizer,
dnn_hidden_units=hidden_units,
dnn_activation_fn=activation_fn,
dnn_dropout=dropout,
gradient_clip_norm=gradient_clip_norm,
enable_centered_bias=enable_centered_bias,
config=config)
self.feature_columns = feature_columns
self.optimizer = optimizer
self.activation_fn = activation_fn
self.dropout = dropout
self.hidden_units = hidden_units
self._feature_columns_inferred = False
# TODO(b/29580537): Remove feature_columns inference.
def _validate_dnn_feature_columns(self, features):
if self._dnn_feature_columns is None:
self._dnn_feature_columns = layers.infer_real_valued_columns(features)
self._feature_columns_inferred = True
elif self._feature_columns_inferred:
this_dict = {c.name: c for c in self._dnn_feature_columns}
that_dict = {
c.name: c for c in layers.infer_real_valued_columns(features)
}
if this_dict != that_dict:
raise ValueError(
"Feature columns, expected %s, got %s.", (this_dict, that_dict))
def _get_train_ops(self, features, targets):
"""See base class."""
self._validate_dnn_feature_columns(features)
return super(DNNClassifier, self)._get_train_ops(features, targets)
def _get_eval_ops(self, features, targets, metrics=None):
self._validate_dnn_feature_columns(features)
return super(DNNClassifier, self)._get_eval_ops(features, targets, metrics)
def _get_predict_ops(self, features):
"""See base class."""
self._validate_dnn_feature_columns(features)
return super(DNNClassifier, self)._get_predict_ops(features)
@property
def weights_(self):
return self.dnn_weights_
@property
def bias_(self):
return self.dnn_bias_
class DNNRegressor(dnn_linear_combined.DNNLinearCombinedRegressor):
"""A regressor for TensorFlow DNN models.
Example:
```python
education = sparse_column_with_hash_bucket(column_name="education",
hash_bucket_size=1000)
occupation = sparse_column_with_hash_bucket(column_name="occupation",
hash_bucket_size=1000)
education_emb = embedding_column(sparse_id_column=education, dimension=16,
combiner="sum")
occupation_emb = embedding_column(sparse_id_column=occupation, dimension=16,
combiner="sum")
estimator = DNNRegressor(
feature_columns=[education_emb, occupation_emb],
hidden_units=[1024, 512, 256])
# Or estimator using the ProximalAdagradOptimizer optimizer with
# regularization.
estimator = DNNRegressor(
feature_columns=[education_emb, occupation_emb],
hidden_units=[1024, 512, 256],
optimizer=tf.train.ProximalAdagradOptimizer(
learning_rate=0.1,
l1_regularization_strength=0.001
))
# Input builders
def input_fn_train: # returns x, Y
pass
estimator.fit(input_fn=input_fn_train)
def input_fn_eval: # returns x, Y
pass
estimator.evaluate(input_fn=input_fn_eval)
estimator.predict(x=x)
```
Input of `fit` and `evaluate` should have following features,
otherwise there will be a `KeyError`:
* if `weight_column_name` is not `None`, a feature with
`key=weight_column_name` whose value is a `Tensor`.
* for each `column` in `feature_columns`:
- if `column` is a `SparseColumn`, a feature with `key=column.name`
whose `value` is a `SparseTensor`.
- if `column` is a `WeightedSparseColumn`, two features: the first with
`key` the id column name, the second with `key` the weight column name.
Both features' `value` must be a `SparseTensor`.
- if `column` is a `RealValuedColumn`, a feature with `key=column.name`
whose `value` is a `Tensor`.
- if `feature_columns` is `None`, then `input` must contain only real
valued `Tensor`.
"""
def __init__(self,
hidden_units,
feature_columns=None,
model_dir=None,
weight_column_name=None,
optimizer=None,
activation_fn=nn.relu,
dropout=None,
gradient_clip_norm=None,
enable_centered_bias=True,
config=None):
"""Initializes a `DNNRegressor` instance.
Args:
hidden_units: List of hidden units per layer. All layers are fully
connected. Ex. `[64, 32]` means first layer has 64 nodes and second one
has 32.
feature_columns: An iterable containing all the feature columns used by
the model. All items in the set should be instances of classes derived
from `FeatureColumn`.
model_dir: Directory to save model parameters, graph and etc. This can also
be used to load checkpoints from the directory into a estimator to continue
training a previously saved model.
weight_column_name: A string defining feature column name representing
weights. It is used to down weight or boost examples during training. It
will be multiplied by the loss of the example.
optimizer: An instance of `tf.Optimizer` used to train the model. If
`None`, will use an Adagrad optimizer.
activation_fn: Activation function applied to each layer. If `None`, will
use `tf.nn.relu`.
dropout: When not `None`, the probability we will drop out a given
coordinate.
gradient_clip_norm: A `float` > 0. If provided, gradients are clipped
to their global norm with this clipping ratio. See
`tf.clip_by_global_norm` for more details.
enable_centered_bias: A bool. If True, estimator will learn a centered
bias variable for each class. Rest of the model structure learns the
residual after centered bias.
config: `RunConfig` object to configure the runtime settings.
Returns:
A `DNNRegressor` estimator.
"""
_changing(feature_columns)
super(DNNRegressor, self).__init__(
model_dir=model_dir,
weight_column_name=weight_column_name,
dnn_feature_columns=feature_columns,
dnn_optimizer=optimizer,
dnn_hidden_units=hidden_units,
dnn_activation_fn=activation_fn,
dnn_dropout=dropout,
gradient_clip_norm=gradient_clip_norm,
enable_centered_bias=enable_centered_bias,
config=config)
self.feature_columns = feature_columns
self.optimizer = optimizer
self.activation_fn = activation_fn
self.dropout = dropout
self.hidden_units = hidden_units
self._feature_columns_inferred = False
# TODO(b/29580537): Remove feature_columns inference.
def _validate_dnn_feature_columns(self, features):
if self._dnn_feature_columns is None:
self._dnn_feature_columns = layers.infer_real_valued_columns(features)
self._feature_columns_inferred = True
elif self._feature_columns_inferred:
this_dict = {c.name: c for c in self._dnn_feature_columns}
that_dict = {
c.name: c for c in layers.infer_real_valued_columns(features)
}
if this_dict != that_dict:
raise ValueError(
"Feature columns, expected %s, got %s.", (this_dict, that_dict))
def _get_train_ops(self, features, targets):
"""See base class."""
self._validate_dnn_feature_columns(features)
return super(DNNRegressor, self)._get_train_ops(features, targets)
def _get_eval_ops(self, features, targets, metrics=None):
self._validate_dnn_feature_columns(features)
return super(DNNRegressor, self)._get_eval_ops(features, targets, metrics)
def _get_predict_ops(self, features):
"""See base class."""
self._validate_dnn_feature_columns(features)
return super(DNNRegressor, self)._get_predict_ops(features)
@property
def weights_(self):
return self.dnn_weights_
@property
def bias_(self):
return self.dnn_bias_
# TensorFlowDNNClassifier and TensorFlowDNNRegressor are deprecated.
class TensorFlowDNNClassifier(DeprecatedMixin, DNNClassifier,
_sklearn.ClassifierMixin):
pass
class TensorFlowDNNRegressor(DeprecatedMixin, DNNRegressor,
_sklearn.RegressorMixin):
pass
| [
"[email protected]"
] | |
93c1cfcec3bc7b70190f5138f4b8fa6e97a0ff16 | 2c989707a10e65c115eff8bbab0f51e510ccf096 | /PythonAdvance/1004pyad.py | 549187a006765355fd624a4fc305df2d8a6dfbba | [] | no_license | qiwsir/LearningWithLaoqi | 42041eccb40788f573485209c82aa5e00549408a | 4c5df8d6f7638ba2ef5ea68b3b169aa4065b43c2 | refs/heads/master | 2021-05-01T19:13:28.686452 | 2018-04-03T11:45:21 | 2018-04-03T11:45:21 | 121,016,704 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 722 | py | #coding:utf-8
class CountWord(dict):
def add(self, item, increment=1):
self[item] = increment + self.get(item, 0)
def sorts(self, reverse=False):
lst = [ (self[k], k) for k in self ]
lst.sort()
if reverse:
lst.reverse()
return [(v, k) for k, v in lst]
if __name__ == "__main__":
s = 'You raise me up, so I can stand on mountains,\
You raise me up to walk on stormy seas,\
I am strong when I am on your shoulders,\
You raise me up to more than I can be.'
words = s.split()
c = CountWord()
for word in words:
c.add(word)
print("从小到大")
print(c.sorts())
print("从大到小")
print(c.sorts(reverse=True)) | [
"[email protected]"
] | |
11815ae3e42c0042d8086fa2b5a0924fcb8f1998 | c29de305e7923acfa6a49a852d730ac607198446 | /ng_opcserver/ng_opcserver.py | 92a6b315f3ab0d29c4a9d2d8c3db8fd92811e7c7 | [
"MIT"
] | permissive | jmosbacher/ng-opcua | 712009cf50e2292abacbe4da269b934c5cfb3bcf | 3a3030a4230a4807b603262f19f66c99a27f75cc | refs/heads/master | 2022-12-16T21:18:02.518113 | 2020-09-24T14:18:31 | 2020-09-24T14:18:31 | 298,301,449 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,098 | py | # -*- coding: utf-8 -*-
from asyncua import ua, Server
from asyncua.common import node
from asyncua.common.methods import uamethod
from enum import IntEnum
import asyncio
import random
import logging
import time
# Not required just for convenience
# Because this example is based on EnumStrings, the values should start at 0 and no gaps are allowed.
class GeneratorState(IntEnum):
off = 0 # No communication
idle = 1 # Communication established, run settings not set
ready = 2 #run settings set, ready to start running
running = 3 # producing neutrons
# helper method to automatically create string list
def enum_to_stringlist(a_enum):
items = []
for value in a_enum:
items.append(ua.LocalizedText(value.name))
return items
logging.basicConfig(level=logging.INFO)
_logger = logging.getLogger('asyncua')
@uamethod
def func(parent, value):
return value * 2
async def serve_state(duration=None, frequency=1, debug=False):
server = Server()
await server.init()
server.set_endpoint("opc.tcp://0.0.0.0:4840/pulsedng/")
# setup our own namespace, not really necessary but should as spec
uri = "http://pulsedng.xenon-sc.lngs.infn.it"
nsidx = await server.register_namespace(uri)
# --------------------------------------------------------
# create custom enum data type
# --------------------------------------------------------
enums = await server.get_root_node().get_child(["0:Types", "0:DataTypes", "0:BaseDataType", "0:Enumeration"])
# 1.
# Create Enum Type
GeneratorState_type = await enums.add_data_type(nsidx, 'GeneratorState')
# Or convert the existing IntEnum GeneratorState
es = await GeneratorState_type.add_property(0, "EnumStrings" , enum_to_stringlist(GeneratorState))
await es.set_value_rank(1)
await es.set_array_dimensions([0])
# --------------------------------------------------------
# create object with enum variable
# --------------------------------------------------------
# get Objects node, this is where we should put our custom stuff
objects = server.get_objects_node()
# create object
myobj = await objects.add_object(nsidx, 'GeneratorObject')
# add var with as type the custom enumeration
GeneratorState_var = await myobj.add_variable(nsidx, 'GeneratorState2Var', GeneratorState.off, datatype = GeneratorState_type.nodeid)
await GeneratorState_var.set_writable()
await GeneratorState_var.set_value(GeneratorState.idle) # change value of enumeration
_logger.info('Starting server!')
async with server:
while True:
for state in GeneratorState:
await asyncio.sleep(2)
_logger.info('Set value of %s to %d', GeneratorState_var, state)
await GeneratorState_var.set_value(state)
def run_server(duration, frequency, debug):
loop = asyncio.get_event_loop()
loop.set_debug(debug)
loop.run_until_complete(serve_state(duration, frequency, debug))
loop.close()
if __name__ == "__main__":
run_server(100, 1, True)
| [
"[email protected]"
] | |
1825d7f8f1f9e66ba3b9c2f500fc015db148d39c | d60e74dae2c4bcef6bc7c8faea51dc6b245de42f | /package/inference/gauss/__init__.py | 06c798718238f04663af5ea96ccdbc202152a445 | [] | no_license | tloredo/inference | 37664ef62317f32ad5ab25c56ead1c49bfc91045 | 215de4e93b5cf79a1e9f380047b4db92bfeaf45c | refs/heads/master | 2021-09-09T06:24:16.690338 | 2021-09-01T21:03:52 | 2021-09-01T21:03:52 | 142,254,094 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 128 | py | """
gauss: Modules for inference tasks using the Gaussian (normal) distribution.
"""
from . import vecba
__all__ = ['vecba']
| [
"[email protected]"
] | |
99188776dea6e29905ef526b4d4799dabf999df0 | 3db75d71bbe018f92be0b1ae006f09f9045baa80 | /Gex.py | d07cde034f0d28fbc65eb120339123e5443c5f02 | [] | no_license | eo1989/SPXg | b5cc5eb702ee3e5eb174c0e2d2e6f080fa991976 | cee290d0de3483f4f52c1f01413129fafab364eb | refs/heads/master | 2022-12-15T23:07:00.379586 | 2020-09-18T22:21:56 | 2020-09-18T22:21:56 | 286,111,850 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,107 | py | # coding: utf-8
"""
Ernest Orlowski
[email protected]
"""
import datetime
import holidays
import numpy as np
import pandas as pd
import requests
import matplotlib.pyplot as plt
from .PyVol import (
blackDelta,
blackGamma,
blackIV,
blackScholesDelta,
blackScholesGamma,
blackScholesIV,
blackTheta,
blackVega,
)
plt.style.use("ggplot")
def TRTH_GEX(raw):
"""
Inputs:
'raw': raw pd DataFrame output from TRTH with 'RIC', 'Trade Date', 'OI', & 'IV' fields
Returns:
pd DataFrame of est. dealer gamma exposure by day
"""
letterToMonth = {
**dict.fromkeys(["a", "m"], 1),
**dict.fromkeys(["b", "n"], 2),
**dict.fromkeys(["c", "o"], 3),
**dict.fromkeys(["d", "p"], 4),
**dict.fromkeys(["e", "q"], 5),
**dict.fromkeys(["f", "r"], 6),
**dict.fromkeys(["g", "s"], 7),
**dict.fromkeys(["h", "t"], 8),
**dict.fromkeys(["i", "u"], 9),
**dict.fromkeys(["j", "v"], 10),
**dict.fromkeys(["k", "w"], 11),
**dict.fromkeys(["l", "x"], 12),
}
letterToFlag = {
**dict.fromkeys(list("abcdefghijkl"), "c"),
**dict.fromkeys(list("mnopqrstuvwx"), "p"),
}
df = raw.copy(deep=True)
df.set_index("Trade Date", drop=True, inplace=True)
df.index = pd.to_datetime(df.index, infer_datetime_format=True)
underlying = sorted(set(df["RIC"]))[0]
divisor = 10 if underlying in [".SPX", "SPXW"] else 100
df["F"] = df[df["RIC"] == underlying]["Last"]
df = df[df["RIC"] != underlying]
# remove options with minimal OI or w/ no bids
df = df[(df["Open Interest"] > 10) & (df["Bid"] > 0.5)].copy(deep=True)
df["Mid"] = np.mean(df[["Bid", "Ask"]], axis=1)
df["TRTH Tag"] = df["RIC"].str[-12]
df = df[df["TRTH Tag"].notnull()]
df["TRTH Tag"] = df["TRTH Tag"].str.lower()
df = df[df["TRTH Tag"].isin(list("abcdefghijklmnopqrstuvwx"))]
df["Month"] = df["TRTH Tag"].apply(lambda x: letterToMonth[x])
# retrieve day and year from TRTH RIC tag
df["Day"] = pd.to_numeric(df["RIC"].str[-11:-9], downcast="signed")
df["Year"] = pd.to_numeric(df["RIC"].str[-9:-7], downcast="signed") + 2000
df["Expiry"] = pd.to_datetime(
dict(year=df.Year, month=df.Month, day=df.Day), infer_datetime_format=True
)
us_holidays = holidays.UnitedStates(years=list(range(2000, 2030)))
us_hlist = list(us_holidays.keys())
A = [d.date() for d in df["Expiry"]]
B = [d.date() for d in df.index]
df["BDTE"] = np.busday_count(B, A, weekmask="1111100", holidays=us_hlist)
df = df[df["BDTE"] >= 1].copy(deep=True)
df["Flag"] = df["TRTH Tag"].apply(lambda x: letterToFlag[x])
# Retrieve strike price from TRTH RIC tag
df["Strike"] = pd.to_numeric(df["RIC"].str[-7:-2]) / divisor
if underlying in [".SPX", "SPXW"]:
df["IV"] = df.apply(blackIV, axis=1)
df["Delta"] = df.apply(blackDelta, axis=1)
df["Gamma"] = df.apply(blackGamma, axis=1)
else:
df["IV"] = df.apply(blackScholesIV, axis=1)
df["Delta"] = df.apply(blackScholesDelta, axis=1)
df["Gamma"] = df.apply(blackScholesGamma, axis=1)
df = df[(df["IV"] > 0.01) & (df["Iv"] < 2.0) & (np.abs(df["Delta"]) < 0.95)].copy(
deep=True
)
df["GEX"] = 10 ** -6 * (
-100 * (df["Flag"] == "p") * df["Open Interest"] * df["Gamma"] * df["F"]
+ 100 * (df["Flag"] == "c") * df["Open Interest"] * df["Gamma"] * df["F"]
)
if underlying in ["SPY", "GLD", "TLT"]:
df["GEX"] /= 10
df1 = df.pivot_table(values="GEX", index=df.index, aggfunc=np.sum)
del df1.index.name
return df1
def CBOE_GEX(filename, sens=True, plot=True, occ=False):
"""
Calculates dealer gamma exposure from latest CBOE option open interest data at http://www.cboe.com/delayedquote/quote-table-download
Parameters:
filename: string referencing path to local drive. Should be something like 'quotedata.dat'
sens: boolean; returns sensitivity if true, spot value if false
plot: boolean; returns plot if True, pandas series if False
occ: boolean; use Options Clearing Corporation open interest data if True, pull from CBOE file if False
"""
# Extract top rows of dataframe for latest spot price and date
raw = pd.read_table("SPX.dat")
spotF = float(raw.columns[0].split(",")[-2])
ticker = raw.columns[0].split(",")[0][1:4]
rf = 0.02
pltDate = raw.loc[0][0].split(",")[0][:11]
pltTime = raw.loc[0][0].split(",")[0][-8:]
dtDate = datetime.datetime.strptime(pltDate, "%b %d %Y").date()
# Extract dataframe for analysis
raw = pd.read_table("SPX.dat", sep=",", header=2)
c = raw.loc[:, :"Strike"].copy(deep=True)
c.columns = c.columns.str.replace("Calls", "ID")
p = (raw.loc[:, "Strike":].join(raw.loc[:, "Expiration Date"])).copy(deep=True)
p.columns = p.columns.str.replace("Puts", "ID")
p.columns = p.columns.str.replace(".1", "")
p = p[c.columns]
c["Flag"] = "c"
p["Flag"] = "p"
c["Expiry"] = pd.to_datetime(c["Expiration Date"], infer_datetime_format=True)
p["Expiry"] = pd.to_datetime(p["Expiration Date"], infer_datetime_format=True)
# Use requests to extract symbol data
if occ:
def getOCC(symbol):
url = "https://www.theocc.com/webapps/series-search"
s = requests.Session()
r = s.post(url, data={"symbolType": "U", "symbolId": symbol})
df = pd.read_html(r.content)[0]
df.columns = df.columns.droplevel()
df1 = df[df["Product Symbol"].isin(["SPX", "SPXW"])].copy(deep=True)
df1.reset_index(drop=True, inplace=True)
df1.rename(
columns={"Integer": "Strike", "Product Symbol": "Symbol"}, inplace=True
)
months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
monthNums = list(range(1, 13))
monthToNum = dict(zip(months, monthNums))
df1["Month"] = df1["Month"].apply(lambda x: monthToNum[x])
df1["Expiry"] = pd.to_datetime(
dict(year=df1.Year, month=df1.Month, day=df1.Day),
infer_datetime_format=True,
)
return df1
print("Getting OI data from OCC...")
df1 = getOCC("SPX")
def idToSymbol(strng):
if strng[3] == "W":
return strng[:4]
else:
return strng[:3]
c["Symbol"] = c["ID"].apply(idToSymbol)
p["Symbol"] = p["ID"].apply(idToSymbol)
c1 = pd.merg(
c,
df1.loc[:, ["Symbol", "Expiry", "Strike", "Call"]],
how="left",
on=["Symbol", "Expiry", "Strike"],
)
p1 = pd.merge(
p,
df1.loc[:, ["Symbol", "Expiry", "Strike", "Put"]],
how="left",
on=["Symbol", "Expiry", "Strike"],
)
c1.drop(["Open Int"], axis=1, inplace=True)
p1.drop(["Open Int"], axis=1, inplace=True)
c1.rename(columns={"Call": "Open Int"}, inplace=True)
p1.rename(columns={"Put": "Open Int"}, inplace=True)
df = c1.append(p1, ignore_index=True)
else:
df = c.append(p, ignore_index=True)
df = df[(df["ID"].str[-3] != "-") & (df["ID"].str[-4] != "-")].copy(deep=True)
for item in [
"Bid",
"Ask",
"Last Sale",
"IV",
"Delta",
"Gamma",
"Open Int",
"Strike",
]:
df[item] = pd.to_numeric(df[item], errors="coerce")
us_holidays = holidays.UnitedStates(years=list(range(2000, 2030)))
us_hlist = list(us_holidays.keys())
A = [d.date() for d in df["Expiry"]]
df["BDTE"] = np.busday_count(dtDate, A, weekmask="1111100", holidays=us_hlist)
df = df.loc[(df["Open Int"] > 10) & (df["Bid"] > 0.05) & (df["BDTE"] >= 1)].copy(
deep=True
)
print("Calculating Greeks...")
df["IV"] = df.apply(lambda x: blackIV(x, F=spotF, rf=rf), axis=1)
df = df[(df["IV"] > 0.01) & (df["IV"] < 2.0)].copy(deep=True)
df["Delta"] = df.apply(lambda x: blackDelta(x, F=spotF, rf=rf), axis=1)
df = df[np.abs(df["Delta"]) < 0.95].copy(deep=True)
if sens:
increment = 10 if ticker in ["SPX", "NDX"] else 1
nPoints = 20
Fs = list(
(
np.linspace(
start=spotF,
stop=spotF + increment * nPoints,
num=nPoints,
endpoint=False,
)
- increment * nPoints // 2
).astype(int)
)
for F in Fs:
df[str(F) + "_g"] = df.apply(lambda x: blackGamma(x, F=F, rf=rf), axis=1)
for F in Fs:
df[str(F) + "_GEX"] = 10 ** -6 * (
100 * F * (df["Flag"] == "c") * df[str(F) + "_g"] * df["Open Int"]
- 100 * F * (df["Flag"] == "p") * df[str(F) + "_g"] * df["Open Int"]
)
GEXs = [
(0.1 if ticker not in ["SPX", "NDX"] else 1)
* np.sum(df[str(F) + "_GEX"], axis=0)
for F in Fs
]
s = pd.Series(dict(zip(Fs, GEXs))).astype(int)
if plot:
fig, ax = plt.subplots(1, 1, figsize=(8, 5))
ax.plot(s, color="xkcd:red")
fig.suptitle(
ticker
+ " Dealer Gamma Exposure per Index Point (=0.1 ETF pt) as of "
+ pltDate
+ " "
+ pltTime,
fontsize=12,
weight="bold",
)
ax.set_ylabel("Dealer Gamma in $mm")
ax.yaxis.set_major_formatter(plt.FuncFormatter("{:,.0f}".format))
ax.axvline(x=spotF, color="xkcd:deep blue", linestyle=":")
zeroGEX = int(np.interp(x=0, xp=s.values, fp=s.index))
ax.axvline(x=zeroGEX, color="xkcd:black", linestyle="--")
ax.legend(labels=["SPX", "Last", "Zero GEX: " + str(zeroGEX)])
plt.xticks(rotation=30)
plt.show()
else:
return s
else:
df["Gamma"] = df.apply(lambda x: blackGamma(x, F=spotF, rf=rf), axis=1)
gams = 10 ** -6 * (
100 * spotF * (df["Flag"] == "c") * df["Gamma"] * df["Open Int"]
- 100 * spotF * (df["Flag"] == "p") * df["Gamma"] * df["Open Int"]
)
gam = (1 if ticker in ["SPX", "NDX"] else 0.1) * np.sum(gams, axis=0)
return gam
def CBOE_Greeks(filename, low, high, incr, expiry, field):
"""
Parameters:
filename: string referencing path to local drive. Should be something like 'quotedata.dat'
low, high, incr: integers describing low and high end of plot range, with increment
expiry: target option expiry in YYYY-MM-DD format
field: 'IV', 'Delta', 'Gamma', 'Vega', 'Gamma/Theta', 'Vega/Theta', or 'Theta/Mid'
Returns:
Plot of option Greeks by strike
"""
fields = [
"IV",
"Delta",
"Gamma",
"Vega",
"Theta",
"Gamma/Theta",
"Vega/Theta",
"Theta/Mid",
]
fltDigs = ["{:,." + str(x) + "f}" for x in [3, 2, 4, 2, 2, 4, 2, 4]]
fltDigDict = dict(zip(fields, fltDigs))
raw = pd.read_table("SPX.dat")
spotF = float(raw.columns[0].split(",")[1])
rf = 0.2
pltDate = raw.loc[0][0][:11]
pltTime = raw.loc[0][0][14:22]
dtDate = datetime.datetime.strptime(pltDate, "%b %d %Y").date()
# extract dataframe for analysis
raw = pd.read_table("SPX.dat", sep=",", header=2)
c = raw.loc[:, :"Strike"].copy(deep=True)
c.columns = c.columns.str.replace("Calls", "ID")
p = raw.loc[
:,
[
"Expiration Date",
"Strike",
"Puts",
"Last Sale.1",
"Net.1",
"Bid.1",
"Ask.1",
"Vol.1",
"IV.1",
"Delta.1",
"Gamma.1",
"Open Int.1",
],
].copy(deep=True)
p.columns = p.columns.str.replace("Puts", "ID")
p.columns = p.columns.str.replace(".1", "")
c["Flag"] = "c"
p["Flag"] = "p"
df = c.append(p, ignore_index=True, sort=True)
df = df[(df["ID"].str[-3] != "-") & (df["ID"].str[-4] != "-")].copy(deep=True)
for item in ["Bid", "Ask", "Last Sale"]:
df[item] = pd.to_numeric(df[item], errors="coerce")
df["Expiry"] = pd.to_datetime(df["Expiration Date"], infer_datetime_format=True)
us_holidays = holidays.UnitedStates(years=list(range(2000, 2030)))
us_hlist = list(us_holidays.keys())
A = [d.date() for d in df["Expiry"]]
df["BDTE"] = np.busday_count(dtDate, A, weekmask="1111100", holidays=us_hlist)
df = df.loc[(df["Open Int"] > 10) & (df["Bid"] > 0.05) & (df["BDTE"] >= 1)].copy(
deep=True
)
df["Mid"] = np.mean(df[["Bid", "Ask"]], axis=1)
df["IV"] = df.apply(lambda x: blackIV(x, F=spotF, rf=rf), axis=1)
df["Delta"] = df.apply(lambda x: blackDelta(x, F=spotF, rf=rf), axis=1)
df = df[np.abs(df["Delta"]) < 0.9].copy(deep=True)
if field in ["Gamma", "Gamma/Theta"]:
df["Gamma"] = df.apply(lambda x: blackGamma(x, F=spotF, rf=rf), axis=1)
if field in ["Vega", "Vega/Theta"]:
df["Vega"] = df.apply(lambda x: blackVega(x, F=spotF, rf=rf), axis=1)
if field in ["Theta", "Gamma/Theta", "Vega/Theta", "Theta/Mid"]:
df["Theta"] = df.apply(lambda x: blackTheta(x, F=spotF, rf=rf), axis=1)
if field == "Gamma/Theta":
df["Gamma/Theta"] = -df["Gamma"] / df["Theta"]
if field == "Vega/Theta":
df["Vega/Theta"] = -df["Vega"] / df["Theta"]
if field == "Theta/Mid":
df["Theta/Mid"] = df["Theta"] / df["Mid"]
pGreeks = (
df[
(df["Expiry"] == expiry)
& (df["Strike"].isin(range(low, high, incr)))
& (df["Flag"] == "p")
]
.groupby("Strike", axis=0)
.mean()[field]
)
cGreeks = (
df[
(df["Expiry"] == expiry)
& (df["Strike"].isin(range(low, high, incr)))
& (df["Flag"] == "c")
]
.groupby("Strike", axis=0)
.mean()[field]
)
fig, ax = plt.subplots(1, 1, figsize=(8, 5))
ax.plot(pGreeks, color="xkcd:red")
ax.plot(cGreeks, color="xkcd:dark green")
fig.suptitle(
"SPX "
+ expiry
+ " Expiry\n"
+ field
+ " by Strike as of "
+ pltDate
+ " "
+ pltTime,
fontsize=12,
weight="bold",
)
ax.set_ylabel(field)
ax.yaxis.set_major_formatter(plt.FuncFormatter(fltDigDict[field].format))
ax.axvline(x=spotF, color="xkcd:deep blue", linestyle=":")
ax.legend(labels=["Puts", "Calls", "Last"])
plt.xticks(rotation=30)
plt.show()
| [
"[email protected]"
] | |
9fbf579ea2337d37e373d71d47d4ef7a48cbef9a | c385cc6c6d69cadfe23664368e592f62e1e2d390 | /Tree/剑指 Offer 26. 树的子结构.py | 69ec6412c750ce3ed8248740308e3370c5da163a | [] | no_license | baketbek/AlgorithmPractice | c5801a374491a2d813fb7504a84aff6a50fc11ab | 5a412bef8602097af43a9134389d334e6f5fa671 | refs/heads/master | 2023-05-23T23:50:25.798825 | 2021-06-19T13:58:45 | 2021-06-19T13:58:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,026 | py | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
这么写有问题,因为recur函数里,如果AB值相等就继续对比,进入下一层后如果不相等,就跳过这层,
在下层对比A.left.left和B.left,是不对的,应该有一个不等了就从头开始,我这个写法跳了一层依然在对比当前的点而非回到头部
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
def recur(A, B):
if B is None:
return True
if A is None:
return False
if A.val == B.val:
return recur(A.left, B.left) and recur(A.right, B.right)
else:
return recur(A.left, B) or recur(A.right, B)
if A is None or B is None:
return False
return recur(A, B)
为啥要另外再定义一个recur?
这个题的思路是先遍历A的每个节点,然后以每个节点为根判断是否存在和B一致的子树
遍历A的每个节点要用外层定义的函数,判断是否存在子树另外def了recur
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
def recur(A, B):
if B is None:
return True
if A is None:
return False
if A.val!=B.val:
return False
return recur(A.left, B.left) and recur(A.right, B.right)
if A is None or B is None:
return False
return recur(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
执行用时:136 ms, 在所有 Python3 提交中击败了49.59%的用户
内存消耗:18.9 MB, 在所有 Python3 提交中击败了5.41%的用户
| [
"[email protected]"
] | |
eeba4aace767cd3308d15373a9beb81f35f19740 | 40195e6f86bf8620850f0c56e98eae5693e88277 | /coremltools/converters/mil/frontend/tensorflow/dialect_ops.py | 010408b706010866823ce1f7b6e8f10534350d69 | [
"MIT",
"BSD-3-Clause"
] | permissive | apple/coremltools | 009dfa7154d34cab8edcafa618e689e407521f50 | feed174188f7773631a3d574e1ff9889a135c986 | refs/heads/main | 2023-09-01T23:26:13.491955 | 2023-08-31T18:44:31 | 2023-08-31T18:44:31 | 95,862,535 | 3,742 | 705 | BSD-3-Clause | 2023-09-14T17:33:58 | 2017-06-30T07:39:02 | Python | UTF-8 | Python | false | false | 6,346 | py | # Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from coremltools.converters.mil.mil import Operation, types
from coremltools.converters.mil.mil.input_type import (DefaultInputs,
InputSpec,
TensorInputType)
from coremltools.converters.mil.mil.ops.registry import SSAOpRegistry
register_op = SSAOpRegistry.register_op
# This file contains the TF dialect of SSA. Briefly, these ops are only
# understandable in the TF frontend and not acceptable in the standard op set.
# No backend would support any of the op here. These ops exist to facilitate
# frontend SSA passes, but must be replaced with standard ops during SSA
# passes.
# All tf op must start with 'tf_' prefix.
#
# tf_make_list allows elem_shape to be unspecified. core op make_list does
# not allow that.
@register_op(namespace="tf")
class tf_make_list(Operation):
input_spec = InputSpec(
init_length=TensorInputType(optional=True, type_domain=types.int32),
dynamic_length=TensorInputType(optional=True, type_domain=types.bool),
elem_shape=TensorInputType(const=True, optional=True, type_domain=types.int32),
dtype=TensorInputType(const=True, optional=True, type_domain=types.str),
)
def default_inputs(self):
return DefaultInputs(
init_length=1,
dynamic_length=True,
dtype="fp32",
)
def type_inference(self):
init_length = self.init_length.val
if self.elem_shape is None or self.elem_shape.sym_val is None:
return types.list(
types.unknown,
init_length=init_length,
dynamic_length=self.dynamic_length.val,
)
builtin_dtype = types.string_to_builtin(self.dtype.val)
elem_type = types.tensor(builtin_dtype, self.elem_shape.sym_val)
return types.list(
elem_type, init_length=init_length, dynamic_length=self.dynamic_length.val
)
class TfLSTMBase(Operation):
"""
Common LSTM inputs for BlockLSTMCell and BlockLSTM.
"""
input_spec = InputSpec(
c_prev=TensorInputType(type_domain="T"), # [batch, hidden_dim]
h_prev=TensorInputType(type_domain="T"), # [batch, hidden_dim]
# weight: [input_dim + hidden_dim, 4*hidden_dim] (icfo layout)
weight=TensorInputType(const=True, type_domain="T"),
forget_bias=TensorInputType(const=True, optional=True, type_domain="T"),
# cell_clip == None implies not using cell clip
cell_clip=TensorInputType(const=True, optional=True, type_domain="T"),
# If use_peephole == False, weight_peep_* is ignored
use_peephole=TensorInputType(const=True, optional=True, type_domain=types.bool),
weight_peep_i=TensorInputType(const=True, optional=True, type_domain="T"), # [hidden_dim,]
weight_peep_f=TensorInputType(const=True, optional=True, type_domain="T"), # [hidden_dim,]
weight_peep_o=TensorInputType(const=True, optional=True, type_domain="T"), # [hidden_dim,]
bias=TensorInputType(const=True, type_domain="T"), # [4*hidden_dim] (icfo layout)
)
type_domains = {
"T": (types.fp16, types.fp32),
}
def default_inputs(self):
return DefaultInputs(
forget_bias=1.,
use_peephole=False,
)
def _check_peephole_weights(self):
# Check weight_peep_*
if self.use_peephole.val:
if (
self.weight_peep_i is None
or self.weight_peep_f is None
or self.weight_peep_o is None
):
raise ValueError(
"weight_peep_* cannot be None when use_peephole is True"
)
@register_op(namespace="tf")
class tf_lstm_block_cell(TfLSTMBase):
"""
xh = [x, h_prev]
[i, ci, f, o] = xh * w + b
f = f + forget_bias
if not use_peephole:
wci = wcf = wco = 0
i = sigmoid(cs_prev .* wci + i)
f = sigmoid(cs_prev .* wcf + f)
ci = tanh(ci)
cs = ci .* i + cs_prev .* f
cs = clip(cs, cell_clip)
o = sigmoid(cs * wco + o)
co = tanh(cs)
h = co .* o
"""
input_spec = (
InputSpec(x=TensorInputType(type_domain="T"),) + TfLSTMBase.input_spec # [batch, input_dim]
)
def __init__(self, **kwargs):
super(tf_lstm_block_cell, self).__init__(**kwargs)
def type_inference(self):
self._check_peephole_weights()
# all return shapes are [batch, hidden_dim]
ret_shape = self.c_prev.shape
dtype = self.x.dtype
# See
# https://www.tensorflow.org/api_docs/python/tf/raw_ops/LSTMBlockCell
# All returned shapes are [batch, hidden_dim]
return (
types.tensor(dtype, ret_shape), # i
types.tensor(dtype, ret_shape), # cs
types.tensor(dtype, ret_shape), # f
types.tensor(dtype, ret_shape), # o
types.tensor(dtype, ret_shape), # ci
types.tensor(dtype, ret_shape), # co
types.tensor(dtype, ret_shape),
) # h
@register_op(namespace="tf")
class tf_lstm_block(TfLSTMBase):
"""
Apply LSTM to an input sequence
"""
input_spec = (
InputSpec(
seq_len=TensorInputType(type_domain=types.int32), # int
x=TensorInputType(type_domain="T"), # [padded_len, batch, input_dim]
)
+ TfLSTMBase.input_spec
)
def type_inference(self):
self._check_peephole_weights()
padded_len = self.x.shape[0]
ret_shape = [padded_len] + list(self.c_prev.shape)
dtype = self.x.dtype
# All returned shapes are [padded_len, b, hidden_dim]
return (
types.tensor(dtype, ret_shape), # i
types.tensor(dtype, ret_shape), # cs
types.tensor(dtype, ret_shape), # f
types.tensor(dtype, ret_shape), # o
types.tensor(dtype, ret_shape), # ci
types.tensor(dtype, ret_shape), # co
types.tensor(dtype, ret_shape),
) # h
| [
"[email protected]"
] | |
e5dc0ac3c5d8a27863f7618f82a43abfc0a2d5f0 | 673f9b85708affe260b892a4eb3b1f6a0bd39d44 | /Botnets/App/App Web/PDG-env/lib/python3.6/site-packages/pandas/tests/series/methods/test_sort_index.py | 6fa4eeaee34c0360b902671615b82294e3eea970 | [
"MIT"
] | permissive | i2tResearch/Ciberseguridad_web | feee3fe299029bef96b158d173ce2d28ef1418e4 | e6cccba69335816442c515d65d9aedea9e7dc58b | refs/heads/master | 2023-07-06T00:43:51.126684 | 2023-06-26T00:53:53 | 2023-06-26T00:53:53 | 94,152,032 | 14 | 0 | MIT | 2023-09-04T02:53:29 | 2017-06-13T00:21:00 | Jupyter Notebook | UTF-8 | Python | false | false | 6,013 | py | import random
import numpy as np
import pytest
from pandas import IntervalIndex, MultiIndex, Series
import pandas._testing as tm
class TestSeriesSortIndex:
def test_sort_index(self, datetime_series):
rindex = list(datetime_series.index)
random.shuffle(rindex)
random_order = datetime_series.reindex(rindex)
sorted_series = random_order.sort_index()
tm.assert_series_equal(sorted_series, datetime_series)
# descending
sorted_series = random_order.sort_index(ascending=False)
tm.assert_series_equal(
sorted_series, datetime_series.reindex(datetime_series.index[::-1])
)
# compat on level
sorted_series = random_order.sort_index(level=0)
tm.assert_series_equal(sorted_series, datetime_series)
# compat on axis
sorted_series = random_order.sort_index(axis=0)
tm.assert_series_equal(sorted_series, datetime_series)
msg = "No axis named 1 for object type <class 'pandas.core.series.Series'>"
with pytest.raises(ValueError, match=msg):
random_order.sort_values(axis=1)
sorted_series = random_order.sort_index(level=0, axis=0)
tm.assert_series_equal(sorted_series, datetime_series)
with pytest.raises(ValueError, match=msg):
random_order.sort_index(level=0, axis=1)
def test_sort_index_inplace(self, datetime_series):
# For GH#11402
rindex = list(datetime_series.index)
random.shuffle(rindex)
# descending
random_order = datetime_series.reindex(rindex)
result = random_order.sort_index(ascending=False, inplace=True)
assert result is None
tm.assert_series_equal(
random_order, datetime_series.reindex(datetime_series.index[::-1])
)
# ascending
random_order = datetime_series.reindex(rindex)
result = random_order.sort_index(ascending=True, inplace=True)
assert result is None
tm.assert_series_equal(random_order, datetime_series)
def test_sort_index_level(self):
mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC"))
s = Series([1, 2], mi)
backwards = s.iloc[[1, 0]]
res = s.sort_index(level="A")
tm.assert_series_equal(backwards, res)
res = s.sort_index(level=["A", "B"])
tm.assert_series_equal(backwards, res)
res = s.sort_index(level="A", sort_remaining=False)
tm.assert_series_equal(s, res)
res = s.sort_index(level=["A", "B"], sort_remaining=False)
tm.assert_series_equal(s, res)
@pytest.mark.parametrize("level", ["A", 0]) # GH#21052
def test_sort_index_multiindex(self, level):
mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC"))
s = Series([1, 2], mi)
backwards = s.iloc[[1, 0]]
# implicit sort_remaining=True
res = s.sort_index(level=level)
tm.assert_series_equal(backwards, res)
# GH#13496
# sort has no effect without remaining lvls
res = s.sort_index(level=level, sort_remaining=False)
tm.assert_series_equal(s, res)
def test_sort_index_kind(self):
# GH#14444 & GH#13589: Add support for sort algo choosing
series = Series(index=[3, 2, 1, 4, 3], dtype=object)
expected_series = Series(index=[1, 2, 3, 3, 4], dtype=object)
index_sorted_series = series.sort_index(kind="mergesort")
tm.assert_series_equal(expected_series, index_sorted_series)
index_sorted_series = series.sort_index(kind="quicksort")
tm.assert_series_equal(expected_series, index_sorted_series)
index_sorted_series = series.sort_index(kind="heapsort")
tm.assert_series_equal(expected_series, index_sorted_series)
def test_sort_index_na_position(self):
series = Series(index=[3, 2, 1, 4, 3, np.nan], dtype=object)
expected_series_first = Series(index=[np.nan, 1, 2, 3, 3, 4], dtype=object)
index_sorted_series = series.sort_index(na_position="first")
tm.assert_series_equal(expected_series_first, index_sorted_series)
expected_series_last = Series(index=[1, 2, 3, 3, 4, np.nan], dtype=object)
index_sorted_series = series.sort_index(na_position="last")
tm.assert_series_equal(expected_series_last, index_sorted_series)
def test_sort_index_intervals(self):
s = Series(
[np.nan, 1, 2, 3], IntervalIndex.from_arrays([0, 1, 2, 3], [1, 2, 3, 4])
)
result = s.sort_index()
expected = s
tm.assert_series_equal(result, expected)
result = s.sort_index(ascending=False)
expected = Series(
[3, 2, 1, np.nan], IntervalIndex.from_arrays([3, 2, 1, 0], [4, 3, 2, 1])
)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("inplace", [True, False])
@pytest.mark.parametrize(
"original_list, sorted_list, ascending, ignore_index, output_index",
[
([2, 3, 6, 1], [2, 3, 6, 1], True, True, [0, 1, 2, 3]),
([2, 3, 6, 1], [2, 3, 6, 1], True, False, [0, 1, 2, 3]),
([2, 3, 6, 1], [1, 6, 3, 2], False, True, [0, 1, 2, 3]),
([2, 3, 6, 1], [1, 6, 3, 2], False, False, [3, 2, 1, 0]),
],
)
def test_sort_index_ignore_index(
self, inplace, original_list, sorted_list, ascending, ignore_index, output_index
):
# GH 30114
ser = Series(original_list)
expected = Series(sorted_list, index=output_index)
kwargs = {
"ascending": ascending,
"ignore_index": ignore_index,
"inplace": inplace,
}
if inplace:
result_ser = ser.copy()
result_ser.sort_index(**kwargs)
else:
result_ser = ser.sort_index(**kwargs)
tm.assert_series_equal(result_ser, expected)
tm.assert_series_equal(ser, Series(original_list))
| [
"[email protected]"
] | |
e25b321b40b2d26cad85048d4c5e8ef0c54588b3 | 34652a47355a8dbe9200db229a1bbc62619de364 | /Maths/Polynomials_Functions/Fast Fourier Transform.py | 3667f91c4d5ebbe4681f2f971d13bc638492912a | [] | no_license | btrif/Python_dev_repo | df34ab7066eab662a5c11467d390e067ab5bf0f8 | b4c81010a1476721cabc2621b17d92fead9314b4 | refs/heads/master | 2020-04-02T13:34:11.655162 | 2019-11-10T11:08:23 | 2019-11-10T11:08:23 | 154,487,015 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 954 | py | # Created by Bogdan Trif on 12-02-2018 , 11:31 AM.
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
N = 100
x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.8
def smooth(y, box_pts):
box = np.ones(box_pts)/box_pts
y_smooth = np.convolve(y, box, mode='same')
return y_smooth
w = scipy.fftpack.rfft(y)
f = scipy.fftpack.rfftfreq(N, x[1]-x[0])
spectrum = w**2
cutoff_idx = spectrum < (spectrum.max()/5)
w2 = w.copy()
w2[cutoff_idx] = 0
y2 = scipy.fftpack.irfft(w2)
fig = plt.figure(1, figsize=(18,10))
plt.title( ' FAST FOURIER TRANSFORM ')
ax = plt.subplot(111)
plt.plot(x, y2,'-' , linewidth = 2 ,label = 'Fast Fourier Transfrom' )
plt.plot( x, smooth(y, 3), 'r-' , lw=1 , label = 'smooth 3' )
plt.plot(x, smooth(y , 19 ), 'g-', lw=1 , label = 'smooth 19')
plt.legend(loc = 0)
plt.grid(which ='both')
plt.show()
plt.plot(x,spectrum, 'm-', lw=1 , label = 'spectrum')
plt.show() | [
"[email protected]"
] | |
f2816e0ff2de1b5a3f38f5624c01e9a11ee49dbe | edbb7a53633cba3b17aad4501d532d92159a1041 | /DirtyBits/wsgi.py | 455df86e3f0091903fefcae922e2e33c885fa158 | [] | no_license | himdhiman/DirtyBitsFinal | b5be2b87f85d15a7dce490692df9b6086aadbb74 | f3bd541426af7633a51ab36579cf61fe28a289dc | refs/heads/master | 2023-06-19T13:05:53.755343 | 2021-07-19T14:46:29 | 2021-07-19T14:46:29 | 385,284,977 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 170 | py | import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DirtyBits.settings')
application = get_wsgi_application()
| [
"[email protected]"
] | |
b9837e4481aada40e2b6e49cb7aa361f626d1e68 | 25ebc03b92df764ff0a6c70c14c2848a49fe1b0b | /daily/20180811/example_wsgiref/00hello.py | 5f59790ba629fefc3066cf9fc505d9309baaa971 | [] | no_license | podhmo/individual-sandbox | 18db414fafd061568d0d5e993b8f8069867dfcfb | cafee43b4cf51a321f4e2c3f9949ac53eece4b15 | refs/heads/master | 2023-07-23T07:06:57.944539 | 2023-07-09T11:45:53 | 2023-07-09T11:45:53 | 61,940,197 | 6 | 0 | null | 2022-10-19T05:01:17 | 2016-06-25T11:27:04 | Python | UTF-8 | Python | false | false | 421 | py | import json
from wsgiref.simple_server import make_server
def app(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'application/json')]
start_response(status, headers)
data = {
"msg": "hello world",
}
return [json.dumps(data).encode("utf-8")]
if __name__ == "__main__":
port = 5000
with make_server('', port, app) as httpd:
httpd.serve_forever()
| [
"[email protected]"
] | |
7fce08c60328e65c1c9c8a5d15b2b979c59657a4 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_103/ch34_2020_03_30_12_51_14_514066.py | b02ea9ff387824b0e5bcc10b0ac45bf455ddf9a1 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 367 | py | def eh_primo(x):
if x%2==0:
return False
elif x%2!=0:
y=3
if x%y==0:
y+=2
return False
elif x==1 or x==0:
return False
elif x==2:
return True
else:
return True
def maior_primo_menor_que(n):
while x<=n:
if n%x==0:
return x
else:
return -1
| [
"[email protected]"
] | |
1884af8f4634d7ebb0c4640f69361692cd0c7867 | 2ba46d8b7ac3538619b074b50bad126867a2c27c | /src/zojax/messaging/browser/breadcrumb.py | df1c4095fb87a19689e3695a70458dccbadea7d9 | [
"ZPL-2.1"
] | permissive | Zojax/zojax.messaging | 2baca5eb4d2d8b3bd23462f6d216925b9ff4cc23 | 7d6c4216763a93ae41251d7d4224c83654806339 | refs/heads/master | 2016-09-06T11:41:41.037505 | 2011-12-16T07:18:52 | 2011-12-16T07:18:52 | 2,026,384 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 989 | py | ##############################################################################
#
# Copyright (c) 2009 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" custom IBreadcrumb implementation for IMessageStorage
$Id$
"""
from zope import interface, component
from z3c.breadcrumb.browser import GenericBreadcrumb
from zojax.messaging.interfaces import _, IMessageStorage
class MessagesBreadcrumb(GenericBreadcrumb):
component.adapts(IMessageStorage, interface.Interface)
name = _(u'My messages')
| [
"[email protected]"
] | |
455590a886a1e5acccb85548fbd3af500d74f358 | 73abb3e522c93f1d0d0b93035b034a9f5b8e9867 | /kevlar/cli/localize.py | e451ae7003db0e55ac891f9dba10c131e49506aa | [
"MIT"
] | permissive | jchow32/kevlar | 4caa3fae43857e30a527871b33bce4b30941e265 | 59bb409407b08011e86fd0a1198584cb4d3d5998 | refs/heads/master | 2021-05-05T15:14:23.071710 | 2018-01-11T20:52:54 | 2018-01-11T20:52:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,828 | py | #!/usr/bin/env python
#
# -----------------------------------------------------------------------------
# Copyright (c) 2017 The Regents of the University of California
#
# This file is part of kevlar (http://github.com/dib-lab/kevlar) and is
# licensed under the MIT license: see LICENSE.
# -----------------------------------------------------------------------------
def subparser(subparsers):
"""Define the `kevlar localize` command-line interface."""
desc = """\
Given a reference genome and a contig (or set of contigs) assembled from
variant-related reads, retrieve the portion of the reference genome
corresponding to the variant. NOTE: this command relies on the `bwa`
program being in the PATH environmental variable.
"""
subparser = subparsers.add_parser('localize', description=desc)
subparser.add_argument('-x', '--max-diff', type=int, metavar='X',
default=10000, help='span of all k-mer starting '
'positions should not exceed X bp; default is '
'10000 (10 kb)')
subparser.add_argument('-d', '--delta', type=int, metavar='D',
default=25, help='retrieve the genomic interval '
'from the reference by extending beyond the span '
'of all k-mer starting positions by D bp')
subparser.add_argument('-o', '--out', metavar='FILE', default='-',
help='output file; default is terminal (stdout)')
subparser.add_argument('-k', '--ksize', type=int, metavar='K', default=31,
help='k-mer size; default is 31')
subparser.add_argument('contigs', help='assembled reads in Fasta format')
subparser.add_argument('refr', help='BWA indexed reference genome')
| [
"[email protected]"
] | |
cb91a4068110a5c6fd0628653fcaba5ac636754d | 6147d3da9c7f31a658f13892de457ed5a9314b22 | /linked_list/python/nth_from_last.py | 314466ee9a99cf03f7eff6af1b33c26300b7d3ec | [] | no_license | ashish-bisht/must_do_geeks_for_geeks | 17ba77608eb2d24cf4adb217c8e5a65980e85609 | 7ee5711c4438660db78916cf876c831259109ecc | refs/heads/master | 2023-02-11T22:37:03.302401 | 2021-01-03T05:53:03 | 2021-01-03T05:53:03 | 320,353,079 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 618 | py | class Node:
def __init__(self, val):
self.val = val
self.next = None
def nth_from_last(head, n):
slow = fast = head
while n > 0 and fast:
fast = fast.next
n -= 1
if n > 0 and not fast:
return "List ni hai bhai"
if not fast:
return head.val
while fast:
fast = fast.next
slow = slow.next
return slow.val
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
print(nth_from_last(head, 2))
print(nth_from_last(head, 5))
print(nth_from_last(head, 6))
| [
"[email protected]"
] | |
2e786f5af1ea5a3664be4e996d7a6b8e922d57c1 | 6c6f439b6777ba08f50de3a84cb236b9506a3216 | /Chapitre_5/tkinter_3.py | 74465851f2c1d2fff4858135861b6ba802f5f1dc | [] | no_license | badiskasmi/py-rasp-2e-edition | 2b87fcd4c3df4ae7ddbb3012c961d7c4fec1450c | c83fe620b6c61e7697af1b4e67a0fc71c5b99a9d | refs/heads/master | 2023-04-09T09:05:22.054570 | 2018-12-27T19:40:46 | 2018-12-27T19:40:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 480 | py | #!/usr/bin/env python3
from tkinter import Tk
LARGEUR = 400
HAUTEUR = 300
def main():
fenetre = Tk()
largeur_div = (fenetre.winfo_screenwidth() - LARGEUR) // 2
hauteur_div = (fenetre.winfo_screenheight() - HAUTEUR) // 2
dimensions = '{f_x}x{f_y}+{p_x}+{p_y}'.format(
f_x=LARGEUR,
f_y=HAUTEUR,
p_x=largeur_div,
p_y=hauteur_div
)
fenetre.geometry(dimensions)
fenetre.mainloop()
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
16a912b2fce7051d68803fddfac2d2466e9eec03 | 2a4cdd62600c95b9a52e198801a042ad77163077 | /forward/common/validate/validate_code.py | 7e52b250ca0530fd242be2afc6be7bcbdec1406b | [] | no_license | thm-tech/forward | 2c0bb004d14ea6ab807e526a1fa88c61e80c80e4 | 01ca49387754d38717f8cc07fd27127edb035b87 | refs/heads/master | 2021-01-10T02:34:35.098761 | 2015-12-08T03:29:47 | 2015-12-08T03:29:47 | 46,783,502 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,259 | py | # -*- encoding: utf-8 -*-
import random
import tempfile
import os
pp = os.path.dirname(os.path.realpath(__file__))
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from forward.common.tools import pathin
_letter_cases = "abcdefghjkmnpqrstuvwxy" # 小写字母,去除可能干扰的i,l,o,z
_upper_cases = _letter_cases.upper() # 大写字母
_numbers = ''.join(map(str, range(3, 10))) # 数字
init_chars = ''.join((_numbers)) + _letter_cases
def create_validate_code(size=(120, 30),
chars=init_chars,
img_type="GIF",
mode="RGB",
bg_color=(255, 255, 255),
fg_color=(0, 0, 255),
font_size=18,
font_type=pathin('./consola.ttf'),
length=4,
draw_lines=True,
n_line=(1, 2),
draw_points=True,
point_chance=2):
"""
@todo: 生成验证码图片
@param size: 图片的大小,格式(宽,高),默认为(120, 30)
@param chars: 允许的字符集合,格式字符串
@param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG
@param mode: 图片模式,默认为RGB
@param bg_color: 背景颜色,默认为白色
@param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
@param font_size: 验证码字体大小
@param font_type: 验证码字体,默认为 consola.ttf
@param length: 验证码字符个数
@param draw_lines: 是否划干扰线
@param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
@param draw_points: 是否画干扰点
@param point_chance: 干扰点出现的概率,大小范围[0, 100]
@return: [0]: PIL Image实例
@return: [1]: 验证码图片中的字符串
"""
width, height = size # 宽, 高
img = Image.new(mode, size, bg_color) # 创建图形
draw = ImageDraw.Draw(img) # 创建画笔
def get_chars():
'''生成给定长度的字符串,返回列表格式'''
return random.sample(chars, length)
def create_lines():
'''绘制干扰线'''
line_num = random.randint(*n_line) # 干扰线条数
for i in range(line_num):
# 起始点
begin = (random.randint(0, size[0]), random.randint(0, size[1]))
# 结束点
end = (random.randint(0, size[0]), random.randint(0, size[1]))
draw.line([begin, end], fill=(0, 0, 0))
def create_points():
'''绘制干扰点'''
chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]
for w in xrange(width):
for h in xrange(height):
tmp = random.randint(0, 100)
if tmp > 100 - chance:
draw.point((w, h), fill=(0, 0, 0))
def create_strs():
'''绘制验证码字符'''
c_chars = get_chars()
strs = ' %s ' % ' '.join(c_chars) # 每个字符前后以空格隔开
font = ImageFont.truetype(font_type, font_size)
font_width, font_height = font.getsize(strs)
draw.text(((width - font_width) / 3, (height - font_height) / 3),
strs, font=font, fill=fg_color)
return ''.join(c_chars)
if draw_lines:
create_lines()
if draw_points:
create_points()
strs = create_strs()
# 图形扭曲参数
params = [1 - float(random.randint(1, 2)) / 100,
0,
0,
0,
1 - float(random.randint(1, 10)) / 100,
float(random.randint(1, 2)) / 500,
0.001,
float(random.randint(1, 2)) / 500
]
img = img.transform(size, Image.PERSPECTIVE, params) # 创建扭曲
img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强(阈值更大)
return img, strs
if __name__ == "__main__":
code = create_validate_code()
code_img = code[0]
code_str = code[1]
print('validate_code', code_str)
code_img.save("validate.gif", "GIF") | [
"[email protected]"
] | |
15cfa42a3931153de4deb6f5d0e9b2313703dec8 | b2c24abff86b28ca8a495b3a3c3227f070737aa2 | /parlai/agents/memnn/memnn.py | 86dac774503cb843f3ae14ef9e0a596e9deace4b | [
"MIT"
] | permissive | hengyicai/AdaND | d5dda1b2fcd2abd17be6603de632f0515382b37b | 5e3fefb1cf40c42215a37246efc64958ae6db005 | refs/heads/master | 2023-09-01T07:38:49.076947 | 2020-10-19T04:58:00 | 2020-10-19T04:58:00 | 204,633,631 | 10 | 2 | MIT | 2023-08-11T19:52:23 | 2019-08-27T06:20:39 | Python | UTF-8 | Python | false | false | 8,249 | py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from functools import lru_cache
import torch
from parlai.core.torch_ranker_agent import TorchRankerAgent
from .modules import MemNN, opt_to_kwargs
class MemnnAgent(TorchRankerAgent):
"""Memory Network agent.
Tips:
- time features are necessary when memory order matters
- multiple hops allow multiple steps of reasoning, but also seem to make it
easier to learn to read the memories if you have at least two hops
- 'adam' seems to work very poorly compared to 'sgd' for hogwild training
"""
@staticmethod
def add_cmdline_args(argparser):
arg_group = argparser.add_argument_group('MemNN Arguments')
arg_group.add_argument(
'-esz',
'--embedding-size',
type=int,
default=128,
help='size of token embeddings',
)
arg_group.add_argument(
'-hops', '--hops', type=int, default=3, help='number of memory hops'
)
arg_group.add_argument(
'--memsize',
type=int,
default=32,
help='size of memory, set to 0 for "nomemnn" model which just '
'embeds query and candidates and picks most similar candidate',
)
arg_group.add_argument(
'-tf',
'--time-features',
type='bool',
default=True,
help='use time features for memory embeddings',
)
arg_group.add_argument(
'-pe',
'--position-encoding',
type='bool',
default=False,
help='use position encoding instead of bag of words embedding',
)
argparser.set_defaults(
split_lines=True, add_p1_after_newln=True, encode_candidate_vecs=True
)
TorchRankerAgent.add_cmdline_args(argparser)
MemnnAgent.dictionary_class().add_cmdline_args(argparser)
return arg_group
@staticmethod
def model_version():
"""
Return current version of this model, counting up from 0.
Models may not be backwards-compatible with older versions.
Version 1 split from version 0 on Sep 7, 2018.
To use version 0, use --model legacy:memnn:0
(legacy agent code is located in parlai/agents/legacy_agents).
"""
# TODO: Update date that Version 2 split and move version 1 to legacy
return 2
def __init__(self, opt, shared=None):
self.id = 'MemNN'
self.memsize = opt['memsize']
if self.memsize < 0:
self.memsize = 0
self.use_time_features = opt['time_features']
super().__init__(opt, shared)
def build_dictionary(self):
"""Add the time features to the dictionary before building the model."""
d = super().build_dictionary()
if self.use_time_features:
# add time features to dictionary before building the model
for i in range(self.memsize):
d[self._time_feature(i)] = 100000000 + i
return d
def build_model(self):
"""Build MemNN model."""
kwargs = opt_to_kwargs(self.opt)
return MemNN(
len(self.dict),
self.opt['embedding_size'],
padding_idx=self.NULL_IDX,
**kwargs,
)
def _score(self, output, cands):
if cands.dim() == 2:
return torch.matmul(output, cands.t())
elif cands.dim() == 3:
return torch.bmm(output.unsqueeze(1), cands.transpose(1, 2)).squeeze(1)
else:
raise RuntimeError(
'Unexpected candidate dimensions {}' ''.format(cands.dim())
)
def encode_candidates(self, padded_cands):
return self.model.answer_embedder(padded_cands)
def score_candidates(self, batch, cand_vecs, cand_encs=None):
mems = self._build_mems(batch.memory_vecs)
# Check for rows that have no non-null tokens
pad_mask = None
if mems is not None:
pad_mask = (mems != self.NULL_IDX).sum(dim=-1) == 0
if cand_encs is not None:
state, _ = self.model(batch.text_vec, mems, None, pad_mask)
else:
state, cand_encs = self.model(batch.text_vec, mems, cand_vecs, pad_mask)
scores = self._score(state, cand_encs)
return scores
@lru_cache(maxsize=None) # bounded by opt['memsize'], cache string concats
def _time_feature(self, i):
"""Return time feature token at specified index."""
return '__tf{}__'.format(i)
def vectorize(self, *args, **kwargs):
"""Override options in vectorize from parent."""
kwargs['add_start'] = False
kwargs['add_end'] = False
return super().vectorize(*args, **kwargs)
def batchify(self, obs_batch, sort=False):
"""Override so that we can add memories to the Batch object."""
batch = super().batchify(obs_batch, sort)
# get valid observations
valid_obs = [(i, ex) for i, ex in enumerate(obs_batch) if self.is_valid(ex)]
if len(valid_obs) == 0:
return batch
valid_inds, exs = zip(*valid_obs)
# get memories for the valid observations
mems = None
if any('memory_vecs' in ex for ex in exs):
mems = [ex.get('memory_vecs', None) for ex in exs]
batch.memory_vecs = mems
return batch
def _set_text_vec(self, obs, history, truncate):
"""Override from Torch Agent so that we can use memories."""
if 'text' not in obs:
return obs
if 'text_vec' not in obs:
# text vec is not precomputed, so we set it using the history
obs['full_text'] = history.get_history_str()
history_vecs = history.get_history_vec_list()
if len(history_vecs) > 0:
obs['memory_vecs'] = history_vecs[:-1]
obs['text_vec'] = history_vecs[-1]
else:
obs['memory_vecs'] = []
obs['text_vec'] = []
# check truncation
if 'text_vec' in obs:
truncated_vec = self._check_truncate(obs['text_vec'], truncate, True)
obs.force_set('text_vec', torch.LongTensor(truncated_vec))
if 'memory_vecs' in obs:
obs.force_set(
'memory_vecs',
[
torch.LongTensor(self._check_truncate(m, truncate, True))
for m in obs['memory_vecs']
],
)
return obs
def _build_mems(self, mems):
"""
Build memory tensors.
During building, will add time features to the memories if enabled.
:param mems:
list of length batchsize containing inner lists of 1D tensors
containing the individual memories for each row in the batch.
:returns:
3d padded tensor of memories (bsz x num_mems x seqlen)
"""
if mems is None:
return None
bsz = len(mems)
if bsz == 0:
return None
num_mems = max(len(mem) for mem in mems)
if num_mems == 0 or self.memsize <= 0:
return None
elif num_mems > self.memsize:
# truncate to memsize most recent memories
num_mems = self.memsize
mems = [mem[-self.memsize:] for mem in mems]
try:
seqlen = max(len(m) for mem in mems for m in mem)
if self.use_time_features:
seqlen += 1 # add time token to each sequence
except ValueError:
return None
padded = torch.LongTensor(bsz, num_mems, seqlen).fill_(0)
for i, mem in enumerate(mems):
tf_offset = len(mem) - 1
for j, m in enumerate(mem):
padded[i, j, : len(m)] = m
if self.use_time_features:
padded[i, j, -1] = self.dict[self._time_feature(tf_offset - j)]
if self.use_cuda:
padded = padded.cuda()
return padded
| [
"[email protected]"
] | |
90e1cd44b44697565e0e3671ecef51463c51e0e1 | 93d43b915b3853eac80975b6692ffed3b146c89f | /network/udp_client.py | d8c1ea926d68997d6e835ad861a700f808eecdb2 | [] | no_license | Killsan/python | 32ca8b4f1fa4a8a5d70ce6949d764938c37ff14d | 0c79a482ade3396309cbd055e996438b82dcd3b1 | refs/heads/master | 2023-06-14T21:44:29.933776 | 2021-07-13T18:28:39 | 2021-07-13T18:28:39 | 220,499,268 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 146 | py | import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(b'connected', ('127.0.0.1', 8888))
#(<ip>, <port>); (unix.sock)
| [
"[email protected]"
] | |
e3f392121a9ec6d09d8a3f65d4276958197c78ce | f07a42f652f46106dee4749277d41c302e2b7406 | /Data Set/bug-fixing-2/6717daf4a6e92aa49da486c4ffc06201b9fa4611-<test_realm_filter_events>-bug.py | 9fab8c660152c9383eb365c715984d751f7b4342 | [] | no_license | wsgan001/PyFPattern | e0fe06341cc5d51b3ad0fe29b84098d140ed54d1 | cc347e32745f99c0cd95e79a18ddacc4574d7faa | refs/heads/main | 2023-08-25T23:48:26.112133 | 2021-10-23T14:11:22 | 2021-10-23T14:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 570 | py |
def test_realm_filter_events(self) -> None:
schema_checker = self.check_events_dict([('type', equals('realm_filters')), ('realm_filters', check_list(None))])
events = self.do_test((lambda : do_add_realm_filter(self.user_profile.realm, '#(?P<id>[123])', 'https://realm.com/my_realm_filter/%(id)s')))
error = schema_checker('events[0]', events[0])
self.assert_on_error(error)
self.do_test((lambda : do_remove_realm_filter(self.user_profile.realm, '#(?P<id>[123])')))
error = schema_checker('events[0]', events[0])
self.assert_on_error(error)
| [
"[email protected]"
] | |
06ae6fcfbeaf3ef19671198d81850f9474d6b46b | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_248/ch76_2020_04_12_20_54_45_523952.py | 3764fea605aa8ea89077073aeb44632ac15ffc01 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 200 | py | def aniversariantes_de_setembro(dicionario):
dicionario={}
for k,v in dicionario.items():
if v[3]=="0" and v[4]=="9":
dicionario[k]=v
i+=1
return dicionario | [
"[email protected]"
] | |
66c9f34aaa92f1e8904248550a68645732122510 | 52194c0bcd56d35a883139349a5ad8637633d725 | /manage.py | 3bb0472906c174a519ffa3ecee58c951b2ffc17b | [] | no_license | cgpalmer/ms4 | d9a9207a03870672a3f72b3e990bceb59a1fa36b | 5a116270c44e8edcbd41128a2416687cd398e529 | refs/heads/master | 2023-02-23T05:45:11.354116 | 2021-01-30T11:56:38 | 2021-01-30T11:56:38 | 299,755,148 | 1 | 2 | null | null | null | null | UTF-8 | Python | false | false | 666 | py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hiddenGems.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
f0137ab6e63d6c82e9a78ca38a0288de3400eee5 | 3b7c8c718588f1ad34dbd6fb38f6566f3e1ad857 | /src/binwalk/modules/extractor.py | c86fc1a83dc50dd92a77304a0f01b0901147753e | [
"MIT"
] | permissive | westnorth/binwalk | c74e42a618cb6c38b01f20ea905a8171fc03d8df | 0726deb5240a5cc2b3a1d509e6d80b2505948670 | refs/heads/master | 2020-12-25T22:28:53.077083 | 2014-02-14T04:19:03 | 2014-02-14T04:19:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 22,532 | py | import os
import re
import sys
import shlex
import tempfile
import subprocess
from binwalk.core.compat import *
from binwalk.core.module import Module, Option, Kwarg
from binwalk.core.common import file_size, unique_file_name, BlockFile
class Extractor(Module):
'''
Extractor class, responsible for extracting files from the target file and executing external applications, if requested.
'''
# Extract rules are delimited with a colon.
# <case insensitive matching string>:<file extension>[:<command to run>]
RULE_DELIM = ':'
# Comments in the extract.conf files start with a pound
COMMENT_DELIM ='#'
# Place holder for the extracted file name in the command
FILE_NAME_PLACEHOLDER = '%e'
TITLE = 'Extraction'
ORDER = 9
PRIMARY = False
CLI = [
Option(short='e',
long='extract',
kwargs={'load_default_rules' : True, 'enabled' : True},
description='Automatically extract known file types'),
Option(short='D',
long='dd',
type=list,
dtype='type:ext:cmd',
kwargs={'manual_rules' : [], 'enabled' : True},
description='Extract <type> signatures, give the files an extension of <ext>, and execute <cmd>'),
Option(short='M',
long='matryoshka',
kwargs={'matryoshka' : 8},
description='Recursively scan extracted files'),
Option(short='d',
long='depth',
type=int,
kwargs={'matryoshka' : 0},
description='Limit matryoshka recursion depth (default: 8 levels deep)'),
Option(short='j',
long='max-size',
type=int,
kwargs={'max_size' : 0},
description='Limit the size of each extracted file'),
Option(short='r',
long='rm',
kwargs={'remove_after_execute' : True},
description='Cleanup extracted / zero-size files after extraction'),
Option(short='z',
long='carve',
kwargs={'run_extractors' : False},
description="Carve data from files, but don't execute extraction utilities"),
]
KWARGS = [
Kwarg(name='max_size', default=None),
Kwarg(name='remove_after_execute', default=False),
Kwarg(name='load_default_rules', default=False),
Kwarg(name='run_extractors', default=True),
Kwarg(name='manual_rules', default=[]),
Kwarg(name='matryoshka', default=0),
Kwarg(name='enabled', default=False),
]
def load(self):
# Holds a list of extraction rules loaded either from a file or when manually specified.
self.extract_rules = []
if self.load_default_rules:
self.load_defaults()
for manual_rule in self.manual_rules:
self.add_rule(manual_rule)
def reset(self):
# Holds a list of pending files that should be scanned; only populated if self.matryoshka == True
self.pending = []
# Holds a dictionary of extraction directories created for each scanned file.
self.extraction_directories = {}
# Holds a dictionary of the last directory listing for a given directory; used for identifying
# newly created/extracted files that need to be appended to self.pending.
self.last_directory_listing = {}
# Set to the directory path of the first extracted directory; this allows us to track recursion depth.
self.base_recursion_dir = ""
def callback(self, r):
# Make sure the file attribute is set to a compatible instance of binwalk.core.common.BlockFile
try:
r.file.size
except KeyboardInterrupt as e:
pass
except Exception as e:
return
if not r.size:
size = r.file.size - r.offset
else:
size = r.size
# Only extract valid results
if r.valid:
# Do the extraction
(extraction_directory, dd_file) = self.extract(r.offset, r.description, r.file.name, size, r.name)
# If the extraction was successful, self.extract will have returned the output directory and name of the dd'd file
if extraction_directory and dd_file:
# Get the full path to the dd'd file
dd_file_path = os.path.join(extraction_directory, dd_file)
# Do a directory listing of the output directory
directory_listing = set(os.listdir(extraction_directory))
# If this is a newly created output directory, self.last_directory_listing won't have a record of it.
# If we've extracted other files to this directory before, it will.
if not has_key(self.last_directory_listing, extraction_directory):
self.last_directory_listing[extraction_directory] = set()
# Loop through a list of newly created files (i.e., files that weren't listed in the last directory listing)
for f in directory_listing.difference(self.last_directory_listing[extraction_directory]):
# Build the full file path and add it to the extractor results
file_path = os.path.join(extraction_directory, f)
real_file_path = os.path.realpath(file_path)
self.result(description=file_path, display=False)
# If recursion was specified, and the file is not the same one we just dd'd, and if it is not a directory
if self.matryoshka and file_path != dd_file_path and not os.path.isdir(file_path):
# If the recursion level of this file is less than or equal to our desired recursion level
if len(real_file_path.split(self.base_recursion_dir)[1].split(os.path.sep)) <= self.matryoshka:
# Add the file to our list of pending files
self.pending.append(file_path)
# Update the last directory listing for the next time we extract a file to this same output directory
self.last_directory_listing[extraction_directory] = directory_listing
def append_rule(self, r):
self.extract_rules.append(r.copy())
def add_rule(self, txtrule=None, regex=None, extension=None, cmd=None):
'''
Adds a set of rules to the extraction rule list.
@txtrule - Rule string, or list of rule strings, in the format <regular expression>:<file extension>[:<command to run>]
@regex - If rule string is not specified, this is the regular expression string to use.
@extension - If rule string is not specified, this is the file extension to use.
@cmd - If rule string is not specified, this is the command to run.
Alternatively a callable object may be specified, which will be passed one argument: the path to the file to extract.
Returns None.
'''
rules = []
match = False
r = {
'extension' : '',
'cmd' : '',
'regex' : None
}
# Process single explicitly specified rule
if not txtrule and regex and extension:
r['extension'] = extension
r['regex'] = re.compile(regex)
if cmd:
r['cmd'] = cmd
self.append_rule(r)
return
# Process rule string, or list of rule strings
if not isinstance(txtrule, type([])):
rules = [txtrule]
else:
rules = txtrule
for rule in rules:
r['cmd'] = ''
r['extension'] = ''
try:
values = self._parse_rule(rule)
match = values[0]
r['regex'] = re.compile(values[0])
r['extension'] = values[1]
r['cmd'] = values[2]
except KeyboardInterrupt as e:
raise e
except Exception:
pass
# Verify that the match string was retrieved.
if match:
self.append_rule(r)
def remove_rule(self, text):
'''
Remove all rules that match a specified text.
@text - The text to match against.
Returns the number of rules removed.
'''
rm = []
for i in range(0, len(self.extract_rules)):
if self.extract_rules[i]['regex'].match(text):
rm.append(i)
for i in rm:
self.extract_rules.pop(i)
return len(rm)
def clear_rules(self):
'''
Deletes all extraction rules.
Returns None.
'''
self.extract_rules = []
def get_rules(self):
'''
Returns a list of all extraction rules.
'''
return self.extract_rules
def load_from_file(self, fname):
'''
Loads extraction rules from the specified file.
@fname - Path to the extraction rule file.
Returns None.
'''
try:
# Process each line from the extract file, ignoring comments
with open(fname, 'r') as f:
for rule in f.readlines():
self.add_rule(rule.split(self.COMMENT_DELIM, 1)[0])
except KeyboardInterrupt as e:
raise e
except Exception as e:
raise Exception("Extractor.load_from_file failed to load file '%s': %s" % (fname, str(e)))
def load_defaults(self):
'''
Loads default extraction rules from the user and system extract.conf files.
Returns None.
'''
# Load the user extract file first to ensure its rules take precedence.
extract_files = [
self.config.settings.get_file_path('user', self.config.settings.EXTRACT_FILE),
self.config.settings.get_file_path('system', self.config.settings.EXTRACT_FILE),
]
for extract_file in extract_files:
if extract_file:
try:
self.load_from_file(extract_file)
except KeyboardInterrupt as e:
raise e
except Exception as e:
if self.config.verbose:
raise Exception("Extractor.load_defaults failed to load file '%s': %s" % (extract_file, str(e)))
def build_output_directory(self, path):
'''
Set the output directory for extracted files.
@path - The path to the file that data will be extracted from.
Returns None.
'''
# If we have not already created an output directory for this target file, create one now
if not has_key(self.extraction_directories, path):
output_directory = os.path.join(os.path.dirname(path), unique_file_name('_' + os.path.basename(path), extension='extracted'))
if not os.path.exists(output_directory):
os.mkdir(output_directory)
self.extraction_directories[path] = output_directory
# Else, just use the already created directory
else:
output_directory = self.extraction_directories[path]
# Set the initial base extraction directory for later determining the level of recusion
if not self.base_recursion_dir:
self.base_recursion_dir = os.path.realpath(output_directory) + os.path.sep
return output_directory
def cleanup_extracted_files(self, tf=None):
'''
Set the action to take after a file is extracted.
@tf - If set to True, extracted files will be cleaned up after running a command against them.
If set to False, extracted files will not be cleaned up after running a command against them.
If set to None or not specified, the current setting will not be changed.
Returns the current cleanup status (True/False).
'''
if tf is not None:
self.remove_after_execute = tf
return self.remove_after_execute
def extract(self, offset, description, file_name, size, name=None):
'''
Extract an embedded file from the target file, if it matches an extract rule.
Called automatically by Binwalk.scan().
@offset - Offset inside the target file to begin the extraction.
@description - Description of the embedded file to extract, as returned by libmagic.
@file_name - Path to the target file.
@size - Number of bytes to extract.
@name - Name to save the file as.
Returns the name of the extracted file (blank string if nothing was extracted).
'''
fname = ''
cleanup_extracted_fname = True
original_dir = os.getcwd()
rules = self._match(description)
file_path = os.path.realpath(file_name)
# No extraction rules for this file
if not rules:
return (None, None)
output_directory = self.build_output_directory(file_name)
# Extract to end of file if no size was specified
if not size:
size = file_size(file_path) - offset
if os.path.isfile(file_path):
os.chdir(output_directory)
# Loop through each extraction rule until one succeeds
for i in range(0, len(rules)):
rule = rules[i]
# Copy out the data to disk, if we haven't already
fname = self._dd(file_path, offset, size, rule['extension'], output_file_name=name)
# If there was a command specified for this rule, try to execute it.
# If execution fails, the next rule will be attempted.
if rule['cmd']:
# Many extraction utilities will extract the file to a new file, just without
# the file extension (i.e., myfile.7z -> myfile). If the presumed resulting
# file name already exists before executing the extract command, do not attempt
# to clean it up even if its resulting file size is 0.
if self.remove_after_execute:
extracted_fname = os.path.splitext(fname)[0]
if os.path.exists(extracted_fname):
cleanup_extracted_fname = False
# Execute the specified command against the extracted file
if self.run_extractors:
extract_ok = self.execute(rule['cmd'], fname)
else:
extract_ok = True
# Only clean up files if remove_after_execute was specified
if extract_ok and self.remove_after_execute:
# Remove the original file that we extracted
try:
os.unlink(fname)
except KeyboardInterrupt as e:
raise e
except Exception as e:
pass
# If the command worked, assume it removed the file extension from the extracted file
# If the extracted file name file exists and is empty, remove it
if cleanup_extracted_fname and os.path.exists(extracted_fname) and file_size(extracted_fname) == 0:
try:
os.unlink(extracted_fname)
except KeyboardInterrupt as e:
raise e
except Exception as e:
pass
# If the command executed OK, don't try any more rules
if extract_ok:
break
# Else, remove the extracted file if this isn't the last rule in the list.
# If it is the last rule, leave the file on disk for the user to examine.
elif i != (len(rules)-1):
try:
os.unlink(fname)
except KeyboardInterrupt as e:
raise e
except Exception as e:
pass
# If there was no command to execute, just use the first rule
else:
break
os.chdir(original_dir)
return (output_directory, fname)
def _entry_offset(self, index, entries, description):
'''
Gets the offset of the first entry that matches the description.
@index - Index into the entries list to begin searching.
@entries - Dictionary of result entries.
@description - Case insensitive description.
Returns the offset, if a matching description is found.
Returns -1 if a matching description is not found.
'''
description = description.lower()
for (offset, infos) in entries[index:]:
for info in infos:
if info['description'].lower().startswith(description):
return offset
return -1
def _match(self, description):
'''
Check to see if the provided description string matches an extract rule.
Called internally by self.extract().
@description - Description string to check.
Returns the associated rule dictionary if a match is found.
Returns None if no match is found.
'''
rules = []
description = description.lower()
for rule in self.extract_rules:
if rule['regex'].search(description):
rules.append(rule)
return rules
def _parse_rule(self, rule):
'''
Parses an extraction rule.
@rule - Rule string.
Returns an array of ['<case insensitive matching string>', '<file extension>', '<command to run>'].
'''
return rule.strip().split(self.RULE_DELIM, 2)
def _dd(self, file_name, offset, size, extension, output_file_name=None):
'''
Extracts a file embedded inside the target file.
@file_name - Path to the target file.
@offset - Offset inside the target file where the embedded file begins.
@size - Number of bytes to extract.
@extension - The file exension to assign to the extracted file on disk.
@output_file_name - The requested name of the output file.
Returns the extracted file name.
'''
total_size = 0
# Default extracted file name is <hex offset>.<extension>
default_bname = "%X" % offset
if self.max_size and size > self.max_size:
size = self.max_size
if not output_file_name or output_file_name is None:
bname = default_bname
else:
# Strip the output file name of invalid/dangerous characters (like file paths)
bname = os.path.basename(output_file_name)
fname = unique_file_name(bname, extension)
try:
# Open the target file and seek to the offset
fdin = self.config.open_file(file_name, length=size, offset=offset)
# Open the output file
try:
fdout = BlockFile(fname, 'w')
except KeyboardInterrupt as e:
raise e
except Exception as e:
# Fall back to the default name if the requested name fails
fname = unique_file_name(default_bname, extension)
fdout = BlockFile(fname, 'w')
while total_size < size:
(data, dlen) = fdin.read_block()
if not data:
break
else:
fdout.write(str2bytes(data[:dlen]))
total_size += dlen
# Cleanup
fdout.close()
fdin.close()
except KeyboardInterrupt as e:
raise e
except Exception as e:
raise Exception("Extractor.dd failed to extract data from '%s' to '%s': %s" % (file_name, fname, str(e)))
return fname
def execute(self, cmd, fname):
'''
Execute a command against the specified file.
@cmd - Command to execute.
@fname - File to run command against.
Returns True on success, False on failure.
'''
tmp = None
retval = True
try:
if callable(cmd):
try:
cmd(fname)
except KeyboardInterrupt as e:
raise e
except Exception as e:
sys.stderr.write("WARNING: Extractor.execute failed to run internal extractor '%s': %s\n" % (str(cmd), str(e)))
else:
# If not in verbose mode, create a temporary file to redirect stdout and stderr to
if not self.config.verbose:
tmp = tempfile.TemporaryFile()
# Replace all instances of FILE_NAME_PLACEHOLDER in the command with fname
cmd = cmd.replace(self.FILE_NAME_PLACEHOLDER, fname)
# Execute.
if subprocess.call(shlex.split(cmd), stdout=tmp, stderr=tmp) != 0:
retval = False
except KeyboardInterrupt as e:
raise e
except Exception as e:
# Silently ignore no such file or directory errors. Why? Because these will inevitably be raised when
# making the switch to the new firmware mod kit directory structure. We handle this elsewhere, but it's
# annoying to see this spammed out to the console every time.
if not hasattr(e, 'errno') or e.errno != 2:
sys.stderr.write("WARNING: Extractor.execute failed to run external extrator '%s': %s\n" % (str(cmd), str(e)))
retval = False
if tmp is not None:
tmp.close()
return retval
| [
"[email protected]"
] | |
4e436d01a7d9d68d3c34894ae9851687f1de4c6f | 700577285824a21df647aba584d51420db59c598 | /OpenColibri/allauth/account/app_settings.py | c7f23b95cd0a2fdd70cdb71e42de82fc305f924b | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | epu-ntua/opencolibri | 2c05acc43ef1b1c86608f6e729a4f83773b01b73 | 78e2411f78a0213b3961145cfe67cd52398cea70 | refs/heads/master | 2016-09-11T02:39:43.798777 | 2014-04-06T11:30:39 | 2014-04-06T11:30:39 | 15,764,540 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,397 | py | class AppSettings(object):
class AuthenticationMethod:
USERNAME = 'username'
EMAIL = 'email'
USERNAME_EMAIL = 'username_email'
class EmailVerificationMethod:
# After signing up, keep the user account inactive until the email
# address is verified
MANDATORY = 'mandatory'
# Allow login with unverified e-mail (e-mail verification is still sent)
OPTIONAL = 'optional'
# Don't send e-mail verification mails during signup
NONE = 'none'
def __init__(self, prefix):
self.prefix = prefix
# If login is by email, email must be required
assert (not self.AUTHENTICATION_METHOD
== self.AuthenticationMethod.EMAIL) or self.EMAIL_REQUIRED
# If login includes email, login must be unique
assert (self.AUTHENTICATION_METHOD
== self.AuthenticationMethod.USERNAME) or self.UNIQUE_EMAIL
assert (self.EMAIL_VERIFICATION
!= self.EmailVerificationMethod.MANDATORY) \
or self.EMAIL_REQUIRED
def _setting(self, name, dflt):
from django.conf import settings
return getattr(settings, self.prefix + name, dflt)
@property
def EMAIL_CONFIRMATION_EXPIRE_DAYS(self):
"""
Determines the expiration date of e-mail confirmation mails (#
of days)
"""
from django.conf import settings
return self._setting("EMAIL_CONFIRMATION_EXPIRE_DAYS",
getattr(settings, "EMAIL_CONFIRMATION_DAYS", 3))
@property
def EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL(self):
"""
The URL to redirect to after a successful e-mail confirmation, in
case of an authenticated user
"""
return self._setting("EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL",
None)
@property
def EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL(self):
"""
The URL to redirect to after a successful e-mail confirmation, in
case no user is logged in
"""
from django.conf import settings
return self._setting("EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL",
settings.LOGIN_URL)
@property
def EMAIL_REQUIRED(self):
"""
The user is required to hand over an e-mail address when signing up
"""
return self._setting("EMAIL_REQUIRED", False)
@property
def EMAIL_VERIFICATION(self):
"""
See e-mail verification method
"""
ret = self._setting("EMAIL_VERIFICATION",
self.EmailVerificationMethod.OPTIONAL)
# Deal with legacy (boolean based) setting
if ret == True:
ret = self.EmailVerificationMethod.MANDATORY
elif ret == False:
ret = self.EmailVerificationMethod.OPTIONAL
return ret
@property
def AUTHENTICATION_METHOD(self):
from django.conf import settings
if hasattr(settings, "ACCOUNT_EMAIL_AUTHENTICATION"):
import warnings
warnings.warn("ACCOUNT_EMAIL_AUTHENTICATION is deprecated,"
" use ACCOUNT_AUTHENTICATION_METHOD",
DeprecationWarning)
if getattr(settings, "ACCOUNT_EMAIL_AUTHENTICATION"):
ret = self.AuthenticationMethod.EMAIL
else:
ret = self.AuthenticationMethod.USERNAME
else:
ret = self._setting("AUTHENTICATION_METHOD",
self.AuthenticationMethod.USERNAME)
return ret
@property
def UNIQUE_EMAIL(self):
"""
Enforce uniqueness of e-mail addresses
"""
return self._setting("UNIQUE_EMAIL", True)
@property
def SIGNUP_PASSWORD_VERIFICATION(self):
"""
Signup password verification
"""
return self._setting("SIGNUP_PASSWORD_VERIFICATION", True)
@property
def PASSWORD_MIN_LENGTH(self):
"""
Minimum password Length
"""
return self._setting("PASSWORD_MIN_LENGTH", 6)
@property
def EMAIL_SUBJECT_PREFIX(self):
"""
Subject-line prefix to use for email messages sent
"""
return self._setting("EMAIL_SUBJECT_PREFIX", None)
@property
def SIGNUP_FORM_CLASS(self):
"""
Signup form
"""
return self._setting("SIGNUP_FORM_CLASS", None)
@property
def USERNAME_REQUIRED(self):
"""
The user is required to enter a username when signing up
"""
return self._setting("USERNAME_REQUIRED", True)
@property
def USERNAME_MIN_LENGTH(self):
"""
Minimum username Length
"""
return self._setting("USERNAME_MIN_LENGTH", 1)
@property
def PASSWORD_INPUT_RENDER_VALUE(self):
"""
render_value parameter as passed to PasswordInput fields
"""
return self._setting("PASSWORD_INPUT_RENDER_VALUE", False)
@property
def ADAPTER(self):
return self._setting('ADAPTER',
'allauth.account.adapter.DefaultAccountAdapter')
# Ugly? Guido recommends this himself ...
# http://mail.python.org/pipermail/python-ideas/2012-May/014969.html
import sys
sys.modules[__name__] = AppSettings('ACCOUNT_')
| [
"[email protected]"
] | |
800456aaf4121ed1d3ea0a210dcc7ad4ab8f7e70 | 039f2c747a9524daa1e45501ada5fb19bd5dd28f | /ABC082/ABC082f.py | 98df19f25eced701e03563a9edc2b78d2d3d02ec | [
"Unlicense"
] | permissive | yuto-moriizumi/AtCoder | 86dbb4f98fea627c68b5391bf0cc25bcce556b88 | 21acb489f1594bbb1cdc64fbf8421d876b5b476d | refs/heads/master | 2023-03-25T08:10:31.738457 | 2021-03-23T08:48:01 | 2021-03-23T08:48:01 | 242,283,632 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 76 | py | #ABC082f
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
| [
"[email protected]"
] | |
a7d91e08aac4a3cbc8c9e57421d6606d8a90881f | a46d135ba8fd7bd40f0b7d7a96c72be446025719 | /packages/python/plotly/plotly/validators/waterfall/_name.py | 608e0ac1ba031e5709a5828581f3e4766451e155 | [
"MIT"
] | permissive | hugovk/plotly.py | 5e763fe96f225d964c4fcd1dea79dbefa50b4692 | cfad7862594b35965c0e000813bd7805e8494a5b | refs/heads/master | 2022-05-10T12:17:38.797994 | 2021-12-21T03:49:19 | 2021-12-21T03:49:19 | 234,146,634 | 0 | 0 | MIT | 2020-01-15T18:33:43 | 2020-01-15T18:33:41 | null | UTF-8 | Python | false | false | 390 | py | import _plotly_utils.basevalidators
class NameValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="name", parent_name="waterfall", **kwargs):
super(NameValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
**kwargs
)
| [
"[email protected]"
] | |
0377cbc8e9ba2d59e28b08a5a1ce0f5fa8ca1010 | ce76b3ef70b885d7c354b6ddb8447d111548e0f1 | /fact/next_government/own_group/call_case_up_problem/large_point/little_life.py | b2b99d6c9740a5162e0e6a7470cbb95876144f50 | [] | no_license | JingkaiTang/github-play | 9bdca4115eee94a7b5e4ae9d3d6052514729ff21 | 51b550425a91a97480714fe9bc63cb5112f6f729 | refs/heads/master | 2021-01-20T20:18:21.249162 | 2016-08-19T07:20:12 | 2016-08-19T07:20:12 | 60,834,519 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 240 | py |
#! /usr/bin/env python
def early_eye(str_arg):
last_company_or_right_company(str_arg)
print('work_world')
def last_company_or_right_company(str_arg):
print(str_arg)
if __name__ == '__main__':
early_eye('place_or_woman')
| [
"[email protected]"
] | |
35eabc71c967a9a494077668c6ff2c0e79563ec9 | 2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02 | /PyTorch/dev/cv/image_classification/SmartSketch_ID1046_for_PyTorch/backend/options/test_options.py | 5350b45b998b8b7c19b0614a90c9ad638c32ab3f | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"LicenseRef-scancode-proprietary-license",
"CC-BY-NC-SA-4.0",
"CC-BY-NC-4.0",
"LicenseRef-scancode-other-copyleft",
"CC-BY-4.0",
"GPL-3.0-only"
] | permissive | Ascend/ModelZoo-PyTorch | 4c89414b9e2582cef9926d4670108a090c839d2d | 92acc188d3a0f634de58463b6676e70df83ef808 | refs/heads/master | 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 | Apache-2.0 | 2022-10-15T09:29:12 | 2022-04-20T04:11:18 | Python | UTF-8 | Python | false | false | 2,673 | py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
#
# BSD 3-Clause License
#
# Copyright (c) 2017 xxxx
# All rights reserved.
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ============================================================================
#
"""
from .base_options import BaseOptions
class TestOptions(BaseOptions):
def initialize(self, parser):
BaseOptions.initialize(self, parser)
parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here.')
parser.add_argument('--which_epoch', type=str, default='latest', help='which epoch to load? set to latest to use latest cached model')
parser.add_argument('--how_many', type=int, default=float("inf"), help='how many test images to run')
parser.set_defaults(preprocess_mode='scale_width_and_crop', crop_size=256, load_size=256, display_winsize=256)
parser.set_defaults(serial_batches=True)
parser.set_defaults(no_flip=True)
parser.set_defaults(phase='test')
self.isTrain = False
return parser
| [
"[email protected]"
] | |
9e25c636f9da9596f495b991c9608fe75b4649d3 | e3d447a81c5462d2d14201f2bc6b82cdcbbca51a | /chapter11/c11_2_city_functions.py | e4ca3478294a70d075558e1ec889a6b75ce34d05 | [] | no_license | barcern/python-crash-course | f6026f13f75ecddc7806711d65bc53cb88e24496 | 8b55775c9f0ed49444becb35b8d529620537fa54 | refs/heads/master | 2023-04-19T17:28:44.342022 | 2021-02-07T23:51:06 | 2021-02-07T23:51:06 | 257,201,280 | 2 | 3 | null | 2021-05-12T17:35:56 | 2020-04-20T07:14:28 | Python | UTF-8 | Python | false | false | 540 | py | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 31 21:29:14 2020
@author: barbora
Store functions for 11-1.
"""
def return_formatted_city_country(city, country, population=''):
"""Return a string formatted as City, Country - population xxx
when population data available. Otherwise return as City, Country.
"""
if population:
formatted = f"{city.title()}, {country.title()}"
formatted += f" - population {population}"
else:
formatted = f"{city.title()}, {country.title()}"
return formatted
| [
"[email protected]"
] | |
16edaa237e253f240e580d3cce27529f3a7004c9 | 5ae01ab82fcdedbdd70707b825313c40fb373fa3 | /scripts/charonInterpreter/parsers/MaterialBlock/TrapSRH/TrapSRHParserLib.py | 4c71b1d4270cf5a60be099655815429e5c8b8c61 | [] | no_license | worthenmanufacturing/tcad-charon | efc19f770252656ecf0850e7bc4e78fa4d62cf9e | 37f103306952a08d0e769767fe9391716246a83d | refs/heads/main | 2023-08-23T02:39:38.472864 | 2021-10-29T20:15:15 | 2021-10-29T20:15:15 | 488,068,897 | 0 | 0 | null | 2022-05-03T03:44:45 | 2022-05-03T03:44:45 | null | UTF-8 | Python | false | false | 3,700 | py |
try:
import coloramaDISABLED as colors
except ImportError:
class stubColors:
"subs for colors when colors doesn't exist on system"
def __init__(self):
self.Fore = colorClass()
self.Back = colorClass()
self.Style = styleClass()
class colorClass():
"stubbed color class"
def __init__(self):
self.BLACK = ""
self.BLUE = ""
self.WHITE = ""
self.RED = ""
self.GREEN = ""
class styleClass():
"stubbed style class"
def __init__(self):
self.RESET_ALL = ""
colors = stubColors()
import sys
from .charonLineParserPhononEnergy import *
from .charonLineParserTrapDensity import *
from .charonLineParserEnergyLevel import *
from .charonLineParserHuangRhysFactor import *
from .charonLineParserTrapType import *
from .charonBlockParserElectronTunnelingParams import *
from .charonBlockParserHoleTunnelingParams import *
from .ElectronTunnelingParams.ElectronTunnelingParamsParserLib import *
from .HoleTunnelingParams.HoleTunnelingParamsParserLib import *
class TrapSRHParserLib:
"This is the TrapSRHParserLib parser library "
def __init__(self):
# set the parser library name
self.parserLibName = "TrapSRHParserLib"
# create the linparser objects
self.lineParsers = []
self.lineParsers.append(charonLineParserPhononEnergy())
self.lineParsers.append(charonLineParserTrapDensity())
self.lineParsers.append(charonLineParserEnergyLevel())
self.lineParsers.append(charonLineParserHuangRhysFactor())
self.lineParsers.append(charonLineParserTrapType())
# create the blockparser objects
self.blockParsers = []
self.blockParsers.append([charonBlockParserElectronTunnelingParams(),ElectronTunnelingParamsParserLib()])
self.blockParsers.append([charonBlockParserHoleTunnelingParams(),HoleTunnelingParamsParserLib()])
# create the parserLibrary objects
parserLibraries = []
parserLibraries.append(ElectronTunnelingParamsParserLib())
parserLibraries.append(HoleTunnelingParamsParserLib())
def isThisMyLine(self,tokenizer,line):
for lP in self.lineParsers:
self.isThisMe = lP.isThisMe(tokenizer,line)
if self.isThisMe == True:
return (True,lP)
return (False,None)
def isThisMyBlock(self,tokenizer,line):
for bP in self.blockParsers:
self.isThisMe = bP[0].isThisMe(tokenizer,line)
if self.isThisMe == True:
return (True,bP[0],bP[1])
return (False,None,None)
def generateHelp(self,genHelp,indent):
self.addIndent = " "
cRStyle = ""
for lP in self.lineParsers:
(self.helpLine,self.helpContent) = lP.getHelp(genHelp)
self.helpContentList = self.helpContent.split("<>")
print (cRStyle+indent+colors.Fore.RED+colors.Back.WHITE+self.helpLine)
cRStyle = "\n"
for hCL in self.helpContentList:
print ("\t"+indent+colors.Fore.BLUE+colors.Back.WHITE+hCL.lstrip())
for bP in range(len(self.blockParsers)):
print (indent+colors.Fore.GREEN+colors.Back.WHITE+self.blockParsers[bP][0].getHelpLine().lstrip())
self.blockParsers[bP][1].generateHelp(genHelp,indent+self.addIndent)
print (indent+colors.Fore.GREEN+colors.Back.WHITE+self.blockParsers[bP][0].getHelpLine().replace("start","end").lstrip())
print (indent+colors.Style.RESET_ALL)
def getName(self):
return self.parserLibName
| [
"[email protected]"
] | |
c5cdf70a00c21b9e801db37dcf16fc563db36592 | 6e4702fa7ff89c59871148e8007b769506fffe5b | /SmartClass/teacher/migrations/0010_cauhoi_dinh_kem.py | 012736603018a2929917ba9730924c58cc1dd535 | [] | no_license | vuvandang1995/hvan | 3a7bd8892bed30c6c6f4062bcf7a2c2804f34b0d | 003d9362739944cb3bcd8d1b11dd5b7481d7bd81 | refs/heads/master | 2020-05-02T02:31:51.121181 | 2019-03-27T02:32:29 | 2019-03-27T02:32:29 | 177,706,377 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 406 | py | # Generated by Django 2.1 on 2018-09-24 08:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('teacher', '0009_auto_20180919_1601'),
]
operations = [
migrations.AddField(
model_name='cauhoi',
name='dinh_kem',
field=models.FileField(blank=True, null=True, upload_to=''),
),
]
| [
"[email protected]"
] | |
b58921544b80556ce223763f385799d172a1203f | 9d6218ca6c75a0e1ec1674fe410100d93d6852cb | /app/supervisor/venvs/supervisor/bin/pidproxy | 067992ca6ce7b31e95969cd766069a5c66c5e897 | [] | no_license | bopopescu/uceo-2015 | 164694268969dd884904f51b00bd3dc034695be8 | 5abcbfc4ff32bca6ca237d71cbb68fab4b9f9f91 | refs/heads/master | 2021-05-28T21:12:05.120484 | 2015-08-05T06:46:36 | 2015-08-05T06:46:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 344 | #!/edx/app/supervisor/venvs/supervisor/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'supervisor==3.1.3','console_scripts','pidproxy'
__requires__ = 'supervisor==3.1.3'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('supervisor==3.1.3', 'console_scripts', 'pidproxy')()
)
| [
"[email protected]"
] | ||
f65d0c089bb934d96b17d265180c2bb68a9ef792 | 251f5c83584666c58fe6d7e28175cf33129eb3e2 | /net/model/decoder/__init__.py | eda63e60cb70e627e96422e4ec0d03f0c200810e | [
"MIT"
] | permissive | haoxizhong/law_pre | 42feefa028560e79f35a4ab214bc7046eb49b733 | 8ca173eba2985583c409c44771ecc0e0afee001e | refs/heads/master | 2018-11-13T05:30:43.591713 | 2018-05-31T14:47:16 | 2018-05-31T14:47:16 | 114,606,216 | 17 | 2 | null | null | null | null | UTF-8 | Python | false | false | 125 | py | from .fc_decoder import FCDecoder
from .lstm_article_decoder import LSTMArticleDecoder
from .lstm_decoder import LSTMDecoder
| [
"[email protected]"
] | |
1fcab6195234c0ee9d1fc17fd7ef16750b34d793 | ede0935c59217973665bc7bef2337f413e5a8c92 | /my_configs/_base_/models/cascade_mask_rcnn_r50_fpn.py | 163f7584fa7ed4e72444fa5786d0073890ffdf7b | [
"Apache-2.0"
] | permissive | Daniel-xsy/MMDet_VisDrone2021 | 6da6d23c324afb7be9056bb6628b25f5d688af2a | 668d10b61a4b99dda0163b67b093cad2e699ee3b | refs/heads/master | 2023-07-10T02:42:06.474341 | 2021-08-14T09:36:12 | 2021-08-14T09:36:12 | 376,227,429 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,410 | py | # model settings
model = dict(
type='CascadeRCNN',
pretrained='torchvision://resnet50',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch'),
neck=dict(
type='FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
num_outs=5),
rpn_head=dict(
type='RPNHead',
in_channels=256,
feat_channels=256,
anchor_generator=dict(
type='AnchorGenerator',
scales=[8],
ratios=[0.5, 1.0, 2.0],
strides=[4, 8, 16, 32, 64]),
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[.0, .0, .0, .0],
target_stds=[1.0, 1.0, 1.0, 1.0]),
loss_cls=dict(
type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)),
roi_head=dict(
type='CascadeRoIHead',
num_stages=3,
stage_loss_weights=[1, 0.5, 0.25],
bbox_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),
out_channels=256,
featmap_strides=[4, 8, 16, 32]),
bbox_head=[
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=10,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.1, 0.1, 0.2, 0.2]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0,
loss_weight=1.0)),
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=10,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.05, 0.05, 0.1, 0.1]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0,
loss_weight=1.0)),
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=10,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.033, 0.033, 0.067, 0.067]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))
]),
# model training and testing settings
train_cfg=dict(
rpn=dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.7,
neg_iou_thr=0.3,
min_pos_iou=0.3,
match_low_quality=True,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=256,
pos_fraction=0.5,
neg_pos_ub=-1,
add_gt_as_proposals=False),
allowed_border=0,
pos_weight=-1,
debug=False),
rpn_proposal=dict(
nms_pre=2000,
max_per_img=2000,
nms=dict(type='nms', iou_threshold=0.7),
min_bbox_size=0),
rcnn=[
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.5,
neg_iou_thr=0.5,
min_pos_iou=0.5,
match_low_quality=False,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
mask_size=28,
pos_weight=-1,
debug=False),
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.6,
neg_iou_thr=0.6,
min_pos_iou=0.6,
match_low_quality=False,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
mask_size=28,
pos_weight=-1,
debug=False),
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.7,
neg_iou_thr=0.7,
min_pos_iou=0.7,
match_low_quality=False,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
mask_size=28,
pos_weight=-1,
debug=False)
]),
test_cfg=dict(
rpn=dict(
nms_pre=1000,
max_per_img=1000,
nms=dict(type='nms', iou_threshold=0.7),
min_bbox_size=0),
rcnn=dict(
score_thr=0.05,
nms=dict(type='nms', iou_threshold=0.5),
max_per_img=100,
mask_thr_binary=0.5)))
| [
"[email protected]"
] | |
4b5f0ee21f4bc0a33955b2e07b728a7a7675a944 | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/synthetic/stdlib-big-2229.py | 5bced3c0a0d97de740437f48ef60853a7415c806 | [] | no_license | Virtlink/ccbench-chocopy | c3f7f6af6349aff6503196f727ef89f210a1eac8 | c7efae43bf32696ee2b2ee781bdfe4f7730dec3f | refs/heads/main | 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,992 | py | # ChocoPy library functions
def int_to_str(x: int) -> str:
digits:[str] = None
result:str = ""
# Set-up digit mapping
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
# Write sign if necessary
if x < 0:
result = "-"
x = -x
# Write digits using a recursive call
if x >= 10:
result = result + int_to_str(x // 10)
result = result + digits[x % 10]
return result
def int_to_str2(x: int, x2: int) -> str:
digits:[str] = None
digits2:[str] = None
result:str = ""
result2:str = ""
# Set-up digit mapping
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
# Write sign if necessary
if x < 0:
result = "-"
x = -x
# Write digits using a recursive call
if x >= 10:
result = result + int_to_str(x // 10)
result = result + digits[x % 10]
return result
def int_to_str3(x: int, x2: int, x3: int) -> str:
digits:[str] = None
digits2:[str] = None
digits3:[str] = None
result:str = ""
result2:str = ""
result3:str = ""
# Set-up digit mapping
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
# Write sign if necessary
if x < 0:
result = "-"
x = -x
# Write digits using a recursive call
if x >= 10:
result = result + int_to_str(x // 10)
result = result + digits[x % 10]
return result
def int_to_str4(x: int, x2: int, x3: int, x4: int) -> str:
digits:[str] = None
digits2:[str] = None
digits3:[str] = None
digits4:[str] = None
result:str = ""
result2:str = ""
result3:str = ""
result4:str = ""
# Set-up digit mapping
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
# Write sign if necessary
if x < 0:
result = "-"
x = -x
# Write digits using a recursive call
if x >= 10:
result = result + int_to_str(x // 10)
result = result + digits[x % 10]
return result
def int_to_str5(x: int, x2: int, x3: int, x4: int, x5: int) -> str:
digits:[str] = None
digits2:[str] = None
digits3:[str] = None
digits4:[str] = None
digits5:[str] = None
result:str = ""
result2:str = ""
result3:str = ""
result4:str = ""
result5:str = ""
# Set-up digit mapping
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
# Write sign if necessary
if x < 0:
result = "-"
x = -x
# Write digits using a recursive call
if x >= 10:
result = result + int_to_str(x // 10)
result = result + digits[x % 10]
return result
def str_to_int(x: str) -> int:
result:int = 0
digit:int = 0
char:str = ""
sign:int = 1
first_char:bool = True
# Parse digits
for char in x:
if char == "-":
if not first_char:
return 0 # Error
sign = -1
elif char == "0":
digit = 0
elif char == "1":
digit = 1
elif char == "2":
digit = 2
elif char == "3":
digit = 3
elif char == "3":
digit = 3
elif char == "4":
digit = 4
elif char == "5":
digit = 5
elif char == "6":
digit = 6
elif char == "7":
digit = 7
elif char == "8":
digit = 8
elif char == "9":
digit = 9
else:
return 0 # On error
first_char = False
result = result * 10 + digit
# Compute result
return result * sign
def str_to_int2(x: str, x2: str) -> int:
result:int = 0
result2:int = 0
digit:int = 0
digit2:int = 0
char:str = ""
char2:str = ""
sign:int = 1
sign2:int = 1
first_char:bool = True
first_char2:bool = True
# Parse digits
for char in x:
if char == "-":
if not first_char:
return 0 # Error
sign = -1
elif char == "0":
digit = 0
elif char == "1":
digit = 1
elif char == "2":
digit = 2
elif char == "3":
digit = 3
elif char == "3":
digit = 3
elif char == "4":
digit = 4
elif char == "5":
digit = 5
elif char == "6":
digit = 6
elif char == "7":
digit = 7
elif char == "8":
digit = 8
elif char == "9":
digit = 9
else:
return 0 # On error
first_char = False
result = result * 10 + digit
# Compute result
return result * sign
def str_to_int3(x: str, x2: str, x3: str) -> int:
result:int = 0
result2:int = 0
result3:int = 0
digit:int = 0
digit2:int = 0
digit3:int = 0
char:str = ""
char2:str = ""
char3:str = ""
sign:int = 1
sign2:int = 1
sign3:int = 1
first_char:bool = True
first_char2:bool = True
first_char3:bool = True
# Parse digits
for char in x:
if char == "-":
if not first_char:
return 0 # Error
sign = -1
elif char == "0":
digit = 0
elif char == "1":
digit = 1
elif char == "2":
digit = 2
elif char == "3":
digit = 3
elif char == "3":
digit = 3
elif char == "4":
digit = 4
elif char == "5":
digit = 5
elif char == "6":
digit = 6
elif char == "7":
digit = 7
elif char == "8":
digit = 8
elif char == "9":
digit = 9
else:
return 0 # On error
first_char = False
result = result * 10 + digit
# Compute result
return result * sign
def str_to_int4(x: str, x2: str, x3: str, x4: str) -> int:
result:int = 0
result2:int = 0
result3:int = 0
result4:int = 0
digit:int = 0
digit2:int = 0
digit3:int = 0
digit4:int = 0
char:str = ""
$VarDef
char3:str = ""
char4:str = ""
sign:int = 1
sign2:int = 1
sign3:int = 1
sign4:int = 1
first_char:bool = True
first_char2:bool = True
first_char3:bool = True
first_char4:bool = True
# Parse digits
for char in x:
if char == "-":
if not first_char:
return 0 # Error
sign = -1
elif char == "0":
digit = 0
elif char == "1":
digit = 1
elif char == "2":
digit = 2
elif char == "3":
digit = 3
elif char == "3":
digit = 3
elif char == "4":
digit = 4
elif char == "5":
digit = 5
elif char == "6":
digit = 6
elif char == "7":
digit = 7
elif char == "8":
digit = 8
elif char == "9":
digit = 9
else:
return 0 # On error
first_char = False
result = result * 10 + digit
# Compute result
return result * sign
def str_to_int5(x: str, x2: str, x3: str, x4: str, x5: str) -> int:
result:int = 0
result2:int = 0
result3:int = 0
result4:int = 0
result5:int = 0
digit:int = 0
digit2:int = 0
digit3:int = 0
digit4:int = 0
digit5:int = 0
char:str = ""
char2:str = ""
char3:str = ""
char4:str = ""
char5:str = ""
sign:int = 1
sign2:int = 1
sign3:int = 1
sign4:int = 1
sign5:int = 1
first_char:bool = True
first_char2:bool = True
first_char3:bool = True
first_char4:bool = True
first_char5:bool = True
# Parse digits
for char in x:
if char == "-":
if not first_char:
return 0 # Error
sign = -1
elif char == "0":
digit = 0
elif char == "1":
digit = 1
elif char == "2":
digit = 2
elif char == "3":
digit = 3
elif char == "3":
digit = 3
elif char == "4":
digit = 4
elif char == "5":
digit = 5
elif char == "6":
digit = 6
elif char == "7":
digit = 7
elif char == "8":
digit = 8
elif char == "9":
digit = 9
else:
return 0 # On error
first_char = False
result = result * 10 + digit
# Compute result
return result * sign
# Input parameters
c:int = 42
c2:int = 42
c3:int = 42
c4:int = 42
c5:int = 42
n:int = 10
n2:int = 10
n3:int = 10
n4:int = 10
n5:int = 10
# Run [-nc, nc] with step size c
s:str = ""
s2:str = ""
s3:str = ""
s4:str = ""
s5:str = ""
i:int = 0
i2:int = 0
i3:int = 0
i4:int = 0
i5:int = 0
i = -n * c
# Crunch
while i <= n * c:
s = int_to_str(i)
print(s)
i = str_to_int(s) + c
| [
"[email protected]"
] | |
8b99bee6c2a0fa65a0e918224fb7fad1370fa83c | 9b80999a1bdd3595022c9abf8743a029fde3a207 | /26-Cluster Analysis in Python /K-Means Clustering /Uniform clustering patterns.py | f00c65cb93f72b60f9ab38a41377633cb2f30563 | [] | no_license | vaibhavkrishna-bhosle/DataCamp-Data_Scientist_with_python | 26fc3a89605f26ac3b77c15dbe45af965080115a | 47d9d2c8c93e1db53154a1642b6281c9149af769 | refs/heads/master | 2022-12-22T14:01:18.140426 | 2020-09-23T11:30:53 | 2020-09-23T11:30:53 | 256,755,894 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,257 | py | '''Now that you are familiar with the impact of seeds, let us look at the bias in k-means clustering towards the formation of uniform clusters.
Let us use a mouse-like dataset for our next exercise. A mouse-like dataset is a group of points that resemble the head of a mouse: it has three clusters of points arranged in circles, one each for the face and two ears of a mouse.
Here is how a typical mouse-like dataset looks like (Source).
The data is stored in a Pandas data frame, mouse. x_scaled and y_scaled are the column names of the standardized X and Y coordinates of the data points.'''
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
mouse = pd.read_csv('/Users/vaibhav/Desktop/Python Projects/DataCamp-Data Scientist with python/26-Cluster Analysis in Python /K-Means Clustering /mouse.csv')
# Import the kmeans and vq functions
from scipy.cluster.vq import kmeans, vq
# Generate cluster centers
cluster_centers, distortion = kmeans(mouse[['x_scaled', 'y_scaled']], 3)
# Assign cluster labels
mouse['cluster_labels'], distortion_list = vq(mouse[['x_scaled', 'y_scaled']], cluster_centers)
# Plot clusters
sns.scatterplot(x='x_scaled', y='y_scaled',
hue='cluster_labels', data = mouse)
plt.show() | [
"[email protected]"
] | |
286d6d8c03a680b5b4551b125a0cded889f6916f | f3e51466d00510f1dae58f1cb87dd53244ce4e70 | /LeetCodes/Trees/SubtreeofAnotherTree.py | c6b61d426d4a645e799a145aaf8d9876fe7dbaec | [] | no_license | chutianwen/LeetCodes | 40d18e7aa270f8235342f0485bfda2bd1ed960e1 | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | refs/heads/master | 2022-08-27T10:28:16.594258 | 2022-07-24T21:23:56 | 2022-07-24T21:23:56 | 96,836,652 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,342 | py | """
iven two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with
a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants.
The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.
"""
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def isSame(p, q):
if p and q:
if p.val != q.val:
return False
else:
return isSame(p.left, q.left) and isSame(p.right, q.right)
else:
return p is q
if s is None:
return False
else:
# res = isSame(s, t)
# if res:
# return True
# else:
# return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
return isSame(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t) | [
"[email protected]"
] | |
52d2e27019d411f0f69b718798e8d4dee6332a77 | 1099d3cc150238b6e764fea8855a9579278bdd1f | /nodes/stop | d842c24c6150242b9cc08d935fb4782724e41b3c | [] | no_license | chili-epfl/ranger_ros | 2b12f3ce3cf2ce70fcfe6a2ebbd659a91ce35e35 | d6cafa055c2c8d706601bdc7793ab1f7a2d08df7 | refs/heads/master | 2016-09-09T21:50:12.181708 | 2015-06-22T09:22:00 | 2015-06-30T07:37:52 | 9,346,098 | 0 | 1 | null | 2015-06-22T09:03:21 | 2013-04-10T12:55:40 | C++ | UTF-8 | Python | false | false | 87 | #!/usr/bin/env python
import ranger
with ranger.Ranger() as robot:
robot.stop()
| [
"[email protected]"
] | ||
283836fff8c95f37f06a4335b71842bfc59315df | 385f0577d98fbf81dd6310b6d826e54f76ae39e7 | /tests/test_param_vasicek.py | 8728a4530f5f14be3f505d5f1c9d7407b5a82ce4 | [
"MIT"
] | permissive | afcarl/diffusions | 4cd5bf32332e64a2352b398eeb69167e98ea35f9 | 87a85b636cc5b78b9a89a8fd1c0c7e7426385952 | refs/heads/master | 2021-05-17T16:02:43.873818 | 2017-09-05T10:14:07 | 2017-09-05T10:14:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,046 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test suite for Vasicek parameter class.
"""
from __future__ import print_function, division
import unittest as ut
import numpy as np
import numpy.testing as npt
from diffusions import VasicekParam
class SDEParameterTestCase(ut.TestCase):
"""Test parameter classes."""
def test_vasicekparam_class(self):
"""Test Vasicek parameter class."""
mean, kappa, eta = 1.5, 1., .2
param = VasicekParam(mean, kappa, eta)
self.assertEqual(param.get_model_name(), 'Vasicek')
self.assertEqual(param.get_names(), ['mean', 'kappa', 'eta'])
self.assertEqual(param.mean, mean)
self.assertEqual(param.kappa, kappa)
self.assertEqual(param.eta, eta)
npt.assert_array_equal(param.get_theta(),
np.array([mean, kappa, eta]))
theta = np.ones(3)
param = VasicekParam.from_theta(theta)
npt.assert_array_equal(param.get_theta(), theta)
mat_k0 = param.kappa * param.mean
mat_k1 = -param.kappa
mat_h0 = param.eta**2
mat_h1 = 0
npt.assert_array_equal(param.mat_k0, mat_k0)
npt.assert_array_equal(param.mat_k1, mat_k1)
npt.assert_array_equal(param.mat_h0, mat_h0)
npt.assert_array_equal(param.mat_h1, mat_h1)
theta *= 2
param.update(theta)
npt.assert_array_equal(param.get_theta(), theta)
mat_k0 = param.kappa * param.mean
mat_k1 = -param.kappa
mat_h0 = param.eta**2
mat_h1 = 0
npt.assert_array_equal(param.mat_k0, mat_k0)
npt.assert_array_equal(param.mat_k1, mat_k1)
npt.assert_array_equal(param.mat_h0, mat_h0)
npt.assert_array_equal(param.mat_h1, mat_h1)
self.assertTrue(param.is_valid())
param = VasicekParam(mean, -kappa, eta)
self.assertFalse(param.is_valid())
param = VasicekParam(mean, kappa, -eta)
self.assertFalse(param.is_valid())
if __name__ == '__main__':
ut.main()
| [
"[email protected]"
] | |
937354f7eaee10d293189248aea1dcf827bd1511 | 3c1639bccf3fc0abc9c82c00ab92ac3f25cf105e | /Python3网络爬虫/section3-基本库使用/06-正则/01-match/04-贪婪与非贪婪.py | 52ca63fa3326f58611c3db3505765dcc9288a9be | [
"Apache-2.0"
] | permissive | LiuJunb/PythonStudy | 783318a64496c2db41442ad66e0cc9253b392734 | 3386b9e3ccb398bfcfcd1a3402182811f9bb37ca | refs/heads/master | 2022-12-11T05:22:53.725166 | 2018-11-15T01:34:37 | 2018-11-15T01:34:37 | 143,956,065 | 1 | 0 | Apache-2.0 | 2022-11-22T01:58:23 | 2018-08-08T03:26:26 | JavaScript | UTF-8 | Python | false | false | 978 | py | import re
# .*? (点星) 可以匹配任意字符(除换行符,例如节点会有换行)
# .? (点) 可以匹配任意字符(除换行符)
# * (星) 又代表匹配前面的字符无限次
content = 'Hello 1234567 World_This is a Regex Demo'
# 1.贪婪匹配(.*)尽量匹配最多的字符: ^He .* (\d+) .* Demo$
result = re.match('^He.*(\d+).*Demo$', content)
print(result) # <re.Match object; span=(0, 40), 01-match='Hello 1234567 World_This is a Regex Demo'>
print(result.group(1)) # 7
# 2.非贪婪匹配(.*?)尽量匹配最少的字符,例如在尾部时可以一个都不匹配: ^He .*? (\d+) .* Demo$
result2 = re.match('^He.*?(\d+).*Demo$', content)
print(result2) # <re.Match object; span=(0, 40), 01-match='Hello 1234567 World_This is a Regex Demo'>
print(result2.group(1)) # 1234567
# 今天天气和好[haha],适合敲代码[xixi]
# '\[ .* \]' --> [haha],适合敲代码[xixi]
# '\[ .*? \]' --> [haha]
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.