blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2
values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220
values | src_encoding stringclasses 30
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 2 10.3M | extension stringclasses 257
values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f993893d9a9ff45bd05d0ee1ea74bd629d2fd4ed | 8c51b635a93d1eff37e996a89d4fe731ebbcde2d | /python_base/code/day04/exercise07.py | adaf42b55aa50297d1e5c494f35c59b37c93a5f0 | [] | no_license | chang821606/storebook | acec847bbc80c06c21892ae9570bcdbcd9705af6 | 83ee5c15f923a7b8a38cb9bac9015a5c6f49a288 | refs/heads/master | 2020-08-25T07:26:44.450812 | 2019-10-23T09:23:41 | 2019-10-23T09:23:41 | 216,982,086 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 236 | py | # 练习:累加10--80之间,个位不是2,5,6的整数
sum_value = 0
for item in range(10,81):
unit = item % 10
if unit == 2 or unit == 5 or unit == 6:
continue
sum_value += item
print(sum_value)
#15:35 上课 | [
"137612497216@163.com"
] | 137612497216@163.com |
337a812f129fb54542dca1dde19841f29a9376bc | efa2114efadf57485e20fad82f26c0bdc0ca033a | /project/settings.py | 67927f384ea94cdca03d86a8d92d214a0a362ac2 | [] | no_license | chaos97/SquirrelSpotter_Django | 3ea3da569789050480ca49b26de77d5585074da8 | 6b4b0b915408f753b07d521f10ca04ac63190647 | refs/heads/master | 2023-05-01T06:33:47.871884 | 2019-12-06T21:59:40 | 2019-12-06T21:59:40 | 223,692,940 | 0 | 0 | null | 2023-04-21T20:51:38 | 2019-11-24T04:37:37 | JavaScript | UTF-8 | Python | false | false | 3,144 | py | """
Django settings for project project.
Generated by 'django-admin startproject' using Django 2.2.7.
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
# 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 = '-lhn)6pr6a66n*+ly6ge242g3w58e3@tk3l7_wyj9@ssh-u46l'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sightings',
]
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 = 'project.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 = 'project.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'),
}
}
# 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/'
STATIC_ROOT = 'collected-static'
| [
"572214728@qq.com"
] | 572214728@qq.com |
e7b2527e9d44eef72048f1bb2f0a78a12a668f9b | 77639380e2c33eee09179f372632bcb57d3f7e3f | /favorita/base_xgb_model.py | d550fd5b81efab514e96961f156451c648bd8a32 | [] | no_license | razmik/demand_forecast_walmart | b8f5c4aaa3cb6dccae102e4ca19f1131131a9f26 | 56292bfbeebc1d3d4962e3ee26d05be2aebd5f4c | refs/heads/master | 2023-01-22T12:30:18.129486 | 2020-08-10T10:44:12 | 2020-08-10T10:44:12 | 283,923,690 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,399 | py | """
Author: Rashmika Nawaratne
Date: 05-Aug-20 at 4:53 PM
"""
import pandas as pd
import numpy as np
from datetime import datetime
import time
import gc
from xgboost import XGBRegressor
from xgboost import Booster
import matplotlib.pyplot as plt
from favorita.load_data import Data
from favorita.evaluation import Evaluator
MODEL_NAME = 'base_xgb'
OUTPUT_FOLDER = 'model_outputs/' + MODEL_NAME
SELECTED_STORES = [i for i in range(1, 55)]
ONLY_EVALUATE = False
if __name__ == "__main__":
start_time = time.time()
data = Data()
end_time = time.time()
print("Load data in: {} mins.".format((end_time - start_time) / 60))
# Filter stores to reduce the dataset
data.train = data.train.loc[data.train.store_nbr.isin(SELECTED_STORES)]
# Feature Engineering
data.train['month'] = data.train['date'].dt.month
data.train['week'] = data.train['date'].dt.week
data.train['day'] = data.train['date'].dt.dayofweek
data.train['month'] = data.train['month'].astype('int8')
data.train['week'] = data.train['week'].astype('int8')
data.train['day'] = data.train['day'].astype('int8')
# Log transform the target variable (unit_sales)
data.train['unit_sales'] = data.train['unit_sales'].apply(lambda u: np.log1p(float(u)) if float(u) > 0 else 0)
# Merge tables
df_full = pd.merge(data.train, data.items[['item_nbr', 'perishable', 'family']],
on='item_nbr') # Train and items (perishable state)
df_full = pd.merge(df_full,
data.weather_oil_holiday[['date', 'store_nbr', 'is_holiday', 'AvgTemp', 'dcoilwtico_imputed']],
on=['date', 'store_nbr'], how='left') # Merge weather, oil and holiday
del df_full['id']
df_full.rename(columns={'dcoilwtico_imputed': 'oil_price', 'AvgTemp': 'avg_temp'}, inplace=True)
# Get test train split
df_train = df_full[(df_full['date'] > datetime(2017, 1, 1)) & (df_full['date'] < datetime(2017, 7, 12))]
df_valid = df_full[(df_full['date'] >= datetime(2017, 7, 12)) & (df_full['date'] < datetime(2017, 7, 31))]
df_test = df_full[df_full['date'] >= datetime(2017, 7, 31)]
# clean variables
del data
del df_full
gc.collect()
# Modeling
feature_columns = ['store_nbr', 'item_nbr', 'onpromotion', 'month', 'week', 'day', 'perishable', 'is_holiday',
'avg_temp', 'oil_price']
target_column = ['unit_sales']
X_train, Y_train = df_train[feature_columns], df_train[target_column]
X_valid, Y_valid = df_valid[feature_columns], df_valid[target_column]
X_test, Y_test = df_test[feature_columns], df_test[target_column]
print('Training dataset: {}'.format(X_train.shape))
print('Testing dataset: {}'.format(X_test.shape))
if not ONLY_EVALUATE:
# Default XGB
model_xgr_1 = XGBRegressor()
start_time = time.time()
model_xgr_1.fit(X_valid, Y_valid)
end_time = time.time()
print("Model Train time: {} mins.".format((end_time - start_time) / 60))
# Save model
model_xgr_1._Booster.save_model(OUTPUT_FOLDER + '.model')
else:
# Load from file
model_xgr_1 = Booster().load_model(OUTPUT_FOLDER + '.model')
Y_pred = model_xgr_1.predict(X_test)
# Get target variables back from log (antilog)
Y_pred_antilog = np.clip(np.expm1(Y_pred), 0, 1000)
Y_test_antilog = np.expm1(Y_test)
# Evaluation
weights = X_test["perishable"].values * 0.25 + 1
eval = Evaluator()
error_data = []
columns = ['Target unit', 'Data split', 'MSE', 'RMSE', 'NWRMSLE', 'MAE', 'MAPE']
mse_val_lg, rmse_val_lg, nwrmsle_val_lg, mae_val_lg, mape_val_lg = eval.get_error(weights, Y_test, Y_pred, 1)
mse_val, rmse_val, nwrmsle_val, mae_val, mape_val = eval.get_error(weights, Y_test_antilog, Y_pred_antilog, 1)
error_data.append(['Log', 'Test', mse_val_lg, rmse_val_lg, nwrmsle_val_lg, mae_val_lg, mape_val_lg])
error_data.append(['Unit', 'Test', mse_val, rmse_val, nwrmsle_val, mae_val, mape_val])
pd.DataFrame(error_data, columns=columns).to_csv(OUTPUT_FOLDER + '_evaluation.csv', index=False)
# Visualize
# plt.figure()
#
# plt.scatter(Y_test_antilog, Y_pred_antilog, color='blue')
# plt.xlabel("Unit Sales")
# plt.ylabel("Predicted Unit Sales")
# plt.title("Actual vs Predicted Unit Sales")
# plt.show()
| [
"razmik89@gmail.com"
] | razmik89@gmail.com |
a3da9504f28fd24a09d5a381d01999f1ecc2ed4b | 7949f96ee7feeaa163608dbd256b0b76d1b89258 | /toontown/catalog/CatalogItemPanel.py | eec5dcc756b6e374f53146c1236fb2ebf461b5a8 | [] | no_license | xxdecryptionxx/ToontownOnline | 414619744b4c40588f9a86c8e01cb951ffe53e2d | e6c20e6ce56f2320217f2ddde8f632a63848bd6b | refs/heads/master | 2021-01-11T03:08:59.934044 | 2018-07-27T01:26:21 | 2018-07-27T01:26:21 | 71,086,644 | 8 | 10 | null | 2018-06-01T00:13:34 | 2016-10-17T00:39:41 | Python | UTF-8 | Python | false | false | 29,895 | py | # File: t (Python 2.4)
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from toontown.toonbase import ToontownGlobals
from toontown.toontowngui import TTDialog
from toontown.toonbase import TTLocalizer
import CatalogItemTypes
import CatalogItem
from CatalogWallpaperItem import getAllWallpapers
from CatalogFlooringItem import getAllFloorings
from CatalogMouldingItem import getAllMouldings
from CatalogWainscotingItem import getAllWainscotings
from CatalogFurnitureItem import getAllFurnitures
from CatalogFurnitureItem import FLTrunk
from toontown.toontowngui.TeaserPanel import TeaserPanel
from otp.otpbase import OTPGlobals
from direct.directnotify import DirectNotifyGlobal
CATALOG_PANEL_WORDWRAP = 10
CATALOG_PANEL_CHAT_WORDWRAP = 9
CATALOG_PANEL_ACCESSORY_WORDWRAP = 11
class CatalogItemPanel(DirectFrame):
notify = DirectNotifyGlobal.directNotify.newCategory('CatalogItemPanel')
def __init__(self, parent = aspect2d, parentCatalogScreen = None, **kw):
optiondefs = (('item', None, DGG.INITOPT), ('type', CatalogItem.CatalogTypeUnspecified, DGG.INITOPT), ('relief', None, None))
self.parentCatalogScreen = parentCatalogScreen
self.defineoptions(kw, optiondefs)
DirectFrame.__init__(self, parent)
self.loaded = 0
self.initialiseoptions(CatalogItemPanel)
def load(self):
if self.loaded:
return None
self.loaded = 1
self.verify = None
self.pictureFrame = self.attachNewNode('pictureFrame')
self.pictureFrame.setScale(0.14999999999999999)
self.itemIndex = 0
self.ival = None
typeCode = self['item'].getTypeCode()
if self['item'].needsCustomize():
if typeCode == CatalogItemTypes.WALLPAPER_ITEM and typeCode == CatalogItemTypes.FLOORING_ITEM and typeCode == CatalogItemTypes.MOULDING_ITEM and typeCode == CatalogItemTypes.FURNITURE_ITEM and typeCode == CatalogItemTypes.WAINSCOTING_ITEM or typeCode == CatalogItemTypes.TOON_STATUE_ITEM:
if typeCode == CatalogItemTypes.WALLPAPER_ITEM:
self.items = getAllWallpapers(self['item'].patternIndex)
elif typeCode == CatalogItemTypes.FLOORING_ITEM:
self.items = getAllFloorings(self['item'].patternIndex)
elif typeCode == CatalogItemTypes.MOULDING_ITEM:
self.items = getAllMouldings(self['item'].patternIndex)
elif typeCode == CatalogItemTypes.FURNITURE_ITEM:
self.items = getAllFurnitures(self['item'].furnitureType)
elif typeCode == CatalogItemTypes.TOON_STATUE_ITEM:
self.items = self['item'].getAllToonStatues()
elif typeCode == CatalogItemTypes.WAINSCOTING_ITEM:
self.items = getAllWainscotings(self['item'].patternIndex)
self.numItems = len(self.items)
if self.numItems > 1:
guiItems = loader.loadModel('phase_5.5/models/gui/catalog_gui')
nextUp = guiItems.find('**/arrow_up')
nextRollover = guiItems.find('**/arrow_Rollover')
nextDown = guiItems.find('**/arrow_Down')
prevUp = guiItems.find('**/arrowUp')
prevDown = guiItems.find('**/arrowDown1')
prevRollover = guiItems.find('**/arrowRollover')
self.nextVariant = DirectButton(parent = self, relief = None, image = (nextUp, nextDown, nextRollover, nextUp), image3_color = (1, 1, 1, 0.40000000000000002), pos = (0.13, 0, 0), command = self.showNextVariant)
self.prevVariant = DirectButton(parent = self, relief = None, image = (prevUp, prevDown, prevRollover, prevUp), image3_color = (1, 1, 1, 0.40000000000000002), pos = (-0.13, 0, 0), command = self.showPrevVariant, state = DGG.DISABLED)
self.variantPictures = [
(None, None)] * self.numItems
else:
self.variantPictures = [
(None, None)]
self.showCurrentVariant()
else:
(picture, self.ival) = self['item'].getPicture(base.localAvatar)
if picture:
picture.reparentTo(self)
picture.setScale(0.14999999999999999)
self.items = [
self['item']]
self.variantPictures = [
(picture, self.ival)]
self.typeLabel = DirectLabel(parent = self, relief = None, pos = (0, 0, 0.23999999999999999), scale = TTLocalizer.CIPtypeLabel, text = self['item'].getTypeName(), text_fg = (0.94999999999999996, 0.94999999999999996, 0, 1), text_shadow = (0, 0, 0, 1), text_font = ToontownGlobals.getInterfaceFont(), text_wordwrap = CATALOG_PANEL_WORDWRAP)
self.auxText = DirectLabel(parent = self, relief = None, scale = 0.050000000000000003, pos = (-0.20000000000000001, 0, 0.16))
self.auxText.setHpr(0, 0, -30)
self.nameLabel = DirectLabel(parent = self, relief = None, text = self['item'].getDisplayName(), text_fg = (0, 0, 0, 1), text_font = ToontownGlobals.getInterfaceFont(), text_scale = TTLocalizer.CIPnameLabel, text_wordwrap = CATALOG_PANEL_WORDWRAP + TTLocalizer.CIPwordwrapOffset)
if self['item'].getTypeCode() == CatalogItemTypes.CHAT_ITEM:
self.nameLabel['text_wordwrap'] = CATALOG_PANEL_CHAT_WORDWRAP
numRows = self.nameLabel.component('text0').textNode.getNumRows()
if numRows == 1:
namePos = (0, 0, -0.059999999999999998)
elif numRows == 2:
namePos = (0, 0, -0.029999999999999999)
else:
namePos = (0, 0, 0)
nameScale = 0.063
elif self['item'].getTypeCode() == CatalogItemTypes.ACCESSORY_ITEM:
self.nameLabel['text_wordwrap'] = CATALOG_PANEL_ACCESSORY_WORDWRAP
namePos = (0, 0, -0.22)
nameScale = 0.059999999999999998
else:
namePos = (0, 0, -0.22)
nameScale = 0.059999999999999998
self.nameLabel.setPos(*namePos)
self.nameLabel.setScale(nameScale)
numericBeanPrice = self['item'].getPrice(self['type'])
priceStr = str(numericBeanPrice) + ' ' + TTLocalizer.CatalogCurrency
priceScale = 0.070000000000000007
if self['item'].isSaleItem():
priceStr = TTLocalizer.CatalogSaleItem + priceStr
priceScale = 0.059999999999999998
self.priceLabel = DirectLabel(parent = self, relief = None, pos = (0, 0, -0.29999999999999999), scale = priceScale, text = priceStr, text_fg = (0.94999999999999996, 0.94999999999999996, 0, 1), text_shadow = (0, 0, 0, 1), text_font = ToontownGlobals.getSignFont(), text_align = TextNode.ACenter)
self.createEmblemPrices(numericBeanPrice)
buttonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui')
upButton = buttonModels.find('**/InventoryButtonUp')
downButton = buttonModels.find('**/InventoryButtonDown')
rolloverButton = buttonModels.find('**/InventoryButtonRollover')
buyText = TTLocalizer.CatalogBuyText
buyTextScale = TTLocalizer.CIPbuyButton
if self['item'].isRental():
buyText = TTLocalizer.CatalogRentText
self.buyButton = DirectButton(parent = self, relief = None, pos = (0.20000000000000001, 0, 0.14999999999999999), scale = (0.69999999999999996, 1, 0.80000000000000004), text = buyText, text_scale = buyTextScale, text_pos = (-0.0050000000000000001, -0.01), image = (upButton, downButton, rolloverButton, upButton), image_color = (1.0, 0.20000000000000001, 0.20000000000000001, 1), image0_color = Vec4(1.0, 0.40000000000000002, 0.40000000000000002, 1), image3_color = Vec4(1.0, 0.40000000000000002, 0.40000000000000002, 0.40000000000000002), command = self._CatalogItemPanel__handlePurchaseRequest)
soundIcons = loader.loadModel('phase_5.5/models/gui/catalogSoundIcons')
soundOn = soundIcons.find('**/sound07')
soundOff = soundIcons.find('**/sound08')
self.soundOnButton = DirectButton(parent = self, relief = None, pos = (0.20000000000000001, 0, -0.14999999999999999), scale = (0.69999999999999996, 1, 0.80000000000000004), text_scale = buyTextScale, text_pos = (-0.0050000000000000001, -0.01), image = (upButton, downButton, rolloverButton, upButton), image_color = (0.20000000000000001, 0.5, 0.20000000000000001, 1), image0_color = Vec4(0.40000000000000002, 0.5, 0.40000000000000002, 1), image3_color = Vec4(0.40000000000000002, 0.5, 0.40000000000000002, 0.40000000000000002), command = self.handleSoundOnButton)
self.soundOnButton.hide()
soundOn.setScale(0.10000000000000001)
soundOn.reparentTo(self.soundOnButton)
self.soundOffButton = DirectButton(parent = self, relief = None, pos = (0.20000000000000001, 0, -0.14999999999999999), scale = (0.69999999999999996, 1, 0.80000000000000004), text_scale = buyTextScale, text_pos = (-0.0050000000000000001, -0.01), image = (upButton, downButton, rolloverButton, upButton), image_color = (0.20000000000000001, 1.0, 0.20000000000000001, 1), image0_color = Vec4(0.40000000000000002, 1.0, 0.40000000000000002, 1), image3_color = Vec4(0.40000000000000002, 1.0, 0.40000000000000002, 0.40000000000000002), command = self.handleSoundOffButton)
self.soundOffButton.hide()
soundOff = self.soundOffButton.attachNewNode('soundOff')
soundOn.copyTo(soundOff)
soundOff.reparentTo(self.soundOffButton)
upGButton = buttonModels.find('**/InventoryButtonUp')
downGButton = buttonModels.find('**/InventoryButtonDown')
rolloverGButton = buttonModels.find('**/InventoryButtonRollover')
self.giftButton = DirectButton(parent = self, relief = None, pos = (0.20000000000000001, 0, 0.14999999999999999), scale = (0.69999999999999996, 1, 0.80000000000000004), text = TTLocalizer.CatalogGiftText, text_scale = buyTextScale, text_pos = (-0.0050000000000000001, -0.01), image = (upButton, downButton, rolloverButton, upButton), image_color = (1.0, 0.20000000000000001, 0.20000000000000001, 1), image0_color = Vec4(1.0, 0.40000000000000002, 0.40000000000000002, 1), image3_color = Vec4(1.0, 0.40000000000000002, 0.40000000000000002, 0.40000000000000002), command = self._CatalogItemPanel__handleGiftRequest)
self.updateButtons()
def createEmblemPrices(self, numericBeanPrice):
priceScale = 0.070000000000000007
emblemPrices = self['item'].getEmblemPrices()
if emblemPrices:
if numericBeanPrice:
self.priceLabel.hide()
beanModel = loader.loadModel('phase_5.5/models/estate/jellyBean')
beanModel.setColorScale(1, 0, 0, 1)
self.beanPriceLabel = DirectLabel(parent = self, relief = None, pos = (0, 0, -0.29999999999999999), scale = priceScale, image = beanModel, image_pos = (-0.40000000000000002, 0, 0.40000000000000002), text = str(numericBeanPrice), text_fg = (0.94999999999999996, 0.94999999999999996, 0, 1), text_shadow = (0, 0, 0, 1), text_font = ToontownGlobals.getSignFont(), text_align = TextNode.ALeft)
else:
self.priceLabel.hide()
goldPrice = 0
silverPrice = 0
emblemIcon = loader.loadModel('phase_3.5/models/gui/tt_m_gui_gen_emblemIcons')
silverModel = emblemIcon.find('**/tt_t_gui_gen_emblemSilver')
goldModel = emblemIcon.find('**/tt_t_gui_gen_emblemGold')
if ToontownGlobals.EmblemTypes.Silver < len(emblemPrices):
silverPrice = emblemPrices[ToontownGlobals.EmblemTypes.Silver]
if silverPrice:
self.silverPriceLabel = DirectLabel(parent = self, relief = None, pos = (0, 0, -0.29999999999999999), scale = priceScale, image = silverModel, image_pos = (-0.40000000000000002, 0, 0.40000000000000002), text = str(silverPrice), text_fg = (0.94999999999999996, 0.94999999999999996, 0, 1), text_shadow = (0, 0, 0, 1), text_font = ToontownGlobals.getSignFont(), text_align = TextNode.ALeft)
if ToontownGlobals.EmblemTypes.Gold < len(emblemPrices):
goldPrice = emblemPrices[ToontownGlobals.EmblemTypes.Gold]
if goldPrice:
self.goldPriceLabel = DirectLabel(parent = self, relief = None, pos = (0, 0, -0.29999999999999999), scale = priceScale, image = goldModel, image_pos = (-0.40000000000000002, 0, 0.40000000000000002), text = str(goldPrice), text_fg = (0.94999999999999996, 0.94999999999999996, 0, 1), text_shadow = (0, 0, 0, 1), text_font = ToontownGlobals.getSignFont(), text_align = TextNode.ALeft)
numPrices = 0
if numericBeanPrice:
numPrices += 1
if silverPrice:
numPrices += 1
if goldPrice:
numPrices += 1
if numPrices == 2:
if not numericBeanPrice:
self.silverPriceLabel.setX(-0.14999999999999999)
self.goldPriceLabel.setX(0.14999999999999999)
if not silverPrice:
self.goldPriceLabel.setX(-0.14999999999999999)
self.beanPriceLabel.setX(0.14999999999999999)
if not goldPrice:
self.silverPriceLabel.setX(-0.14999999999999999)
self.beanPriceLabel.setX(0.14999999999999999)
elif numPrices == 3:
self.silverPriceLabel.setX(-0.20000000000000001)
self.goldPriceLabel.setX(0)
self.beanPriceLabel.setX(0.14999999999999999)
def showNextVariant(self):
messenger.send('wakeup')
self.hideCurrentVariant()
self.itemIndex += 1
if self.itemIndex >= self.numItems - 1:
self.itemIndex = self.numItems - 1
self.nextVariant['state'] = DGG.DISABLED
else:
self.nextVariant['state'] = DGG.NORMAL
self.prevVariant['state'] = DGG.NORMAL
self.showCurrentVariant()
def showPrevVariant(self):
messenger.send('wakeup')
self.hideCurrentVariant()
self.itemIndex -= 1
if self.itemIndex < 0:
self.itemIndex = 0
self.prevVariant['state'] = DGG.DISABLED
else:
self.prevVariant['state'] = DGG.NORMAL
self.nextVariant['state'] = DGG.NORMAL
self.showCurrentVariant()
def showCurrentVariant(self):
(newPic, self.ival) = self.variantPictures[self.itemIndex]
if self.ival:
self.ival.finish()
if not newPic:
variant = self.items[self.itemIndex]
(newPic, self.ival) = variant.getPicture(base.localAvatar)
self.variantPictures[self.itemIndex] = (newPic, self.ival)
newPic.reparentTo(self.pictureFrame)
if self.ival:
self.ival.loop()
if self['item'].getTypeCode() == CatalogItemTypes.TOON_STATUE_ITEM:
if hasattr(self, 'nameLabel'):
self.nameLabel['text'] = self.items[self.itemIndex].getDisplayName()
self['item'].gardenIndex = self.items[self.itemIndex].gardenIndex
def hideCurrentVariant(self):
currentPic = self.variantPictures[self.itemIndex][0]
if currentPic:
currentPic.detachNode()
def unload(self):
if not self.loaded:
DirectFrame.destroy(self)
return None
self.loaded = 0
if self['item'].getTypeCode() == CatalogItemTypes.TOON_STATUE_ITEM:
self['item'].deleteAllToonStatues()
self['item'].gardenIndex = self['item'].startPoseIndex
self.nameLabel['text'] = self['item'].getDisplayName()
self['item'].requestPurchaseCleanup()
for (picture, ival) in self.variantPictures:
if picture:
picture.destroy()
if ival:
ival.finish()
continue
self.variantPictures = None
if self.ival:
self.ival.finish()
self.ival = None
if len(self.items):
self.items[0].cleanupPicture()
self.pictureFrame.remove()
self.pictureFrame = None
self.items = []
if self.verify:
self.verify.cleanup()
DirectFrame.destroy(self)
def destroy(self):
self.parentCatalogScreen = None
self.unload()
def getTeaserPanel(self):
typeName = self['item'].getTypeName()
if typeName == TTLocalizer.EmoteTypeName or typeName == TTLocalizer.ChatTypeName:
page = 'emotions'
elif typeName == TTLocalizer.GardenTypeName or typeName == TTLocalizer.GardenStarterTypeName:
page = 'gardening'
else:
page = 'clothing'
def showTeaserPanel():
TeaserPanel(pageName = page)
return showTeaserPanel
def updateBuyButton(self):
if not self.loaded:
return None
if not base.cr.isPaid():
self.buyButton['command'] = self.getTeaserPanel()
self.buyButton.show()
typeCode = self['item'].getTypeCode()
orderCount = base.localAvatar.onOrder.count(self['item'])
if orderCount > 0:
if orderCount > 1:
auxText = '%d %s' % (orderCount, TTLocalizer.CatalogOnOrderText)
else:
auxText = TTLocalizer.CatalogOnOrderText
else:
auxText = ''
isNameTag = typeCode == CatalogItemTypes.NAMETAG_ITEM
if isNameTag and not (localAvatar.getGameAccess() == OTPGlobals.AccessFull):
if self['item'].nametagStyle == 100:
if localAvatar.getFont() == ToontownGlobals.getToonFont():
auxText = TTLocalizer.CatalogCurrent
self.buyButton['state'] = DGG.DISABLED
elif self['item'].getPrice(self['type']) > base.localAvatar.getMoney() + base.localAvatar.getBankMoney():
self.buyButton['state'] = DGG.DISABLED
elif isNameTag and self['item'].nametagStyle == localAvatar.getNametagStyle():
auxText = TTLocalizer.CatalogCurrent
self.buyButton['state'] = DGG.DISABLED
elif self['item'].reachedPurchaseLimit(base.localAvatar):
max = self['item'].getPurchaseLimit()
if max <= 1:
auxText = TTLocalizer.CatalogPurchasedText
if self['item'].hasBeenGifted(base.localAvatar):
auxText = TTLocalizer.CatalogGiftedText
else:
auxText = TTLocalizer.CatalogPurchasedMaxText
self.buyButton['state'] = DGG.DISABLED
elif hasattr(self['item'], 'noGarden') and self['item'].noGarden(base.localAvatar):
auxText = TTLocalizer.NoGarden
self.buyButton['state'] = DGG.DISABLED
elif hasattr(self['item'], 'isSkillTooLow') and self['item'].isSkillTooLow(base.localAvatar):
auxText = TTLocalizer.SkillTooLow
self.buyButton['state'] = DGG.DISABLED
elif hasattr(self['item'], 'getDaysToGo') and self['item'].getDaysToGo(base.localAvatar):
auxText = TTLocalizer.DaysToGo % self['item'].getDaysToGo(base.localAvatar)
self.buyButton['state'] = DGG.DISABLED
elif self['item'].getEmblemPrices() and not base.localAvatar.isEnoughMoneyAndEmblemsToBuy(self['item'].getPrice(self['type']), self['item'].getEmblemPrices()):
self.buyButton['state'] = DGG.DISABLED
elif self['item'].getPrice(self['type']) <= base.localAvatar.getMoney() + base.localAvatar.getBankMoney():
self.buyButton['state'] = DGG.NORMAL
self.buyButton.show()
else:
self.buyButton['state'] = DGG.DISABLED
self.buyButton.show()
self.auxText['text'] = auxText
def _CatalogItemPanel__handlePurchaseRequest(self):
if self['item'].replacesExisting() and self['item'].hasExisting():
if self['item'].getFlags() & FLTrunk:
message = TTLocalizer.CatalogVerifyPurchase % {
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']) }
else:
message = TTLocalizer.CatalogOnlyOnePurchase % {
'old': self['item'].getYourOldDesc(),
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']) }
elif self['item'].isRental():
message = TTLocalizer.CatalogVerifyRent % {
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']) }
else:
emblemPrices = self['item'].getEmblemPrices()
if emblemPrices:
silver = emblemPrices[ToontownGlobals.EmblemTypes.Silver]
gold = emblemPrices[ToontownGlobals.EmblemTypes.Gold]
price = self['item'].getPrice(self['type'])
if price and silver and gold:
message = TTLocalizer.CatalogVerifyPurchaseBeanSilverGold % {
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']),
'silver': silver,
'gold': gold }
elif price and silver:
message = TTLocalizer.CatalogVerifyPurchaseBeanSilver % {
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']),
'silver': silver,
'gold': gold }
elif price and gold:
message = TTLocalizer.CatalogVerifyPurchaseBeanGold % {
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']),
'silver': silver,
'gold': gold }
elif silver and gold:
message = TTLocalizer.CatalogVerifyPurchaseSilverGold % {
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']),
'silver': silver,
'gold': gold }
elif silver:
message = TTLocalizer.CatalogVerifyPurchaseSilver % {
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']),
'silver': silver,
'gold': gold }
elif gold:
message = TTLocalizer.CatalogVerifyPurchaseGold % {
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']),
'silver': silver,
'gold': gold }
else:
self.notify.warning('is this a completely free item %s?' % self['item'].getName())
message = TTLocalizer.CatalogVerifyPurchase % {
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']) }
else:
message = TTLocalizer.CatalogVerifyPurchase % {
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']) }
self.verify = TTDialog.TTGlobalDialog(doneEvent = 'verifyDone', message = message, style = TTDialog.TwoChoice)
self.verify.show()
self.accept('verifyDone', self._CatalogItemPanel__handleVerifyPurchase)
def _CatalogItemPanel__handleVerifyPurchase(self):
if base.config.GetBool('want-qa-regression', 0):
self.notify.info('QA-REGRESSION: CATALOG: Order item')
status = self.verify.doneStatus
self.ignore('verifyDone')
self.verify.cleanup()
del self.verify
self.verify = None
if status == 'ok':
item = self.items[self.itemIndex]
messenger.send('CatalogItemPurchaseRequest', [
item])
self.buyButton['state'] = DGG.DISABLED
def _CatalogItemPanel__handleGiftRequest(self):
if self['item'].replacesExisting() and self['item'].hasExisting():
message = TTLocalizer.CatalogOnlyOnePurchase % {
'old': self['item'].getYourOldDesc(),
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']) }
else:
friendIndex = self.parentCatalogScreen.friendGiftIndex
friendText = 'Error'
numFriends = len(base.localAvatar.friendsList) + len(base.cr.avList) - 1
if numFriends > 0:
friendText = self.parentCatalogScreen.receiverName
message = TTLocalizer.CatalogVerifyGift % {
'item': self['item'].getName(),
'price': self['item'].getPrice(self['type']),
'friend': friendText }
self.verify = TTDialog.TTGlobalDialog(doneEvent = 'verifyGiftDone', message = message, style = TTDialog.TwoChoice)
self.verify.show()
self.accept('verifyGiftDone', self._CatalogItemPanel__handleVerifyGift)
def _CatalogItemPanel__handleVerifyGift(self):
if base.config.GetBool('want-qa-regression', 0):
self.notify.info('QA-REGRESSION: CATALOG: Gift item')
status = self.verify.doneStatus
self.ignore('verifyGiftDone')
self.verify.cleanup()
del self.verify
self.verify = None
if status == 'ok':
self.giftButton['state'] = DGG.DISABLED
item = self.items[self.itemIndex]
messenger.send('CatalogItemGiftPurchaseRequest', [
item])
def updateButtons(self, giftActivate = 0):
if self.parentCatalogScreen.gifting == -1:
self.updateBuyButton()
if self.loaded:
self.giftButton.hide()
else:
self.updateGiftButton(giftActivate)
if self.loaded:
self.buyButton.hide()
def updateGiftButton(self, giftUpdate = 0):
if not self.loaded:
return None
self.giftButton.show()
if giftUpdate == 0:
return None
if not base.cr.isPaid():
self.giftButton['command'] = self.getTeaserPanel()
self.auxText['text'] = ' '
numFriends = len(base.localAvatar.friendsList) + len(base.cr.avList) - 1
if numFriends > 0:
self.giftButton['state'] = DGG.DISABLED
self.giftButton.show()
auxText = ' '
if self['item'].isGift() <= 0:
self.giftButton.show()
self.giftButton['state'] = DGG.DISABLED
auxText = TTLocalizer.CatalogNotAGift
self.auxText['text'] = auxText
return None
elif self.parentCatalogScreen.gotAvatar == 1:
avatar = self.parentCatalogScreen.giftAvatar
if (self['item'].forBoysOnly() or avatar.getStyle().getGender() == 'f' or self['item'].forGirlsOnly()) and avatar.getStyle().getGender() == 'm':
self.giftButton.show()
self.giftButton['state'] = DGG.DISABLED
auxText = TTLocalizer.CatalogNoFit
self.auxText['text'] = auxText
return None
elif self['item'].reachedPurchaseLimit(avatar):
self.giftButton.show()
self.giftButton['state'] = DGG.DISABLED
auxText = TTLocalizer.CatalogPurchasedGiftText
self.auxText['text'] = auxText
return None
elif len(avatar.mailboxContents) + len(avatar.onGiftOrder) >= ToontownGlobals.MaxMailboxContents:
self.giftButton.show()
self.giftButton['state'] = DGG.DISABLED
auxText = TTLocalizer.CatalogMailboxFull
self.auxText['text'] = auxText
return None
elif self['item'].getPrice(self['type']) <= base.localAvatar.getMoney() + base.localAvatar.getBankMoney():
self.giftButton['state'] = DGG.NORMAL
self.giftButton.show()
def handleSoundOnButton(self):
item = self.items[self.itemIndex]
self.soundOnButton.hide()
self.soundOffButton.show()
if hasattr(item, 'changeIval'):
if self.ival:
self.ival.finish()
self.ival = None
self.ival = item.changeIval(volume = 1)
self.ival.loop()
def handleSoundOffButton(self):
item = self.items[self.itemIndex]
self.soundOffButton.hide()
self.soundOnButton.show()
if hasattr(item, 'changeIval'):
if self.ival:
self.ival.finish()
self.ival = None
self.ival = item.changeIval(volume = 0)
self.ival.loop()
| [
"fr1tzanatore@aol.com"
] | fr1tzanatore@aol.com |
c79c81164b271f1d1496685ba5622aac52e7171a | 2e2b87f7152d9578f4445e1a62029c78f89add05 | /pycog-master/pycog/theanotools.py | 8f0909ec63b2c887ec851c322723c1f7fcbb3798 | [
"MIT"
] | permissive | amartyap/Mitigating-Catastrophic-Forgetting-in-Biologically-Inspired-RNNs-Using-Deep-Generative-Replay | cd2d3ae4be8f5e8f5e4210da5e81688459aa8808 | 726f76f6aa9758c2df7bd717517c3871743a925e | refs/heads/main | 2023-02-26T15:27:27.277408 | 2021-02-08T00:43:58 | 2021-02-08T00:43:58 | 336,893,535 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,192 | py | """
Theano-specific functions.
"""
import numpy as np
import theano
import theano.tensor as T
#=========================================================================================
# Activation functions and some of their derivatives
#=========================================================================================
# Newer version of Theano has built-in ReLU
if hasattr(T.nnet, 'relu'):
rectify = T.nnet.relu
else:
def rectify(x):
return T.switch(x > 0, x, 0)
def d_rectify(x):
return T.switch(x > 0, 1, 0)
def rectify_power(x, n=2):
return T.switch(x > 0, x**n, 0)
def d_rectify_power(x, n=2):
return T.switch(x > 0, n*x**(n-1), 0)
sigmoid = T.nnet.sigmoid
def d_sigmoid(x):
return sigmoid(x)*(1 - sigmoid(x))
tanh = T.tanh
def d_tanh(x):
return 1 - tanh(x)**2
def rtanh(x):
return rectify(tanh(x))
def d_rtanh(x):
return T.switch(x > 0, d_tanh(x), 0)
def softplus(x):
return T.log(1 + T.exp(x))
d_softplus = sigmoid
def softmax(x):
"""
Softmax function.
Parameters
----------
x : theano.tensor.tensor3
This function assumes the outputs are the third dimension of x.
"""
sh = x.shape
x = x.reshape((sh[0]*sh[1], sh[2]))
fx = T.nnet.softmax(x)
fx = fx.reshape(sh)
return fx
#-----------------------------------------------------------------------------------------
# Gather all functions into a convenient dictionary.
#-----------------------------------------------------------------------------------------
hidden_activations = {
'linear': (lambda x: x, lambda x: 1),
'rectify': (rectify, d_rectify),
'rectify_power': (rectify_power, d_rectify_power),
'sigmoid': (sigmoid, d_sigmoid),
'tanh': (tanh, d_tanh),
'rtanh': (rtanh, d_rtanh),
'softplus': (softplus, d_softplus)
}
output_activations = {
'linear': (lambda x: x),
'rectify': rectify,
'rectify_power': rectify_power,
'sigmoid': sigmoid,
'softmax': softmax
}
#=========================================================================================
# Loss functions
#=========================================================================================
epsilon = 1e-10
def binary_crossentropy(y, t):
return -t*T.log(y + epsilon) - (1-t)*T.log((1-y) + epsilon)
def categorical_crossentropy(y, t):
return -t*T.log(y + epsilon)
def L2(y, t):
return (y - t)**2
#=========================================================================================
# Theano
#=========================================================================================
def grad(*args, **kwargs):
kwargs.setdefault('disconnected_inputs', 'warn')
return T.grad(*args, **kwargs)
def function(*args, **kwargs):
kwargs.setdefault('on_unused_input', 'warn')
return theano.function(*args, **kwargs)
#=========================================================================================
# NumPy-Theano
#=========================================================================================
def shared(x, dtype=theano.config.floatX, **kwargs):
if x.dtype == dtype:
return theano.shared(x, **kwargs)
return theano.shared(np.asarray(x, dtype=dtype), **kwargs)
def shared_scalar(x, dtype=theano.config.floatX, **kwargs):
return theano.shared(np.cast[dtype](x), **kwargs)
def shared_zeros(shape, dtype=theano.config.floatX, **kwargs):
return theano.shared(np.zeros(shape), dtype=dtype, **kwargs)
#=========================================================================================
# GPU
#=========================================================================================
def get_processor_type():
"""
Test whether the GPU is being used, based on the example in
http://deeplearning.net/software/theano/tutorial/using_gpu.html
"""
rng = np.random.RandomState(22)
n = 10*30*768
x = shared(rng.rand(n))
f = function([], T.exp(x))
if np.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]):
return 'cpu'
return 'gpu'
| [
"noreply@github.com"
] | amartyap.noreply@github.com |
4103376dbbca20b7caa6c000a96c5304895c31f9 | e017eca53dbe0d35977546df1bb36a59915f6899 | /debugging/assert_variable.py | 8aec26cfafa0f80b02465a455cc3c785aa89bd35 | [] | no_license | clivejan/python_basic | 7d14b7335f253658f8814acbdb753a735481e377 | 773de644a87792b872e38017dcac34c1691ccc87 | refs/heads/master | 2020-12-04T17:44:24.737370 | 2020-01-09T14:43:36 | 2020-01-18T03:11:20 | 231,856,419 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 334 | py | #!/usr/bin/env python3 -O
# Assertion is used for programmer errors and
# should not use try except to handle it.
# Status well
job_title = 'DevOps'
assert job_title == "DevOps", "Tansform from SE to DevOps"
# Status wrong
job_title = 'Systems Engineer'
assert job_title == "DevOps", "Tansform from SE to DevOps"
print(job_title)
| [
"clive.jan@gmail.com"
] | clive.jan@gmail.com |
0116db3631d3d531836248a0bca1d5d46ba83d49 | 302442c32bacca6cde69184d3f2d7529361e4f3c | /cidtrsend-all/stage3-model/pytz/zoneinfo/Africa/Bujumbura.py | 76c4c7a6e44ba67e832b34d93a452c2827caf84f | [] | no_license | fucknoob/WebSemantic | 580b85563072b1c9cc1fc8755f4b09dda5a14b03 | f2b4584a994e00e76caccce167eb04ea61afa3e0 | refs/heads/master | 2021-01-19T09:41:59.135927 | 2015-02-07T02:11:23 | 2015-02-07T02:11:23 | 30,441,659 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 391 | py | '''tzinfo timezone information for Africa/Bujumbura.'''
from pytz.tzinfo import StaticTzInfo
from pytz.tzinfo import memorized_timedelta as timedelta
class Bujumbura(StaticTzInfo):
'''Africa/Bujumbura timezone definition. See datetime.tzinfo for details'''
zone = 'Africa/Bujumbura'
_utcoffset = timedelta(seconds=7200)
_tzname = 'CAT'
Bujumbura = Bujumbura()
| [
"learnfuzzy@gmail.com"
] | learnfuzzy@gmail.com |
2cce0f58bbafa9e5f7a2c1eccbc003d304a93de3 | 48372a9277013edb66f66624a26f5a4af2770c3b | /venv/Scripts/pip-script.py | 1c6164604ad89129d1ff06c983053dbc4a938f29 | [] | no_license | vhyu/test | a9e9374edd25bffc09d46428364487ecbbed5557 | 69a5717910dcaa493e884c66cdb1878db2aa068b | refs/heads/master | 2020-03-20T07:57:33.725580 | 2018-11-20T07:05:21 | 2018-11-20T07:05:21 | 137,295,386 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 393 | py | #!D:\pycharm_Pros\test\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip'
__requires__ = 'pip==10.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==10.0.1', 'console_scripts', 'pip')()
)
| [
"1185895906@qq.com"
] | 1185895906@qq.com |
ab96c2674dd84ae1432b1ef67ca398aa1e033854 | 71f3ecb8fc4666fcf9a98d39caaffc2bcf1e865c | /.history/第2章/2-2/lishi_20200527235931.py | 947e75d59de12d8489b2a6b14a7c1c09b49fe148 | [
"MIT"
] | permissive | dltech-xyz/Alg_Py_Xiangjie | 03a9cac9bdb062ce7a0d5b28803b49b8da69dcf3 | 877c0f8c75bf44ef524f858a582922e9ca39bbde | refs/heads/master | 2022-10-15T02:30:21.696610 | 2020-06-10T02:35:36 | 2020-06-10T02:35:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 955 | py | #!/usr/bin/env python
# coding=utf-8
'''
@version:
@Author: steven
@Date: 2020-05-27 22:20:22
@LastEditors: steven
@LastEditTime: 2020-05-27 23:59:31
@Description:将列表的最后几项作为历史记录的过程。
'''
from _collections import deque
def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line, previous_lines
previous_lines.append(line)
# Example use on a file
if __name__ == '__main__':
with open('\123.txt') as f:
# with open('123.txt') as f: # FileNotFoundError: [Errno 2] No such file or directory: '123.txt'
for line, prevlines in search(f, 'python', 5):
for pline in prevlines:
print(pline) # print (pline, end='')
print(line) # print (pline, end='')
print('-' * 20)
q = deque(maxlen=3)
q.append(1)
q.append(2)
q.append(3)
print(q)
q.append(4)
print(q)
| [
"a867907127@gmail.com"
] | a867907127@gmail.com |
82c5ce7b4ebbb0b5752945713ead109a06be2960 | 16ba38ef11b82e93d3b581bbff2c21e099e014c4 | /haohaninfo/Python_Future_Sample/實單交易/90.py | dbf39a68d38224f520449600d95099dfb3431206 | [] | no_license | penguinwang96825/Auto-Trading | cb7a5addfec71f611bdd82534b90e5219d0602dd | a031a921dbc036681c5054f2c035f94499b95d2e | refs/heads/master | 2022-12-24T21:25:34.835436 | 2020-09-22T09:59:56 | 2020-09-22T09:59:56 | 292,052,986 | 2 | 5 | null | null | null | null | UTF-8 | Python | false | false | 1,692 | py | # -*- coding: UTF-8 -*-
# 載入相關套件
import sys,indicator,datetime,haohaninfo
# 券商
Broker = 'Masterlink_Future'
# 定義資料類別
Table = 'match'
# 定義商品名稱
Prod = sys.argv[1]
# 取得當天日期
Date = datetime.datetime.now().strftime("%Y%m%d")
# K棒物件
KBar = indicator.KBar(Date,'time',1)
# 定義威廉指標的週期、超買區、超賣區
WILLRPeriod = 14
OverBuy = -20
OverSell = -80
# 預設趨勢為1,假設只有多單進場
Trend=1
# 進場判斷
Index=0
GO = haohaninfo.GOrder.GOQuote()
for i in GO.Describe(Broker, Table, Prod):
time = datetime.datetime.strptime(i[0],'%Y/%m/%d %H:%M:%S.%f')
price=float(i[2])
qty=int(i[3])
tag=KBar.TimeAdd(time,price,qty)
# 更新K棒才判斷,若要逐筆判斷則 註解下面兩行
if tag != 1:
continue
Real = KBar.GetWILLR(WILLRPeriod)
# 當威廉指標已經計算完成,才會去進行判斷
if len(Real) > WILLRPeriod+1:
ThisReal = Real[-1-tag]
LastReal = Real[-2-tag]
# 進入超賣區 並且回檔
if Trend==1 and ThisReal > OverSell and LastReal <= OverSell:
Index=1
OrderTime=time
OrderPrice=price
print(OrderTime,"Order Buy Price:",OrderPrice,"Success!")
GO.EndDescribe()
# 進入超買區 並且回檔
elif Trend==-1 and ThisReal < OverBuy and LastReal >= OverBuy:
Index=-1
OrderTime=time
OrderPrice=price
print(OrderTime,"Order Sell Price:",OrderPrice,"Success!")
GO.EndDescribe()
| [
"penguinwang@smail.nchu.edu.tw"
] | penguinwang@smail.nchu.edu.tw |
f7556c2c0872e68f85c41540f2e3065b1dd4e43c | d3ed759fa163fd9dbf8c89f214bf098e6467ffef | /evaluate_models.py | 998e4350abe0f923666ee33cb0a7ca034fc6b173 | [] | no_license | BasdekD/adaptive-goal-setting | 83ab0191a01b1f9d133d41d2f4643efc03629bcc | 3a36abba86733f8c406d2e10b137d6d366e60ea9 | refs/heads/master | 2023-03-27T00:25:50.799358 | 2021-03-30T17:31:24 | 2021-03-30T17:31:24 | 320,591,695 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,049 | py | import utilities
import pickle
from sklearn.model_selection import KFold, GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from matplotlib import pyplot
from sklearn.metrics import mean_absolute_error
n_per_in = 5
n_per_out = 1
X, y = utilities.get_dataset(n_per_in, n_per_out)
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42)
# create pipeline
rfe = utilities.get_feature_selector('gbr', n_per_in)
models = utilities.get_models(['dt', 'gbr'])
results, names = list(), list()
for name, model in models.items():
cv = KFold(n_splits=5, shuffle=False)
pipeline = Pipeline(steps=[('feature_selector', rfe), ('model', model['estimator'])])
print("Creating pipeline with %s model..." % name)
predictor = GridSearchCV(
estimator=pipeline,
param_grid=model['grid_params'],
scoring='neg_mean_absolute_error',
cv=cv,
refit=True
)
predictor.fit(x_train, y_train)
filename = 'model_%s_%d.sav' % (name, n_per_in)
print("Writing %s model to file..." % name)
pickle.dump(predictor, open(filename, 'wb'))
# evaluate model
print("Getting predictions for validation set")
y_predicted = predictor.predict(x_test)
print('MAE in validation set for %s: %.3f' % (name, mean_absolute_error(y_test, y_predicted)))
score = predictor.best_score_
results.append(score)
names.append(name)
# report performance
print('>%s %.3f' % (name, score))
pyplot.plot(y_predicted, label='Predicted')
# Printing and plotting the actual values
pyplot.plot(y_test, label='Actual')
pyplot.title(f"Predicted vs Actual Daily Step Counts")
pyplot.ylabel("Steps")
pyplot.legend()
pyplot.show()
pyplot.figure()
pyplot.title('CV MAE PER MODEL')
pyplot.xlabel("Algorithms")
pyplot.ylabel("MAE")
pyplot.bar(names, results)
pyplot.show()
# plot model performance for comparison
pyplot.figure()
pyplot.title('CV MAE PER MODEL')
pyplot.boxplot(results, labels=names, showmeans=True)
pyplot.show()
| [
"basdekd@gmail.com"
] | basdekd@gmail.com |
656cf5d3b96ae6e55fabe7ef867931afbe05fcec | 1712da976dcde5e618c3036a3e321abfeb9ae10e | /facefrontend.py | 510dd8662308bfeacb77d74299d6e7b9d8f14127 | [] | no_license | rasikasd/Face-Recognition | 5478ce4e4b98c94ab8a478603fa8c3b576bcfbd9 | a07ef677ba740de47a0fba5527a63d550a4cfc72 | refs/heads/master | 2022-12-25T04:41:41.531909 | 2020-10-13T14:44:58 | 2020-10-13T14:44:58 | 303,730,919 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,227 | py | # Face Recognition
# Importing the libraries
from PIL import Image
from keras.applications.vgg16 import preprocess_input
import base64
from io import BytesIO
import json
import random
import cv2
from keras.models import load_model
import numpy as np
from keras.preprocessing import image
model = load_model('facefeatures1_new_model.h5')
# Loading the cascades
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
def face_extractor(img):
# Function detects faces and returns the cropped face
# If no face detected, it returns the input image
#gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(img, 1.3, 5)
if faces is ():
return None
# Crop all faces found
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,255),2)
cropped_face = img[y:y+h, x:x+w]
return cropped_face
# Doing some Face Recognition with the webcam
video_capture = cv2.VideoCapture(0)
while True:
_, frame = video_capture.read()
#canvas = detect(gray, frame)
#image, face =face_detector(frame)
face=face_extractor(frame)
if type(face) is np.ndarray:
face = cv2.resize(face, (224, 224))
im = Image.fromarray(face, 'RGB')
#Resizing into 128x128 because we trained the model with this image size.
img_array = np.array(im)
#Our keras model used a 4D tensor, (images x height x width x channel)
#So changing dimension 128x128x3 into 1x128x128x3
img_array = np.expand_dims(img_array, axis=0)
pred = model.predict(img_array)
print(pred)
name="None matching"
if(pred[0][1]>0.5):
name='Rasika'
if(pred[0][0]>0.5):
name='Punit'
cv2.putText(frame,name, (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
else:
cv2.putText(frame,"No face found", (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows() | [
"noreply@github.com"
] | rasikasd.noreply@github.com |
b8bda1432b11e5c0d7a42b0917e667b6dd531d95 | 35139f27f0164435ea4ab9d74eea0bef094fd7f5 | /game/models.py | a65ef63c6a9e215d5ac9c17ed4fb62c8229a7e44 | [
"MIT"
] | permissive | robertoassuncaofilho/break2moveapi | eeae67bd99d4d2e180715361bb120da7e04d88bb | 9261030b5806ac0b6db26518758bab2545da4d37 | refs/heads/main | 2023-03-27T11:34:11.682617 | 2021-03-18T14:04:07 | 2021-03-18T14:04:07 | 344,245,788 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,116 | py | from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.contrib.auth.models import User
CHALLENGE_TYPE_CHOICES = [('body','body'), ('eye', 'eye')]
class Challenge (models.Model):
type = models.CharField(max_length=10,choices=CHALLENGE_TYPE_CHOICES)
description = models.CharField(max_length=255)
points = models.IntegerField(validators = [MinValueValidator(0), MaxValueValidator(100)])
def __str__(self):
return self.description
class Profile (models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
picture = models.ImageField(blank=True, null=True)
def __str__(self):
return self.user.get_full_name()
class CompletedChallenge(models.Model):
challenge = models.ForeignKey('Challenge', on_delete=models.PROTECT)
completed_at = models.DateTimeField(auto_now_add=True)
profile = models.ForeignKey('Profile', on_delete=models.CASCADE)
def __str__(self):
return "Challenge completed by %s at %s" % (self.profile.user.first_name, self.completed_at.strftime('%d/%m/%Y'))
| [
"roberto.16@gmail.com"
] | roberto.16@gmail.com |
09f31b04bd8dec149b4f477b92f1b1a0af7bcc03 | 6464d555f711d5f9903c5b8ac50b67ef6adf0335 | /audit_rest/audit_rest/client.py | 2e0f0e3173705dd56e7504ae30a34c5b61865530 | [] | no_license | markcxli/Auditing_service_for_HIL | eccc2caa5c47627d067bcd3f93d5ae6d1e466b36 | 9b36300a2b064168609407caad039908477b6231 | refs/heads/master | 2022-06-09T18:42:30.634406 | 2019-01-31T20:22:39 | 2019-01-31T20:22:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,348 | py | #!/usr/bin/env python
import sys
import os
from hil_calls import HILCLI
import SwitchCalls
class AuditClient(object):
def list_nodes(self, list_type):
response = HILCLI().list_nodes(list_type)
return response
def list_projects(self):
response = HILCLI().list_projects()
return response
def list_project_network(self, project):
response = HILCLI().list_project_network(project)
return response
def show_network(self, network):
response = HILCLI().show_network(network)
return response
def show_node(self,node_name):
response = HILCLI().show_node(node_name)
return response
def get_node_info(self, node_name):
response = {}
node_info = HILCLI().show_node(node_name)
if (node_info["project"] != None):
response["project"] = node_info["project"]
network = self.list_project_network(response["project"])
response["network"] = network
vlan = []
for n in network:
vlan.append(AuditClient().show_network(n)["channels"])
response["vlan"] = vlan
else:
response["project"] = ""
response["network"] = []
response["vlan"] = [[]]
return response
# -------- SWITCH FUNCTIONS ------------
def list_switch_vlans(self, port):
response = SwitchCalls.list_vlans(port)
return response
def list_switch_ports(self, vlan):
response = SwitchCalls.list_ports(vlan)
return response
| [
"markli@vpn-offcampus-168-122-67-34.bu.edu"
] | markli@vpn-offcampus-168-122-67-34.bu.edu |
e8cbf6ff31b09f8e7a3f1d5399007bd968c2e0c9 | 572326c2beaf2a801672e79d1759d50e8195c512 | /tests/database/contentdb_tests.py | e6dbd0ee44057b3261228cf7511dbe32c3d0029d | [] | no_license | eirikba/ebakup | 84e76939b77e5890326d387a5793b5c2ec854ff4 | 577dc175ceed90704453aa3e7db55adfcb28bc91 | refs/heads/master | 2023-01-22T06:44:23.594212 | 2023-01-15T11:36:03 | 2023-01-15T12:07:01 | 39,680,008 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,173 | py | #!/usr/bin/env python3
import datetime
import unittest
import testdata
import pyebakup.database.contentdb as contentdb
class FakeDatabase(object):
def __init__(self, tree, path):
self._tree = tree
self._path = path
class FakeTree(object):
def __init__(self):
self._files = {}
def _add_file(self, path, content):
self._files[path] = FakeFileData(content)
def get_item_at_path(self, path):
return FakeFile(self._files[path])
def get_modifiable_item_at_path(self, path):
f = FakeFile(self._files[path])
f._modifiable = True
return f
def is_open_file_same_as_path(self, f, path):
return f._is_same_as(self._files[path])
class FakeFileData(object):
def __init__(self, content):
self._content = content
self._locked_for_reading = False
self._locked_for_writing = False
class FakeFile(object):
def __init__(self, fd):
self._fd = fd
self._locked_for_reading = False
self._locked_for_writing = False
self._modifiable = False
def _assertLockedForReading(self):
assert self._locked_for_reading
assert self._fd._locked_for_reading
def _assertLockedForWriting(self):
self._assertLockedForReading()
assert self._locked_for_writing
assert self._fd._locked_for_writing
def lock_for_reading(self):
assert not self._locked_for_reading
assert not self._locked_for_writing
assert not self._fd._locked_for_reading
assert not self._fd._locked_for_writing
self._locked_for_reading = True
self._fd._locked_for_reading = True
def lock_for_writing(self):
self.lock_for_reading()
self._locked_for_writing = True
self._fd._locked_for_writing = True
def get_data_slice(self, start, end):
self._assertLockedForReading()
return self._fd._content[start:end]
def write_data_slice(self, start, data):
self._assertLockedForWriting()
assert 0 <= start <= len(self._fd._content)
old = self._fd._content
self._fd._content = old[:start] + data + old[start + len(data):]
def get_size(self):
return len(self._fd._content)
def close(self):
if self._locked_for_writing:
assert self._fd._locked_for_writing
self._fd._locked_for_writing = False
if self._locked_for_reading:
assert self._fd._locked_for_reading
self._fd._locked_for_reading = False
def _is_same_as(self, other):
return self._fd == other
class TestContentDB(unittest.TestCase):
def setUp(self):
self.tree = FakeTree()
self.tree._add_file(
('db', 'content'), testdata.dbfiledata('content-1'))
self.db = FakeDatabase(self.tree, ('db',))
self.contentfile = contentdb.ContentInfoFile(self.db)
def test_iterate_contentids(self):
cids = (
b'\x92!G\xa0\xbfQ\x8bQL\xb5\xc1\x1e\x1a\x10\xbf\xeb;y\x00'
b'\xe3/~\xd7\x1b\xf4C\x04\xd1a*\xf2^',
b'P\xcd\x91\x14\x0b\x0c\xd9\x95\xfb\xd1!\xe3\xf3\x05'
b'\xe7\xd1[\xe6\xc8\x1b\xc5&\x99\xe3L\xe9?\xdaJ\x0eF\xde',
b"(n\x1a\x8bM\xf0\x98\xfe\xbc[\xea\x9b{Soi\x9e\xaf\x00"
b"\x8e\xca\x93\xf7\x8c\xc5'y\x15\xab5\xee\x98\x37\x73")
self.assertCountEqual(
cids, [x for x in self.contentfile.iterate_contentids()])
def test_info_for_cid(self):
cid = (b'P\xcd\x91\x14\x0b\x0c\xd9\x95\xfb\xd1!\xe3\xf3\x05'
b'\xe7\xd1[\xe6\xc8\x1b\xc5&\x99\xe3L\xe9?\xdaJ\x0eF\xde')
info = self.contentfile.get_info_for_cid(cid)
self.assertEqual(cid, info.get_contentid())
self.assertEqual(cid, info.get_good_checksum())
self.assertEqual(
datetime.datetime(2015, 3, 27, 11, 35, 20),
info.get_first_seen_time())
def test_get_infos_for_checksum(self):
cid = (b'\x92!G\xa0\xbfQ\x8bQL\xb5\xc1\x1e\x1a\x10\xbf\xeb;y\x00'
b'\xe3/~\xd7\x1b\xf4C\x04\xd1a*\xf2^')
infos = self.contentfile.get_all_content_infos_with_checksum(cid)
self.assertCountEqual((cid,), [x.get_contentid() for x in infos])
def test_add_item(self):
firstseen = datetime.datetime(2015, 5, 12, 6, 22, 57)
checksum = b'new content checksum'
cid = self.contentfile.add_content_item(firstseen, checksum)
self.assertIn(
b'\x14' + checksum,
self.tree._files[('db', 'content')]._content)
cf2 = contentdb.ContentInfoFile(self.db)
info = cf2.get_info_for_cid(cid)
self.assertEqual(checksum, info.get_good_checksum())
self.assertEqual(firstseen, info.get_first_seen_time())
self.assertEqual(cid, info.get_contentid())
def test_add_two_items_with_same_checksum(self):
firstseen = datetime.datetime(2015, 5, 12, 6, 22, 57)
checksum = b'new content checksum'
cid = self.contentfile.add_content_item(firstseen, checksum)
cid2 = self.contentfile.add_content_item(firstseen, checksum)
self.assertNotEqual(cid, cid2)
| [
"eirik@eirikba.org"
] | eirik@eirikba.org |
41c0cf4c4c0df70bdf1820d5bad71cd39958f878 | 068845f7c38caf032df2b62fa6f4261e85295979 | /maps/send_mail.py | e30fbcc3188833700b805c9432dee94906f3475f | [] | no_license | Karthik-SIES-GST/treeplantation | 7a2852092e778725c1784600d4126cf4cbc4d5af | 1d9cbb052d417fa5c3a95fcc59ea18125b4eb6b5 | refs/heads/master | 2023-04-06T11:51:21.374443 | 2021-04-11T07:59:19 | 2021-04-11T07:59:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,716 | py | import MySQLdb
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from home.mysql import mysqldb
def mail_seder(receiver_email, user, event, date, place, flag):
sender_email = "treeasurenss@gmail.com"
password = 'treeasure@nss123'
message = MIMEMultipart("alternative")
message["From"] = sender_email
message["To"] = receiver_email
# Create the plain-text and HTML version of your message
if flag == 1:
message["Subject"] = "Nature is calling you........"
text = """\
Hello """ + user + """
We have a new event organized on """ + date + """.
The name of the event is """ + event + """ organized at location """ + place + """.
Do visit our website to participate.
"""
html = """\
<html>
<body>
<p>Hello """ + user + """,<br>
We have a new event organized on """ + date + """.
The name of the event is """ + event + """ organized at location """ + place + """.
Do visit our website to participate.
</p>
</body>
</html>
"""
elif flag==0:
message["Subject"] = "Nature is calling you........"
mydb = mysqldb()
mycursor = mydb.cursor()
query = 'select info from schedule_tt where event_name="'+event+'"'
mycursor.execute(query)
result = mycursor.fetchall()
text = """\
Hello """ + user + """
You are sucessfully registered to the event """ + event + """
Details
Date: """ + date + """
Place: """ + place + """
Information: """ + result[0][0] +"""
Do visit our website to participate.
"""
html = """\
<html>
<body>
<p>Hello """ + user + """,<br>
You are sucessfully registered to the event """ + event + """<br>
Details<br>
Date: """ + date + """<br>
Place: """ + place + """<br>
Information: """ + result[0][0] +"""<br>
Do visit our website to participate.
</p>
</body>
</html>
"""
elif flag == 3:
message["Subject"] = "We are disappointed"
text = """\
Hello """ + user + """
You have been reported.
"""
html = """\
<html>
<body>
<p>Hello """ + user + """,<br>
You have been reported
</p>
</body>
</html>
"""
# Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)
# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)
def send_email(username, event, date, place, flag):
mydb = mysqldb()
mycursor = mydb.cursor()
print(username)
if flag == 0:
query = 'select email, username from auth_user where username="'+username+'"'
else:
query = 'select email, username from auth_user where not username="'+username+'"'
mycursor.execute(query)
result = mycursor.fetchall()
for i in result:
print(i[0], i[1])
mail_seder(i[0], i[1], event, date, place, flag) | [
"65714335+blackhawk005@users.noreply.github.com"
] | 65714335+blackhawk005@users.noreply.github.com |
33d501d883a85c515435da4a4643f3a84a7bcfce | 272721e2bac4fbb9ce98fef6dad6b9c195dcfa40 | /Day-10/8.py | 93759144499bb9f14404cbc868cc5cfad0ac2e52 | [] | no_license | chimnanishankar4/Logic-Building | ab0ab8fe3154659e4b020fbc0370ea52a294d623 | 45bc21e6bfc0a52ac2136221fc6571826985ac54 | refs/heads/master | 2022-10-06T04:08:03.918135 | 2020-06-08T09:47:05 | 2020-06-08T09:47:05 | 266,101,127 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 268 | py | #8.Write a NumPy program to create an array with the values 1, 7, 13, 105 and determine the size of the memory occupied by the array.
import numpy as np
array_a=np.array([1,7,13,105])
print("Original array:",array_a)
print("%d bytes:"%(array_a.size*array_a.itemsize))
| [
"chimnanishankar4@gmail.com"
] | chimnanishankar4@gmail.com |
5106152e77d060a927253686296d12540bed8155 | 2a94e60460f91c4a4b919953ef1a15de4d89166a | /argil_cb_pos_ticket/pos.py | 79525802be904af3b677e6207922930e7981aaf3 | [] | no_license | germanponce/addons_cb | de8ddee13df36cf2278edbbc495564bbff8ea29e | 858453d4f4c3e8b43d34a759b20306926f0bf63e | refs/heads/master | 2021-01-22T23:20:16.826694 | 2015-10-29T22:05:03 | 2015-10-29T22:05:03 | 41,502,521 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,265 | py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api, _
from openerp.tools import float_compare
import openerp.addons.decimal_precision as dp
from datetime import time, datetime
from openerp import SUPERUSER_ID
from openerp import tools
from openerp.osv import osv, fields, expression
from openerp.tools.translate import _
from openerp.exceptions import except_orm, Warning, RedirectWarning
import base64
import amount_to_text_mx as amount_to
# AMOUNT TO TEXT
class pos_order(osv.osv):
_name ='pos.order'
_inherit = 'pos.order'
def _amount_text(self, cr, uid, ids, field_name, args, context=None):
if not context:
context = {}
res = {}
amount_to_text = ''
for record in self.browse(cr, uid, ids, context=context):
if record.amount_total > 0:
amount_to_text = amount_to.get_amount_to_text(
self, record.amount_total, 'es_cheque', record.pricelist_id.currency_id.name
)
res[record.id] = amount_to_text
return res
_columns = {
'amount_to_text': fields.function(_amount_text, method=True, string='Monto en Letra', type='char', size=256, store=True),
}
| [
"german_442@hotmail.com"
] | german_442@hotmail.com |
d68ae1f08eae0ab2cde22e3ce0773e460f8d4bc6 | 37ec3ba90e8c44d60a6db9fd19ea362ee88d3314 | /accounts/migrations/0001_initial.py | a0586b67cc10ff3f3ed544f8783c04a793791aea | [] | no_license | souckkr/djangoproject-hangungmackgg | f862cedadd7c667bc65a11870dd1da9ef3cec2b8 | caa5625278f8bb8524959061ed51f135802eb7d3 | refs/heads/master | 2022-11-16T02:52:51.383735 | 2020-07-16T08:46:41 | 2020-07-16T08:46:41 | 280,101,253 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,061 | py | # Generated by Django 3.0.7 on 2020-07-06 06:16
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='CustomUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('name', models.CharField(max_length=100, verbose_name='이름')),
('email', models.EmailField(max_length=100, verbose_name='이메일')),
('gender', models.CharField(choices=[['M', '남성'], ['F', '여성']], max_length=1, verbose_name='성별')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
| [
"souckkr@gmail.com"
] | souckkr@gmail.com |
0a97d29e2bec4a1a9d370b41f0a000614f2f24db | c3e2f56672e01590dc7dc7e184f30c2884ce5d3a | /Programs/MyPythonXII/Unit1/PyChap06/filera.py | 9500b097eee3e35d0a288c02f76d1e850d45b55f | [] | no_license | mridulrb/Basic-Python-Examples-for-Beginners | ef47e830f3cc21cee203de2a7720c7b34690e3e1 | 86b0c488de4b23b34f7424f25097afe1874222bd | refs/heads/main | 2023-01-04T09:38:35.444130 | 2020-10-18T15:59:29 | 2020-10-18T15:59:29 | 305,129,417 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 364 | py | # File name: ...\\MyPythonXII\Unit1\PyChap06\filera.py
import os
txtfile = "Friends.txt" # Text file is assigned
if os.path.isfile(txtfile):
print ("Friends names are...")
print ("-------------------")
for F in open(txtfile).read(): # Both open and read the contents
print (F, end="")
else:
print ("File does not exist.")
| [
"mridurb@gmail.com"
] | mridurb@gmail.com |
7abfd9989d9f62ece57d29c9cbc1bfaadc32610f | 8d92693d2ab3d19981a79a008756cbe4d81b4eea | /Clients/Python-rAIcer-Client/NeatClient.py | 6a2d6c4f2fac109c9c5328aa37cf4bc9edcc89af | [] | no_license | MiWerner/rAIcer | c1ef9153592f59dc8a3cee5933a5c4e1ff5f30a1 | a9f930ce1f6b4e16a3d527520cd06c1188731e97 | refs/heads/master | 2020-03-12T21:29:44.193530 | 2019-02-05T13:06:25 | 2019-02-05T13:06:25 | 130,829,370 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,487 | py | import sys
sys.argv.append("--direc_dist")
sys.argv.append("--speed")
sys.argv.append("--cp_ids")
sys.argv.append("2")
sys.argv.append("--output_mode_2")
sys.argv.append("--restore_folder")
sys.argv.append("E4")
import RaicerSocket
import pygame
from Utils import S_WAIT, S_COUNTDOWN, S_RUNNING, S_FINISHED, S_CRASHED, S_CANCELED, IMG_WIDTH, IMG_HEIGHT, print_debug
from Utils import PATH_TO_EXPERIMENTS, ARGS
import pickle
import numpy as np
import os
from Features import FeatureCalculator
import time
import neat
fc = None
display = pygame.display.set_mode((IMG_WIDTH, IMG_HEIGHT))
display.fill((255, 64, 64))
genome = pickle.load(open(os.path.join(PATH_TO_EXPERIMENTS, ARGS.restore_folder, "winner.p"), "rb"))
neat_config = neat.Config(neat.DefaultGenome,
neat.DefaultReproduction,
neat.DefaultSpeciesSet,
neat.DefaultStagnation,
os.path.join(PATH_TO_EXPERIMENTS, ARGS.restore_folder, "configfile"))
net = neat.nn.FeedForwardNetwork.create(genome=genome, config=neat_config)
socket = RaicerSocket.RaicerSocket()
socket.connect()
status = -1
try:
while 1:
if socket.new_message:
ID, status, lap_id, lap_total, damage, rank, image = socket.receive()
if fc is not None:
fc.update(img=image, print_features=False)
if status == S_RUNNING:
# check keys and send commands to server
inputs = np.asarray(list(fc.features), dtype=np.int64)
# calculate key strokes
output = np.asarray(list(map(lambda x: x + .5, net.activate(inputs=inputs))),
dtype=np.int8)
if ARGS.output_mode_2:
keys = np.zeros(4)
# vertical control
if output[0] <= .25: # down
keys[1] = 1
elif output[0] >= .75: # up
keys[0] = 1
# horizontal control
if output[1] <= .25: # right
keys[3] = 1
elif output[1] >= .75: # left
keys[2] = 1
else:
keys = output
# if not power_up_used:
# power_up_used = True
# if keys[0] == 0 and keys[1] == 0 and keys[2] == 0 and keys[3] == 0:
# keys[3] = 1
# send keys strokes to server
socket.send_key_msg(keys[0], keys[1], keys[2], keys[3])
display.blit(pygame.surfarray.make_surface(image), (0, 0))
fc.draw_features(display)
pygame.display.update()
elif status == S_COUNTDOWN:
display.blit(pygame.surfarray.make_surface(image), (0, 0))
pygame.display.update()
if fc is None:
fc = FeatureCalculator(img=image, client_id=ID)
time.sleep(0.1)
elif status == S_WAIT:
display.blit(pygame.surfarray.make_surface(image), (0, 0))
pygame.display.update()
elif status == S_FINISHED:
display.blit(pygame.surfarray.make_surface(image), (0, 0))
pygame.display.update()
print_debug('Finished!')
break
elif status == S_CRASHED:
print_debug('Crashed')
break
elif status == S_CANCELED:
print_debug('Canceled')
break
time.sleep(.1)
finally:
socket.close()
| [
"franz.werner@student.uni-luebeck.de"
] | franz.werner@student.uni-luebeck.de |
fac0af8592608b6af1402e8e48927e5e60bf25e2 | 69d1a3a31ad2254fa76c64d4f199bb8b40ed5db9 | /smartystreets_python_sdk/us_reverse_geo/lookup.py | d44e52a168ca975233b87c2205839907f22d1017 | [
"Apache-2.0"
] | permissive | zackary-naas/smartystreets-python-sdk | 6807f46b19ddb891288a23a3f417902c38704731 | 0988fd4c400419e0c1d1366d56a3ba6f177e5294 | refs/heads/master | 2023-08-19T06:38:20.510727 | 2021-10-05T20:39:03 | 2021-10-05T20:39:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 459 | py | class Lookup:
def __init__(self, latitude=None, longitude=None):
"""
In addition to holding the lat/lon data for this lookup, this class also will contain the
result of the lookup after it comes back from the API.
See https://smartystreets.com/docs/cloud/us-reverse-geo-api#http-input-fields
"""
self.response = None
self.latitude = round(latitude, 8)
self.longitude = round(longitude, 8)
| [
"duncan@smartystreets.com"
] | duncan@smartystreets.com |
8349ebff92aca5b7c4f09f14395daad1d788a59b | 188d6557711a002d5e7c4444c788f69463017091 | /basic_test/deepcopytest2.py | 3f30240feb00f454ca81080ef5da6a8a042ad091 | [] | no_license | guozeliang/pyCode | dfd853c1f51871806e5de2e6d7e80c774602e03a | 2a6d52b20204f8adc42e48f7b99bf3a77d7abc67 | refs/heads/master | 2021-04-27T05:27:16.199978 | 2018-07-19T12:52:42 | 2018-07-19T12:52:42 | 122,597,196 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 794 | py | import copy
'''
will = ['will',28,['python','C#','javascript']]
wilber = will #对象的赋值
print(id(will))
print(will)
print([id(ele) for ele in will])
print(id(wilber))
print(wilber)
print([id(ele) for ele in wilber])
will[0] = 'wilber'
will[2].append('CSS')
print(id(will))
print(will)
print([id(ele) for ele in will])
print(id(wilber))
print(wilber)
print([id(ele) for ele in wilber])
'''
#浅拷贝
will = ['will',28,['python','C#','javaScript']]
wilber = copy.copy(will)
print(id(will))
print(will)
print([id(ele) for ele in will])
print(id(wilber))
print(wilber)
print([id(ele) for ele in wilber])
will[0] = 'wilber'
will[2].append("CSS")
print(id(will))
print(will)
print([id(ele) for ele in will])
print(id(wilber))
print(wilber)
print([id(ele) for ele in wilber])
| [
"932356614@qq.com"
] | 932356614@qq.com |
d01c5b9d6bf14820b60e6001294c2677de1b6eb1 | b2bfba9ad1a704453f900f46e9b9ed8bd605943a | /polls/urls.py | 26cb8beab4d227eafa90850acdac6b32bd857c8c | [] | no_license | shiv-konar/PollsWebsite | e28ad40be9b4ee4498f67687b8e8ada8e1b4c1b3 | c672bf491a03e7363d579bddd3a9184d91bed234 | refs/heads/master | 2020-12-25T06:02:25.201037 | 2016-07-11T15:05:03 | 2016-07-11T15:05:03 | 63,077,805 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 343 | py | from django.conf.urls import url
from . import views
app_name="polls"
urlpatterns = [
url("^$", views.index, name="index"),
url("^(?P<question_id>[0-9]+)/$", views.details, name="detail"),
url("^(?P<question_id>[0-9]+)/results$", views.results, name="results"),
url("^(?P<question_id>[0-9]+)/vote$", views.vote, name="vote")
] | [
"shiv.konar@outlook.com"
] | shiv.konar@outlook.com |
d608f202740b1523189a09cb7912021be96cf299 | 9950d61161a2fffa03d2fe71eef33748255ab826 | /src/imdb/settings/local.py | 3b039a59a2b41ca4f694871f064a3640dee1c940 | [] | no_license | imtiaz-emu/django_imdb | 6f3530629726154b977bfd9ca3f5fd27a861b4f8 | fee1b20db0c217e176d7616498d1f389cfbfd506 | refs/heads/master | 2021-01-22T10:51:43.126526 | 2017-03-01T06:15:48 | 2017-03-01T06:15:48 | 82,047,276 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,230 | py | """Development settings and globals."""
from __future__ import absolute_import
from os.path import join, normpath
from .base import *
########## DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
# TEMPLATE_DEBUG = DEBUG
########## END DEBUG CONFIGURATION
########## EMAIL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
########## END EMAIL CONFIGURATION
########## DATABASE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'imdb',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
########## END DATABASE CONFIGURATION
########## CACHE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
########## END CACHE CONFIGURATION
| [
"himtiaz@dohatec.com.bd"
] | himtiaz@dohatec.com.bd |
3f153710fe899705b2484722c43539921809e850 | 6f041cfcadc66206a00eca5eafb1378fe261d2dd | /8x26tools/tools/ramdump-parser/classfication.py | 567d76aaf367546b73bc2f923fd23689e4dae977 | [] | no_license | kalmuthu/slos | bf857aaa80c33f0a59361614702740c46fa20d01 | 7516632037f788b00e1137619b88ecca1ac66fa3 | refs/heads/master | 2021-01-18T03:38:55.509889 | 2017-02-26T15:24:34 | 2017-02-26T15:24:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,790 | py | # =======================================================
# hagisiro.py
# -------------------------------------------------------
# 2013/04/16 v0.1 Initial release by darkwood.kim
# =======================================================
import sys
import os
def process_dmesg(dmesg):
start_oops=0
end_oops=0
start_regs=0
time_table=[]
dmesg_sorted=[]
#make list which include time and order
for i, data in enumerate(dmesg):
if (data != '' and data[0] == '<' and len(data) > 16):
time_table.append([data[4:].split()[0], i])
#sort dmesg by time
time_table.sort()
for i, data in enumerate(time_table):
#make dmesg which sorted by time
dmesg_sorted.append(dmesg[time_table[i][1]])
#find starting point of oops message
if (dmesg[time_table[i][1]].find("Internal error: ") > 0):
start_oops = i - 3
start_regs = i + 5
elif (start_oops == 0) and (dmesg[time_table[i][1]].find("Kernel panic - not syncing: ") > 0):
start_oops = i - 2
#find end point of oops message
elif (dmesg[time_table[i][1]].find("Rebooting in 5 seconds..") > 0):
end_oops = i - 1
#write oops message
output_file = open("kernel_crash.log", "w")
for i in range(end_oops - start_oops + 1):
output_file.write(dmesg[time_table[start_oops+i][1]] + '\n')
output_file.close()
#write dmesg which sorted by time
output_file = open("dmesg.log", "w")
for i, data in enumerate(dmesg_sorted):
output_file.write(dmesg_sorted[i] + '\n')
output_file.close()
#write regs_panic.cmm
if(start_regs != 0):
search_list = [["pc", "lr"], ["sp", "ip", "fp"], ["r10", "r9", "r8"], ["r7", "r6", "r5", "r4"], ["r3", "r2", "r1", "r0"]]
write_list = [["pc", "r14"], ["r13", "r12", "r11"], ["r10", "r9", "r8"], ["r7", "r6", "r5", "r4"], ["r3", "r2", "r1", "r0"]]
search_offset = [[7, 7], [5, 5, 5], [5, 5, 5], [5, 5, 5, 5], [5, 5, 5, 5]]
output_file = open("regs_panic.cmm", "w")
for i in range(5):
for j in range(len(search_offset[i])):
index = dmesg[time_table[start_regs+i][1]].find(search_list[i][j]) + search_offset[i][j]
output_file.write("r.s " + write_list[i][j] + " 0x" + dmesg[time_table[start_regs+i][1]][index:index+8] + '\n')
output_file.close()
def process_kernel_crash(dmseg_TZ):
start = dmseg_TZ.find("---- dmesg ----")
start += dmseg_TZ[start:].find('\n') + 1
end = dmseg_TZ.find("---- end dmesg----") - 1
dmesg = dmseg_TZ[start:end].split('\n')
process_dmesg(dmesg)
def process_apps_watchdog(dmseg_TZ):
start = dmseg_TZ.find("------ watchdog state ------")
start += dmseg_TZ[start:].find('\n') + 1
end = dmseg_TZ.find("-------- end watchdog state -------") - 1
output_file = open("apps_watchdog.log", "w")
output_file.write(dmseg_TZ[start:end])
output_file.close()
def process_other_crash(other_crash):
output_file = open(other_crash + '.log', "w")
output_file.write(other_crash)
output_file.close()
def find_crash_type(input_file):
idx=0
dmseg_TZ = input_file.read()
#check apps_watchdog
if (dmseg_TZ.find("Core 0 recieved the watchdog interrupt") > 0):
process_apps_watchdog(dmseg_TZ)
#check kernel crash
elif (dmseg_TZ.find("Internal error: ") > 0):
process_kernel_crash(dmseg_TZ)
elif (dmseg_TZ.find("mdm_errfatal: Received err fatal from mdm") > 0):
process_other_crash("external_modem")
else:
#check subsystem_crash
idx = dmseg_TZ.find("subsys-restart: Resetting the SoC - ")
if (idx > 0):
process_other_crash(dmseg_TZ[idx+36:idx+36+14].split()[0])
#check kernel crash again for panic() call
elif (dmseg_TZ.find("Kernel panic - not syncing: ") > 0):
process_kernel_crash(dmseg_TZ)
else:
process_other_crash("unknown reset")
if __name__ == "__main__":
#open files
input_file = open(sys.argv[1], "r")
#find crash type
find_crash_type(input_file)
#close files
input_file.close()
| [
"chungae9ri@gmail.com"
] | chungae9ri@gmail.com |
b8e7b0de85b7573829e61fafb9cd287c1173b9af | fbd5c602a612ea9e09cdd35e3a2120eac5a43ccf | /Finished/old_py/75.颜色分类.py | 7bd771f54cb7ff8dcc151c48d2e2b94a7f6bf8e8 | [] | no_license | czccc/LeetCode | 0822dffee3b6fd8a6c6e34be2525bbd65ccfa7c0 | ddeb1c473935480c97f3d7986a602ee2cb3acaa8 | refs/heads/master | 2023-09-01T18:18:45.973563 | 2023-08-27T02:44:00 | 2023-08-27T02:44:00 | 206,226,364 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,119 | py | #
# @lc app=leetcode.cn id=75 lang=python
#
# [75] 颜色分类
#
# @lc code=start
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
left, right = -1, len(nums)
p = 0
while p < right:
if nums[p] == 2:
right -= 1
nums[p] = nums[right]
nums[right] = 2
elif nums[p] == 1:
p += 1
else:
left += 1
nums[p] = 1
nums[left] = 0
p += 1
return
# @lc code=end
# TEST ONLY
import unittest
import sys
sys.path.append("..")
from Base.PyVar import *
class SolutionTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._func = Solution().sortColors
def test_1(self):
args = [[2, 0, 2, 1, 1, 0]]
ans = [0, 0, 1, 1, 2, 2]
cur_ans = self._func(*args)
self.assertEqual(args[0], ans)
if __name__ == "__main__":
unittest.main(verbosity=2)
| [
"lichchchn@gmail.com"
] | lichchchn@gmail.com |
c7143bcfc57aabf16b264551d39b4e0786229945 | 11055fb57d1b9bd107185cbbfdfd0a8676d0d81d | /game/admin.py | b3ee84d1632f31a5eb8e033ad8469cf311a59893 | [] | no_license | KashinYana/hat | bc9d46ca0e813f1fedacc92b146273848f7b6ce7 | 2d325faec62f827d6f930e6956c2b6ec0ec89273 | refs/heads/master | 2021-01-10T19:47:49.511468 | 2013-05-19T08:40:15 | 2013-05-19T08:40:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 207 | py | from django.contrib import admin
from game.models import Game, Word, ReportGame, UserWord
admin.site.register(Game)
admin.site.register(Word)
admin.site.register(ReportGame)
admin.site.register(UserWord)
| [
"kashin.yana@gmail.com"
] | kashin.yana@gmail.com |
5c9dac8602f051955f5bba3b5b992bee8b05f77a | 88900156c1fc6d496e87a0c403811e30a7398cfc | /check4fsm/Communication.py | 70dd87ad40c4646164be3443114f9caeac43fce8 | [] | no_license | Totoro2205/check4fsm | 4be7b73b9331ed2d46ce119b762d67a64a4420cc | 4245b7f0babca6f5d15d1f85ee85fddc69cf0196 | refs/heads/main | 2023-08-10T07:32:22.121413 | 2021-09-20T09:28:57 | 2021-09-20T09:28:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,207 | py | #!/usr/bin/env python
from check4fsm.ProccesText import ProcessText
from check4fsm.TonalizeText import TonalText
from check4fsm.ProcessAppeal import ProcessAppeal
from check4fsm.extractAllData import ExtractData
from check4fsm import *
from natasha import Segmenter, Doc
from loguru import logger
from flask_cors import CORS
import flask
import time
import nltk
import os
logger.add(f"{os.getcwd()}/.logger.log", format="{time} {level} {message}", rotation="50 MB")
ed = ExtractData(os.getcwd() + "/../data/cities.json", os.getcwd() + "/../data/NER.json")
app = flask.Flask(__name__)
class CommunicationFlask:
CORS(app)
def __init__(self, cities: str = os.getcwd() + "/../data/cities.json",
ner: str = os.getcwd() + "/../data/NER.json"):
global ed
ed = ExtractData(cities, ner)
@staticmethod
@logger.catch
@app.route('/', methods=["GET"])
def main_route():
data = flask.request.json
global ed
if data is None:
logger.error(f" failed data is None")
return {}
output_data = dict()
try:
output_data = ed(data["text"])
except Exception as ex:
logger.error(f" failed on the server {ex}")
return {}
return output_data
@staticmethod
@logger.catch
@app.route('/', methods=["POST"])
def hooks():
data = flask.request.json
global ed
if data is None:
logger.error(f" failed data is None")
return {}
output_data = dict()
try:
output_data = ed(data["text"])
except Exception as ex:
logger.error(f" failed on the server {ex}")
return {}
return output_data
@logger.catch
def run_flask(self):
global app
app.run(host="0.0.0.0", port=9000)
def run(cities: str = os.getcwd() + "/data/cities.json", ner: str = os.getcwd() + "/data/NER.json"):
logger.info("Loading all systems")
p = CommunicationFlask(cities, ner)
logger.info("Loaded all systems")
p.run_flask()
if __name__ == '__main__':
run( os.getcwd() + "/data/cities.json", os.getcwd() + "/data/NER.json") | [
"you@example.com"
] | you@example.com |
c8c514fc8dd83265f096c8411ddcd4366f9d850b | 42316eaeb927b3b04c9652a6d0d395477b10cad5 | /pypsrp/__init__.py | c2d9f0b37b2820868477abc2865e0bcaf2e1a526 | [
"MIT"
] | permissive | graingert/pypsrp | 7505bb2ce2946cd69e2e4749709268352fb9f02c | baf61c9d0cd68fe51bb0698e4fb6d7e7b209f503 | refs/heads/master | 2023-05-30T22:48:45.368609 | 2020-07-23T03:57:48 | 2020-07-23T03:57:48 | 285,619,356 | 0 | 0 | MIT | 2020-08-06T16:29:55 | 2020-08-06T16:29:54 | null | UTF-8 | Python | false | false | 1,073 | py | # Copyright: (c) 2018, Jordan Borean (@jborean93) <jborean93@gmail.com>
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
import json
import logging
import logging.config
import os
try:
from logging import NullHandler
except ImportError: # pragma: no cover
class NullHandler(logging.Handler):
def emit(self, record):
pass
def _setup_logging(logger):
log_path = os.environ.get('PYPSRP_LOG_CFG', None)
if log_path is not None and os.path.exists(log_path): # pragma: no cover
# log log config from JSON file
with open(log_path, 'rt') as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
# no logging was provided
logger.addHandler(NullHandler())
logger = logging.getLogger(__name__)
_setup_logging(logger)
# Contains a list of features, used by external libraries to determine whether
# a new enough pypsrp is installed to support the features it needs
FEATURES = [
'wsman_locale',
'wsman_read_timeout',
'wsman_reconnections',
]
| [
"jborean93@gmail.com"
] | jborean93@gmail.com |
da75cf735352245840ff25ebe7b8b0f2db95a437 | 0df0d6c1c53cc8667019d4f44df7fa986f08e7a8 | /Arrays/twosum_full.py | b5592ca008a4ef260d002d3ca44a27496bcf6e3e | [] | no_license | sulaimantok/Data-Structures-With-Python | c3ddac35351aa797e2d1d246b2922676d4d29d00 | 98285b16d4d915cedb05afc3418c41c619ca6386 | refs/heads/master | 2020-09-22T00:12:12.054978 | 2020-04-23T13:02:20 | 2020-04-23T13:02:20 | 224,982,137 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 897 | py | A = [-2, 1, 2, 4, 7, 11]
target = 13
# Time Complexity: O(n^2)
# Space Complexity: O(1)
def two_sum_brute_force(A, target):
for i in range(len(A)-1):
for j in range(i+1, len(A)):
if A[i] + A[j] == target:
print(A[i], A[j])
return True
return False
# Time Complexity: O(n)
# Space Complexity: O(n)
def two_sum_hash_table(A, target):
ht = dict()
for i in range(len(A)):
if A[i] in ht:
print(ht[A[i]], A[i])
return True
else:
ht[target - A[i]] = A[i]
return False
# Time Complexity: O(n)
# Space Complexity: O(1)
def two_sum(A, target):
i = 0
j = len(A) - 1
while i < j:
if A[i] + A[j] == target:
print(A[i], A[j])
return True
elif A[i] + A[j] < target:
i += 1
else:
j -= 1
return False
print(two_sum_brute_force(A, target))
print(two_sum_hash_table(A, target))
print(two_sum(A, target)) | [
"sulaimanniceguy@gmail.com"
] | sulaimanniceguy@gmail.com |
c34df89c9830d46f28b1d2fc7719374d907b074a | a27c13c55680e95a0cfe375dd02daae9d8e64d04 | /src/build/open_source_test.py | 3baee3f5ad690b5f27c1f8f34c6447395026505e | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | NaiveTorch/ARC | 4572ed94d01f3b237492579be4091f3874a8dfe0 | 4007a4e72f742bb50de5615b2adb7e46d569b7ed | refs/heads/master | 2021-01-22T06:38:12.078262 | 2014-10-22T15:43:28 | 2014-10-22T15:43:28 | 25,082,433 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,435 | py | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests covering open_source management"""
import open_source
import os
import unittest
_PATH_PREFIX = 'src/build/tests/open_source'
class TestOpenSource(unittest.TestCase):
RULES = ['foobar.c*', 'subdir']
def test_open_source_repo(self):
# We do not run tests in the open source repo.
self.assertFalse(open_source.is_open_source_repo())
def test_is_basename_open_sourced_true(self):
for p in ['foobar.c', 'foobar.cpp', 'subdir']:
self.assertTrue(open_source.is_basename_open_sourced(p, self.RULES))
def test_is_basename_open_sourced_false(self):
for p in ['', 'other', 'foobar.h', 'xfoobar.c', 'subdir2']:
self.assertFalse(open_source.is_basename_open_sourced(p, self.RULES))
def test_is_basename_open_sourced_bang_means_not(self):
self.assertFalse(open_source.is_basename_open_sourced('!foo', ['!foo']))
def test_is_basename_open_sourced_conflict(self):
def _test_in_and_out(rules):
self.assertTrue(open_source.is_basename_open_sourced('in', rules))
self.assertFalse(open_source.is_basename_open_sourced('out', rules))
def _test_out_and_out2(rules):
self.assertFalse(open_source.is_basename_open_sourced('out', rules))
self.assertFalse(open_source.is_basename_open_sourced('out2', rules))
self.assertFalse(open_source.is_basename_open_sourced('foo',
['foo', '!foo']))
_test_in_and_out(['*', '!out'])
_test_in_and_out(['!out', '*'])
_test_in_and_out(['in', 'out', '!out'])
_test_out_and_out2(['out', '!*'])
_test_out_and_out2(['!*', 'out'])
def test_is_open_sourced_true(self):
for p in ['yes', 'yes/anything.c', 'selective/foobar.c',
'selective/foobar.cpp', 'selective/subdir/file.c']:
self.assertTrue(open_source.is_open_sourced(
os.path.join(_PATH_PREFIX, p)))
def test_is_open_sourced_false(self):
for p in ['no', 'no/file.c', 'selective/xfoobar.c',
'selective/subdir2/file.c']:
self.assertFalse(open_source.is_open_sourced(
os.path.join(_PATH_PREFIX, p)))
def test_is_third_party_open_sourced_true(self):
for p in ['third_party/android']:
self.assertTrue(open_source.is_open_sourced(p))
| [
"elijahtaylor@google.com"
] | elijahtaylor@google.com |
09a53f5f138f99f620cd6ce77126883840240b39 | 9c85d132b2ed8c51f021f42ed9f20652827bca45 | /source/res/scripts/client/gui/shared/gui_items/vehicle.py | 3abc3d8ff7ab639c495503159428a7e726120fa4 | [] | no_license | Mododejl/WorldOfTanks-Decompiled | 0f4063150c7148184644768b55a9104647f7e098 | cab1b318a58db1e428811c41efc3af694906ba8f | refs/heads/master | 2020-03-26T18:08:59.843847 | 2018-06-12T05:40:05 | 2018-06-12T05:40:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 52,084 | py | # Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/gui/shared/gui_items/Vehicle.py
import math
import random
from itertools import izip
from operator import itemgetter
import BigWorld
import constants
from AccountCommands import LOCK_REASON, VEHICLE_SETTINGS_FLAG
from account_shared import LayoutIterator
from constants import WIN_XP_FACTOR_MODE
from gui import makeHtmlString
from gui.Scaleform.locale.ITEM_TYPES import ITEM_TYPES
from gui.Scaleform.locale.RES_ICONS import RES_ICONS
from gui.prb_control import prb_getters
from gui.prb_control.settings import PREBATTLE_SETTING_NAME
from gui.shared.economics import calcRentPackages, getActionPrc, calcVehicleRestorePrice
from gui.shared.formatters import text_styles
from gui.shared.gui_items import CLAN_LOCK, GUI_ITEM_TYPE, getItemIconName, GUI_ITEM_ECONOMY_CODE
from gui.shared.gui_items.vehicle_equipment import VehicleEquipment
from gui.shared.gui_items.gui_item import HasStrCD
from gui.shared.gui_items.fitting_item import FittingItem, RentalInfoProvider
from gui.shared.gui_items.Tankman import Tankman
from gui.shared.money import MONEY_UNDEFINED, Currency, Money
from gui.shared.gui_items.customization.outfit import Outfit
from gui.shared.gui_items.gui_item_economics import ItemPrice, ItemPrices, ITEM_PRICE_EMPTY
from gui.shared.utils import makeSearchableString
from helpers import i18n, time_utils, dependency
from items import vehicles, tankmen, customizations, getTypeInfoByName, getTypeOfCompactDescr
from items.components.c11n_constants import SeasonType, CustomizationType, StyleFlags
from shared_utils import findFirst, CONST_CONTAINER
from skeletons.gui.game_control import IIGRController
from skeletons.gui.lobby_context import ILobbyContext
from skeletons.gui.server_events import IEventsCache
class VEHICLE_CLASS_NAME(CONST_CONTAINER):
LIGHT_TANK = 'lightTank'
MEDIUM_TANK = 'mediumTank'
HEAVY_TANK = 'heavyTank'
SPG = 'SPG'
AT_SPG = 'AT-SPG'
VEHICLE_TYPES_ORDER = (VEHICLE_CLASS_NAME.LIGHT_TANK,
VEHICLE_CLASS_NAME.MEDIUM_TANK,
VEHICLE_CLASS_NAME.HEAVY_TANK,
VEHICLE_CLASS_NAME.AT_SPG,
VEHICLE_CLASS_NAME.SPG)
VEHICLE_TYPES_ORDER_INDICES = dict(((n, i) for i, n in enumerate(VEHICLE_TYPES_ORDER)))
UNKNOWN_VEHICLE_CLASS_ORDER = 100
def compareByVehTypeName(vehTypeA, vehTypeB):
return VEHICLE_TYPES_ORDER_INDICES[vehTypeA] - VEHICLE_TYPES_ORDER_INDICES[vehTypeB]
def compareByVehTableTypeName(vehTypeA, vehTypeB):
return VEHICLE_TABLE_TYPES_ORDER_INDICES[vehTypeA] - VEHICLE_TABLE_TYPES_ORDER_INDICES[vehTypeB]
VEHICLE_TABLE_TYPES_ORDER = (VEHICLE_CLASS_NAME.HEAVY_TANK,
VEHICLE_CLASS_NAME.MEDIUM_TANK,
VEHICLE_CLASS_NAME.LIGHT_TANK,
VEHICLE_CLASS_NAME.AT_SPG,
VEHICLE_CLASS_NAME.SPG)
VEHICLE_TABLE_TYPES_ORDER_INDICES = dict(((n, i) for i, n in enumerate(VEHICLE_TABLE_TYPES_ORDER)))
VEHICLE_TABLE_TYPES_ORDER_INDICES_REVERSED = dict(((n, i) for i, n in enumerate(reversed(VEHICLE_TABLE_TYPES_ORDER))))
VEHICLE_BATTLE_TYPES_ORDER = (VEHICLE_CLASS_NAME.HEAVY_TANK,
VEHICLE_CLASS_NAME.MEDIUM_TANK,
VEHICLE_CLASS_NAME.AT_SPG,
VEHICLE_CLASS_NAME.LIGHT_TANK,
VEHICLE_CLASS_NAME.SPG)
VEHICLE_BATTLE_TYPES_ORDER_INDICES = dict(((n, i) for i, n in enumerate(VEHICLE_BATTLE_TYPES_ORDER)))
class VEHICLE_TAGS(CONST_CONTAINER):
PREMIUM = 'premium'
PREMIUM_IGR = 'premiumIGR'
CANNOT_BE_SOLD = 'cannot_be_sold'
SECRET = 'secret'
SPECIAL = 'special'
OBSERVER = 'observer'
DISABLED_IN_ROAMING = 'disabledInRoaming'
EVENT = 'event_battles'
EXCLUDED_FROM_SANDBOX = 'excluded_from_sandbox'
TELECOM = 'telecom'
UNRECOVERABLE = 'unrecoverable'
CREW_LOCKED = 'lockCrew'
OUTFIT_LOCKED = 'lockOutfit'
class Vehicle(FittingItem, HasStrCD):
__slots__ = ('__descriptor', '__customState', '_inventoryID', '_xp', '_dailyXPFactor', '_isElite', '_isFullyElite', '_clanLock', '_isUnique', '_rentPackages', '_hasRentPackages', '_isDisabledForBuy', '_isSelected', '_restorePrice', '_canTradeIn', '_canTradeOff', '_tradeOffPriceFactor', '_tradeOffPrice', '_searchableUserName', '_personalDiscountPrice', '_rotationGroupNum', '_rotationBattlesLeft', '_isRotationGroupLocked', '_isInfiniteRotationGroup', '_settings', '_lock', '_repairCost', '_health', '_gun', '_turret', '_engine', '_chassis', '_radio', '_fuelTank', '_optDevices', '_shells', '_equipment', '_equipmentLayout', '_bonuses', '_crewIndices', '_crew', '_lastCrew', '_hasModulesToSelect', '_customOutfits', '_styledOutfits')
NOT_FULL_AMMO_MULTIPLIER = 0.2
MAX_RENT_MULTIPLIER = 2
class VEHICLE_STATE(object):
DAMAGED = 'damaged'
EXPLODED = 'exploded'
DESTROYED = 'destroyed'
UNDAMAGED = 'undamaged'
BATTLE = 'battle'
IN_PREBATTLE = 'inPrebattle'
LOCKED = 'locked'
CREW_NOT_FULL = 'crewNotFull'
AMMO_NOT_FULL = 'ammoNotFull'
AMMO_NOT_FULL_EVENTS = 'ammoNotFullEvents'
SERVER_RESTRICTION = 'serverRestriction'
RENTAL_IS_OVER = 'rentalIsOver'
IGR_RENTAL_IS_OVER = 'igrRentalIsOver'
IN_PREMIUM_IGR_ONLY = 'inPremiumIgrOnly'
GROUP_IS_NOT_READY = 'group_is_not_ready'
NOT_PRESENT = 'notpresent'
UNAVAILABLE = 'unavailable'
UNSUITABLE_TO_QUEUE = 'unsuitableToQueue'
UNSUITABLE_TO_UNIT = 'unsuitableToUnit'
CUSTOM = (UNSUITABLE_TO_QUEUE, UNSUITABLE_TO_UNIT)
DEAL_IS_OVER = 'dealIsOver'
ROTATION_GROUP_UNLOCKED = 'rotationGroupUnlocked'
ROTATION_GROUP_LOCKED = 'rotationGroupLocked'
CAN_SELL_STATES = [VEHICLE_STATE.UNDAMAGED,
VEHICLE_STATE.CREW_NOT_FULL,
VEHICLE_STATE.AMMO_NOT_FULL,
VEHICLE_STATE.GROUP_IS_NOT_READY,
VEHICLE_STATE.UNSUITABLE_TO_QUEUE,
VEHICLE_STATE.UNSUITABLE_TO_UNIT,
VEHICLE_STATE.ROTATION_GROUP_UNLOCKED,
VEHICLE_STATE.ROTATION_GROUP_LOCKED]
GROUP_STATES = [VEHICLE_STATE.GROUP_IS_NOT_READY]
class VEHICLE_STATE_LEVEL(object):
CRITICAL = 'critical'
INFO = 'info'
WARNING = 'warning'
RENTED = 'rented'
igrCtrl = dependency.descriptor(IIGRController)
eventsCache = dependency.descriptor(IEventsCache)
lobbyContext = dependency.descriptor(ILobbyContext)
def __init__(self, strCompactDescr=None, inventoryID=-1, typeCompDescr=None, proxy=None):
if strCompactDescr is not None:
vehDescr = vehicles.VehicleDescr(compactDescr=strCompactDescr)
else:
_, nID, innID = vehicles.parseIntCompactDescr(typeCompDescr)
vehDescr = vehicles.VehicleDescr(typeID=(nID, innID))
self.__descriptor = vehDescr
HasStrCD.__init__(self, strCompactDescr)
FittingItem.__init__(self, vehDescr.type.compactDescr, proxy)
self._inventoryID = inventoryID
self._xp = 0
self._dailyXPFactor = -1
self._isElite = False
self._isFullyElite = False
self._clanLock = 0
self._isUnique = self.isHidden
self._rentPackages = []
self._hasRentPackages = False
self._isDisabledForBuy = False
self._isSelected = False
self._restorePrice = None
self._canTradeIn = False
self._canTradeOff = False
self._tradeOffPriceFactor = 0
self._tradeOffPrice = MONEY_UNDEFINED
self._rotationGroupNum = 0
self._rotationBattlesLeft = 0
self._isRotationGroupLocked = False
self._isInfiniteRotationGroup = False
self._customOutfits = {}
self._styledOutfits = {}
if self.isPremiumIGR:
self._searchableUserName = makeSearchableString(self.shortUserName)
else:
self._searchableUserName = makeSearchableString(self.userName)
invData = dict()
tradeInData = None
if proxy is not None and proxy.inventory.isSynced() and proxy.stats.isSynced() and proxy.shop.isSynced() and proxy.vehicleRotation.isSynced() and proxy.recycleBin.isSynced():
invDataTmp = proxy.inventory.getItems(GUI_ITEM_TYPE.VEHICLE, inventoryID)
if invDataTmp is not None:
invData = invDataTmp
tradeInData = proxy.shop.tradeIn
self._xp = proxy.stats.vehiclesXPs.get(self.intCD, self._xp)
if proxy.shop.winXPFactorMode == WIN_XP_FACTOR_MODE.ALWAYS or self.intCD not in proxy.stats.multipliedVehicles and not self.isOnlyForEventBattles:
self._dailyXPFactor = proxy.shop.dailyXPFactor
self._isElite = not vehDescr.type.unlocksDescrs or self.intCD in proxy.stats.eliteVehicles
self._isFullyElite = self.isElite and not any((data[1] not in proxy.stats.unlocks for data in vehDescr.type.unlocksDescrs))
clanDamageLock = proxy.stats.vehicleTypeLocks.get(self.intCD, {}).get(CLAN_LOCK, 0)
clanNewbieLock = proxy.stats.globalVehicleLocks.get(CLAN_LOCK, 0)
self._clanLock = clanDamageLock or clanNewbieLock
self._isDisabledForBuy = self.intCD in proxy.shop.getNotToBuyVehicles()
self._hasRentPackages = bool(proxy.shop.getVehicleRentPrices().get(self.intCD, {}))
self._isSelected = bool(self.invID in proxy.stats.oldVehInvIDs)
self._customOutfits = self._parseCustomOutfits(self.intCD, proxy)
self._styledOutfits = self._parseStyledOutfits(self.intCD, proxy)
restoreConfig = proxy.shop.vehiclesRestoreConfig
self._restorePrice = calcVehicleRestorePrice(self.buyPrices.itemPrice.defPrice, proxy.shop)
self._restoreInfo = proxy.recycleBin.getVehicleRestoreInfo(self.intCD, restoreConfig.restoreDuration, restoreConfig.restoreCooldown)
self._personalDiscountPrice = proxy.shop.getPersonalVehicleDiscountPrice(self.intCD)
self._rotationGroupNum = proxy.vehicleRotation.getGroupNum(self.intCD)
self._rotationBattlesLeft = proxy.vehicleRotation.getBattlesCount(self.rotationGroupNum)
self._isRotationGroupLocked = proxy.vehicleRotation.isGroupLocked(self.rotationGroupNum)
self._isInfiniteRotationGroup = proxy.vehicleRotation.isInfinite(self.rotationGroupNum)
self._inventoryCount = 1 if invData.keys() else 0
data = invData.get('rent')
if data is not None:
self._rentInfo = RentalInfoProvider(isRented=True, *data)
self._settings = invData.get('settings', 0)
self._lock = invData.get('lock', (0, 0))
self._repairCost, self._health = invData.get('repair', (0, 0))
self._gun = self.itemsFactory.createVehicleGun(vehDescr.gun.compactDescr, proxy, vehDescr.gun)
self._turret = self.itemsFactory.createVehicleTurret(vehDescr.turret.compactDescr, proxy, vehDescr.turret)
self._engine = self.itemsFactory.createVehicleEngine(vehDescr.engine.compactDescr, proxy, vehDescr.engine)
self._chassis = self.itemsFactory.createVehicleChassis(vehDescr.chassis.compactDescr, proxy, vehDescr.chassis)
self._radio = self.itemsFactory.createVehicleRadio(vehDescr.radio.compactDescr, proxy, vehDescr.radio)
self._fuelTank = self.itemsFactory.createVehicleFuelTank(vehDescr.fuelTank.compactDescr, proxy, vehDescr.fuelTank)
sellPrice = self._calcSellPrice(proxy)
defaultSellPrice = self._calcDefaultSellPrice(proxy)
self._sellPrices = ItemPrices(itemPrice=ItemPrice(price=sellPrice, defPrice=defaultSellPrice), itemAltPrice=ITEM_PRICE_EMPTY)
if tradeInData is not None and tradeInData.isEnabled and self.isPremium and not self.isPremiumIGR:
self._tradeOffPriceFactor = tradeInData.sellPriceFactor
tradeInLevels = tradeInData.allowedVehicleLevels
self._canTradeIn = not self.isPurchased and not self.isHidden and self.isUnlocked and not self.isRestorePossible() and self.level in tradeInLevels
self._canTradeOff = self.isPurchased and not self.canNotBeSold and self.intCD not in tradeInData.forbiddenVehicles and self.level in tradeInLevels
if self.canTradeOff:
self._tradeOffPrice = Money(gold=int(math.ceil(self.tradeOffPriceFactor * self.buyPrices.itemPrice.price.gold)))
self._optDevices = self._parserOptDevs(vehDescr.optionalDevices, proxy)
gunAmmoLayout = []
for shell in self.gun.defaultAmmo:
gunAmmoLayout += (shell.intCD, shell.defaultCount)
self._shells = self._parseShells(invData.get('shells', list()), invData.get('shellsLayout', dict()).get(self.shellsLayoutIdx, gunAmmoLayout), proxy)
self._equipment = VehicleEquipment(proxy, invData.get('eqs'))
self._equipmentLayout = VehicleEquipment(proxy, invData.get('eqsLayout'))
defaultCrew = [None] * len(vehDescr.type.crewRoles)
crewList = invData.get('crew', defaultCrew)
self._bonuses = self._calcCrewBonuses(crewList, proxy)
self._crewIndices = dict([ (invID, idx) for idx, invID in enumerate(crewList) ])
self._crew = self._buildCrew(crewList, proxy)
self._lastCrew = invData.get('lastCrew')
self._rentPackages = calcRentPackages(self, proxy)
self._hasModulesToSelect = self.__hasModulesToSelect()
self.__customState = ''
return
@property
def buyPrices(self):
currency = self._buyPrices.itemPrice.price.getCurrency()
if self._personalDiscountPrice is not None and self._personalDiscountPrice.get(currency) <= self._buyPrices.itemPrice.price.get(currency):
currentPrice = self._personalDiscountPrice
else:
currentPrice = self._buyPrices.itemPrice.price
if self.isRented and not self.rentalIsOver:
buyPrice = currentPrice - self.rentCompensation
else:
buyPrice = currentPrice
return ItemPrices(itemPrice=ItemPrice(price=buyPrice, defPrice=self._buyPrices.itemPrice.defPrice), itemAltPrice=self._buyPrices.itemAltPrice)
@property
def searchableUserName(self):
return self._searchableUserName
def getUnlockDescrByIntCD(self, intCD):
for unlockIdx, data in enumerate(self.descriptor.type.unlocksDescrs):
if intCD == data[1]:
return (unlockIdx, data[0], set(data[2:]))
return (-1, 0, set())
def _calcSellPrice(self, proxy):
if self.isRented:
return MONEY_UNDEFINED
price = self.sellPrices.itemPrice.price
defaultDevices, installedDevices, _ = self.descriptor.getDevices()
for defCompDescr, instCompDescr in izip(defaultDevices, installedDevices):
if defCompDescr == instCompDescr:
continue
modulePrice = FittingItem(defCompDescr, proxy).sellPrices.itemPrice.price
price = price - modulePrice
modulePrice = FittingItem(instCompDescr, proxy).sellPrices.itemPrice.price
price = price + modulePrice
return price
def _calcDefaultSellPrice(self, proxy):
if self.isRented:
return MONEY_UNDEFINED
price = self.sellPrices.itemPrice.defPrice
defaultDevices, installedDevices, _ = self.descriptor.getDevices()
for defCompDescr, instCompDescr in izip(defaultDevices, installedDevices):
if defCompDescr == instCompDescr:
continue
modulePrice = FittingItem(defCompDescr, proxy).sellPrices.itemPrice.defPrice
price = price - modulePrice
modulePrice = FittingItem(instCompDescr, proxy).sellPrices.itemPrice.defPrice
price = price + modulePrice
return price
def _calcCrewBonuses(self, crew, proxy):
bonuses = dict()
bonuses['equipment'] = 0.0
for eq in self.equipment.regularConsumables.getInstalledItems():
bonuses['equipment'] += eq.crewLevelIncrease
for battleBooster in self.equipment.battleBoosterConsumables.getInstalledItems():
bonuses['equipment'] += battleBooster.getCrewBonus(self)
bonuses['optDevices'] = self.descriptor.miscAttrs['crewLevelIncrease']
bonuses['commander'] = 0
commanderEffRoleLevel = 0
bonuses['brotherhood'] = tankmen.getSkillsConfig().getSkill('brotherhood').crewLevelIncrease
for tankmanID in crew:
if tankmanID is None:
bonuses['brotherhood'] = 0.0
continue
tmanInvData = proxy.inventory.getItems(GUI_ITEM_TYPE.TANKMAN, tankmanID)
if not tmanInvData:
continue
tdescr = tankmen.TankmanDescr(compactDescr=tmanInvData['compDescr'])
if 'brotherhood' not in tdescr.skills or tdescr.skills.index('brotherhood') == len(tdescr.skills) - 1 and tdescr.lastSkillLevel != tankmen.MAX_SKILL_LEVEL:
bonuses['brotherhood'] = 0.0
if tdescr.role == Tankman.ROLES.COMMANDER:
factor, addition = tdescr.efficiencyOnVehicle(self.descriptor)
commanderEffRoleLevel = round(tdescr.roleLevel * factor + addition)
bonuses['commander'] += round((commanderEffRoleLevel + bonuses['brotherhood'] + bonuses['equipment']) / tankmen.COMMANDER_ADDITION_RATIO)
return bonuses
def _buildCrew(self, crew, proxy):
crewItems = list()
crewRoles = self.descriptor.type.crewRoles
for idx, tankmanID in enumerate(crew):
tankman = None
if tankmanID is not None:
tmanInvData = proxy.inventory.getItems(GUI_ITEM_TYPE.TANKMAN, tankmanID)
tankman = self.itemsFactory.createTankman(strCompactDescr=tmanInvData['compDescr'], inventoryID=tankmanID, vehicle=self, proxy=proxy)
crewItems.append((idx, tankman))
return _sortCrew(crewItems, crewRoles)
@staticmethod
def __crewSort(t1, t2):
return 0 if t1 is None or t2 is None else t1.__cmp__(t2)
def _parseCompDescr(self, compactDescr):
nId, innID = vehicles.parseVehicleCompactDescr(compactDescr)
return (GUI_ITEM_TYPE.VEHICLE, nId, innID)
def _parseShells(self, layoutList, defaultLayoutList, proxy):
shellsDict = dict(((cd, count) for cd, count, _ in LayoutIterator(layoutList)))
defaultsDict = dict(((cd, (count, isBoughtForCredits)) for cd, count, isBoughtForCredits in LayoutIterator(defaultLayoutList)))
layoutList = list(layoutList)
for shot in self.descriptor.gun.shots:
cd = shot.shell.compactDescr
if cd not in shellsDict:
layoutList.extend([cd, 0])
result = list()
for intCD, count, _ in LayoutIterator(layoutList):
defaultCount, isBoughtForCredits = defaultsDict.get(intCD, (0, False))
result.append(self.itemsFactory.createShell(intCD, count, defaultCount, proxy, isBoughtForCredits))
return result
@classmethod
def _parseCustomOutfits(cls, compactDescr, proxy):
outfits = {}
for season in SeasonType.SEASONS:
outfitData = proxy.inventory.getOutfitData(compactDescr, season)
if outfitData:
outfits[season] = cls.itemsFactory.createOutfit(outfitData.compDescr, bool(outfitData.flags & StyleFlags.ENABLED), bool(outfitData.flags & StyleFlags.INSTALLED), proxy)
outfits[season] = cls.itemsFactory.createOutfit()
return outfits
@classmethod
def _parseStyledOutfits(cls, compactDescr, proxy):
outfits = {}
outfitData = proxy.inventory.getOutfitData(compactDescr, SeasonType.ALL)
if not outfitData or not bool(outfitData.flags & StyleFlags.ENABLED):
return outfits
component = customizations.parseCompDescr(outfitData.compDescr)
styleIntCD = vehicles.makeIntCompactDescrByID('customizationItem', CustomizationType.STYLE, component.styleId)
style = vehicles.getItemByCompactDescr(styleIntCD)
for styleSeason in SeasonType.SEASONS:
compDescr = style.outfits.get(styleSeason).makeCompDescr()
outfits[styleSeason] = cls.itemsFactory.createOutfit(compDescr, bool(outfitData.flags & StyleFlags.ENABLED), bool(outfitData.flags & StyleFlags.INSTALLED), proxy)
return outfits
@classmethod
def _parserOptDevs(cls, layoutList, proxy):
result = list()
for i in xrange(len(layoutList)):
optDevDescr = layoutList[i]
result.append(cls.itemsFactory.createOptionalDevice(optDevDescr.compactDescr, proxy) if optDevDescr is not None else None)
return result
@property
def iconContour(self):
return getContourIconPath(self.name)
@property
def iconUnique(self):
return getUniqueIconPath(self.name, withLightning=False)
@property
def iconUniqueLight(self):
return getUniqueIconPath(self.name, withLightning=True)
@property
def shellsLayoutIdx(self):
return (self.turret.descriptor.compactDescr, self.gun.descriptor.compactDescr)
@property
def invID(self):
return self._inventoryID
@property
def xp(self):
return self._xp
@property
def dailyXPFactor(self):
return self._dailyXPFactor
@property
def isElite(self):
return self._isElite
@property
def isFullyElite(self):
return self._isFullyElite
@property
def clanLock(self):
return self._clanLock
@property
def isUnique(self):
return self._isUnique
@property
def rentPackages(self):
return self._rentPackages
@property
def hasRentPackages(self):
return self._hasRentPackages
@property
def isDisabledForBuy(self):
return self._isDisabledForBuy
@property
def isSelected(self):
return self._isSelected
@property
def restorePrice(self):
return self._restorePrice
@property
def canTradeIn(self):
return self._canTradeIn
@property
def canTradeOff(self):
return self._canTradeOff
@property
def tradeOffPriceFactor(self):
return self._tradeOffPriceFactor
@property
def tradeOffPrice(self):
return self._tradeOffPrice
@property
def rotationGroupNum(self):
return self._rotationGroupNum
@property
def rotationBattlesLeft(self):
return self._rotationBattlesLeft
@property
def isRotationGroupLocked(self):
return self._isRotationGroupLocked
@property
def isInfiniteRotationGroup(self):
return self._isInfiniteRotationGroup
@property
def settings(self):
return self._settings
@settings.setter
def settings(self, value):
self._settings = value
@property
def lock(self):
return self._lock
@property
def repairCost(self):
return self._repairCost
@property
def health(self):
return self._health
@property
def gun(self):
return self._gun
@gun.setter
def gun(self, value):
self._gun = value
@property
def turret(self):
return self._turret
@turret.setter
def turret(self, value):
self._turret = value
@property
def engine(self):
return self._engine
@engine.setter
def engine(self, value):
self._engine = value
@property
def chassis(self):
return self._chassis
@chassis.setter
def chassis(self, value):
self._chassis = value
@property
def radio(self):
return self._radio
@radio.setter
def radio(self, value):
self._radio = value
@property
def fuelTank(self):
return self._fuelTank
@fuelTank.setter
def fuelTank(self, value):
self._fuelTank = value
@property
def optDevices(self):
return self._optDevices
@property
def shells(self):
return self._shells
@property
def equipment(self):
return self._equipment
@property
def equipmentLayout(self):
return self._equipmentLayout
@property
def modules(self):
return (self.chassis,
self.turret if self.hasTurrets else None,
self.gun,
self.engine,
self.radio)
@property
def bonuses(self):
return self._bonuses
@property
def crewIndices(self):
return self._crewIndices
@property
def crew(self):
return self._crew
@crew.setter
def crew(self, value):
self._crew = value
@property
def lastCrew(self):
return self._lastCrew
@property
def hasModulesToSelect(self):
return self._hasModulesToSelect
@property
def isRentable(self):
return self.hasRentPackages and not self.isPurchased
@property
def isPurchased(self):
return self.isInInventory and not self.rentInfo.isRented
def isPreviewAllowed(self):
return not self.isInInventory and not self.isSecret
@property
def rentExpiryTime(self):
return self.rentInfo.rentExpiryTime
@property
def rentCompensation(self):
return self.rentInfo.compensations
@property
def isRentAvailable(self):
return self.maxRentDuration - self.rentLeftTime >= self.minRentDuration
@property
def minRentPrice(self):
minRentPackage = self.getRentPackage()
return minRentPackage.get('rentPrice', MONEY_UNDEFINED) if minRentPackage is not None else MONEY_UNDEFINED
@property
def isRented(self):
return self.rentInfo.isRented
@property
def rentLeftTime(self):
return self.rentInfo.getTimeLeft()
@property
def maxRentDuration(self):
return max((item['days'] for item in self.rentPackages)) * self.MAX_RENT_MULTIPLIER * time_utils.ONE_DAY if self.rentPackages else 0
@property
def minRentDuration(self):
return min((item['days'] for item in self.rentPackages)) * time_utils.ONE_DAY if self.rentPackages else 0
@property
def rentalIsOver(self):
return self.isRented and self.rentExpiryState and not self.isSelected
@property
def rentalIsActive(self):
return self.isRented and not self.rentExpiryState
@property
def rentLeftBattles(self):
return self.rentInfo.battlesLeft
@property
def rentExpiryState(self):
return self.rentInfo.getExpiryState()
@property
def descriptor(self):
return self.__descriptor
@property
def type(self):
return set(vehicles.VEHICLE_CLASS_TAGS & self.tags).pop()
@property
def typeUserName(self):
return getTypeUserName(self.type, self.isElite)
@property
def hasTurrets(self):
vDescr = self.descriptor
return len(vDescr.hull.fakeTurrets['lobby']) != len(vDescr.turrets)
@property
def hasBattleTurrets(self):
vDescr = self.descriptor
return len(vDescr.hull.fakeTurrets['battle']) != len(vDescr.turrets)
@property
def ammoMaxSize(self):
return self.descriptor.gun.maxAmmo
@property
def isAmmoFull(self):
return sum((s.count for s in self.shells)) >= self.ammoMaxSize * self.NOT_FULL_AMMO_MULTIPLIER
@property
def hasShells(self):
return sum((s.count for s in self.shells)) > 0
@property
def hasCrew(self):
return findFirst(lambda x: x[1] is not None, self.crew) is not None
@property
def hasEquipments(self):
return findFirst(None, self.equipment.regularConsumables) is not None
@property
def hasOptionalDevices(self):
return findFirst(None, self.optDevices) is not None
@property
def modelState(self):
if self.health < 0:
return Vehicle.VEHICLE_STATE.EXPLODED
return Vehicle.VEHICLE_STATE.DESTROYED if self.repairCost > 0 and self.health == 0 else Vehicle.VEHICLE_STATE.UNDAMAGED
def getState(self, isCurrnentPlayer=True):
ms = self.modelState
if not self.isInInventory and isCurrnentPlayer:
ms = Vehicle.VEHICLE_STATE.NOT_PRESENT
if self.isInBattle:
ms = Vehicle.VEHICLE_STATE.BATTLE
elif self.rentalIsOver:
ms = Vehicle.VEHICLE_STATE.RENTAL_IS_OVER
if self.isPremiumIGR:
ms = Vehicle.VEHICLE_STATE.IGR_RENTAL_IS_OVER
elif self.isTelecom:
ms = Vehicle.VEHICLE_STATE.DEAL_IS_OVER
elif self.isDisabledInPremIGR:
ms = Vehicle.VEHICLE_STATE.IN_PREMIUM_IGR_ONLY
elif self.isInPrebattle:
ms = Vehicle.VEHICLE_STATE.IN_PREBATTLE
elif self.isLocked:
ms = Vehicle.VEHICLE_STATE.LOCKED
elif self.isDisabledInRoaming:
ms = Vehicle.VEHICLE_STATE.SERVER_RESTRICTION
elif self.isRotationGroupLocked:
ms = Vehicle.VEHICLE_STATE.ROTATION_GROUP_LOCKED
ms = self.__checkUndamagedState(ms, isCurrnentPlayer)
if ms in Vehicle.CAN_SELL_STATES and self.__customState:
ms = self.__customState
return (ms, self.__getStateLevel(ms))
def setCustomState(self, state):
self.__customState = state
def getCustomState(self):
return self.__customState
def clearCustomState(self):
self.__customState = ''
def isCustomStateSet(self):
return self.__customState != ''
def __checkUndamagedState(self, state, isCurrnentPlayer=True):
if state == Vehicle.VEHICLE_STATE.UNDAMAGED and isCurrnentPlayer:
if self.isBroken:
return Vehicle.VEHICLE_STATE.DAMAGED
if not self.isCrewFull:
return Vehicle.VEHICLE_STATE.CREW_NOT_FULL
if not self.isAmmoFull:
return Vehicle.VEHICLE_STATE.AMMO_NOT_FULL
if not self.isRotationGroupLocked and self.rotationGroupNum != 0:
return Vehicle.VEHICLE_STATE.ROTATION_GROUP_UNLOCKED
return state
@classmethod
def __getEventVehicles(cls):
return cls.eventsCache.getEventVehicles()
def isRotationApplied(self):
return self.rotationGroupNum != 0
def isGroupReady(self):
return (True, '')
def __getStateLevel(self, state):
if state in (Vehicle.VEHICLE_STATE.CREW_NOT_FULL,
Vehicle.VEHICLE_STATE.DAMAGED,
Vehicle.VEHICLE_STATE.EXPLODED,
Vehicle.VEHICLE_STATE.DESTROYED,
Vehicle.VEHICLE_STATE.SERVER_RESTRICTION,
Vehicle.VEHICLE_STATE.RENTAL_IS_OVER,
Vehicle.VEHICLE_STATE.IGR_RENTAL_IS_OVER,
Vehicle.VEHICLE_STATE.AMMO_NOT_FULL_EVENTS,
Vehicle.VEHICLE_STATE.UNSUITABLE_TO_QUEUE,
Vehicle.VEHICLE_STATE.DEAL_IS_OVER,
Vehicle.VEHICLE_STATE.UNSUITABLE_TO_UNIT,
Vehicle.VEHICLE_STATE.ROTATION_GROUP_LOCKED):
return Vehicle.VEHICLE_STATE_LEVEL.CRITICAL
return Vehicle.VEHICLE_STATE_LEVEL.INFO if state in (Vehicle.VEHICLE_STATE.UNDAMAGED, Vehicle.VEHICLE_STATE.ROTATION_GROUP_UNLOCKED) else Vehicle.VEHICLE_STATE_LEVEL.WARNING
@property
def isPremium(self):
return checkForTags(self.tags, VEHICLE_TAGS.PREMIUM)
@property
def isPremiumIGR(self):
return checkForTags(self.tags, VEHICLE_TAGS.PREMIUM_IGR)
@property
def isSecret(self):
return checkForTags(self.tags, VEHICLE_TAGS.SECRET)
@property
def isSpecial(self):
return checkForTags(self.tags, VEHICLE_TAGS.SPECIAL)
@property
def isExcludedFromSandbox(self):
return checkForTags(self.tags, VEHICLE_TAGS.EXCLUDED_FROM_SANDBOX)
@property
def isObserver(self):
return checkForTags(self.tags, VEHICLE_TAGS.OBSERVER)
@property
def isEvent(self):
return self.isOnlyForEventBattles and self in Vehicle.__getEventVehicles()
@property
def isDisabledInRoaming(self):
return checkForTags(self.tags, VEHICLE_TAGS.DISABLED_IN_ROAMING) and self.lobbyContext.getServerSettings().roaming.isInRoaming()
@property
def canNotBeSold(self):
return checkForTags(self.tags, VEHICLE_TAGS.CANNOT_BE_SOLD)
@property
def isUnrecoverable(self):
return checkForTags(self.tags, VEHICLE_TAGS.UNRECOVERABLE)
@property
def isCrewLocked(self):
return checkForTags(self.tags, VEHICLE_TAGS.CREW_LOCKED)
@property
def isOutfitLocked(self):
return checkForTags(self.tags, VEHICLE_TAGS.OUTFIT_LOCKED)
@property
def isDisabledInPremIGR(self):
return self.isPremiumIGR and self.igrCtrl.getRoomType() != constants.IGR_TYPE.PREMIUM
@property
def name(self):
return self.descriptor.type.name
@property
def userName(self):
return getUserName(self.descriptor.type)
@property
def longUserName(self):
typeInfo = getTypeInfoByName('vehicle')
tagsDump = [ typeInfo['tags'][tag]['userString'] for tag in self.tags if typeInfo['tags'][tag]['userString'] != '' ]
return '%s %s' % (''.join(tagsDump), getUserName(self.descriptor.type))
@property
def shortUserName(self):
return getShortUserName(self.descriptor.type)
@property
def level(self):
return self.descriptor.type.level
@property
def fullDescription(self):
return self.descriptor.type.description if self.descriptor.type.description.find('_descr') == -1 else ''
@property
def tags(self):
return self.descriptor.type.tags
@property
def rotationGroupIdx(self):
return self.rotationGroupNum - 1
@property
def canSell(self):
if not self.isInInventory:
return False
st, _ = self.getState()
if self.isRented:
if not self.rentalIsOver:
return False
if st in (self.VEHICLE_STATE.RENTAL_IS_OVER, self.VEHICLE_STATE.IGR_RENTAL_IS_OVER):
st = self.__checkUndamagedState(self.modelState)
return st in self.CAN_SELL_STATES and not checkForTags(self.tags, VEHICLE_TAGS.CANNOT_BE_SOLD)
@property
def isLocked(self):
return self.lock[0] != LOCK_REASON.NONE
@property
def isInBattle(self):
return self.lock[0] == LOCK_REASON.ON_ARENA
@property
def isInPrebattle(self):
return self.lock[0] in (LOCK_REASON.PREBATTLE, LOCK_REASON.UNIT)
@property
def isAwaitingBattle(self):
return self.lock[0] == LOCK_REASON.IN_QUEUE
@property
def isInUnit(self):
return self.lock[0] == LOCK_REASON.UNIT
@property
def typeOfLockingArena(self):
return None if not self.isLocked else self.lock[1]
@property
def isBroken(self):
return self.repairCost > 0
@property
def isAlive(self):
return not self.isBroken and not self.isLocked
@property
def isCrewFull(self):
crew = [ tman for _, tman in self.crew ]
return None not in crew and len(crew)
@property
def isOnlyForEventBattles(self):
return checkForTags(self.tags, VEHICLE_TAGS.EVENT)
@property
def isTelecom(self):
return checkForTags(self.tags, VEHICLE_TAGS.TELECOM)
@property
def isTelecomDealOver(self):
return self.isTelecom and self.rentExpiryState
def hasLockMode(self):
isBS = prb_getters.isBattleSession()
if isBS:
isBSVehicleLockMode = bool(prb_getters.getPrebattleSettings()[PREBATTLE_SETTING_NAME.VEHICLE_LOCK_MODE])
if isBSVehicleLockMode and self.clanLock > 0:
return True
return False
def isReadyToPrebattle(self, checkForRent=True):
if checkForRent and self.rentalIsOver:
return False
if not self.isGroupReady()[0]:
return False
result = not self.hasLockMode()
if result:
result = not self.isBroken and self.isCrewFull and not self.isDisabledInPremIGR and not self.isInBattle and not self.isRotationGroupLocked
return result
@property
def isReadyToFight(self):
if self.rentalIsOver:
return False
if not self.isGroupReady()[0]:
return False
result = not self.hasLockMode()
if result:
result = self.isAlive and self.isCrewFull and not self.isDisabledInRoaming and not self.isDisabledInPremIGR and not self.isRotationGroupLocked
return result
@property
def isXPToTman(self):
return bool(self.settings & VEHICLE_SETTINGS_FLAG.XP_TO_TMAN)
@property
def isAutoRepair(self):
return bool(self.settings & VEHICLE_SETTINGS_FLAG.AUTO_REPAIR)
@property
def isAutoLoad(self):
return bool(self.settings & VEHICLE_SETTINGS_FLAG.AUTO_LOAD)
@property
def isAutoEquip(self):
return bool(self.settings & VEHICLE_SETTINGS_FLAG.AUTO_EQUIP)
def isAutoBattleBoosterEquip(self):
return bool(self.settings & VEHICLE_SETTINGS_FLAG.AUTO_EQUIP_BOOSTER)
@property
def isFavorite(self):
return bool(self.settings & VEHICLE_SETTINGS_FLAG.GROUP_0)
@property
def isAutoRentStyle(self):
return bool(self.settings & VEHICLE_SETTINGS_FLAG.AUTO_RENT_CUSTOMIZATION)
def isAutoLoadFull(self):
if self.isAutoLoad:
for shell in self.shells:
if shell.count != shell.defaultCount:
return False
return True
def isAutoEquipFull(self):
return self.equipment.regularConsumables == self.equipmentLayout.regularConsumables if self.isAutoEquip else True
def mayPurchase(self, money):
if self.isOnlyForEventBattles:
return (False, 'isDisabledForBuy')
if self.isDisabledForBuy:
return (False, 'isDisabledForBuy')
return (False, 'premiumIGR') if self.isPremiumIGR else super(Vehicle, self).mayPurchase(money)
def mayRent(self, money):
if getattr(BigWorld.player(), 'isLongDisconnectedFromCenter', False):
return (False, GUI_ITEM_ECONOMY_CODE.CENTER_UNAVAILABLE)
if self.isDisabledForBuy and not self.isRentable:
return (False, GUI_ITEM_ECONOMY_CODE.RENTAL_DISABLED)
if self.isRentable and not self.isRentAvailable:
return (False, GUI_ITEM_ECONOMY_CODE.RENTAL_TIME_EXCEEDED)
minRentPrice = self.minRentPrice
return self._isEnoughMoney(minRentPrice, money) if minRentPrice else (False, GUI_ITEM_ECONOMY_CODE.NO_RENT_PRICE)
def mayRestore(self, money):
if getattr(BigWorld.player(), 'isLongDisconnectedFromCenter', False):
return (False, GUI_ITEM_ECONOMY_CODE.CENTER_UNAVAILABLE)
return (False, GUI_ITEM_ECONOMY_CODE.RESTORE_DISABLED) if not self.isRestoreAvailable() or constants.IS_CHINA and self.rentalIsActive else self._isEnoughMoney(self.restorePrice, money)
def mayRestoreWithExchange(self, money, exchangeRate):
mayRestore, reason = self.mayRestore(money)
if mayRestore:
return mayRestore
if reason == GUI_ITEM_ECONOMY_CODE.NOT_ENOUGH_CREDITS and money.isSet(Currency.GOLD):
money = money.exchange(Currency.GOLD, Currency.CREDITS, exchangeRate, default=0)
mayRestore, reason = self._isEnoughMoney(self.restorePrice, money)
return mayRestore
return False
def getRentPackage(self, days=None):
if days is not None:
for package in self.rentPackages:
if package.get('days', None) == days:
return package
elif self.rentPackages:
return min(self.rentPackages, key=itemgetter('rentPrice'))
return
def getGUIEmblemID(self):
return self.icon
def getRentPackageActionPrc(self, days=None):
package = self.getRentPackage(days)
return getActionPrc(package['rentPrice'], package['defaultRentPrice']) if package else 0
def getAutoUnlockedItems(self):
return self.descriptor.type.autounlockedItems[:]
def getAutoUnlockedItemsMap(self):
return dict(((vehicles.getItemByCompactDescr(nodeCD).itemTypeName, nodeCD) for nodeCD in self.descriptor.type.autounlockedItems))
def getUnlocksDescrs(self):
for unlockIdx, data in enumerate(self.descriptor.type.unlocksDescrs):
yield (unlockIdx,
data[0],
data[1],
set(data[2:]))
def getUnlocksDescr(self, unlockIdx):
try:
data = self.descriptor.type.unlocksDescrs[unlockIdx]
except IndexError:
data = (0, 0, set())
return (data[0], data[1], set(data[2:]))
def getPerfectCrew(self):
return self.getCrewBySkillLevels(100)
def getCrewWithoutSkill(self, skillName):
crewItems = list()
crewRoles = self.descriptor.type.crewRoles
for slotIdx, tman in self.crew:
if tman and skillName in tman.skillsMap:
tmanDescr = tman.descriptor
skills = tmanDescr.skills[:]
if tmanDescr.skillLevel(skillName) < tankmen.MAX_SKILL_LEVEL:
lastSkillLevel = tankmen.MAX_SKILL_LEVEL
else:
lastSkillLevel = tmanDescr.lastSkillLevel
skills.remove(skillName)
unskilledTman = self.itemsFactory.createTankman(tankmen.generateCompactDescr(tmanDescr.getPassport(), tmanDescr.vehicleTypeID, tmanDescr.role, tmanDescr.roleLevel, skills, lastSkillLevel), vehicle=self)
crewItems.append((slotIdx, unskilledTman))
crewItems.append((slotIdx, tman))
return _sortCrew(crewItems, crewRoles)
def getCrewBySkillLevels(self, defRoleLevel, skillsByIdxs=None, levelByIdxs=None, nativeVehsByIdxs=None):
skillsByIdxs = skillsByIdxs or {}
levelByIdxs = levelByIdxs or {}
nativeVehsByIdxs = nativeVehsByIdxs or {}
crewItems = list()
crewRoles = self.descriptor.type.crewRoles
for idx, _ in enumerate(crewRoles):
defRoleLevel = levelByIdxs.get(idx, defRoleLevel)
if defRoleLevel is not None:
role = self.descriptor.type.crewRoles[idx][0]
nativeVehicle = nativeVehsByIdxs.get(idx)
if nativeVehicle is not None:
nationID, vehicleTypeID = nativeVehicle.descriptor.type.id
else:
nationID, vehicleTypeID = self.descriptor.type.id
tankman = self.itemsFactory.createTankman(tankmen.generateCompactDescr(tankmen.generatePassport(nationID), vehicleTypeID, role, defRoleLevel, skillsByIdxs.get(idx, [])), vehicle=self)
else:
tankman = None
crewItems.append((idx, tankman))
return _sortCrew(crewItems, crewRoles)
def getOutfit(self, season):
for outfit in (self._styledOutfits.get(season), self._customOutfits.get(season)):
if outfit and outfit.isActive():
return outfit
outfit = Outfit(isEnabled=True, isInstalled=True)
return outfit
def setCustomOutfit(self, season, outfit):
self._customOutfits[season] = outfit
def setOutfits(self, fromVehicle):
for season in SeasonType.SEASONS:
self._customOutfits[season] = fromVehicle.getCustomOutfit(season)
self._styledOutfits[season] = fromVehicle.getStyledOutfit(season)
def getCustomOutfit(self, season):
return self._customOutfits.get(season)
def getStyledOutfit(self, season):
return self._styledOutfits.get(season)
def hasOutfit(self, season):
outfit = self.getOutfit(season)
return outfit is not None
def hasOutfitWithItems(self, season):
outfit = self.getOutfit(season)
return outfit is not None and not outfit.isEmpty()
def getBonusCamo(self):
for season in SeasonType.SEASONS:
outfit = self.getOutfit(season)
if not outfit:
continue
camo = outfit.hull.slotFor(GUI_ITEM_TYPE.CAMOUFLAGE).getItem()
if camo:
return camo
return None
def getAnyOutfitSeason(self):
activeSeasons = []
for season in SeasonType.SEASONS:
if self.hasOutfitWithItems(season):
activeSeasons.append(season)
return random.choice(activeSeasons) if activeSeasons else SeasonType.SUMMER
def isRestorePossible(self):
return self.restoreInfo.isRestorePossible() if not self.isPurchased and not self.isUnrecoverable and self.lobbyContext.getServerSettings().isVehicleRestoreEnabled() and self.restoreInfo is not None else False
def isRestoreAvailable(self):
return self.isRestorePossible() and not self.restoreInfo.isInCooldown()
def hasLimitedRestore(self):
return self.isRestorePossible() and self.restoreInfo.isLimited() and self.restoreInfo.getRestoreTimeLeft() > 0
def hasRestoreCooldown(self):
return self.isRestorePossible() and self.restoreInfo.isInCooldown()
def isRecentlyRestored(self):
return self.isPurchased and self.restoreInfo.isInCooldown() if self.restoreInfo is not None else False
def __cmp__(self, other):
if self.isRestorePossible() and not other.isRestorePossible():
return -1
if not self.isRestorePossible() and other.isRestorePossible():
return 1
return cmp(other.hasLimitedRestore(), self.hasLimitedRestore()) or cmp(self.restoreInfo.getRestoreTimeLeft(), other.restoreInfo.getRestoreTimeLeft()) if self.isRestorePossible() and other.isRestorePossible() else super(Vehicle, self).__cmp__(other)
def __eq__(self, other):
return False if other is None else self.descriptor.type.id == other.descriptor.type.id
def __repr__(self):
return 'Vehicle<id:%d, intCD:%d, nation:%d, lock:%s>' % (self.invID,
self.intCD,
self.nationID,
self.lock)
def _mayPurchase(self, price, money):
return (False, GUI_ITEM_ECONOMY_CODE.CENTER_UNAVAILABLE) if getattr(BigWorld.player(), 'isLongDisconnectedFromCenter', False) else super(Vehicle, self)._mayPurchase(price, money)
def _getShortInfo(self, vehicle=None, expanded=False):
description = i18n.makeString('#menu:descriptions/' + self.itemTypeName)
caliber = self.descriptor.gun.shots[0].shell.caliber
armor = findVehicleArmorMinMax(self.descriptor)
return description % {'weight': BigWorld.wg_getNiceNumberFormat(float(self.descriptor.physics['weight']) / 1000),
'hullArmor': BigWorld.wg_getIntegralFormat(armor[1]),
'caliber': BigWorld.wg_getIntegralFormat(caliber)}
def _sortByType(self, other):
return compareByVehTypeName(self.type, other.type)
def __hasModulesToSelect(self):
components = []
for moduleCD in self.descriptor.type.installableComponents:
moduleType = getTypeOfCompactDescr(moduleCD)
if moduleType == GUI_ITEM_TYPE.FUEL_TANK:
continue
if moduleType in components:
return True
components.append(moduleType)
return False
def getTypeUserName(vehType, isElite):
return i18n.makeString('#menu:header/vehicleType/elite/%s' % vehType) if isElite else i18n.makeString('#menu:header/vehicleType/%s' % vehType)
def getTypeShortUserName(vehType):
return i18n.makeString('#menu:classes/short/%s' % vehType)
def _getLevelIconName(vehLevel, postfix=''):
return 'tank_level_%s%d.png' % (postfix, int(vehLevel))
def getLevelBigIconPath(vehLevel):
return '../maps/icons/levels/%s' % _getLevelIconName(vehLevel, 'big_')
def getLevelSmallIconPath(vehLevel):
return '../maps/icons/levels/%s' % _getLevelIconName(vehLevel, 'small_')
def getLevelIconPath(vehLevel):
return '../maps/icons/levels/%s' % _getLevelIconName(vehLevel)
def getIconPath(vehicleName):
return '../maps/icons/vehicle/%s' % getItemIconName(vehicleName)
def getContourIconPath(vehicleName):
return '../maps/icons/vehicle/contour/%s' % getItemIconName(vehicleName)
def getSmallIconPath(vehicleName):
return '../maps/icons/vehicle/small/%s' % getItemIconName(vehicleName)
def getUniqueIconPath(vehicleName, withLightning=False):
return '../maps/icons/vehicle/unique/%s' % getItemIconName(vehicleName) if withLightning else '../maps/icons/vehicle/unique/normal_%s' % getItemIconName(vehicleName)
def getTypeSmallIconPath(vehicleType, isElite=False):
key = vehicleType + '.png'
return RES_ICONS.maps_icons_vehicletypes_elite(key) if isElite else RES_ICONS.maps_icons_vehicletypes(key)
def getTypeBigIconPath(vehicleType, isElite):
key = 'big/' + vehicleType
if isElite:
key += '_elite'
key += '.png'
return RES_ICONS.maps_icons_vehicletypes(key)
def getUserName(vehicleType, textPrefix=False):
return _getActualName(vehicleType.userString, vehicleType.tags, textPrefix)
def getShortUserName(vehicleType, textPrefix=False):
return _getActualName(vehicleType.shortUserString, vehicleType.tags, textPrefix)
def _getActualName(name, tags, textPrefix=False):
if checkForTags(tags, VEHICLE_TAGS.PREMIUM_IGR):
if textPrefix:
return i18n.makeString(ITEM_TYPES.MARKER_IGR, vehName=name)
return makeHtmlString('html_templates:igr/premium-vehicle', 'name', {'vehicle': name})
return name
def checkForTags(vTags, tags):
if not hasattr(tags, '__iter__'):
tags = (tags,)
return bool(vTags & frozenset(tags))
def findVehicleArmorMinMax(vd):
def findComponentArmorMinMax(armor, minMax):
for value in armor:
if value != 0:
if minMax is None:
minMax = [value, value]
else:
minMax[0] = min(minMax[0], value)
minMax[1] = max(minMax[1], value)
return minMax
minMax = None
minMax = findComponentArmorMinMax(vd.hull.primaryArmor, minMax)
for turrets in vd.type.turrets:
for turret in turrets:
minMax = findComponentArmorMinMax(turret.primaryArmor, minMax)
return minMax
def _sortCrew(crewItems, crewRoles):
RO = Tankman.TANKMEN_ROLES_ORDER
return sorted(crewItems, cmp=lambda a, b: RO[crewRoles[a[0]][0]] - RO[crewRoles[b[0]][0]])
def getLobbyDescription(vehicle):
return text_styles.stats(i18n.makeString('#menu:header/level/%s' % vehicle.level)) + ' ' + text_styles.main(i18n.makeString('#menu:header/level', vTypeName=getTypeUserName(vehicle.type, vehicle.isElite)))
def getOrderByVehicleClass(className=None):
if className and className in VEHICLE_BATTLE_TYPES_ORDER_INDICES:
result = VEHICLE_BATTLE_TYPES_ORDER_INDICES[className]
else:
result = UNKNOWN_VEHICLE_CLASS_ORDER
return result
def getVehicleClassTag(tags):
subSet = vehicles.VEHICLE_CLASS_TAGS & tags
result = None
if subSet:
result = list(subSet).pop()
return result
_VEHICLE_STATE_TO_ICON = {Vehicle.VEHICLE_STATE.BATTLE: RES_ICONS.MAPS_ICONS_VEHICLESTATES_BATTLE,
Vehicle.VEHICLE_STATE.IN_PREBATTLE: RES_ICONS.MAPS_ICONS_VEHICLESTATES_INPREBATTLE,
Vehicle.VEHICLE_STATE.DAMAGED: RES_ICONS.MAPS_ICONS_VEHICLESTATES_DAMAGED,
Vehicle.VEHICLE_STATE.DESTROYED: RES_ICONS.MAPS_ICONS_VEHICLESTATES_DAMAGED,
Vehicle.VEHICLE_STATE.EXPLODED: RES_ICONS.MAPS_ICONS_VEHICLESTATES_DAMAGED,
Vehicle.VEHICLE_STATE.CREW_NOT_FULL: RES_ICONS.MAPS_ICONS_VEHICLESTATES_CREWNOTFULL,
Vehicle.VEHICLE_STATE.RENTAL_IS_OVER: RES_ICONS.MAPS_ICONS_VEHICLESTATES_RENTALISOVER,
Vehicle.VEHICLE_STATE.UNSUITABLE_TO_UNIT: RES_ICONS.MAPS_ICONS_VEHICLESTATES_UNSUITABLETOUNIT,
Vehicle.VEHICLE_STATE.UNSUITABLE_TO_QUEUE: RES_ICONS.MAPS_ICONS_VEHICLESTATES_UNSUITABLETOUNIT,
Vehicle.VEHICLE_STATE.GROUP_IS_NOT_READY: RES_ICONS.MAPS_ICONS_VEHICLESTATES_GROUP_IS_NOT_READY}
def getVehicleStateIcon(vState):
if vState in _VEHICLE_STATE_TO_ICON:
icon = _VEHICLE_STATE_TO_ICON[vState]
else:
icon = ''
return icon
def getBattlesLeft(vehicle):
return i18n.makeString('#menu:infinitySymbol') if vehicle.isInfiniteRotationGroup else str(vehicle.rotationBattlesLeft)
| [
"StranikS_Scan@mail.ru"
] | StranikS_Scan@mail.ru |
a9d8055b3ad212516084b0bb991e89c971e57587 | 51a01e2cae03e741440b4ce4ddd36178c16daead | /new/login/migrations/0004_shopcars.py | aeaa2af1fbb96f94afabc659ab81ff0199fb3a1c | [] | no_license | Zhang-LXuan/Molv | 8d2554eebc7049a3091d9b1acfc25c8c489ee927 | c1b6cbc35e1595cc83408a010bbc16cf9b6dc210 | refs/heads/main | 2023-06-24T18:05:48.785683 | 2021-07-28T13:32:07 | 2021-07-28T13:32:07 | 343,711,382 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 837 | py | # Generated by Django 3.1.1 on 2021-02-20 11:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('login', '0003_itrecord'),
]
operations = [
migrations.CreateModel(
name='shopcars',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('car_no', models.IntegerField(null=True)),
('user_name', models.CharField(max_length=100, null=True)),
('item_id', models.IntegerField(null=True)),
('item_counter', models.IntegerField(null=True)),
('item_value', models.CharField(max_length=30)),
('item_money', models.CharField(max_length=30)),
],
),
]
| [
"1257037084@qq.com"
] | 1257037084@qq.com |
62cfb6b503b6ce9ea99f372bcf8a13687c42dca9 | b3b68efa404a7034f0d5a1c10b281ef721f8321a | /Scripts/simulation/conditional_layers/conditional_layer_handlers.py | 9f92448745a071c4aac20c994e6eed081d12f54c | [
"Apache-2.0"
] | permissive | velocist/TS4CheatsInfo | 62195f3333076c148b2a59f926c9fb5202f1c6fb | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | refs/heads/main | 2023-03-08T01:57:39.879485 | 2021-02-13T21:27:38 | 2021-02-13T21:27:38 | 337,543,310 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,967 | py | # uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\conditional_layers\conditional_layer_handlers.py
# Compiled at: 2018-05-11 22:46:41
# Size of source mod 2**32: 5273 bytes
from gsi_handlers.gameplay_archiver import GameplayArchiver
from sims4.gsi.dispatcher import GsiHandler
from sims4.gsi.schema import GsiGridSchema, GsiFieldVisualizers
import date_and_time, enum, services
conditional_layer_service_schema = GsiGridSchema(label='Conditional Layers/Conditional Layer Service')
conditional_layer_service_schema.add_field('conditional_layer', label='Class Name', width=1, unique_field=True)
conditional_layer_service_schema.add_field('layer_hash', label='Layer Name', width=1)
conditional_layer_service_schema.add_field('objects_created', label='Objects Created', width=1)
conditional_layer_service_schema.add_field('requests_waiting', label='Requests Waiting', width=1)
conditional_layer_service_schema.add_field('last_request', label='Last Request', width=1)
with conditional_layer_service_schema.add_has_many('Objects', GsiGridSchema) as (sub_schema):
sub_schema.add_field('object_id', label='Object Id')
sub_schema.add_field('object', label='Object')
with conditional_layer_service_schema.add_has_many('Requests', GsiGridSchema) as (sub_schema):
sub_schema.add_field('request', label='Request')
sub_schema.add_field('speed', label='Speed')
sub_schema.add_field('timer_interval', label='Timer Interval')
sub_schema.add_field('timer_object_count', label='Timer Object Count')
@GsiHandler('conditional_layer_service', conditional_layer_service_schema)
def generate_conditional_layer_service_data(zone_id: int=None):
layer_data = []
conditional_layer_service = services.conditional_layer_service()
if conditional_layer_service is None:
return layer_data
object_manager = services.object_manager()
for conditional_layer, layer_info in conditional_layer_service._layer_infos.items():
object_data = []
for object_id in layer_info.objects_loaded:
obj = object_manager.get(object_id)
object_data.append({'object_id':str(object_id),
'object':str(obj)})
request_data = []
for request in conditional_layer_service.requests:
if request.conditional_layer is conditional_layer:
request_data.append({'request':str(request),
'speed':request.speed.name,
'timer_interval':str(request.timer_interval),
'timer_object_count':str(request.timer_object_count)})
layer_data.append({'layer_hash':str(conditional_layer.layer_name),
'conditional_layer':str(conditional_layer),
'objects_created':str(len(layer_info.objects_loaded)),
'requests_waiting':str(len(request_data)),
'last_request':str(layer_info.last_request_type),
'Objects':object_data,
'Requests':request_data})
return layer_data
class LayerRequestAction(enum.Int, export=False):
SUBMITTED = ...
EXECUTING = ...
COMPLETED = ...
conditional_layer_request_archive_schema = GsiGridSchema(label='Conditional Layers/Conditional Layer Request Archive', sim_specific=False)
conditional_layer_request_archive_schema.add_field('game_time', label='Game/Sim Time', type=(GsiFieldVisualizers.TIME))
conditional_layer_request_archive_schema.add_field('request', label='Request')
conditional_layer_request_archive_schema.add_field('action', label='Action')
conditional_layer_request_archive_schema.add_field('layer_hash', label='Layer Hash')
conditional_layer_request_archive_schema.add_field('speed', label='Speed')
conditional_layer_request_archive_schema.add_field('timer_interval', label='Timer Interval')
conditional_layer_request_archive_schema.add_field('timer_object_count', label='Timer Object Count')
conditional_layer_request_archive_schema.add_field('objects_in_layer_count', label='Object Count')
archiver = GameplayArchiver('conditional_layer_requests', conditional_layer_request_archive_schema,
add_to_archive_enable_functions=True)
def is_archive_enabled():
return archiver.enabled
def archive_layer_request_culling(request, action, objects_in_layer_count=None):
time_service = services.time_service()
if time_service.sim_timeline is None:
time = 'zone not running'
else:
time = time_service.sim_now
entry = {'game_type':str(time), 'request':str(request),
'action':action.name,
'layer_hash':str(hex(request.conditional_layer.layer_name)),
'speed':request.speed.name,
'timer_interval':str(request.timer_interval),
'timer_object_count':str(request.timer_object_count),
'objects_in_layer_count':str(objects_in_layer_count) if objects_in_layer_count else ''}
archiver.archive(entry) | [
"cristina.caballero2406@gmail.com"
] | cristina.caballero2406@gmail.com |
78de7289058ba6cd0376717e3c054543a4765a6e | dda618067f13657f1afd04c94200711c1920ea5f | /scoop/user/util/inlines.py | fae84630c7d38141cbccae33232c7d71bd188d6d | [] | no_license | artscoop/scoop | 831c59fbde94d7d4587f4e004f3581d685083c48 | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | refs/heads/master | 2020-06-17T20:09:13.722360 | 2017-07-12T01:25:20 | 2017-07-12T01:25:20 | 74,974,701 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 952 | py | # coding: utf-8
from django_inlines import inlines
from django_inlines.inlines import TemplateInline
from scoop.user.models import User
class UserInline(TemplateInline):
"""
Inline d'insertion d'utilisateur
Format : {{user id [style=link|etc.]}}
Exemple : {{user 2490 style="link"}}
"""
inline_args = [{'name': 'style'}]
def get_context(self):
""" Renvoyer le contexte d'affichage du template """
identifier = self.value
style = self.kwargs.get('style', 'link')
# Vérifier que l'utilisateur demandé existe
user = User.objects.get_or_none(id=identifier)
return {'user': user, 'style': style}
def get_template_name(self):
""" Renvoyer le chemin du template """
base = super(UserInline, self).get_template_name()[0]
path = "user/%s" % base
return path
# Enregistrer les classes d'inlines
inlines.registry.register('user', UserInline)
| [
"steve.kossouho@gmail.com"
] | steve.kossouho@gmail.com |
a74b2c4c92d32f8db846368e12cf2a70c596f2a8 | e9239cdd1f03ccc299311276b8df995dc03ec137 | /buy/migrations/0001_initial.py | 3ff1ea1d36d0f856229572f291378bd01729de3d | [] | no_license | 3b3al/marketplace | 02bb9b60a8013b1c96b4f1618a87e59aced327ad | d56009af0c6389cfcd3b808fe702513c3d0ba7de | refs/heads/master | 2023-09-03T03:04:16.383146 | 2021-10-28T14:28:43 | 2021-10-28T14:28:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,767 | py | # Generated by Django 3.1.5 on 2021-06-23 21:20
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Customer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=50)),
('last_name', models.CharField(max_length=50)),
('email', models.EmailField(max_length=254)),
('phone', models.CharField(max_length=50)),
('address1', models.TextField()),
('address2', models.TextField()),
],
),
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('price', models.DecimalField(decimal_places=2, default=0.0, max_digits=100)),
('description', models.TextField(null=True)),
('summary', models.TextField(null=True)),
('type', models.CharField(max_length=50, null=True)),
('brand', models.CharField(max_length=50, null=True)),
('weight', models.DecimalField(decimal_places=3, default=0.0, max_digits=100)),
('picture', models.ImageField(null=True, upload_to='images/')),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
],
),
migrations.CreateModel(
name='OrderQuantity',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('quantity', models.PositiveIntegerField()),
('product', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='buy.item')),
],
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('address', models.TextField()),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('customer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='buy.customer')),
('ordered_item', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='buy.orderquantity')),
],
),
]
| [
"gamaleyas@gmail.com"
] | gamaleyas@gmail.com |
bbcde66a1ba9ee74d286698425ce9b4a489d5c96 | 842296d48452463055494da9b09b49d805077c0f | /nameAge.py | ebd174764e46363a085bdb6ca4ee6427a81753d1 | [] | no_license | JamesRoth/Unit-1 | 1f3e5f79044d598708360ebff9547ab029c498b2 | 30b25874458d5c76215f139d0cbaab5876e5640a | refs/heads/master | 2021-05-11T13:43:32.897594 | 2018-01-26T13:14:51 | 2018-01-26T13:14:51 | 117,686,332 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 343 | py | #James Roth
#1/17/18
#nameAge.py - splitting and characters in a string
name=input("What is your first and last name? ")
age=int(input("What is your age? "))
firstName,lastName=name.split()
print("Your first name has ", len(firstName), "letters")
print("Your last name has ", len(lastName), "letters")
print("You will be", age+1, "next year.") | [
"35492763+JamesRoth@users.noreply.github.com"
] | 35492763+JamesRoth@users.noreply.github.com |
c387bf8145f4fb230a3446850b2101b88050201a | acb8e84e3b9c987fcab341f799f41d5a5ec4d587 | /langs/8/uz4.py | eb498670c22bbeea754028188e9d8126364e9394 | [] | 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] == 'uZ4':
printFunction(data[1:])
else:
print 'ERROR'
return
if __name__ == '__main__':
main(sys.argv[1]) | [
"juliettaylorswift@gmail.com"
] | juliettaylorswift@gmail.com |
132721dbb13b99666f81c07a2a6c12d61872d3b5 | 6354a9a3eb5fd920085e4f92887cdd98b8a5a0af | /level_five/basic_app/views.py | 34646c1aed286a191704a1620514501c42c24b23 | [] | no_license | ujithendrakumar/django-projects | e47d2c38535b755f8191d81fade3c79b28c3faa0 | 2c22a6acb28a966cac4076afd939eb09929e30ea | refs/heads/master | 2022-12-28T21:28:01.255828 | 2019-01-06T13:36:37 | 2019-01-06T13:36:37 | 157,509,802 | 2 | 1 | null | 2022-12-08T13:37:11 | 2018-11-14T07:38:55 | Python | UTF-8 | Python | false | false | 2,423 | py | from django.shortcuts import render,redirect
from basic_app.forms import UserForm,UserProfileInfoForm
#Login code goes here
from django.contrib.auth import login,logout,authenticate
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
context ={}
return render(request,'basic_app/index.html',context)
def register(request):
registered = False
context = {'registered':registered}
if request.method == "POST":
user_form = UserForm(data=request.POST)
user_profile = UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and user_profile.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = user_profile.save(commit=False)
profile.user = user
if 'profile_image' in request.FILES:
profile.profile_image = request.FILES['profile_image']
profile.save()
registered = True
else:
print(user_form.errors,user_profile.errors)
else:
user_form = UserForm()
user_profile = UserProfileInfoForm()
context = {'user_form':user_form,'user_profile':user_profile,'registered':registered}
return render(request,'basic_app/registration.html',context)
def user_login(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
print(username)
print(password)
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('basic_app:index'))
else:
return HttpResponse("Account Not Active..!")
else:
print("Someone trying to login and Failed!")
print("Username : {} and Password : {}".format(username,password))
return HttpResponse("Invalid Login Details")
else:
return render(request,'basic_app/login.html')
@login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('basic_app:user_login'))
@login_required
def special(request):
return render(request,'basic_app/special.html')
| [
"ujk222@gmail.com"
] | ujk222@gmail.com |
3f56e0b32438cf0782e92e5ea2de9f3379161e3d | 679cbcaa1a48c7ec9a4f38fa42d2dc06d7e7b6ef | /main.py | d5f2cef309384ff826e8e3934d2f1a1e69578595 | [] | no_license | roblivesinottawa/canada_provinces_game | cb2242845e3dd3a3902c0f416ac1a4efa485aecf | 2aa5c7236c2ac7381522b493fddf415ece9c3a87 | refs/heads/main | 2023-03-04T08:08:31.409489 | 2021-02-17T21:46:18 | 2021-02-17T21:46:18 | 339,863,158 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,000 | py | import turtle
import pandas
screen = turtle.Screen()
screen.title("Canada Provinces Game")
image = "canada_map.gif"
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv("canada_provinces.csv")
all_provinces = data.province.to_list()
guessed = []
while len(guessed) < 50:
answer = screen.textinput(title=f"{len(guessed)} / 12 Provinces Correct",
prompt="What's another provinces's name? ").title()
if answer == "Exit":
missing = []
for province in all_provinces:
if province not in guessed:
missing.append(province)
new_data = pandas.DataFrame(missing)
new_data.to_csv("provinces_to_learn.csv")
break
if answer in all_provinces:
guessed.append(guessed)
t = turtle.Turtle()
t.hideturtle()
t.penup()
province_data = data[data.province == answer]
t.goto(float(province_data.x), float(province_data.y))
t.write(answer)
# turtle.mainloop() | [
"tech.rob@icloud.com"
] | tech.rob@icloud.com |
de432ff29979217cb022d735deddbd110e866064 | c8e96ac26c4ec9f997549056be77452d2875ed77 | /corgie/cli/merge_copy.py | 1e139dfda245cb4fd34fedee59febf8f6ae67c5f | [
"Apache-2.0"
] | permissive | seung-lab/corgie_deprecated | 7b72dc18d7443e5f6cf0ed5feb7ea595bf80b303 | 4d03ca129718b6e52f5161c1bb36fd20c78d2388 | refs/heads/master | 2023-03-15T05:09:56.847570 | 2021-03-24T19:49:26 | 2021-03-24T19:49:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,275 | py | import click
from corgie import scheduling, helpers, stack
from corgie.log import logger as corgie_logger
from corgie.layers import get_layer_types, DEFAULT_LAYER_TYPE, \
str_to_layer_type
from corgie.boundingcube import get_bcube_from_coords
from corgie.argparsers import LAYER_HELP_STR, \
create_layer_from_spec, corgie_optgroup, corgie_option, \
create_stack_from_spec
import json
class MergeCopyJob(scheduling.Job):
def __init__(self,
src_stack,
dst_stack,
mip,
bcube,
z_list,
chunk_xy):
"""Copy multiple images to the same destination image
Args:
src_stack (Stack)
dst_stack (Stack)
mip (int)
bcube (BoundingCube)
z_list ([int]): : ranked by layer priority (first image overwrites later images)
"""
self.src_stack = src_stack
self.dst_stack = dst_stack
self.mip = mip
self.bcube = bcube
self.chunk_xy = chunk_xy
self.z_list = z_list
super().__init__()
def task_generator(self):
chunks = self.dst_stack.get_layers()[0].break_bcube_into_chunks(
bcube=self.bcube,
chunk_xy=self.chunk_xy,
chunk_z=1,
mip=self.mip)
tasks = [MergeCopyTask(src_stack=self.src_stack,
dst_stack=self.dst_stack,
mip=self.mip,
bcube=input_chunk,
z_list=self.z_list) for input_chunk in chunks]
corgie_logger.info(f"Yielding copy tasks for bcube: {self.bcube}, MIP: {self.mip}")
yield tasks
class MergeCopyTask(scheduling.Task):
def __init__(self,
src_stack,
dst_stack,
mip,
bcube,
z_list):
"""Copy multiple images to the same destination image
Args:
src_stack (Stack)
dst_stack (Stack)
mip (int)
bcube (BoundingCube)
z_list ([int]): : ranked by layer priority (first image overwrites later images)
"""
super().__init__(self)
self.src_stack = src_stack
self.dst_stack = dst_stack
self.mip = mip
self.bcube = bcube
self.z_list = z_list
def execute(self):
for k, z in enumerate(self.z_list[::-1]):
src_bcube = self.bcube.reset_coords(zs=z, ze=z+1, in_place=False)
src_trans, src_data_dict = self.src_stack.read_data_dict(src_bcube,
mip=self.mip,
translation_adjuster=None,
stack_name='src')
img_name = self.src_stack.get_layers_of_type('img')[0].name
src_image = src_data_dict[f"src_{img_name}"]
mask_name = self.src_stack.get_layers_of_type('mask')[0].name
mask = src_data_dict[f"src_{mask_name}"]
# mask_layers = src_stack.get_layers_of_type(["mask"])
# mask = helpers.read_mask_list(mask_layers, src_bcube, self.mip)
if k == 0:
dst_image = src_image
dst_image[~mask] = 0
else:
dst_image[mask] = src_image[mask]
dst_layer = self.dst_stack.get_layers_of_type("img")[0]
dst_layer.write(dst_image, bcube=self.bcube, mip=self.mip)
@click.command()
@corgie_optgroup('Layer Parameters')
@corgie_option('--src_layer_spec', '-s', nargs=1,
type=str, required=True, multiple=True,
help='Source layer spec. Order img, mask, img, mask, etc. List must have length of multiple two.' + \
LAYER_HELP_STR)
#
@corgie_option('--dst_folder', nargs=1,
type=str, required=False,
help= "Destination folder for the copied stack")
@corgie_option('--spec_path', nargs=1,
type=str, required=True,
help= "JSON spec relating src stacks, src z to dst z")
@corgie_optgroup('Copy Method Specification')
@corgie_option('--chunk_xy', '-c', nargs=1, type=int, default=1024)
@corgie_option('--mip', nargs=1, type=int, required=True)
@corgie_optgroup('Data Region Specification')
@corgie_option('--start_coord', nargs=1, type=str, required=True)
@corgie_option('--end_coord', nargs=1, type=str, required=True)
@corgie_option('--coord_mip', nargs=1, type=int, default=0)
@corgie_option('--suffix', nargs=1, type=str, default=None)
@click.pass_context
def merge_copy(ctx,
src_layer_spec,
dst_folder,
spec_path,
chunk_xy,
start_coord,
end_coord,
coord_mip,
mip,
suffix):
scheduler = ctx.obj['scheduler']
if suffix is None:
suffix = ''
else:
suffix = f"_{suffix}"
corgie_logger.debug("Setting up layers...")
assert(len(src_layer_spec) % 2 == 0)
src_stacks = {}
for k in range(len(src_layer_spec) // 2):
src_stack = create_stack_from_spec(src_layer_spec[2*k:2*k+2],
name='src',
readonly=True)
name = src_stack.get_layers_of_type('img')[0].path
src_stacks[name] = src_stack
with open(spec_path, 'r') as f:
spec = json.load(f)
# if force_chunk_xy:
# force_chunk_xy = chunk_xy
# else:
# force_chunk_xy = None
# if force_chunk_z:
# force_chunk_z = chunk_z
# else:
# force_chunk_z = None
dst_stack = stack.create_stack_from_reference(reference_stack=list(src_stacks.values())[0],
folder=dst_folder,
name="dst",
types=["img"],
readonly=False,
suffix=suffix,
force_chunk_xy=None,
force_chunk_z =None,
overwrite=True)
bcube = get_bcube_from_coords(start_coord, end_coord, coord_mip)
for z in range(*bcube.z_range()):
spec_z = str(z)
if spec_z in spec.keys():
src_dict = spec[str(z)]
job_bcube = bcube.reset_coords(zs=z, ze=z+1, in_place=False)
src_stack = src_stacks[src_dict['cv_path']]
z_list = src_dict['z_list']
copy_job = MergeCopyJob(src_stack=src_stack,
dst_stack=dst_stack,
mip=mip,
bcube=job_bcube,
chunk_xy=chunk_xy,
z_list=z_list)
# create scheduler and execute the job
scheduler.register_job(copy_job, job_name="MergeCopy {}".format(job_bcube))
scheduler.execute_until_completion()
| [
"noreply@github.com"
] | seung-lab.noreply@github.com |
362cabb65372ed498a9525dfcfd7c9452b03fbdc | 8cb886d37acc4ac03d83c88f91bb4991b7b4f15d | /prueba.py | 36030efd337d5a769ae35888af0ddac49776718b | [] | no_license | gsi-upm/Sensato | 35762c17733885cb95719d01157310e12578e898 | 879dbf59b93d04f58f5eac908cf835a6a52416aa | refs/heads/master | 2021-01-10T10:54:37.393690 | 2013-06-25T10:21:28 | 2013-06-25T10:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 274 | py | import edges
prueba = edges.make_edge ("HasPrerequisite","/c/es/navegadorON", "/c/es/tabletON","/GSI","GSI",["/GSI/u","/GSI/l"]);
print prueba['start']
prueba2 = edges.SolrEdgeWriter('/home/alopez/temp')
prueba2.write_header()
prueba2.write(prueba)
prueba2.write_footer()
| [
"al.lopezf@gmail.com"
] | al.lopezf@gmail.com |
5cdf2ebb543035deab7264327b6d2bf1585576e0 | 09d5d385fec8774f1953a5039c67ef6bd525722b | /configs/0. TGRS-sampling-balance-detector/SBNet_x101_64x4d_fpn_1x_NWPU.py | 5a1fd822a58cf1a396f9b6349ff9bc2467b83ca2 | [] | no_license | yawudede/Sampling-Balance_Multi-stage_Network | f10db07447a4f3ad583660e1f0b67ddfebba9bdb | 1b1910dc0c39f975b53a81d31489709ff75703a8 | refs/heads/master | 2023-01-30T18:17:41.711878 | 2020-12-16T03:23:42 | 2020-12-16T03:23:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,455 | py | # model settings
#--out results.pkl
#loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=0.005)
model = dict(
type='CascadeRCNN',
num_stages=3,
pretrained='open-mmlab://resnext101_64x4d',
backbone=dict(
type='ResNeXt',
depth=101,
groups=64,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
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_scales=[8],
anchor_ratios=[0.5, 1.0, 2.0],
anchor_strides=[4, 8, 16, 32, 64],
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)),
bbox_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAlign', out_size=7, sample_num=2),
out_channels=256,
featmap_strides=[4, 8, 16, 32]),
bbox_head=[
dict(
type='SharedFCBBoxHead',
num_fcs=2,
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=81,
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)
loss_bbox=dict(type='BalancedL1Loss', alpha=0.5, gamma=1.5, beta=1.0,loss_weight=1.0)
),
dict(
type='SharedFCBBoxHead',
num_fcs=2,
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=81,
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)
loss_bbox=dict(type='BalancedL1Loss', alpha=0.5, gamma=1.5, beta=1.0,loss_weight=1.0)
),
dict(
type='SharedFCBBoxHead',
num_fcs=2,
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=81,
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='BalancedL1Loss', alpha=0.5, gamma=1.5, beta=1.0,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,
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_across_levels=False,
nms_pre=2000,
nms_post=2000,
max_num=2000,
nms_thr=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,
ignore_iof_thr=-1),
#sampler=dict(type='RandomSampler',num=512,pos_fraction=0.25,neg_pos_ub=-1,add_gt_as_proposals=True),
sampler=dict(
type='CombinedSampler',
num=512,
pos_fraction=0.25,
add_gt_as_proposals=True,
pos_sampler=dict(type='InstanceBalancedPosSampler'),
neg_sampler=dict(
type='IoUBalancedNegSampler',
floor_thr=-1,
floor_fraction=0,
num_bins=3)),
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,
ignore_iof_thr=-1),
#sampler=dict(type='RandomSampler',num=512,pos_fraction=0.25,neg_pos_ub=-1,add_gt_as_proposals=True),
sampler=dict(
type='CombinedSampler',
num=512,
pos_fraction=0.25,
add_gt_as_proposals=True,
pos_sampler=dict(type='InstanceBalancedPosSampler'),
neg_sampler=dict(
type='IoUBalancedNegSampler',
floor_thr=-1,
floor_fraction=0,
num_bins=3)),
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,
ignore_iof_thr=-1),
# sampler=dict(type='RandomSampler',num=512,pos_fraction=0.25,neg_pos_ub=-1,add_gt_as_proposals=True),
sampler=dict(
type='CombinedSampler',
num=512,
pos_fraction=0.25,
add_gt_as_proposals=True,
pos_sampler=dict(type='InstanceBalancedPosSampler'),
neg_sampler=dict(
type='IoUBalancedNegSampler',
floor_thr=-1,
floor_fraction=0,
num_bins=3)),
pos_weight=-1,
debug=False)
],
stage_loss_weights=[1, 0.5, 0.25])
test_cfg = dict(
rpn=dict(
nms_across_levels=False,
nms_pre=1000,
nms_post=1000,
max_num=1000,
nms_thr=0.7,
min_bbox_size=0),
rcnn=dict(
score_thr=0.05, nms=dict(type='nms', iou_thr=0.5), max_per_img=100))
# dataset settings
#NWPU
dataset_type = 'VOCDataset'
data_root = '/home/han/Desktop/DOTA/mmdetection-master/data/VOCdevkit/VOC2007/'
data_root_test = '/home/han/Desktop/DOTA/mmdetection-master/data/VOCdevkit/VOC2007/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
#multi-scale training
dict(
type='Resize',
#img_scale=(1400, 1100),
img_scale=[(1400, 1100),(1333, 800), (1000, 800),(800, 600),(600,400)],
multiscale_mode='value',
keep_ratio=True),
#single-scale training
#dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
#img_scale=[(1400, 1100),(1333, 800), (1000, 800),(800, 600),(600,400)],
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
imgs_per_gpu=3,
workers_per_gpu=2,
train=dict(
type=dataset_type,
ann_file=data_root + 'ImageSets/Mains/trainval.txt',
img_prefix=data_root ,
pipeline=train_pipeline),
val=dict(
type=dataset_type,
ann_file=data_root + 'ImageSets/Mains/trainval.txt',
img_prefix=data_root ,
pipeline=test_pipeline),
test=dict(
type=dataset_type,
ann_file=data_root + 'ImageSets/Mains/test.txt',
img_prefix=data_root,
pipeline=test_pipeline))
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=100,
warmup_ratio=1.0 / 3,
step=[40, 46])
checkpoint_config = dict(interval=1)
# yapf:disable
log_config = dict(
interval=1,
hooks=[
dict(type='TextLoggerHook'),
# dict(type='TensorboardLoggerHook')
])
# yapf:enable
# runtime settings
total_epochs = 48
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = './work_dirs/cascade_rcnn_x101_64x4d_fpn_1x'
load_from = None
resume_from =None
workflow = [('train', 1)]
| [
"noreply@github.com"
] | yawudede.noreply@github.com |
1c21321b1839dedf3e417c61d3f0cfc9eed72b12 | b3dc4a1513ac185f57437df543fc79c5453bd948 | /CSCD27/Homework/xor-base64-starter/main.py | aa440cf9c2207657e8412cb8d1fd6d83a09b6fe9 | [] | no_license | AdamRWatchorn/Old-Stuff | 4692665a353dc418cdf2f0e098d49e018549aed0 | c57f32ef64072f876a1bacc7dc7780fd6fffd8de | refs/heads/master | 2021-04-25T19:36:51.190698 | 2018-03-06T08:22:03 | 2018-03-06T08:22:03 | 124,042,208 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,849 | py | #!/usr/local/bin/python3
import os, sys, getopt
from xor64 import encrypt, decrypt
def run(mode, keyFile, outputFile, inputFile):
with open(keyFile, "r") as keyStream:
key = keyStream.read()
with open(inputFile, "r") as inputStream:
data = inputStream.read()
output = mode(key, data)
with open(outputFile, "w") as outputStream:
outputStream.write(output)
def usage():
print ('Usage: ' + os.path.basename(__file__) + ' options file ')
print ('Options:')
print ('\t -e, --encrypt')
print ('\t -d, --decrypt')
print ('\t -k key_file, --key=key_file')
print ('\t -o output_file, --output=output_file')
sys.exit(2)
def main(argv):
try:
opts, args = getopt.getopt(argv,"hedk:o:",["help", "encrypt", "decrypt", "key=", "output="])
except getopt.GetoptError as err:
print(err)
usage()
# extract arguments
mode = None
keyFile = None
outputFile = None
inputFile = args[0] if len(args) > 0 else None
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
elif opt in ("-e", "--encrypt"):
mode = encrypt
elif opt in ("-d", "--decrypt"):
mode = decrypt
elif opt in ("-k", "--key"):
keyFile = arg
elif opt in ("-o", "--output"):
outputFile = arg
# check arguments
if (mode is None):
print('encrypt/decrypt option is missing\n')
usage()
if (keyFile is None):
print('key option is missing\n')
usage()
if (outputFile is None):
print('output option is missing\n')
usage()
if (inputFile is None):
print('input file is missing\n')
usage()
# run command
run(mode, keyFile, outputFile, inputFile)
if __name__ == "__main__":
main(sys.argv[1:]) | [
"watchor3@IITS-B473-22.utsc-labs.utoronto.ca"
] | watchor3@IITS-B473-22.utsc-labs.utoronto.ca |
decafa66e1555da2bd0f810d3799dac9343e120e | 362b2ecc6bb81a36f4d13ca8de2ac81dc5ec62c4 | /chameleon/tuner/sampler.py | 32e71175c30085796a8d0b61ecdf4c61efefdcc5 | [] | no_license | he-actlab/chameleon | 850a68325d25f03a85d05c308c4569a6061725bb | 1699894b6f8cec37af4fef0b90fd6e6441f584ae | refs/heads/master | 2023-03-27T22:34:37.621897 | 2020-03-23T07:00:48 | 2020-03-23T07:00:48 | 354,714,079 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,855 | py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# pylint: disable=unused-argument, no-self-use, invalid-name
""" Base class of samplers
[*] Chameleon: Adaptive Code Optimization for
Expedited Deep Neural Network Compilation
Byung Hoon Ahn, Prannoy Pilligundla, Amir Yazdanbakhsh, Hadi Esmaeilzadeh
https://openreview.net/forum?id=rygG4AVFvH
"""
import logging
import numpy as np
from ..env import GLOBAL_SCOPE
logger = logging.getLogger('autotvm')
class Sampler(object):
"""Base class for samplers
Parameters
----------
task: autotvm.task.Task
The tuning task
plan_size: int
The number of samples the sampler receives
"""
def __init__(self, task, plan_size=64):
# space
self.task = task
self.space = task.config_space
self.dims = [len(x) for x in self.space.space_map.values()]
self.plan_size = plan_size
def sample(self, xs):
"""Sample
Parameters
----------
xs: Array of int
The indices of configs from the optimizer
"""
return xs
| [
"bhahn221@eng.ucsd.edu"
] | bhahn221@eng.ucsd.edu |
f558116cdf1d988cf68a9f58d19c5c9af8ce0214 | 62531bce62949e0f79f55136e2d12c63f0d01cbb | /Traffic light.py | 2c00fdd656c236fe6990b164c57a2bed63323a7e | [] | no_license | icicchen/PythonGameProgramming | 7bf23b7c7bf2b1af53b564b726b6513b140a32a6 | 1d733e3c7cbccd308dd20fc05f3588a78c0b1e58 | refs/heads/master | 2020-08-03T22:42:48.051686 | 2017-05-25T01:24:26 | 2017-05-25T01:24:26 | 66,228,806 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,208 | py | import pygame as pg
import sys
from pygame.locals import *
# initialize the pygame library
pg.init()
# sets the size of the window
winSize = (800, 700)
window = pg.display.set_mode(winSize)
# title
pg.display.set_caption('Traffic light')
# The clock will be used to control how fast the screen updates
clock = pg.time.Clock()
off_light = pg.image.load('off_light.png')
red_light = pg.image.load('red_light.png')
yellow_light = pg.image.load('yellow_light.png')
green_light = pg.image.load('green_light.png')
traffic = {'off':off_light,
'red':red_light,
'yellow':yellow_light,
'green':green_light,
'pos_x':80,
'pos_y':0}
state = {'state':'off', 'count':0}
while True:
for event in pg.event.get():
if event.type is QUIT:
pg.quit()
sys.exit()
keys = pg.key.get_pressed()
window.fill((255,255,255))
if keys[pg.K_SPACE]:
state['state'] = 'red' if state['state'] is 'off' else 'off'
if state['state'] is 'off':
offState = pg.Rect(traffic['pos_x'], traffic['pos_y'], 50, 50)
window.blit(traffic['off'], offState)
elif state['state'] is 'red':
redState = pg.Rect(traffic['pos_x'], traffic['pos_y'], 50, 50)
window.blit(traffic['red'], redState)
state['count'] += 1
if state['count'] >= 60:
state['state'] = 'green'
state['count'] = 0
else:
state['state'] = 'red'
elif state['state'] is 'green':
greenState = pg.Rect(traffic['pos_x'], traffic['pos_y'], 50, 50)
window.blit(traffic['green'], greenState)
state['count'] += 1
if state['count'] >= 60:
state['state'] = 'yellow'
state['count'] = 0
else:
state['state'] = 'green'
elif state['state'] is 'yellow':
yellowState = pg.Rect(traffic['pos_x'], traffic['pos_y'], 50, 50)
window.blit(traffic['yellow'], yellowState)
state['count'] += 1
if state['count'] >= 10:
state['state'] = 'red'
state['count'] = 0
else:
state['state'] = 'yellow'
pg.display.flip()
clock.tick(10)
| [
"noreply@github.com"
] | icicchen.noreply@github.com |
6605d4e27c4cb4a040af60508ae4e17b5382aed8 | f594560136416be39c32d5ad24dc976aa2cf3674 | /mmdet/core/bbox/samplers/__init__.py | f58505b59dca744e489328a39fdabb02a893fb51 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | ShiqiYu/libfacedetection.train | bd9eb472c2599cbcb2f028fe7b51294e76868432 | dce01651d44d2880bcbf4e296ad5ef383a5a611e | refs/heads/master | 2023-07-14T02:37:02.517740 | 2023-06-12T07:42:00 | 2023-06-12T07:42:00 | 245,094,849 | 732 | 206 | Apache-2.0 | 2023-06-12T07:42:01 | 2020-03-05T07:19:23 | Python | UTF-8 | Python | false | false | 827 | py | # Copyright (c) OpenMMLab. All rights reserved.
from .base_sampler import BaseSampler
from .combined_sampler import CombinedSampler
from .instance_balanced_pos_sampler import InstanceBalancedPosSampler
from .iou_balanced_neg_sampler import IoUBalancedNegSampler
from .mask_pseudo_sampler import MaskPseudoSampler
from .mask_sampling_result import MaskSamplingResult
from .ohem_sampler import OHEMSampler
from .pseudo_sampler import PseudoSampler
from .random_sampler import RandomSampler
from .sampling_result import SamplingResult
from .score_hlr_sampler import ScoreHLRSampler
__all__ = [
'BaseSampler', 'PseudoSampler', 'RandomSampler',
'InstanceBalancedPosSampler', 'IoUBalancedNegSampler', 'CombinedSampler',
'OHEMSampler', 'SamplingResult', 'ScoreHLRSampler', 'MaskPseudoSampler',
'MaskSamplingResult'
]
| [
"noreply@github.com"
] | ShiqiYu.noreply@github.com |
3f51256e5c2abd6fa2c7eb93027771aa19c14c92 | c290dfb910bd64af7ad63c26c1135c4ddcd4a1a4 | /akirachix/models.py | 59e8bfc16b736ce1ecf0c8fc0d145be2f8dded9f | [] | no_license | susanawiti/Todos-endpoints | 056eca3a83998839be0932637965c222d2109b8a | 93fded1b419b64deee2f27bdab32a912dc1d9784 | refs/heads/master | 2021-04-25T23:43:22.232859 | 2017-10-17T10:52:41 | 2017-10-17T10:52:41 | 107,254,656 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 306 | py | from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Post(models.Model):
userId = models.IntegerField(default= 1)
tiltle = models.CharField(default="Default Title",max_length = 200)
body= models.TextField(default='Body of post goes here')
| [
"susanawiti95@gmail.com"
] | susanawiti95@gmail.com |
61341b91bc47aff8dfd5d07dc9c6112e6972e30c | 28825a9ad777362d470b1e0ffc042aa2253d121d | /project1/setup1.py | b7f31e279f8620d5585aa0a20c352cfe2acc51a6 | [] | no_license | lacra-oloeriu/learn-python | 30c249a5340b5f752bf372a1b7991d015614770e | 5a5d5b1d74db0875b09d2a49258215116b7e73d5 | refs/heads/master | 2020-12-30T15:08:30.492589 | 2018-01-26T19:17:32 | 2018-01-26T19:17:32 | 91,110,147 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 448 | py | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'I learn python',
'author': 'Lora',
'url': 'URL to get it at.',
'download_url': 'Where to download it.',
'author_email': 'lacramioara.oloeriu@gmail.com.',
'version': '0.1',
'install_requires': ['nose'],
'packages': ['NAME1'],
'scripts': [pro1.py],
'name': 'project1'
}
setup(**config)
| [
"lacramioara.oloeriu@gmail.com"
] | lacramioara.oloeriu@gmail.com |
e8a7fc344022ebaf43a723a5788a515ef3ec03c5 | a43d2571d056f76c5c7e3ee272cfb029332bad24 | /inheritance.py | b410b2f198206703e92f2fd082447875fdf87380 | [] | no_license | TazzyG/python_random_lessons | ad3e3c5c401c3853eec04a6d80a6053d84f52d7f | 113d5b40d357996a71ea3b20b1c140c66d22114d | refs/heads/master | 2021-01-01T19:48:18.643632 | 2017-07-28T21:57:23 | 2017-07-28T21:57:23 | 98,690,526 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 917 | py | class Parent():
def __init__(self, last_name, eye_color):
print("Parent Contstructor called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("Last Name - "+self.last_name)
print("Eye Color - "+self.eye_color)
class Child(Parent):
def __init__(self, last_name, eye_color, number_of_toys):
print("Child Constructor Called")
Parent.__init__(self, last_name, eye_color)
self.number_of_toys = number_of_toys
def show_info(self):
print("Last Name = "+self.last_name)
print("Eye Color = "+self.eye_color)
print("Number of Toys = "+str(self.number_of_toys))
billy_cyrus = Parent("Cyrus", "blue")
# print(billy_cyrus.last_name)
miley_cyrus = Child("Cyrus", "Blue", 5)
# print(miley_cyrus.last_name)
# billy_cyrus.show_info()
# print(miley_cyrus.number_of_toys)
miley_cyrus.show_info()
| [
"laurie@friendlyroad.com"
] | laurie@friendlyroad.com |
b5fb6f6ffa25358d3c2ad5a5124d8d9e39fd8e9b | b522843a8a60f092c8c9ae80bfaab0379674dcb9 | /revisedRAS.py | c41278f958dd0721cff760cb49f27a3664b9c680 | [] | no_license | xfLee/IOtools | 5495dae91176cdceb97ee4691ec5032fbec97c9c | 0961b61a2cd1519df42f565d6563eb836b6ceb65 | refs/heads/master | 2020-07-27T11:53:06.382235 | 2019-10-26T10:42:34 | 2019-10-26T10:42:34 | 209,081,315 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,639 | py | # -*- coding: utf-8 -*-
# @Time : 2019/9/23
# @Author : github.com/xfLee
import numpy as np
class RAS(object):
def __init__(self, A0, X1, u1, v1, epsilon, revisedElements):
self.A0 = A0
self.X1 = X1
self.u1 = u1
self.v1 = v1
self.i = np.ones((1, A0.shape[0]))
self.epsilon = epsilon
self.revisedElements = revisedElements
def revise(self):
for idx, val in self.revisedElements.items():
self.A0[idx] = 0
self.X1[idx[0], idx[0]] -= val
self.u1[idx[0]] -= val
self.v1[idx[1]] -= val
def run(self):
Zk = np.dot(self.A0, self.X1)
uk = np.dot(self.i, np.transpose(Zk))
vk = np.dot(self.i, Zk)
k = 1
R = np.diag(self.u1 * (1 / uk))
S = np.diag(self.v1 * (1 / vk))
u1, v1 = self.u1, self.v1
while sum(abs(u1 - uk)) >= self.epsilon or sum(abs(v1 - vk)) >= self.epsilon:
Rk = u1 * (1 / uk)
Zk = np.dot(np.diag(Rk), Zk)
u1 = np.dot(self.i, np.transpose(Zk))
vk = np.dot(self.i, Zk)
Sk = v1 * (1 / vk)
Zk = np.dot(Zk, np.diag(Sk))
uk = np.dot(self.i, np.transpose(Zk))
v1 = np.dot(self.i, Zk)
if k == 1:
R = np.diag(Rk)
S = np.diag(Sk)
else:
R = np.dot(np.diag(Rk), R)
S = np.dot(np.diag(Sk), S)
k += 1
Z2n = np.dot(np.dot(np.dot(R, self.A0), self.X1), S)
A1 = np.dot(np.dot(R, self.A0), S)
for idx, val in self.revisedElements.items():
Z2n[idx] = val
A1[idx] = val / (self.X1[idx[0], idx[0]] + val)
return k, A1, Z2n, R, S
def test():
Z0 = np.array([[0, 120, 40],
[90, 60, 90],
[60, 40, 100]])
X0 = np.array([300, 400, 500])
A0 = np.dot(Z0, np.linalg.inv(np.diag(X0)))
X1 = np.diag([400, 500, 600])
u1 = np.array([180, 330, 220])
v1 = np.array([200, 240, 290])
epsilon = 0.01
revisedElements = {(1, 1): 75}
ras = RAS(A0, X1, u1, v1, epsilon, revisedElements)
ras.revise()
k, A1, Z2n, R, S = ras.run()
print("1.修正RAS法计算过程循环次数:" + str(k - 1))
print("2.修正RAS法估计的目标年直接消耗系数矩阵A1:")
print(A1)
print("3.修正RAS法估计的目标年消耗矩阵A1*X1:")
print(Z2n)
print("4.修正RAS法估计的目标年R矩阵:")
print(R)
print("5.修正RAS法估计的目标年S矩阵:")
print(S)
# if __name__ == "main":
test() | [
"hensherl@sina.com"
] | hensherl@sina.com |
95bd533c71288b3f5335ed21e13942f5d7a24460 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03501/s994611067.py | 15296b32c0316cdc8748c1ea5d5ad1e71546c200 | [] | 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 | 73 | py | n,a,b=map(int,raw_input().split())
if a*n <b:
print a*n
else:
print b | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
78a54771d395abae7a5403a3cdbd6b176f71da9e | d4252920cf72df6973c31dad81aacd5d9ad6d4c6 | /core_example/core_export_with_name.py | 52b36666b3edfbf02e3adaec01909a7214c30acb | [] | no_license | tnakaicode/GeomSurf | e1894acf41d09900906c8d993bb39e935e582541 | 4481180607e0854328ec2cca1a33158a4d67339a | refs/heads/master | 2023-04-08T15:23:22.513937 | 2023-03-20T04:56:19 | 2023-03-20T04:56:19 | 217,652,775 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,697 | py | import numpy as np
import sys
import time
import os
from OCC.Display.SimpleGui import init_display
from OCC.Core.gp import gp_Pnt
from OCC.Core.XSControl import XSControl_Writer, XSControl_WorkSession
from OCC.Core.XCAFApp import XCAFApp_Application
from OCC.Core.XCAFDoc import XCAFDoc_DocumentTool_ShapeTool
from OCC.Core.STEPCAFControl import STEPCAFControl_Writer
from OCC.Core.STEPControl import STEPControl_Writer, STEPControl_Reader
from OCC.Core.STEPControl import STEPControl_AsIs
from OCC.Core.Interface import Interface_Static_SetCVal
from OCC.Core.IFSelect import IFSelect_RetDone
from OCC.Core.TDF import TDF_LabelSequence, TDF_Label, TDF_Tool, TDF_Data
from OCC.Core.TDocStd import TDocStd_Document
from OCC.Core.TDataStd import TDataStd_Name, TDataStd_Name_GetID
from OCC.Core.TCollection import TCollection_AsciiString
from OCC.Core.TCollection import TCollection_ExtendedString
from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox
from OCC.Extend.DataExchange import write_step_file, read_step_file
from OCC.Extend.DataExchange import read_step_file_with_names_colors
from OCCUtils.Construct import make_plane, make_vertex, make_circle
# https://www.opencascade.com/doc/occt-7.4.0/refman/html/class_t_collection___extended_string.html
# https://www.opencascade.com/doc/occt-7.4.0/refman/html/class_x_c_a_f_app___application.html
# https://www.opencascade.com/doc/occt-7.4.0/refman/html/class_t_doc_std___document.html
class ExportCAFMethod (object):
def __init__(self, name="name", tol=1.0E-10):
self.name = name
self.writer = STEPCAFControl_Writer()
self.writer.SetNameMode(True)
self.doc = TDocStd_Document(
TCollection_ExtendedString("pythonocc-doc"))
#self.x_app = XCAFApp_Application.GetApplication()
# self.x_app.NewDocument(
# TCollection_ExtendedString("MDTV-CAF"), self.doc)
self.shape_tool = XCAFDoc_DocumentTool_ShapeTool(self.doc.Main())
Interface_Static_SetCVal("write.step.schema", "AP214")
def Add(self, shape, name="name"):
"""
STEPControl_AsIs translates an Open CASCADE shape to its highest possible STEP representation.
STEPControl_ManifoldSolidBrep translates an Open CASCADE shape to a STEP manifold_solid_brep or brep_with_voids entity.
STEPControl_FacetedBrep translates an Open CASCADE shape into a STEP faceted_brep entity.
STEPControl_ShellBasedSurfaceModel translates an Open CASCADE shape into a STEP shell_based_surface_model entity.
STEPControl_GeometricCurveSet translates an Open CASCADE shape into a STEP geometric_curve_set entity.
"""
label = self.shape_tool.AddShape(shape)
self.writer.Transfer(self.doc, STEPControl_AsIs)
def Write(self, filename=None):
if not filename:
filename = self.name
path, ext = os.path.splitext(filename)
if not ext:
ext = ".stp"
status = self.writer.Write(path + ext)
assert(status == IFSelect_RetDone)
if __name__ == "__main__":
display, start_display, add_menu, add_function_to_menu = init_display()
display.DisplayShape(gp_Pnt())
root = ExportCAFMethod(name="root")
root.Add(make_vertex(gp_Pnt()), name="pnt")
root.Add(make_plane(center=gp_Pnt(0, 0, 0)), name="pln0")
root.Add(make_plane(center=gp_Pnt(0, 0, 100)), name="pln1")
root.Add(make_circle(gp_Pnt(0, 0, 0), 100), name="circle")
root.Write()
display.FitAll()
box = BRepPrimAPI_MakeBox(10, 10, 10).Solid()
writer = STEPControl_Writer()
fp = writer.WS().TransferWriter().FinderProcess()
print(fp)
# start_display()
| [
"tnakaicode@gmail.com"
] | tnakaicode@gmail.com |
6fb8a316e09f23ade26ce6c74bd7240690c47841 | eb51c3ff51a1d7d6e55eb40d446657e5863b9d4b | /pokitdok/__init__.py | 70476751df74ede506a1c0845e11ef1fbcb3142d | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | tommyyama2020/pokitdok-python | 8be1bf6089c4b890c4a2a464a05f286c6229ab0b | d1ececfe0ea14d29cb00fcabbb145395e2b397fb | refs/heads/master | 2020-04-19T16:50:38.179735 | 2018-12-14T13:41:34 | 2018-12-14T13:41:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 415 | py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2014-2018, All Rights Reserved, PokitDok, Inc.
# https://www.pokitdok.com
#
# Please see the License.txt file for more information.
# All other rights reserved.
#
from __future__ import absolute_import
__title__ = 'pokitdok'
__version__ = '2.8.0'
__author__ = 'PokitDok, Inc.'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014-2018 PokitDok, Inc.'
import pokitdok.api
| [
"brian.corbin@pokitdok.com"
] | brian.corbin@pokitdok.com |
1404b6bb41fe178935afb1916f7825127a8d1301 | ad274914cac73a47cce9b90de3152b02fcf75be9 | /example_files/Ex3-5_Show_StatusBar.py | a4e973c2701781e9629c66da849bb38d438766ea | [] | no_license | limhoontaig/Pyqt5 | 014fe7953125ee845a521cad71c96728a79c169c | 7a87142fd4960eefdde3a7d9c92559e942cdbc3a | refs/heads/main | 2023-05-28T23:28:21.892599 | 2021-06-07T21:32:23 | 2021-06-07T21:32:23 | 355,725,342 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 494 | py | ## Ex 3-5. 상태바 만들기.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
class MyApp(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.statusBar().showMessage('Ready to go')
self.setWindowTitle('Statusbar for who')
self.setGeometry(300, 300, 300, 200)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_()) | [
"limhoontaig@gmail.com"
] | limhoontaig@gmail.com |
c116261efdbfd8e7028b91803627518d781d088c | d7d2712ed98c748fda35c47c8f6ae21ea1d3b421 | /users/settings.py | 30b0ed03d895aee405e289d97f99c6386f3b049e | [] | no_license | kamral/user_models | 5bdd4bd5583b075cfef70a2b7be229575518ad97 | b75c6441be9ed51268f1370051eab3aa572ed228 | refs/heads/main | 2023-01-14T20:38:10.342545 | 2020-11-30T12:32:34 | 2020-11-30T12:32:34 | 317,218,291 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,232 | py | """
Django settings for users project.
Generated by 'django-admin startproject' using Django 2.2.13.
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
# 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 = '*6p%-fe7t_=nq^sar=twz!0!9how%x)a743e97!217-(!@0ilb'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users_app'
]
AUTH_USER_MODEL='users_app.User'
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 = 'users.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 = 'users.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db_models',
'HOST':'127.0.0.1',
'PORT':'5432',
'PASSWORD':'password',
'USER':'users_top'
}
}
# 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/'
| [
"kamral010101@gmail.com"
] | kamral010101@gmail.com |
fbbbb3dcfb6e7c05adc6803d454bc37f5120d619 | 5780a8a4da834d25e6d85cddf8364de3edcc7044 | /stp/settings.py | ad32fead9bca4892e9e2811903d1191f4039d2a2 | [] | no_license | qwad1000/stp | 37b0ce8e4c0f0c0c523f378093f7e3bd6d5915f4 | 95388a7d24deadeeb2f9be19fa4680012fb578cd | refs/heads/master | 2021-01-20T17:14:53.846194 | 2016-06-22T14:24:31 | 2016-06-22T14:24:31 | 61,167,245 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,875 | py | """
Django settings for stp project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# 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/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$3o6iti^a=v=3xirhv3!x8y$vew9ewp$*r5=$!_nkm06b^7oke'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'registration',
'bootstrapform',
'snowpenguin.django.recaptcha2',
'codebin',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'stp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'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 = 'stp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/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',
},
]
REGISTRATION_OPEN = True # If True, users can register
ACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window; you may, of course, use a different value.
REGISTRATION_AUTO_LOGIN = True
LOGIN_REDIRECT_URL = '/'
INCLUDE_AUTH_URLS = True
INCLUDE_REGISTER_URL = True
# Internationalization
# https://docs.djangoproject.com/en/1.9/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/1.9/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_LOADERS = (
'django_jinja.loaders.AppLoader',
'django_jinja.loaders.FileSystemLoader',
)
# Google reCaptcha keys for qwad1000.pythonanywhere.com
RECAPTCHA_PRIVATE_KEY = '6LeQCCMTAAAAAD8ehbdZGEuRQSp3VmgAihINzIcI'
RECAPTCHA_PUBLIC_KEY = '6LeQCCMTAAAAALA2RZ23eutgHdc5PzvIs2KPEBId' | [
"qwad1000@ukr.net"
] | qwad1000@ukr.net |
f30c3783a1a4e4b219f87f0abc2e42095ca4b8d9 | 8b45e1eda6403f7687970feaec4aa28f9e74d8bf | /feedback/views.py | 6278cbed603bb368e324d0328d40487a60127073 | [] | no_license | git-audo/starthub | 0e560d4bef54306c6661d59964ac561614124915 | ced2ff25c6791ffc7b47e99d0abbc8684b10ff8d | refs/heads/master | 2023-01-21T20:05:30.086088 | 2020-12-02T21:01:35 | 2020-12-02T21:01:35 | 299,434,509 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 766 | py | from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseRedirect
from django.shortcuts import render
from feedback.models import Feedback
from .forms import FeedbackForm
import datetime
@csrf_exempt
def new_feedback(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
feedback = Feedback()
feedback.description = request.POST.get('description')
feedback.contact = request.POST.get('contact')
feedback.date = datetime.date.today()
feedback.save()
return HttpResponseRedirect('/board/')
else:
form = FeedbackForm()
return render(request, 'form.html', {'form': form})
| [
"gabrieleghiba@icloud.com"
] | gabrieleghiba@icloud.com |
eca1253cacfe387f0158e74e429a230886e9f470 | be354dd1537282b6066ac109aeb8c0afb3cb6d72 | /code/modelEvalUtils.py | d03c13d7cd0498858b553a9930c7b4312fab0b35 | [] | no_license | nkinnaird/GeneticVariantClassification | 8e24931fb45d8c58868962cbee763899af1571f9 | 93aafb0d03d646ee66a487b0cf235a1d49a15c64 | refs/heads/master | 2023-03-03T14:03:51.455053 | 2021-02-11T15:54:35 | 2021-02-11T15:54:35 | 333,960,096 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,336 | py | from sklearn import metrics
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
plt.rcParams['figure.figsize'] = (8, 8)
sns.set(context='notebook', style='whitegrid', font_scale=1.2)
def printMetricsAndConfMat(y_train, y_pred, modelAbrev):
print(metrics.classification_report(y_train, y_pred))
conf_mat = metrics.confusion_matrix(y_train, y_pred)
plt.figure()
sns.heatmap(conf_mat, cmap=plt.cm.Blues, annot=True, square=True, fmt='d',
xticklabels=['non-conflicting', 'conflicting']);
plt.yticks(np.array([0.25, 1.35]),('non-conflicting','conflicting'))
plt.xlabel('Predicted Target')
plt.ylabel('Actual Target')
plt.title(modelAbrev + " Confusion Matrix")
filename = "Images/ConfMat_{}.png".format(str(modelAbrev).replace(" ", "_"))
print('saving image:', filename)
plt.savefig(filename)
plt.show()
def makeMetricPlots(pipeline, inputX, inputY, model_name, inputThreshold, testData=False):
# plot ROC curve
# roc = metrics.plot_roc_curve(pipeline, inputX, inputY, name=model_name)
# replaced with the code below
fpr, tpr, thresholds = metrics.roc_curve(inputY, pipeline.predict_proba(inputX)[:,1])
auc_score = metrics.auc(fpr, tpr)
fig = plt.figure(dpi=80)
ax = fig.add_subplot(111)
# plot the roc curve for the model
plt.plot([0,1], [0,1], linestyle='--', label='No Skill')
plt.plot(fpr, tpr, label='{0} (AUC : {1:.2f})'.format(model_name, auc_score))
best_roc_threshold = 0.5 # set this value so it doesn't complain when I run on the test data, for which the best threshold will have already been set
if not testData:
# calculate the g-mean for each threshold
gmeans = np.sqrt(tpr * (1-fpr))
# locate the index of the largest g-mean
ix = np.argmax(gmeans)
best_roc_threshold = thresholds[ix]
print('Best ROC Threshold=%f' % (best_roc_threshold))
plt.scatter(fpr[ix], tpr[ix], marker='o', color='black', label='Best ROC Threshold: {0:.2f}'.format(best_roc_threshold))
iClosest = (np.abs(thresholds - inputThreshold)).argmin()
plt.scatter(fpr[iClosest], tpr[iClosest], marker='o', color='blue', label='Chosen Threshold: {0:.2f}'.format(inputThreshold))
plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
ax.set_aspect('equal', adjustable='box')
# axis labels
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve for Train Data');
if testData: plt.title('ROC Curve for Test Data')
plt.legend()
if(testData):
filename = "Images/ROC_Test_{}.png".format(model_name)
else:
filename = "Images/ROC_Train_{}.png".format(model_name)
print('saving image:', filename)
plt.savefig(filename)
plt.show()
# plot precision and recall curves against threshold (but only for non-test data)
if not testData:
precision_curve, recall_curve, threshold_curve = metrics.precision_recall_curve(inputY, pipeline.predict_proba(inputX)[:,1] )
curve_fig = plt.figure(dpi=80)
curve_ax = curve_fig.add_subplot(111)
plt.plot(threshold_curve, precision_curve[1:],label='precision')
plt.plot(threshold_curve, recall_curve[1:], label='recall')
plt.axvline(x=inputThreshold, color='k', linestyle='--', label='chosen threshold')
plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
curve_ax.set_aspect(0.75)
plt.legend(loc='lower left')
plt.xlabel('Threshold (above this probability, label as conflicting)');
plt.title('{} Precision and Recall Curves for Train Data'.format(model_name));
filename = "Images/PrecisionRecall_Test_{}.png".format(model_name)
print('saving image:', filename)
plt.savefig(filename)
plt.show()
# plot precision curve vs recall curve (I think for threshold of 0.5 but I'm not entirely sure)
# replaced with the above code
# prec_vs_rec = metrics.plot_precision_recall_curve(pipeline, inputX, inputY, name=model_name)
return best_roc_threshold, (fpr, tpr)
# from https://towardsdatascience.com/fine-tuning-a-classifier-in-scikit-learn-66e048c21e65
def adjusted_classes(y_probs, threshold):
"""
This function adjusts class predictions based on the prediction threshold (t).
Will only work for binary classification problems.
"""
return [1 if y_prob > threshold else 0 for y_prob in y_probs]
def makeCombinedROC(tuples, model_names):
fig = plt.figure(dpi=80)
ax = fig.add_subplot(111)
plt.plot([0,1], [0,1], linestyle='--', label='No Skill')
for i, data in enumerate(tuples):
auc_score = metrics.auc(data[0], data[1])
plt.plot(data[0], data[1], label='{0} (AUC : {1:.2f})'.format(model_names[i], auc_score))
plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
ax.set_aspect('equal', adjustable='box')
# axis labels
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curves for Test Data');
plt.legend()
filename = "Images/ROC_Comparison.png"
print('saving image:', filename)
plt.savefig(filename)
plt.show()
| [
"nickkinn@bu.edu"
] | nickkinn@bu.edu |
f8f06cef7eb7f8000f785ce17005caaadfb5e2b9 | 7241ebc05ce727585224b3a98b0824f99e63627d | /tool/parser/JsonParser.py | d6539c8d86cf5900ad1f23f9402586f492b77105 | [] | no_license | mabenteng/ai-kg-neo4j | ca0cc161244229821e3b89e516fb616828823609 | 713e978ffedda7986245307cace02fb7ec240acd | refs/heads/master | 2021-10-20T03:50:43.583436 | 2019-02-25T14:25:11 | 2019-02-25T14:25:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,037 | py | # -*- coding: utf-8 -*-
# coding=utf-8
"""
create_author : zhangcl
create_time : 2018-07-01
program : *_* parse the parameter and generate cypher *_*
"""
import json
class JsonParser:
"""
Parser of request parameter.
"""
def __init__(self):
"""
initialize local variables.
"""
self.jsondata = None
self.result = {}
def parseJson(self, queryparam):
"""
Parse the parameter string to json object .
:param queryparam: json string
The json object holds the detail of request all infomation.
"""
self.querystring = queryparam
flag = True
try:
self.jsondata = json.loads(queryparam)
self.result['code'] = 200
self.result['message'] = 'sucess'
except Exception as err:
flag = False
print err
self.result['code'] = 500
self.result['message'] = err.message
self.result['data'] = ''
return flag
| [
"254675123@qq.com"
] | 254675123@qq.com |
bcc9f50e79bc76fc958fb5af4610f1cf265ea29f | a2dc75a80398dee58c49fa00759ac99cfefeea36 | /bluebottle/projects/migrations/0087_merge_20190130_1355.py | 705027f9fe948f888b16eb0437a1f45584ffd9db | [
"BSD-2-Clause"
] | permissive | onepercentclub/bluebottle | e38b0df2218772adf9febb8c6e25a2937889acc0 | 2b5f3562584137c8c9f5392265db1ab8ee8acf75 | refs/heads/master | 2023-08-29T14:01:50.565314 | 2023-08-24T11:18:58 | 2023-08-24T11:18:58 | 13,149,527 | 15 | 9 | BSD-3-Clause | 2023-09-13T10:46:20 | 2013-09-27T12:09:13 | Python | UTF-8 | Python | false | false | 341 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-01-30 12:55
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('projects', '0086_auto_20190117_1007'),
('projects', '0086_merge_20190121_1425'),
]
operations = [
]
| [
"ernst@onepercentclub.com"
] | ernst@onepercentclub.com |
df3b97760d799a524bc90991a8483636f5148ebe | 6066cafe70d7c8a4f29b92c77578aa4cf8df6208 | /[Client]Praktikum 10 Kegiatan 2.py | 061abe85fba3ed5be6c2899a4e56623763d1f041 | [] | no_license | L200180183/Praktikum_Algopro | a2d74b7af6e932ee1bbe8760e70f5dc9edb60637 | bedd6cdbe12cf66189abe2b45e8e1abf854a01fd | refs/heads/master | 2020-04-01T20:55:29.795001 | 2018-12-20T14:35:14 | 2018-12-20T14:35:14 | 153,627,027 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 402 | py | import socket
hostname = 'localhost'
pesan = ''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, 50007))
print "Program komunikasi tentang server"
while pesan.lower() != 'quit':
pesan = raw_input('Command: ')
s.send(pesan)
if pesan.lower() != 'quit':
response = s.recv(1024)
print 'Response', response
else:
s.close()
| [
"noreply@github.com"
] | L200180183.noreply@github.com |
b6cc78babcc620397f669740f31cb9ac205285e7 | 122c0ce4b8709872f8ffa962708b26806a0b41ee | /PackEXEC/PackDATA/SiteVisite.py | c100515d63abbffc93840da36f960328e19c6300 | [] | no_license | Sniper099/WorkTest | de1d6729a01890706053e7c8434aac34421c59c9 | 5377f5cc7d3ed89f597be9ea0e39b8a148656737 | refs/heads/master | 2022-05-30T12:04:15.027020 | 2020-04-22T23:15:50 | 2020-04-22T23:15:50 | 256,840,217 | 0 | 3 | null | null | null | null | UTF-8 | Python | false | false | 302 | py | class SiteVisite:
Vis=['Le Musee Mohammed VI','Musee Belghazi']
def VisiteI(self):
print('------Les Sites qui proposent une visite guidee sont:------\n')
print('\t' ,self.Vis[0], 'Avec le Prix de 50DH \n \t',self.Vis[1], 'Avec le Prix de 20DH\n')
return(True)
| [
"nj.nava.99@gmail.com"
] | nj.nava.99@gmail.com |
4e9bbbac9df318146b90a29763b8c05a6ccbd41b | 73a4a91cfc4db3976266d779e859556a69a8aa73 | /The_initial_exercises/employee_info.py | 8b80bf28f9d243ca0c20b86eb6a1c329c6b797c9 | [] | no_license | fujunguo/learning_python | fe51977dd58ee55264305696f0d5ba31ce4b82ab | 8e29210e8b25f80ac08b99535385f02a6f1ff2c8 | refs/heads/master | 2021-07-09T12:41:06.698406 | 2019-06-12T05:52:04 | 2019-06-12T05:52:04 | 101,965,637 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 420 | py | class Employee():
"""docstring for Employee"""
def __init__(self, firstname, lastname, salary):
# super(Employee, self).__init__()
'''__init__方法接收名、姓、薪水三个参数'''
self.firstname = firstname
self.lastname = lastname
self.salary = salary
def give_raise(self, addtion=5000):
'''
默认将薪水增加5000
但同时也能接受其他薪水增加量
'''
self.salary += addtion | [
"william_0416@163.com"
] | william_0416@163.com |
ad2f2987898e888752369a1f058485c8cf258c64 | 2b416e14c109bd22bba94f88f1b46804968619d3 | /Grafy/malejace_krawedzie_najkrotsza.py | 13b9fea115fdd85cb268f0cb74a04fd86254a70f | [] | no_license | zofiagrodecka/ASD | 71ecbb5acc926b22cb31e54e7e028609cfd3f644 | fb1f2359b859effdb68ce2d409f844e7c0f239b7 | refs/heads/master | 2023-08-01T03:18:55.319931 | 2021-09-15T16:13:27 | 2021-09-15T16:13:27 | 406,815,109 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,966 | py | def parent(i):
return i // 2
def left(i):
return i * 2
def right(i):
return 2 * i + 1
def empty(k):
if k[0] == 0:
return True
else:
return False
def heapify(k, i):
l = left(i)
r = right(i)
mini = i
size = k[0]
if l <= size and k[l][1] < k[mini][1]:
mini = l
if r <= size and k[r][1] < k[mini][1]:
mini = r
if mini != i:
k[i], k[mini] = k[mini], k[i]
heapify(k, mini)
def getmin(k):
res = k[1]
size = k[0]
k[1] = k[size]
k[0] -= 1
heapify(k, 1)
return res
def insert(k, x):
k[0] += 1
size = k[0]
k[size] = x
i = size
while i > 1 and k[i][1] < k[parent(i)][1]:
k[i], k[parent(i)] = k[parent(i)], k[i]
i = parent(i)
inf = 100000
def dijkstra(G, s):
n = len(G)
global inf
dist = [inf] * n
visited = [False] * n
parent = [None] * n
Queue = [0] * 50
dist[s] = 0
insert(Queue, (s, 0, 0)) # wstawiam: (numer wierzcholka, odleglosc dojscia, min waga krawedzi by tu dojsc)
while not empty(Queue):
u, cost, mini = getmin(Queue)
if not visited[u]:
visited[u] = True
for v in range(n):
if (G[u][v] > mini and dist[v] > dist[u] + G[u][v]) or (dist[v] < dist[u] + G[u][v] and G[u][v] < mini):
dist[v] = dist[u] + G[u][v]
parent[v] = u
if G[u][v] < mini:
mini = G[u][v]
insert(Queue, (v, dist[v], mini))
return dist, parent
def decreasing_edges(G, x, y):
dist, parent = dijkstra(G, y)
return dist[x]
G = [[ 0 for i in range(8)] for j in range(8)]
G[0][1] = 6
G[1][0] = 6
G[1][2] = 5
G[2][1] = 5
G[2][5] = 2
G[5][2] = 2
G[5][7] = 1
G[7][5] = 1
G[0][3] = 6
G[3][0] = 6
G[3][4] = 3
G[4][3] = 3
G[4][2] = 2
G[2][4] = 2
G[2][6] = 1
G[6][2] = 1
G[6][7] = 5
G[7][6] = 5
print(decreasing_edges(G, 0, 7)) | [
"69384237+zofiagrodecka@users.noreply.github.com"
] | 69384237+zofiagrodecka@users.noreply.github.com |
b19523f9a715f2ca411b6ca4ed4c5b164df4a27a | 00dfeccd2f1b934b945ff125b7a523e05107cc3c | /ch1/problem1.9.py | 8a63503bb69a73b6604e929391e3946357da1b39 | [] | no_license | anamikasen/ctci_solutions | 2de379257b4800a700c1032421d38fd2028c53f0 | 7375f94b7c00baf9e084b70c7326878753902ddd | refs/heads/master | 2020-03-29T04:26:11.165885 | 2018-10-09T15:41:14 | 2018-10-09T15:41:14 | 149,531,502 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 313 | py | def main():
return isRotation(s1, s2)
def isRotation(s1, s2):
if len(s1)!=len(s2):
return False
else:
return isSubstring(s1, s2)
def isSubstring(s1, s2):
s1 += s1
return s1.find(s2)>-1
if __name__ == "__main__":
s1 = "body"
s2 = "dybo"
print(isRotation(s1, s2))
| [
"anamika13sen@gmail.com"
] | anamika13sen@gmail.com |
7023e5ecdc00bc0113342ae94985d9d03e3efcba | afc693a1095f99cc586770fbd5a65dd40f2d822f | /docs/conf.py | 82c0e03d8f2804c1c403a6bc1943dfa63271cb9d | [
"LicenseRef-scancode-homebrewed",
"Beerware"
] | permissive | ndkoch/ihatemoney | 974f3b75d3bc2519d3c17f492d221da9fa780236 | 51bc76ecc5e310602216fb8eaa2ede2ab43b3d00 | refs/heads/master | 2020-09-27T00:03:31.320035 | 2019-12-09T00:19:22 | 2019-12-09T00:19:22 | 226,371,920 | 0 | 2 | NOASSERTION | 2019-12-09T00:19:23 | 2019-12-06T16:48:41 | Python | UTF-8 | Python | false | false | 266 | py | # coding: utf8
import sys, os
templates_path = ["_templates"]
source_suffix = ".rst"
master_doc = "index"
project = "I hate money"
copyright = "2011, The 'I hate money' team"
version = "1.0"
release = "1.0"
exclude_patterns = ["_build"]
pygments_style = "sphinx"
| [
"alexis@notmyidea.org"
] | alexis@notmyidea.org |
57193af10c81f5ef76431078de1981e625175b91 | f0279d8dfae89c6a6830023dfa353f0963914554 | /passwordgenerator.py | 2925da8a81c6a40c06d07154b9192cd79abede10 | [] | no_license | NILESH-17/Password-Generator | 5dd69c12f8c7227a9361735343ec391900faa462 | 3045d21da1a48320e96fd622dd920c8d266118e8 | refs/heads/main | 2023-01-29T18:41:30.995151 | 2020-12-14T08:03:58 | 2020-12-14T08:03:58 | 321,275,028 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 244 | py | import random
bigletters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
smallletters='abcdefghijklmnopqrstuvwxyz'
symbol='_-,:'
numbers='123456789'
all=bigletters+smallletters+symbol+numbers
length=16
password =''.join(random.sample(all,length))
print(password)
| [
"noreply@github.com"
] | NILESH-17.noreply@github.com |
a138938f68658430a7186f241fa868fec2590e61 | 865bd5e42a4299f78c5e23b5db2bdba2d848ab1d | /Python/322.coin-change.135397822.ac.python3.py | 5e9a0619060981526f9753a831b848d95c17ab70 | [] | no_license | zhiymatt/Leetcode | 53f02834fc636bfe559393e9d98c2202b52528e1 | 3a965faee2c9b0ae507991b4d9b81ed0e4912f05 | refs/heads/master | 2020-03-09T08:57:01.796799 | 2018-05-08T22:01:38 | 2018-05-08T22:01:38 | 128,700,683 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,207 | py | #
# [322] Coin Change
#
# https://leetcode.com/problems/coin-change/description/
#
# algorithms
# Medium (26.58%)
# Total Accepted: 92.2K
# Total Submissions: 346.9K
# Testcase Example: '[1]\n0'
#
#
# You are given coins of different denominations and a total amount of money
# amount. Write a function to compute the fewest number of coins that you need
# to make up that amount. If that amount of money cannot be made up by any
# combination of the coins, return -1.
#
#
#
# Example 1:
# coins = [1, 2, 5], amount = 11
# return 3 (11 = 5 + 5 + 1)
#
#
#
# Example 2:
# coins = [2], amount = 3
# return -1.
#
#
#
# Note:
# You may assume that you have an infinite number of each kind of coin.
#
#
# Credits:Special thanks to @jianchao.li.fighter for adding this problem and
# creating all test cases.
#
class Solution:
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
MAX = float('inf')
dp = [0] + [MAX] * amount
for i in range(1, amount + 1):
dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1
return [dp[amount], -1][dp[amount] == MAX]
| [
"miylolmiy@gmail.com"
] | miylolmiy@gmail.com |
e599683e6de6a34f420ee2c585761d68a85808b2 | 62db602fe91e6ca7eb3cd877819da3d30c964c3a | /perfis/urls.py | 2abe1a9ff2e8aefe218afdd466ec59615952d986 | [] | no_license | BiancaArantes28/django-alura | 505ea2fabc0f65db477a7ccef2957b29a44652e1 | c445e342cf922102e03a6b8ff9d90ffe43d06c9e | refs/heads/master | 2021-01-20T02:12:00.718799 | 2017-05-12T18:16:26 | 2017-05-12T18:16:26 | 89,386,814 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 421 | py | from django.conf.urls import patterns, include, url
from django.contrib import admin
from perfis import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'perfis/(?P<perfil_id>\d+)$',views.exibir, name='exibir'),
url(r'^perfis/(?P<perfil_id>\d+)/convidar$', views.convidar , name='convidar'),
url(r'^convite/(?P<convite_id>\d)/aceitar$', views.aceitar , name='aceitar')
)
| [
"biancaarantes28@gmail.com"
] | biancaarantes28@gmail.com |
152b8449140b19f5fa06511d121dd6d4982fbef3 | 5fce342c9e598ac7ef2ab06047081db4d6661b9d | /python/code-festival/2014/b.py | 84db2177afeb5d4ee3d43f2be922828eec9c5434 | [] | no_license | kp047i/AtCoder | 679493203023a14a10fca22479dbeae4986d2046 | 276ad0fab8d39d5d9a1251bb2a533834124f3e77 | refs/heads/master | 2022-07-26T21:49:29.490556 | 2020-06-28T14:28:12 | 2020-06-28T14:28:12 | 208,727,698 | 0 | 0 | null | 2022-06-22T02:11:01 | 2019-09-16T06:37:50 | Python | UTF-8 | Python | false | false | 225 | py | n = input()
sum_odd = 0
sum_even = 0
for i in range(len(n)):
if i % 2:
sum_odd += int(n[i])
else:
sum_even += int(n[i])
if len(n) % 2:
print(sum_odd, sum_even)
else:
print(sum_even, sum_odd)
| [
"takayuki.miura28@gmail.com"
] | takayuki.miura28@gmail.com |
e82fc6e5d49682038fe7616476667e6a70b3b716 | 7c58d5001325296a7d331dfa64ec2bd4672bf937 | /canvas_crop/canvas_crop.py | f4dc38dd5f1401e11c97d1a656549a5a424e23fa | [] | no_license | madara-tribe/tkinter-ML-GUI | 3f2bd260bd7f04065cde7baeb9aadfe9a5c6eba4 | f8d0ed6be887be3b40d6ca8a73acb9af46a29fe6 | refs/heads/main | 2023-08-06T18:05:13.206550 | 2021-10-12T05:42:02 | 2021-10-12T05:42:02 | 404,902,483 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,290 | py | import tkinter
import tkinter.filedialog
from PIL import Image, ImageTk
class Model():
# 画像処理前か画像処理後かを指定
BEFORE = 1
AFTER = 2
def __init__(self):
# PIL画像オブジェクトを参照
self.before_image = None
self.after_image = None
# Tkinter画像オブジェクトを参照
self.before_image_tk = None
self.after_image_tk = None
def get_image(self, type):
'Tkinter画像オブジェクトを取得する'
if type == Model.BEFORE:
if self.before_image is not None:
# Tkinter画像オブジェクトに変換
self.before_image_tk = ImageTk.PhotoImage(self.before_image)
return self.before_image_tk
elif type == Model.AFTER:
if self.after_image is not None:
# Tkinter画像オブジェクトに変換
self.after_image_tk = ImageTk.PhotoImage(self.after_image)
return self.after_image_tk
else:
return None
def read(self, path):
'画像の読み込みを行う'
# pathの画像を読み込んでPIL画像オブジェクト生成
self.before_image = Image.open(path)
def round(self, value, min, max):
'valueをminからmaxの範囲に丸める'
ret = value
if(value < min):
ret = min
if(value > max):
ret = max
return ret
def crop(self, param):
'画像をクロップ'
if len(param) != 4:
return
if self.before_image is None:
return
print(param)
# 画像上の選択範囲を取得(x1,y1)-(x2,y2)
x1, y1, x2, y2 = param
# 画像外の選択範囲を画像内に切り詰める
x1 = self.round(x1, 0, self.before_image.width)
x2 = self.round(x2, 0, self.before_image.width)
y1 = self.round(y1, 0, self.before_image.height)
y2 = self.round(y2, 0, self.before_image.height)
# x1 <= x2 になるように座標を調節
if x1 <= x2:
crop_x1 = x1
crop_x2 = x2
else:
crop_x1 = x2
crop_x2 = x1
# y1 <= y2 になるように座標を調節
if y1 <= y2:
crop_y1 = y1
crop_y2 = y2
else:
crop_y1 = y2
crop_y2 = y1
# PIL Imageのcropを実行
self.after_image = self.before_image.crop(
(
crop_x1,
crop_y1,
crop_x2,
crop_y2
)
)
class View():
# キャンバス指定用
LEFT_CANVAS = 1
RIGHT_CANVAS = 2
def __init__(self, app, model):
self.master = app
self.model = model
# アプリ内のウィジェットを作成
self.create_widgets()
def create_widgets(self):
'アプリ内にウィジェットを作成・配置する'
# キャンバスのサイズ
canvas_width = 400
canvas_height = 400
# キャンバスとボタンを配置するフレームの作成と配置
self.main_frame = tkinter.Frame(
self.master
)
self.main_frame.pack()
# ラベルを配置するフレームの作成と配置
self.sub_frame = tkinter.Frame(
self.master
)
self.sub_frame.pack()
# キャンバスを配置するフレームの作成と配置
self.canvas_frame = tkinter.Frame(
self.main_frame
)
self.canvas_frame.grid(column=1, row=1)
# ボタンを8位するフレームの作成と配置
self.button_frame = tkinter.Frame(
self.main_frame
)
self.button_frame.grid(column=2, row=1)
# 1つ目のキャンバスの作成と配置
self.left_canvas = tkinter.Canvas(
self.canvas_frame,
width=canvas_width,
height=canvas_height,
bg="gray",
)
self.left_canvas.grid(column=1, row=1)
# 2つ目のキャンバスの作成と配置
self.right_canvas = tkinter.Canvas(
self.canvas_frame,
width=canvas_width,
height=canvas_height,
bg="gray",
)
self.right_canvas.grid(column=2, row=1)
# ファイル読み込みボタンの作成と配置
self.load_button = tkinter.Button(
self.button_frame,
text="ファイル選択"
)
self.load_button.pack()
# メッセージ表示ラベルの作成と配置
# メッセージ更新用
self.message = tkinter.StringVar()
self.message_label = tkinter.Label(
self.sub_frame,
textvariable=self.message
)
self.message_label.pack()
def draw_image(self, type):
'画像をキャンバスに描画'
# typeに応じて描画先キャンバスを決定
if type == View.LEFT_CANVAS:
canvas = self.left_canvas
image = self.model.get_image(Model.BEFORE)
elif type == View.RIGHT_CANVAS:
canvas = self.right_canvas
image = self.model.get_image(Model.AFTER)
else:
return
if image is not None:
# キャンバス上の画像の左上座標を決定
sx = (canvas.winfo_width() - image.width()) // 2
sy = (canvas.winfo_height() - image.height()) // 2
# キャンバスに描画済みの画像を削除
objs = canvas.find_withtag("image")
for obj in objs:
canvas.delete(obj)
# 画像をキャンバスの真ん中に描画
canvas.create_image(
sx, sy,
image=image,
anchor=tkinter.NW,
tag="image"
)
def draw_selection(self, selection, type):
'選択範囲を描画'
# typeに応じて描画先キャンバスを決定
if type == View.LEFT_CANVAS:
canvas = self.left_canvas
elif type == View.RIGHT_CANVAS:
canvas = self.right_canvas
else:
return
# 一旦描画済みの選択範囲を削除
self.delete_selection(type)
if selection:
# 選択範囲を長方形で描画
canvas.create_rectangle(
selection[0],
selection[1],
selection[2],
selection[3],
outline="red",
width=3,
tag="selection_rectangle"
)
def delete_selection(self, type):
'選択範囲表示用オブジェクトを削除する'
# typeに応じて描画先キャンバスを決定
if type == View.LEFT_CANVAS:
canvas = self.left_canvas
elif type == View.RIGHT_CANVAS:
canvas = self.right_canvas
else:
return
# キャンバスに描画済みの選択範囲を削除
objs = canvas.find_withtag("selection_rectangle")
for obj in objs:
canvas.delete(obj)
def draw_message(self, message):
self.message.set(message)
def select_file(self):
'ファイル選択画面を表示'
# ファイル選択ダイアログを表示
file_path = tkinter.filedialog.askopenfilename(
initialdir="."
)
return file_path
class Controller():
INTERVAL = 50
def __init__(self, app, model, view):
self.master = app
self.model = model
self.view = view
# マウスボタン管理用
self.pressing = False
self.selection = None
# ラベル表示メッセージ管理用
self.message = "ファイルを読み込んでください"
self.set_events()
def set_events(self):
'受け付けるイベントを設定する'
# キャンバス上のマウス押し下げ開始イベント受付
self.view.left_canvas.bind(
"<ButtonPress>",
self.button_press
)
# キャンバス上のマウス動作イベント受付
self.view.left_canvas.bind(
"<Motion>",
self.mouse_motion,
)
# キャンバス上のマウス押し下げ終了イベント受付
self.view.left_canvas.bind(
"<ButtonRelease>",
self.button_release,
)
# 読み込みボタン押し下げイベント受付
self.view.load_button['command'] = self.push_load_button
# 画像の描画用のタイマーセット
self.master.after(Controller.INTERVAL, self.timer)
def timer(self):
'一定間隔で画像等を描画'
# 画像処理前の画像を左側のキャンバスに描画
self.view.draw_image(
View.LEFT_CANVAS
)
# 画像処理後の画像を右側のキャンバスに描画
self.view.draw_image(
View.RIGHT_CANVAS
)
# トリミング選択範囲を左側のキャンバスに描画
self.view.draw_selection(
self.selection,
View.LEFT_CANVAS
)
# ラベルにメッセージを描画
self.view.draw_message(
self.message
)
# 再度タイマー設定
self.master.after(Controller.INTERVAL, self.timer)
def push_load_button(self):
'ファイル選択ボタンが押された時の処理'
# ファイル選択画面表示
file_path = self.view.select_file()
# 画像ファイルの読み込みと描画
if len(file_path) != 0:
self.model.read(file_path)
self.selection = None
# 選択範囲を表示するオブジェクトを削除
self.view.delete_selection(view.LEFT_CANVAS)
# メッセージを更新
self.message = "トリミングする範囲を指定してください"
def button_press(self, event):
'マウスボタン押し下げ開始時の処理'
# マウスクリック中に設定
self.pressing = True
self.selection = None
# 現在のマウスでの選択範囲を設定
self.selection = [
event.x,
event.y,
event.x,
event.y
]
# 選択範囲を表示するオブジェクトを削除
self.view.delete_selection(View.LEFT_CANVAS)
def mouse_motion(self, event):
'マウスボタン移動時の処理'
if self.pressing:
# マウスでの選択範囲を更新
self.selection[2] = event.x
self.selection[3] = event.y
def button_release(self, event):
'マウスボタン押し下げ終了時の処理'
if self.pressing:
# マウスボタン押し下げ終了
self.pressing = False
# マウスでの選択範囲を更新
self.selection[2] = event.x
self.selection[3] = event.y
# 画像の描画位置を取得
objs = self.view.left_canvas.find_withtag("image")
if len(objs) != 0:
draw_coord = self.view.left_canvas.coords(objs[0])
# 選択範囲をキャンバス上の座標から画像上の座標に変換
x1 = self.selection[0] - draw_coord[0]
y1 = self.selection[1] - draw_coord[1]
x2 = self.selection[2] - draw_coord[0]
y2 = self.selection[3] - draw_coord[1]
# 画像をcropでトリミング
self.model.crop(
(int(x1), int(y1), int(x2), int(y2))
)
# メッセージを更新
self.message = "トリミングしました!"
app = tkinter.Tk()
# アプリのウィンドウのサイズ設定
app.geometry("1000x430")
app.title("トリミングアプリ")
model = Model()
view = View(app, model)
controller = Controller(app, model, view)
app.mainloop()
| [
"hagiharatatsuya@hagiharatatsuyanoMacBook-Air.local"
] | hagiharatatsuya@hagiharatatsuyanoMacBook-Air.local |
ceabe5894c58bfbcbf63efe4e773e09601fdbe2f | b9bd88c0f7034acdf1c2b79c13afe537a5027460 | /cellular_modem/simcom/sim800.py | 1c5b256707fd655d72e4c9baa8449b94731284a5 | [
"MIT"
] | permissive | andreaskuster/cellular-modem | 8d769e0b27e8de7538c9561bd0051f0a44a32bb6 | a8b662b65a596f9c2ca73a42e2b8dbb39552a177 | refs/heads/master | 2020-12-26T12:50:13.456423 | 2020-04-06T21:33:38 | 2020-04-06T21:33:38 | 237,514,324 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,819 | py | #!/usr/bin/env python3
# encoding: utf-8
"""
MIT License
Copyright (c) 2020 cellular-modem, Andreas Kuster
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, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following 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 MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS 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.
"""
__author__ = "Andreas Kuster"
__copyright__ = "Copyright 2020, cellular-modem, Andreas Kuster"
__license__ = "MIT"
from cellular_modem import AbstractModem
from cellular_modem.io import SerialHandler
class SIM800(AbstractModem, SerialHandler):
def __init__(self, pin=None, **kwds):
super().__init__(**kwds)
self.pin = pin
def send_sms(self):
raise NotImplementedError()
def receive_sms(self):
print("sms received")
def data_received(self, data):
print("data received: {}".format(data))
def connection_made(self):
print("connection made")
def connection_lost(self):
print("connection closed")
| [
"mail@andreaskuster.ch"
] | mail@andreaskuster.ch |
59ec3812dd12a3af309dfdcc37161df0ee23d29f | 2e89ff0a41c5ae40bc420e5d298504927ceed010 | /anything/users/migrations/0001_initial.py | fdaae19b9ff03d88bd74ac05938ab739e8e817a4 | [] | no_license | darkblank/anything | 6dc676b7a099ddfce0c511db9234715a4f0ca66c | 17589f8988ed1cb6fa049962bfd3fbe57c392fba | refs/heads/master | 2020-03-11T09:40:32.608171 | 2018-05-12T09:20:27 | 2018-05-12T09:20:27 | 129,918,989 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 989 | py | # Generated by Django 2.0.3 on 2018-05-11 23:36
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')),
('nickname', models.CharField(max_length=20)),
('is_active', models.BooleanField(default=True)),
('is_admin', models.BooleanField(default=False)),
],
options={
'abstract': False,
},
),
]
| [
"darkblank1990@gmail.com"
] | darkblank1990@gmail.com |
e851b85d403874ebdcdf93dea55a5b22953f360c | eed034d151bea6702cd35f48e9b9440f9625d167 | /Rpi-Python_SourceCode/myUART.py | 7e8c1616a7bd6750855d2caf51d32871401cd2be | [] | no_license | MazenOsamaFarouk/ITI_GP_Smart_Meter | 17c5550be8787d26ae82857d7af9d52911ea7b5b | 2571be2edbcbb5e5a091d385e502e248ded4469e | refs/heads/main | 2023-03-23T06:44:48.778965 | 2021-03-19T17:26:48 | 2021-03-19T17:26:48 | 340,630,157 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,784 | py | # sudo stty -echo -F /dev/ttyS0 115200 command to change baudrate
# of com-port
# the -echo flag prevents the tty from sending back "echoing"
# the recieved input
import serial
import logging
logging.basicConfig(filename="meter.log", level=logging.DEBUG, format="%(asctime)s:%(levelno)s:%(message)s" )
COM_PORT = "/dev/ttyS0"
BAUD_RATE = 115200
MAX_LINE_LEN = 30
def Init():
global stream
global stream_status
try:
stream = serial.Serial(COM_PORT,BAUD_RATE, timeout=1)
except serial.SerialException as e:
logging.error("Could not Open Serial Port.Check UART pins Connections")
def Getline():
global stream
global stream_status
try:
stream_status = stream.isOpen()
if stream_status == False:
# print("Error: can not open Serial Stream!")
raise serial.SerialException
except serial.SerialException:
logging.error("Serial Port Not Open.Check UART pins Connections")
return 0
try:
rx = stream.readline(MAX_LINE_LEN)
except serial.SerialTimeoutException:
logging.error("UART Reading timed out")
return 0
try:
output= rx.decode("utf-8")
except (UnicodeDecodeError,UnicodeTranslateError):
logging.error("Decoding Error:UART Recieved Corrupted Data")
return 0
else:
return output
def SendLine(line):
global stream
global stream_status
if stream_status == False:
print("Error: can not open Serial Stream!")
return 0
else:
stream.write(line.encode())
return 1
if __name__=="__main__":
UART_Init()
print("Listening to Serial Port...\n")
while True:
rx_line = UART_Getline()
print(rx_line)
# UART_SendLine(rx_line)
| [
"mazen.osama.017@gmail.com"
] | mazen.osama.017@gmail.com |
c83ab40bba1b9903dab1492e228360c3e913ad50 | 57250f6f60d1c31bbda76fd6fa2724d0987c6833 | /contrib/spendfrom/spendfrom.py | d4b5d6a795c2031b8f71ca604f47ab988606830e | [
"MIT"
] | permissive | hivprojekt/hiv | 6ca786fa93121de2ca3d210e9e1ef2dfdde5c7f2 | 933f01e6a467a3dd9d781f2d5e23ada8c167a3bb | refs/heads/master | 2021-06-26T17:30:30.973415 | 2017-09-09T22:51:08 | 2017-09-09T22:51:08 | 102,989,492 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 10,055 | py | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bitcoin-Qt running
# on localhost.
#
# Depends on jsonrpc
#
from decimal import *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def determine_db_dir():
"""Return the default location of the bitcoin data directory"""
if platform.system() == "Darwin":
return os.path.expanduser("~/Library/Application Support/Bitcoin/")
elif platform.system() == "Windows":
return os.path.join(os.environ['APPDATA'], "Bitcoin")
return os.path.expanduser("~/.bitcoin")
def read_bitcoin_config(dbdir):
"""Read the bitcoin.conf file from dbdir, returns dictionary of settings"""
from ConfigParser import SafeConfigParser
class FakeSecHead(object):
def __init__(self, fp):
self.fp = fp
self.sechead = '[all]\n'
def readline(self):
if self.sechead:
try: return self.sechead
finally: self.sechead = None
else:
s = self.fp.readline()
if s.find('#') != -1:
s = s[0:s.find('#')].strip() +"\n"
return s
config_parser = SafeConfigParser()
config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "bitcoin.conf"))))
return dict(config_parser.items("all"))
def connect_JSON(config):
"""Connect to a bitcoin JSON-RPC server"""
testnet = config.get('testnet', '0')
testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False
if not 'rpcport' in config:
config['rpcport'] = 121794 if testnet else 21794
connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport'])
try:
result = ServiceProxy(connect)
# ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors,
# but also make sure the bitcoind we're talking to is/isn't testnet:
if result.getmininginfo()['testnet'] != testnet:
sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n")
sys.exit(1)
return result
except:
sys.stderr.write("Error connecting to RPC server at "+connect+"\n")
sys.exit(1)
def unlock_wallet(bitcoind):
info = bitcoind.getinfo()
if 'unlocked_until' not in info:
return True # wallet is not encrypted
t = int(info['unlocked_until'])
if t <= time.time():
try:
passphrase = getpass.getpass("Wallet is locked; enter passphrase: ")
bitcoind.walletpassphrase(passphrase, 5)
except:
sys.stderr.write("Wrong passphrase\n")
info = bitcoind.getinfo()
return int(info['unlocked_until']) > time.time()
def list_available(bitcoind):
address_summary = dict()
address_to_account = dict()
for info in bitcoind.listreceivedbyaddress(0):
address_to_account[info["address"]] = info["account"]
unspent = bitcoind.listunspent(0)
for output in unspent:
# listunspent doesn't give addresses, so:
rawtx = bitcoind.getrawtransaction(output['txid'], 1)
vout = rawtx["vout"][output['vout']]
pk = vout["scriptPubKey"]
# This code only deals with ordinary pay-to-bitcoin-address
# or pay-to-script-hash outputs right now; anything exotic is ignored.
if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash":
continue
address = pk["addresses"][0]
if address in address_summary:
address_summary[address]["total"] += vout["value"]
address_summary[address]["outputs"].append(output)
else:
address_summary[address] = {
"total" : vout["value"],
"outputs" : [output],
"account" : address_to_account.get(address, "")
}
return address_summary
def select_coins(needed, inputs):
# Feel free to improve this, this is good enough for my simple needs:
outputs = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
n += 1
return (outputs, have-needed)
def create_tx(bitcoind, fromaddresses, toaddress, amount, fee):
all_coins = list_available(bitcoind)
total_available = Decimal("0.0")
needed = amount+fee
potential_inputs = []
for addr in fromaddresses:
if addr not in all_coins:
continue
potential_inputs.extend(all_coins[addr]["outputs"])
total_available += all_coins[addr]["total"]
if total_available < needed:
sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed));
sys.exit(1)
#
# Note:
# Python's json/jsonrpc modules have inconsistent support for Decimal numbers.
# Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode
# Decimals, I'm casting amounts to float before sending them to bitcoind.
#
outputs = { toaddress : float(amount) }
(inputs, change_amount) = select_coins(needed, potential_inputs)
if change_amount > BASE_FEE: # don't bother with zero or tiny change
change_address = fromaddresses[-1]
if change_address in outputs:
outputs[change_address] += float(change_amount)
else:
outputs[change_address] = float(change_amount)
rawtx = bitcoind.createrawtransaction(inputs, outputs)
signed_rawtx = bitcoind.signrawtransaction(rawtx)
if not signed_rawtx["complete"]:
sys.stderr.write("signrawtransaction failed\n")
sys.exit(1)
txdata = signed_rawtx["hex"]
return txdata
def compute_amount_in(bitcoind, txinfo):
result = Decimal("0.0")
for vin in txinfo['vin']:
in_info = bitcoind.getrawtransaction(vin['txid'], 1)
vout = in_info['vout'][vin['vout']]
result = result + vout['value']
return result
def compute_amount_out(txinfo):
result = Decimal("0.0")
for vout in txinfo['vout']:
result = result + vout['value']
return result
def sanity_test_fee(bitcoind, txdata_hex, max_fee):
class FeeError(RuntimeError):
pass
try:
txinfo = bitcoind.decoderawtransaction(txdata_hex)
total_in = compute_amount_in(bitcoind, txinfo)
total_out = compute_amount_out(txinfo)
if total_in-total_out > max_fee:
raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out))
tx_size = len(txdata_hex)/2
kb = tx_size/1000 # integer division rounds down
if kb > 1 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes")
if total_in < 0.01 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee, tiny-amount transaction")
# Exercise for the reader: compute transaction priority, and
# warn if this is a very-low-priority transaction
except FeeError as err:
sys.stderr.write((str(err)+"\n"))
sys.exit(1)
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--from", dest="fromaddresses", default=None,
help="addresses to get bitcoins from")
parser.add_option("--to", dest="to", default=None,
help="address to get send bitcoins to")
parser.add_option("--amount", dest="amount", default=None,
help="amount to send")
parser.add_option("--fee", dest="fee", default="0.0",
help="fee to include")
parser.add_option("--datadir", dest="datadir", default=determine_db_dir(),
help="location of bitcoin.conf file with RPC username/password (default: %default)")
parser.add_option("--testnet", dest="testnet", default=False, action="store_true",
help="Use the test network")
parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true",
help="Don't broadcast the transaction, just create and print the transaction data")
(options, args) = parser.parse_args()
check_json_precision()
config = read_bitcoin_config(options.datadir)
if options.testnet: config['testnet'] = True
bitcoind = connect_JSON(config)
if options.amount is None:
address_summary = list_available(bitcoind)
for address,info in address_summary.iteritems():
n_transactions = len(info['outputs'])
if n_transactions > 1:
print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions))
else:
print("%s %.8f %s"%(address, info['total'], info['account']))
else:
fee = Decimal(options.fee)
amount = Decimal(options.amount)
while unlock_wallet(bitcoind) == False:
pass # Keep asking for passphrase until they get it right
txdata = create_tx(bitcoind, options.fromaddresses.split(","), options.to, amount, fee)
sanity_test_fee(bitcoind, txdata, amount*Decimal("0.01"))
if options.dry_run:
print(txdata)
else:
txid = bitcoind.sendrawtransaction(txdata)
print(txid)
if __name__ == '__main__':
main()
| [
"hivdevel@yandex.ru"
] | hivdevel@yandex.ru |
03ecf964bb2cbdcb3a5662a899748372d076cd58 | 4063c54d9480e37674e5f752f65df1d8e948877b | /project_48.py | f1dd136ebe9ae7b9bb2191b9727cdc521535c5c6 | [] | no_license | RiyanMohammed/projects | 6e5842ebda3b611721c8e7f05e4b2ff1a9b62ba4 | b0e0c3a9bebcea55dc672cd7f5f2a28a2ae14a9e | refs/heads/main | 2023-08-14T15:33:37.171221 | 2021-09-24T03:08:15 | 2021-09-24T03:08:15 | 409,812,312 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,307 | py | # -*- coding: utf-8 -*-
"""Project 48
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1dhKYYmtOcXqKT7p6mr6BB6ygBSxP5uBv
### Instructions
#### Activity 1: Calculate the probability of a random variable
Calculate the probability of solving 35 questions correctly by fluke in an MCQ test having 250 questions (each question have 4 options).
**Steps to follow:**
1. Create a function to calculate the factorial of a number. It takes an integer as an input for which the factorial value needs to be calculated.
2. Create a function to calculate the probability of a random variable. It takes the total number of trials `num_trials`, a random variable `random_var` and the probability of success `prob_success` as inputs.
- First, calculate the value of ${}^nC_{r} = \frac{n!}{(n - r)! \times r!}$ and store in the `num_trials_choose_random_var` variable.
- Then calculate the probability of random variable $P(X = r) = {}^nC_r \times s^r \times f^{n - r}$ and store in the `prob_random_var` variable.
- The function returns the value of `prob_random_var`.
- Note that the probability of failure is `1 - prob_success`.
"""
# Write your solution here
# Function to calculate the factorial value of a number 'n'.
def factorial(num):
factorial = 1
if num < 0:
return "Undefined."
else:
while num > 0:
factorial *= num
num -= 1
return factorial
# Function to calculate the probability of a random variable X = r.
def prob_random_var(num_trials, random_var, prob_success):
num_trials_choose_random_var = factorial(num_trials) / ((factorial(num_trials - random_var)) * (factorial(random_var))) # nCr
prob_random_var = num_trials_choose_random_var * (prob_success ** random_var) * ((1 - prob_success) ** (num_trials - random_var))
return prob_random_var
# The probability of solving say 35 questions correctly by fluke in an MCQ test having 250 questions
prob_random_var(250, 35, 0.25)
"""**Question**: What is the probability of solving say 35 questions correctly by fluke in an MCQ test having 250 questions?
**Answers**: 7.85
---
#### Activity 2: Expected value
Find out the average number of questions that can be solved correctly by fluke in an MCQ test having 300 questions.
"""
# Find the average number of questions that can be solved correctly by fluke in an MCQ test having 300 questions.
import numpy as np
rand_var = np.arange(301)
prob_rand_var_list = [prob_random_var(300, i, 0.25) for i in range(301)]
expected_val = np.sum(rand_var * np.array(prob_rand_var_list))
expected_val
"""**Question**: How many average number questions can be solved correctly by fluke in an MCQ test having 300 questions?
**Answers**: On an average, you are expected to solve 75 questions correctly by fluke in an MCQ test having 300 questions.
**Hints**:
1. Use the concept of expected value. The expected value is the sum of the product of the random variables with their corresponding probabilities.
2. Let $X$ be a random variable denoting $N$ events $x_1, x_2, x_3 \dots x_N$ and let $p(x_1), p(x_2), p(x_3) \dots p(x_N)$ be their corresponding probabilities, then the expected value $E(X)$ is given by
$$E(X) = x_1 p(x_1) + x_2 p(x_2) + x_3 p(x_3) + \dots + x_N p(x_N)$$
---
""" | [
"noreply@github.com"
] | RiyanMohammed.noreply@github.com |
615bcc7e7e8afc56a8dc513da89e9d4f4faab88d | 83f78318d1a85045b0e29f3fed10e8ba3e5c107c | /throwback/root.py | a5a39de95633bd252ed2a43ca57c8e352c04ff32 | [] | no_license | kadrlica/throwback | c396d00230ec0e6ed4ce8c31ac6cd12e2ee76690 | c628acb9716aad433c49de4e2f71c54d2a0bc83e | refs/heads/master | 2020-03-24T09:33:03.127648 | 2018-08-02T15:04:00 | 2018-08-02T15:04:00 | 142,631,826 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,349 | py | #!/usr/bin/env python
"""
Generic python script.
"""
__author__ = "Alex Drlica-Wagner"
import matplotlib
from collections import OrderedDict as odict
# A modern version (v6-14-02) of the Palette from TColor...
# https://github.com/root-project/root/blob/2762a32343f57664b42558cd3af4031fe2f4f086/core/base/src/TColor.cxx#L2404-L2408
PALETTE = [19,18,17,16,15,14,13,12,11,20,
21,22,23,24,25,26,27,28,29,30, 8,
31,32,33,34,35,36,37,38,39,40, 9,
41,42,43,44,45,47,48,49,46,50, 2,
7, 6, 5, 4, 3, 2,1]
#7, 6, 5, 4, 3, 112,1] # original with typo
#7, 6, 5, 4, 3, 5,1] # corrected to match
# Going back in time to 2007 (v5-17-06), here was the origin palette
# Note the typo in entry 48: 112 (pink) not 2 (red)
# https://github.com/root-project/root/blob/9294cc60a9a70dece4f24f0bc0399cc00c0f78b5/base/src/TStyle.cxx#L1445-L1449
# The commit of the fix:
# https://github.com/root-project/root/commit/d3e92e5de7e76c1ded2af7218adc9bc20b7f0c9f
PALETTE07 = list(PALETTE)
PALETTE07[-2] = 5 # typo was 112, but end up being magenta
# These are the basic root colors.
# https://github.com/root-project/root/blob/2762a32343f57664b42558cd3af4031fe2f4f086/core/base/src/TColor.cxx#L1077
# This list was generated with:
# for (int i=1; i<51; i++) {gROOT->GetColor()->Print; }
TCOLORS = [
(1.000000, 1.000000, 1.000000), # Name=background
(0.000000, 0.000000, 0.000000), # Name=black
(1.000000, 0.000000, 0.000000), # Name=red
(0.000000, 1.000000, 0.000000), # Name=green
(0.000000, 0.000000, 1.000000), # Name=blue
(1.000000, 0.000000, 1.000000), # Name=magenta
(0.000000, 1.000000, 0.800000), # Name=teal
(1.000000, 0.800000, 0.000000), # Name=orange
(0.350000, 0.830000, 0.330000), # Name=Color8
(0.350000, 0.330000, 0.850000), # Name=Color9
(0.999000, 0.999000, 0.999000), # Name=white
(0.754000, 0.715000, 0.676000), # Name=editcol
(0.300000, 0.300000, 0.300000), # Name=grey12
(0.400000, 0.400000, 0.400000), # Name=grey13
(0.500000, 0.500000, 0.500000), # Name=grey14
(0.600000, 0.600000, 0.600000), # Name=grey15
(0.700000, 0.700000, 0.700000), # Name=grey16
(0.800000, 0.800000, 0.800000), # Name=grey17
(0.900000, 0.900000, 0.900000), # Name=grey18
(0.950000, 0.950000, 0.950000), # Name=grey19
(0.800000, 0.780000, 0.670000), # Name=Color20
(0.800000, 0.780000, 0.670000), # Name=Color21
(0.760000, 0.750000, 0.660000), # Name=Color22
(0.730000, 0.710000, 0.640000), # Name=Color23
(0.700000, 0.650000, 0.590000), # Name=Color24
(0.720000, 0.640000, 0.610000), # Name=Color25
(0.680000, 0.600000, 0.550000), # Name=Color26
(0.610000, 0.560000, 0.510000), # Name=Color27
(0.530000, 0.400000, 0.340000), # Name=Color28
(0.690000, 0.810000, 0.780000), # Name=Color29
(0.520000, 0.760000, 0.640000), # Name=Color30
(0.540000, 0.660000, 0.630000), # Name=Color31
(0.510000, 0.620000, 0.550000), # Name=Color32
(0.680000, 0.740000, 0.780000), # Name=Color33
(0.480000, 0.560000, 0.600000), # Name=Color34
(0.460000, 0.540000, 0.570000), # Name=Color35
(0.410000, 0.510000, 0.590000), # Name=Color36
(0.430000, 0.480000, 0.520000), # Name=Color37
(0.490000, 0.600000, 0.820000), # Name=Color38
(0.500000, 0.500000, 0.610000), # Name=Color39
(0.670000, 0.650000, 0.750000), # Name=Color40
(0.830000, 0.810000, 0.530000), # Name=Color41
(0.870000, 0.730000, 0.530000), # Name=Color42
(0.740000, 0.620000, 0.510000), # Name=Color43
(0.780000, 0.600000, 0.490000), # Name=Color44
(0.750000, 0.510000, 0.470000), # Name=Color45
(0.810000, 0.370000, 0.380000), # Name=Color46
(0.670000, 0.560000, 0.580000), # Name=Color47
(0.650000, 0.470000, 0.480000), # Name=Color48
(0.580000, 0.410000, 0.440000), # Name=Color49
(0.830000, 0.350000, 0.330000), # Name=Color50
]
root_cmap = matplotlib.colors.ListedColormap([TCOLORS[i] for i in PALETTE])
root_cmap.set_over(TCOLORS[PALETTE[-1]]);
root_cmap.set_under(TCOLORS[PALETTE[0]])
root07_cmap = matplotlib.colors.ListedColormap([TCOLORS[i] for i in PALETTE07])
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description=__doc__)
args = parser.parse_args()
import numpy as np
import pylab as plt
from mpl_toolkits.mplot3d import Axes3D
def fn(x,y):
return 0.1+(1-(x-2)*(x-2))*(1-(y-2)*(y-2))
xx,yy = np.meshgrid(np.linspace(1,3,1000),np.linspace(1,3,1000))
plt.figure(figsize=(6,4))
levels = np.arange(0.1,1.2,0.1)
plt.contourf(xx,yy,fn(xx,yy),levels,vmin=0.07,vmax=1.05,cmap=root_cmap)
plt.colorbar(ticks=levels,pad=0.01,aspect=10)
plt.subplots_adjust(left=0.08,right=0.99)
""" Equivalent in ROOT:
TCanvas *c1 = new TCanvas("c1","c1",0,0,600,400);
TF2 *f1 = new TF2("f1","0.1+(1-(x-2)*(x-2))*(1-(y-2)*(y-2))",1,3,1,3);
f1->SetNpx(1000);
f1->SetNpy(1000);
Double_t levels[] = {0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1};
f1->SetContour(10,levels);
gStyle->SetPalette(-1);
f1->Draw("colz")
"""
fig = plt.figure(figsize=(6,4))
ax = fig.add_subplot(111, projection='3d')
im = ax.plot_surface(xx,yy,fn(xx,yy),vmin=0.1,vmax=1.09,cmap=root_cmap)
plt.colorbar(im,ticks=np.arange(0,1.2,0.1))
"""
TCanvas *c2 = new TCanvas("c2","c2",0,0,600,400);
f1->SetContour(20);
f1->SetNpx(20);
f1->SetNpy(20)
f1->Draw("surf1z");
"""
| [
"kadrlica@fnal.gov"
] | kadrlica@fnal.gov |
a4ddeb30ebe9368c8a592f4757fdb8780d01cdf0 | 34301251486d79caf7d07bfacf241cec57e30c61 | /PooIII.py | b63a447d52d1802f6db177d24dba83fff8ba7637 | [] | no_license | quirogaluistomas/PythonTest | 055255551459e818c878f49666dde37c3c0eee77 | 612478923f365573b0b313907f184c439df8dad5 | refs/heads/master | 2022-12-26T12:43:17.358500 | 2020-10-15T13:44:19 | 2020-10-15T13:44:19 | 288,061,316 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,081 | py | class Vehiculos():
def __init__(self,marca,modelo):
self.marca = marca
self.modelo = modelo
self.enMarcha = False
self.acelera = False
self.frena = False
def arrancar(self):
self.enMarcha = True
def acelerar(self):
self.acelera = True
def frenar(self):
self.frena = True
def estado(self):
print("Marca: ", self.marca, "\nModelo: ", self.modelo, "\nEn Marcha: ", self.enMarcha,
"\nAcelerando: ", self.acelera, "\nFrenando: ", self.frena)
class Furgoneta(Vehiculos):
def carga(self, cargar):
self.cargado = cargar
if(self.cargado):
return "La furgoneta está cargada"
else:
return "La furgoneta no está cargada"
##La sintaxis para heredar es simplemente pasando a la clase el nombre de la clase de la que se hereda
class Moto(Vehiculos):
hCaballito = ""
#Creamos el método propio de la moto
def caballito(self):
self.hCaballito = "Voy haciendo willy"
#Acá se sobreescribe el método agregando el método propio, cuando se llama a estado se llama a este y no al del metodo padre
def estado(self):
print("Marca ", self.marca, "\nModelo: ", self.modelo, "\nEn Marcha: ", self.enMarcha,
"\nAcelerando: ", self.acelera, "\nFrenando: ", self.frena, "\n" + self.hCaballito)
class VElectricos(Vehiculos):
def __init__(self,marca,modelo):
super().__init__(marca,modelo)
self.autonomia = 100
def cargarEnergia(self):
self.cargando = True
miMoto = Moto("Yamaha", "CBR")
miMoto.caballito()
miMoto.estado()
miFurgoneta = Furgoneta("Renault", "Kangoo")
miFurgoneta.arrancar()
miFurgoneta.estado()
print(miFurgoneta.carga(True))
#Herencia múltiple. Toma siempre como prioridad la herencia del primer argumento, utiliza ese init
class BicicletaElectrica(VElectricos, Vehiculos):
pass
miBici = BicicletaElectrica("Orbea", "hp1500")
#Como accedemos a las propiedades de la clase de la que hereda? Se ve en el script HerenciaSuper | [
"quirogaluistomas@gmail.com"
] | quirogaluistomas@gmail.com |
fdccefb8b24772533cbe29a0df527b73e97df056 | 9c6546b424d51fac8f0950578014c0d6ac96b62e | /homework/CountNumber.py | 4ed08a0ad33b3f5111e82b213a43ad557a51e0bb | [] | no_license | dandan1232/pythonclass | 2661f3dd4ed4667207df8845999ab5633b850e52 | 04096c249c298e093a536f9718b142b4452c876b | refs/heads/main | 2023-08-22T02:48:27.145969 | 2021-10-21T06:49:12 | 2021-10-21T06:49:12 | 402,329,938 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 658 | py | # -*- coding: utf-8 -*-
# @Time : 2021/10/8 14:28
# @Author : Lindand
# @File : CountNumber.py
# @Description :统计字符串个数
# python 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
s = input("请输入字符串:")
alphaNum = 0
spaceNum = 0
numbers = 0
otherNum = 0
for str in s:
if str.isalpha():
alphaNum += 1
elif str.isnumeric():
numbers += 1
elif str.isspace():
spaceNum += 1
else:
otherNum += 1
print("字母char=%d" % alphaNum)
print("空格space=%d" % spaceNum)
print("数字digit=%d" % numbers)
print("其他others=%d" % otherNum)
| [
"345652127@qq.com"
] | 345652127@qq.com |
10b33dc86f16462895fcf09221b4b5715675f34a | da0728ae02ee1178bf97d976c2c589454a871742 | /apps/exam/models.py | 7d3d8dde6b38baae6e6a3b4cb75340c2959a9624 | [] | no_license | luffyliu1993/wish_lists | 9f330e12fbf0d3034ee14fdfdd0d3a582e2924d6 | 91473160b007db155a7e110088dad931d94f240a | refs/heads/master | 2020-07-03T14:17:59.999168 | 2016-11-19T08:36:28 | 2016-11-19T08:36:28 | 74,164,399 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,350 | py | from __future__ import unicode_literals
from django.db import models
import bcrypt, re
# Create your models here.
class UserManager(models.Manager):
def login(self,session,user_name,password):
messages = {'errors':[]}
if len(user_name) == 0:
messages['errors'].append('Please enter an user name')
if len(password) == 0:
messages['errors'].append('Please enter a password')
if len(messages['errors']) > 0:
return (False, messages)
result = self.filter(user_name=user_name)
if len(result) == 0:
messages['errors'].append('Incorrect user name!')
return (False, messages)
if not bcrypt.checkpw(str(password),str(result[0].password)):
messages['errors'].append('Incorrect password!')
return (False, messages)
session['id'] = result[0].id
return (True, messages)
def register_check(self,session,name,user_name,password,conf_pw):
messages = {'errors':[]}
if len(name) < 3:
messages['errors'].append('Name should be at least 2 characters long')
elif not str.isalpha(name):
messages['errors'].append('Name should be letters only')
if len(user_name) == 0:
messages['errors'].append('Username cannot be empty')
elif len(self.filter(user_name=user_name)) > 0:
messages['errors'].append('The user name you entered is used by another account')
if len(password) < 8:
messages['errors'].append('Password should have at least 8 characters')
if len(conf_pw) == 0:
messages['errors'].append('Please confirm your password')
elif password != conf_pw:
messages['errors'].append('Password and confirm password are not match')
if len(messages['errors']) > 0:
return (False, messages)
result = self.create(name=name,user_name=user_name,password=bcrypt.hashpw(str(password),bcrypt.gensalt()))
#session['id'] = self.all().order_by('-id')[0].id
session['id'] = result.id
return (True, messages)
class AddItemManager(models.Manager):
def add_item(self,session,item):
if len(item) == 0:
return (False,'No item entry')
if len(item) < 4:
return (False, 'Item entry should be more than 3 characters')
result = self.filter(item_name=item)
if len(result) > 0:
return (False, 'Item exists already')
user = User.userManager.get(id=session['id'])
item = self.create(item_name=item,add_user=user)
item.wish_users.add(user)
return (True, result)
class User(models.Model):
name = models.CharField(max_length=255)
user_name = models.CharField(max_length=255)
password = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
userManager = UserManager()
class AddItem(models.Model):
item_name = models.CharField(max_length=255)
add_user = models.ForeignKey('User',on_delete=models.CASCADE,related_name='add_user')
wish_users = models.ManyToManyField(User)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
addItemManager = AddItemManager()
| [
"zekailiu1993@gmail.com"
] | zekailiu1993@gmail.com |
dfbe47a2b098d23c9dc19dd09ea91b39f17d1ced | dd2171786e3dfb8458237af24beef7470336a046 | /scripts/tile-add-extended-cols.py | 457ae497e81a519673cd34248bebb873341389af | [
"MIT"
] | permissive | sweverett/Balrog-GalSim | d0a9401e45ef2b70efe4ed186ac13f893dadd3bc | 2e20abaff70dbe59634c9f18d87ceb75b41d63fe | refs/heads/master | 2022-08-27T22:09:06.405636 | 2022-08-09T19:18:47 | 2022-08-09T19:18:47 | 101,892,741 | 5 | 9 | MIT | 2022-08-09T19:18:48 | 2017-08-30T14:39:16 | Python | UTF-8 | Python | false | false | 5,988 | py | """
Add EXTENDED object classifier columns to Balrog outputs.
For Y3, see:
https://cdcvs.fnal.gov/redmine/projects/des-y3/wiki/Y3_Extended_Classifier_v2
"""
import numpy as np
import os
import fitsio
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument(
'catfile',
type=str,
help='ngmix or gold catalog to add classifier to'
)
parser.add_argument(
'--mode',
type=str,
default='all',
choices=['all', 'mof', 'sof'],
help='Can choose to include only one of MOF and SOF in merging & flattening'
)
parser.add_argument(
'--ngmix_only',
action='store_true',
default=False,
help='Use to only compute MOF & SOF EXTENDED classifiers.'
)
parser.add_argument(
'--vb',
action='store_true',
default=False,
help='Set to print out more information'
)
def add_ext_mof(cat, fits, vb=False):
selection_1 = (cat['MOF_CM_T'] + 5. * cat['MOF_CM_T_ERR']) > 0.1
selection_2 = (cat['MOF_CM_T'] + 1. * cat['MOF_CM_T_ERR']) > 0.05
selection_3 = (cat['MOF_CM_T'] - 1. * cat['MOF_CM_T_ERR']) > 0.02
ext_mof = selection_1.astype(int) + selection_2.astype(int) + selection_3.astype(int)
# Special case
ext_mof[cat['MOF_CM_T'] < -9000] = -9
if vb:
print('Writing EXTENDED_CLASS_MOF...')
try:
# If it hasn't been computed yet
fits[1].insert_column('EXTENDED_CLASS_MOF', ext_mof)
except:
fits[1].write_column('EXTENDED_CLASS_MOF', ext_mof)
return
def add_ext_sof(cat, fits, vb=False):
selection_1 = (cat['SOF_CM_T'] + 5. * cat['SOF_CM_T_ERR']) > 0.1
selection_2 = (cat['SOF_CM_T'] + 1. * cat['SOF_CM_T_ERR']) > 0.05
selection_3 = (cat['SOF_CM_T'] - 1. * cat['SOF_CM_T_ERR']) > 0.02
ext_sof = selection_1.astype(int) + selection_2.astype(int) + selection_3.astype(int)
# Special case
ext_sof[cat['SOF_CM_T'] < -9000] = -9
if vb:
print('Writing EXTENDED_CLASS_SOF...')
try:
# If it hasn't been computed yet
fits[1].insert_column('EXTENDED_CLASS_SOF', ext_sof)
except:
fits[1].write_column('EXTENDED_CLASS_SOF', ext_sof)
return
def add_ext_wavg(cat, fits, vb=False):
selection_1 = (cat['WAVG_SPREAD_MODEL_I'] + 3. * cat['WAVG_SPREADERR_MODEL_I']) > 0.005
selection_2 = (cat['WAVG_SPREAD_MODEL_I'] + 1. * cat['WAVG_SPREADERR_MODEL_I']) > 0.003
selection_3 = (cat['WAVG_SPREAD_MODEL_I'] - 1. * cat['WAVG_SPREADERR_MODEL_I']) > 0.001
ext_wavg = selection_1.astype(int) + selection_2.astype(int) + selection_3.astype(int)
if vb:
print('Writing EXTENDED_CLASS_WAVG...')
try:
# If it hasn't been computed yet
fits[1].insert_column('EXTENDED_CLASS_WAVG', ext_wavg)
except:
fits[1].write_column('EXTENDED_CLASS_WAVG', ext_wavg)
return
def add_ext_coadd(cat, fits, vb=False):
selection_1 = (cat['SPREAD_MODEL_I'] + 3. * cat['SPREADERR_MODEL_I']) > 0.005
selection_2 = (cat['SPREAD_MODEL_I'] + 1. * cat['SPREADERR_MODEL_I']) > 0.003
selection_3 = (cat['SPREAD_MODEL_I'] - 1. * cat['SPREADERR_MODEL_I']) > 0.001
ext_wavg = selection_1.astype(int) + selection_2.astype(int) + selection_3.astype(int)
if vb:
print('Writing EXTENDED_CLASS_COADD...')
try:
# If it hasn't been computed yet
fits[1].insert_column('EXTENDED_CLASS_COADD', ext_coadd)
except:
fits[1].write_column('EXTENDED_CLASS_COADD', ext_coadd)
return
def add_ext_mash_mof(cat, fits, vb=False):
if vb:
print('Writing EXTENDED_CLASS_MASH_MOF...')
try:
# If it hasn't been computed yet
fits[1].insert_column('EXTENDED_CLASS_MASH_MOF', ext_mash_mof)
except:
fits[1].write_column('EXTENDED_CLASS_MASH_MOF', ext_mash_mof)
return
def add_ext_mash_sof(cat, fits, vb=False):
if vb:
print('Writing EXTENDED_CLASS_MASH_SOF...')
try:
# If it hasn't been computed yet
fits[1].insert_column('EXTENDED_CLASS_MASH_SOF', ext_mash_sof)
except:
fits[1].write_column('EXTENDED_CLASS_MASH_SOF', ext_mash_sof)
return
def add_ext_models(cat, fits, mode='all', ngmix_only=False, vb=False):
if mode != 'sof':
if vb:
print('Calculating EXTEND_CLASS_MOF...')
add_ext_mof(cat, fits, vb=vb)
if mode != 'mof':
if vb:
print('Calculating EXTEND_CLASS_SOF...')
add_ext_sof(cat, fits, vb=vb)
if ngmix_only is not True:
if vb:
print('Calculating EXTEND_CLASS_WAVG...')
add_ext_wavg(cat, fits, vb=vb)
if vb:
print('Calculating EXTEND_CLASS_COADD...')
add_ext_coadd(cat, fits, vb=vb)
if mode != 'sof':
if vb:
print('Calculating EXTEND_CLASS_MASH_MOF...')
add_ext_mash_mof(cat, fits, vb=vb)
if mode != 'mof':
if vb:
print('Calculating EXTEND_CLASS_MASH_SOF...')
add_ext_mash_sof(cat, fits, vb=vb)
return
def main():
args = parser.parse_args()
vb = args.vb
catfile = args.catfile
ngmix_only = args.ngmix_only
mode = args.mode
if not os.path.exists(catfile):
raise IOError('{} does not exist!'.format(catfile))
catfile = os.path.abspath(catfile)
if vb:
print('Grabbing col data...')
# Which cols are grabbed depends on the mode
cols = []
if (mode == 'all') or (mode == 'mof'):
cols += ['mof_cm_T', 'mof_cm_T_err']
if (mode == 'all') or (mode == 'sof'):
cols += ['sof_cm_T', 'sof_cm_T_err']
if ngmix_only is not True:
cols += ['wavg_spread_model_i', 'wavg_spreaderr_model_i',
'spread_model_i', 'spreaderr_model_i']
cat = fitsio.read(catfile, columns=cols, ext=1)
# Used to write new cols
fits = fitsio.FITS(catfile, 'rw')
add_ext_models(cat, fits, mode=mode, ngmix_only=ngmix_only, vb=vb)
return
if __name__=="__main__":
main()
| [
"spencerweverett@gmail.com"
] | spencerweverett@gmail.com |
8272dedd8b444e882ee9e14ac62bff2a78249d40 | ecb8dd72612b2a670235fafea53f142173f25b5e | /book.py | bcd89b4e43bccd23151a9e37f3aea86cd78d63f9 | [] | no_license | ido2267/Python_Yaniv_final | bb5f2808c6a1c908b9914067c142a614bae1de7e | 1e90d3df00b1ff71615328d822f62bc9ec9f6983 | refs/heads/master | 2020-04-23T14:35:01.173049 | 2019-02-18T07:42:04 | 2019-02-18T07:42:04 | 171,236,424 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 683 | py | class Book():
def __init__(self, bookName,writterName ,number_of_pages):
self.__bookName = bookName
self.__writterName = writterName
self.__number_of_pages = number_of_pages
def __str__(self):
return ("'{}' by {}, {} pages \n"
.format( self.__bookName,self.__writterName, str( self.__number_of_pages)))
@property
def bookName(self):
return self.__bookName
@property
def number_of_pages(self):
return self.__number_of_pages
@property
def writterName(self):
return self.__writterName
def __gt__(self, other):
return self.__number_of_pages > other.number_of_pages | [
"ido2267@gmail.com"
] | ido2267@gmail.com |
7c7591d11d06e75c548d9a4e2b88875b73d167e8 | 41409584b4381abc3dfd7db9c08d9a1bb2c0fbb5 | /OuiCheff/serializers.py | 4317c510fd03883ceacbc449d73739b502f78818 | [] | no_license | 0ndreu/cookbook | 418d25cb9cb9060eeb6f82c7e4a95bf715985c1e | b22ff0cd78414249e4912d839778d6ca7c11fd71 | refs/heads/master | 2022-12-14T21:32:15.112358 | 2019-12-10T02:09:45 | 2019-12-10T02:09:45 | 217,125,329 | 0 | 0 | null | 2022-12-11T10:35:58 | 2019-10-23T18:23:06 | Python | UTF-8 | Python | false | false | 2,580 | py | from rest_framework import serializers
from .models import *
class UserSerializer(serializers.ModelSerializer):
""""
Сериализация пользователя
"""
class Meta:
model = User
fields = ('id', 'username')
class ProductSerializer(serializers.ModelSerializer):
"""
Сериализация продуктов
"""
class Meta:
model = Product
fields = ('title', 'description', 'metric', 'calories', 'proteins', 'fats', 'carbohydrates')
class TimeToEatSerializer(serializers.ModelSerializer):
class Meta:
model = TimeToEat
fields = 'time_to_eat' # is that true??
class ProductForFridgeSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('title', 'description', 'metric')
class ReceiptSerializer(serializers.ModelSerializer):
"""
Сериализация рецептов
"""
# creator = UserSerializer()
# time_to_eat = TimeToEatSerializer(many=False)
creator = serializers.HiddenField(default=serializers.CurrentUserDefault())
# products = ProductSerializer(many=True)
# product = PrimaryKeyRelatedField(required=True,
# queryset=Product.objects.all())
class Meta:
model = Receipt
fields = ('title', 'description', 'date', 'calories',
'proteins', 'fats', 'carbohydrates', 'time_to_eat', 'creator')
# fields = '__all__'
class FridgeSerializer(serializers.ModelSerializer):
user = serializers.HiddenField(default=serializers.CurrentUserDefault())
how_many = serializers.IntegerField(required=True,
min_value=0)
product = serializers.PrimaryKeyRelatedField(required=True,
queryset=Product.objects.all())
class Meta:
model = Fridge
fields = '__all__'
class ProductsInReceiptSerializer(serializers.ModelSerializer):
product = serializers.PrimaryKeyRelatedField(required=True,
queryset=Product.objects.all())
receipt = serializers.PrimaryKeyRelatedField(required=True,
queryset=Receipt.objects.all())
# receipt = serializers.PrimaryKeyRelatedField(default=serializers.)
count_of_product = serializers.IntegerField(required=True,
min_value=0)
class Meta:
model = ReceiptHasProduct
fields = '__all__'
| [
"andrey.artyushov@yandex.ru"
] | andrey.artyushov@yandex.ru |
e1fa257261bc5d47b7097ab9dcd9e881f4142e17 | 667b09b40e1d7cdb166f49b1e13b5f726758cd2f | /djangodev/lib/python2.7/site-packages/rest_framework/utils/encoders.py | adc83e574aac44169f5ad77abd9302a5782f21e5 | [
"MIT"
] | permissive | openworm/movement_validation_cloud | 5f5e1c2569948ee901f4aca574a7e07f252f99fa | f0794d4e800b6594c89c1ae3129949b19bd79ce7 | refs/heads/master | 2021-01-18T06:20:21.660679 | 2017-05-13T07:43:23 | 2017-05-13T07:43:23 | 30,842,893 | 1 | 0 | null | 2015-02-15T21:28:29 | 2015-02-15T21:28:29 | null | UTF-8 | Python | false | false | 4,549 | py | """
Helper classes for parsers.
"""
from __future__ import unicode_literals
from django.db.models.query import QuerySet
from django.utils import six, timezone
from django.utils.encoding import force_text
from django.utils.functional import Promise
from rest_framework.compat import OrderedDict
import datetime
import decimal
import types
import json
class JSONEncoder(json.JSONEncoder):
"""
JSONEncoder subclass that knows how to encode date/time/timedelta,
decimal types, generators and other basic python objects.
"""
def default(self, obj):
# For Date Time string spec, see ECMA 262
# http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
if isinstance(obj, Promise):
return force_text(obj)
elif isinstance(obj, datetime.datetime):
representation = obj.isoformat()
if obj.microsecond:
representation = representation[:23] + representation[26:]
if representation.endswith('+00:00'):
representation = representation[:-6] + 'Z'
return representation
elif isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance(obj, datetime.time):
if timezone and timezone.is_aware(obj):
raise ValueError("JSON can't represent timezone-aware times.")
representation = obj.isoformat()
if obj.microsecond:
representation = representation[:12]
return representation
elif isinstance(obj, datetime.timedelta):
return six.text_type(obj.total_seconds())
elif isinstance(obj, decimal.Decimal):
# Serializers will coerce decimals to strings by default.
return float(obj)
elif isinstance(obj, QuerySet):
return tuple(obj)
elif hasattr(obj, 'tolist'):
# Numpy arrays and array scalars.
return obj.tolist()
elif hasattr(obj, '__getitem__'):
try:
return dict(obj)
except:
pass
elif hasattr(obj, '__iter__'):
return tuple(item for item in obj)
return super(JSONEncoder, self).default(obj)
try:
import yaml
except ImportError:
SafeDumper = None
else:
# Adapted from http://pyyaml.org/attachment/ticket/161/use_ordered_dict.py
class SafeDumper(yaml.SafeDumper):
"""
Handles decimals as strings.
Handles OrderedDicts as usual dicts, but preserves field order, rather
than the usual behaviour of sorting the keys.
"""
def represent_decimal(self, data):
return self.represent_scalar('tag:yaml.org,2002:str', six.text_type(data))
def represent_mapping(self, tag, mapping, flow_style=None):
value = []
node = yaml.MappingNode(tag, value, flow_style=flow_style)
if self.alias_key is not None:
self.represented_objects[self.alias_key] = node
best_style = True
if hasattr(mapping, 'items'):
mapping = list(mapping.items())
if not isinstance(mapping, OrderedDict):
mapping.sort()
for item_key, item_value in mapping:
node_key = self.represent_data(item_key)
node_value = self.represent_data(item_value)
if not (isinstance(node_key, yaml.ScalarNode) and not node_key.style):
best_style = False
if not (isinstance(node_value, yaml.ScalarNode) and not node_value.style):
best_style = False
value.append((node_key, node_value))
if flow_style is None:
if self.default_flow_style is not None:
node.flow_style = self.default_flow_style
else:
node.flow_style = best_style
return node
SafeDumper.add_representer(
decimal.Decimal,
SafeDumper.represent_decimal
)
SafeDumper.add_representer(
OrderedDict,
yaml.representer.SafeRepresenter.represent_dict
)
# SafeDumper.add_representer(
# DictWithMetadata,
# yaml.representer.SafeRepresenter.represent_dict
# )
# SafeDumper.add_representer(
# OrderedDictWithMetadata,
# yaml.representer.SafeRepresenter.represent_dict
# )
SafeDumper.add_representer(
types.GeneratorType,
yaml.representer.SafeRepresenter.represent_list
)
| [
"joe.bowen@toptal.com"
] | joe.bowen@toptal.com |
cf15b9c34c3a33e2206bb3e10dadb2ed97d43d14 | 353ab54435ef77b395de476a38f5a9cc253c1b9c | /src/api/urls.py | 19cd94292ecf1e027086a7917c07dd807423903f | [] | no_license | mymacy/django-rest-template | e90d4a462a3f7518c510d15a70a6098d2b79fe33 | 58a8fcd580dd534799dbe19466374e798e6804db | refs/heads/master | 2020-03-22T09:44:07.824825 | 2018-07-05T13:56:23 | 2018-07-05T13:56:23 | 139,208,531 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,737 | py | # Urls are simply redirect the request to the right view
from django.urls import re_path, path, include
from . import views
'''
########################## Custom Email templates
'''
from djoser.email import *
from settings import BASE_DIR
import os
template_path = os.path.join(BASE_DIR, 'api/templates/email')
ActivationEmail.template_name = template_path+'/activation.html'
ConfirmationEmail.template_name = template_path+'/confirmation.html'
PasswordResetEmail.template_name = template_path+'/password_reset.html'
'''
########################## User Auth and Profile:
http://djoser.readthedocs.io/en/latest/base_endpoints.html
'''
urlpatterns = [
path('', include('djoser.urls.base')),
path('', include('djoser.urls.authtoken')),
path('', include('djoser.urls.jwt')),
path('', include('djoser.social.urls')),
re_path(r'^activate/(?P<uid>[A-Za-z0-9]+)/(?P<token>[A-Za-z0-9-]+)/$', views.ActivationLink.as_view()), # links the user to the site and give activation credentials
re_path(r'^password/reset/confirm/(?P<uid>[A-Za-z0-9]+)/(?P<token>[A-Za-z0-9-]+)/$', views.ResetConfirm.as_view()),
path('showUsers/', views.UserList.as_view()),
path('checkauth/', views.CheckAuth.as_view()),
path('updateprofile/', views.UpdateProfile.as_view()),
]
'''
########################## Generics
'''
urlpatterns += [
path('rezept/all/', views.RezeptListView.as_view()),
path('rezept/create/', views.RezeptCreateView.as_view()),
re_path(r'rezept/rud/(?P<pk>\d+)/$', views.RezeptRudView.as_view()),
# re_path(r'rud/title/(?P<titel>[\w-]+)/$', views.RezeptTitleRudView.as_view()), # search by title
]
'''
########################## API Custom Classes
'''
urlpatterns += [
]
| [
"marcelalbrink@googlemail.com"
] | marcelalbrink@googlemail.com |
1352defb4615592e809e5d9cf707e497e6f14e13 | 964774524786c8fc07031498ded56947d937ad63 | /Spark/Events/SparkEvents.py | 6d470ec2151ed5d8caa19a7954f5afde50b5ac29 | [] | no_license | cabhi/SparkGraph | 9102080242c0dea4425a96370a1dbc00ed2172a3 | bebd46196872b527dcf56d8f1757208c4a11ede9 | refs/heads/master | 2021-01-01T05:21:14.812171 | 2016-05-25T07:57:51 | 2016-05-25T07:57:51 | 59,642,587 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 990 | py | import abc
import json
class SparkEvents(object):
"""docstring for SparkEvents"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def getStartTime(self):
"""Returns the ingredient list."""
raise NotImplementedError
@abc.abstractmethod
def getEndTime(self):
"""Returns the ingredient list."""
raise NotImplementedError
def setRank(self,rank):
self.rank = rank
def getRank(self):
return self.rank
def __init__(self, arg):
self.eventJson = arg
self.id = None
def getId(self):
return self.id
def __eq__(self, other):
return type(self).__name__ == type(other).__name__ and self.id == other.id
def parentName(self):
allParents = []
for base in self.__class__.__bases__ :
allParents.append(base.__name__)
return allParents
def printClassdump(self):
print json.dumps(self.eventJson, indent=4, sort_keys=True)
| [
"abhishek.choudhary@guavus.com"
] | abhishek.choudhary@guavus.com |
6d46122b44155acca766720a29c0b494099568c6 | cde8a46ede72a4cbd4bb19c765e590c6e2897fb1 | /mIRCColors.py | a6a06f993b9150521323ab7203dff8ef1779c3a0 | [] | no_license | dom96/nyx | 39d6b96654ea54533112c59c81e66af743b26e5b | 6d1bbd53e80fefab1de2429d4fd6d72dfc3cccf0 | refs/heads/master | 2016-09-10T10:01:35.245151 | 2013-03-06T22:34:30 | 2013-03-06T22:34:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,150 | py | #!/usr/bin/env python
"""
Nyx - A powerful IRC Client
Copyright (C) 2009 Mad Dog Software
http://maddogsoftware.co.uk - morfeusz8@yahoo.co.uk
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
"""
import gtk
import pygtk
mIRCColors=dict()
mIRCColors[0]=gtk.gdk.Color(red=204 * 257, green=204 * 257, blue=204 * 257, pixel=0)
mIRCColors[1]=gtk.gdk.Color(red=0, green=0, blue=0, pixel=0)
mIRCColors[2]=gtk.gdk.Color(red=54 * 257, green=54 * 257, blue=178 * 257, pixel=0)
mIRCColors[3]=gtk.gdk.Color(red=42 * 257, green=140 * 257, blue=42 * 257, pixel=0)
mIRCColors[4]=gtk.gdk.Color(red=195 * 257, green=59 * 257, blue=59 * 257, pixel=0)
mIRCColors[5]=gtk.gdk.Color(red=199 * 257, green=50 * 257, blue=50 * 257, pixel=0)
mIRCColors[6]=gtk.gdk.Color(red=128 * 257, green=38 * 257, blue=127 * 257, pixel=0)
mIRCColors[7]=gtk.gdk.Color(red=102 * 257, green=54 * 257, blue=31 * 257, pixel=0)
mIRCColors[8]=gtk.gdk.Color(red=217 * 257, green=166 * 257, blue=65 * 257, pixel=0)
mIRCColors[9]=gtk.gdk.Color(red=61 * 257, green=204 * 257, blue=61 * 257, pixel=0)
mIRCColors[10]=gtk.gdk.Color(red=26 * 257, green=85 * 257, blue=85 * 257, pixel=0)
mIRCColors[11]=gtk.gdk.Color(red=47 * 257, green=140 * 257, blue=116 * 257, pixel=0)
mIRCColors[12]=gtk.gdk.Color(red=69 * 257, green=69 * 257, blue=230 * 257, pixel=0)
mIRCColors[13]=gtk.gdk.Color(red=176 * 257, green=55 * 257, blue=176 * 257, pixel=0)
mIRCColors[14]=gtk.gdk.Color(red=76 * 257, green=76 * 257, blue=76 * 257, pixel=0)
mIRCColors[15]=gtk.gdk.Color(red=149 * 257, green=149 * 257, blue=149 * 257, pixel=0)
mIRCColors[16]=gtk.gdk.Color(red=204 * 257, green=204 * 257, blue=204 * 257, pixel=0)
mIRCColors[17]=gtk.gdk.Color(red=0, green=0, blue=0, pixel=0)
mIRCColors[18]=gtk.gdk.Color(red=54 * 257, green=54 * 257, blue=178 * 257, pixel=0)
mIRCColors[19]=gtk.gdk.Color(red=42 * 257, green=140 * 257, blue=42 * 257, pixel=0)
mIRCColors[20]=gtk.gdk.Color(red=195 * 257, green=59 * 257, blue=59 * 257, pixel=0)
mIRCColors[21]=gtk.gdk.Color(red=255 * 257, green=0 * 257, blue=0 * 257, pixel=0)#Changed this because it's dull...
mIRCColors[22]=gtk.gdk.Color(red=128 * 257, green=38 * 257, blue=127 * 257, pixel=0)
mIRCColors[23]=gtk.gdk.Color(red=102 * 257, green=54 * 257, blue=31 * 257, pixel=0)
mIRCColors[24]=gtk.gdk.Color(red=217 * 257, green=166 * 257, blue=65 * 257, pixel=0)
mIRCColors[25]=gtk.gdk.Color(red=61 * 257, green=204 * 257, blue=61 * 257, pixel=0)
mIRCColors[26]=gtk.gdk.Color(red=26 * 257, green=85 * 257, blue=85 * 257, pixel=0)
mIRCColors[27]=gtk.gdk.Color(red=47 * 257, green=140 * 257, blue=116 * 257, pixel=0)
mIRCColors[28]=gtk.gdk.Color(red=50 * 257, green=150 * 257, blue=255 * 257, pixel=0)#Changed this because it's dull...
mIRCColors[29]=gtk.gdk.Color(red=176 * 257, green=55 * 257, blue=176 * 257, pixel=0)
mIRCColors[30]=gtk.gdk.Color(red=76 * 257, green=76 * 257, blue=76 * 257, pixel=0)
mIRCColors[31]=gtk.gdk.Color(red=149 * 257, green=149 * 257, blue=149 * 257, pixel=0)
def canonicalColor(s, bg=False, shift=0):
"""Assigns an (fg, bg) canonical color pair to a string based on its hash
value. This means it might change between Python versions. This pair can
be used as a *parameter to mircColor. The shift parameter is how much to
right-shift the hash value initially.
"""
h = hash(s) >> shift
fg = h % 14 + 2 # The + 2 is to rule out black and white.
if bg:
bg = (h >> 4) & 3 # The 5th, 6th, and 7th least significant bits.
if fg < 8:
bg += 8
else:
bg += 2
return (fg, bg)
else:
return (fg, None)
| [
"dominikpicheta@googlemail.com"
] | dominikpicheta@googlemail.com |
5389b7b7a0af6813f7e9bc479671cd79ef29c03d | e6795a438d0d45ad590e4867fc1d674e6a1b2433 | /config.py | d97fe414d8d7f98e0a2ec4f3e3b72a69f31b2293 | [] | no_license | snagiri/ECE285_Jarvis_ProjectA | ef96e49764f1c0569ad940a7416cb7185b28f2eb | 73ae0ee9ba5c98e4160f1b0c77a2879513e66367 | refs/heads/master | 2020-06-01T20:56:21.502596 | 2019-06-10T03:06:07 | 2019-06-10T03:06:07 | 190,922,720 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,243 | py | # paths
qa_path = 'qa_path' # directory containing the question and annotation jsons
train_path = '/datasets/home/49/049/s2solomo/show_tell2/show-attend-and-tell-tensorflow/image/train2014' # directory of training images
val_path = '/datasets/home/49/049/s2solomo/show_tell2/show-attend-and-tell-tensorflow/image/val2014' # directory of validation images
test_path = 'mscoco/test2015' # directory of test images
preprocessed_path = './resnet-14x14.h5' # path where preprocessed features are saved to and loaded from
vocabulary_path = 'vocab.json' # path where the used vocabularies for question and answers are saved to
task = 'OpenEnded'
dataset = 'mscoco'
# preprocess config
preprocess_batch_size = 64
image_size = 448 # scale shorter end of image to this size and centre crop
output_size = image_size // 32 # size of the feature maps after processing through a network
output_features = 2048 # number of feature maps thereof
central_fraction = 0.875 # only take this much of the centre when scaling and centre cropping
# training config
epochs = 50
batch_size = 128
initial_lr = 1e-3 # default Adam lr
lr_halflife = 50000 # in iterations
data_workers = 8
max_answers = 3000
#test config
test_batch_size = 1
test_epochs = 1
| [
"s2solomo@eng.ucsd.edu"
] | s2solomo@eng.ucsd.edu |
4d07a112b1fd0deef9cd0bc0d3083f52c4acf5cd | 5b24eaa4b38778a2cc794d038f074bf03a20b63e | /Previous versions/test.py | 9c19fcd447a05546e27d6bccd40e5c5b9e46e3a9 | [] | no_license | BH4/Isolation | daefb2d230397c57da9ace9ea2f833a20b1a946c | d75ae2d4baced82e80f3097a55fbec8fbbb7bedd | refs/heads/master | 2021-01-13T00:56:31.745119 | 2019-02-05T09:10:03 | 2019-02-05T09:10:03 | 48,250,932 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,417 | py |
from random import randint
from copy import deepcopy
def legal(board,pos):
if pos[0]<0 or pos[1]<0 or pos[0]>=7 or pos[1]>=7:
return False
if board[pos[0]][pos[1]]==0:
return True
return False
def neighbors(board,pos):
n=[]
moves=[(0,1),(1,0),(0,-1),(-1,0),(1,1),(-1,1),(-1,-1),(1,-1)]
for m in moves:
test=(pos[0]+m[0],pos[1]+m[1])
if legal(board,test):
n.append(test)
return n
def bfsScore(board,pos):
board=deepcopy(board)
score=0
q=[]
curr=(0,pos)
done=False
while not done and curr[0]<7:
neigh=neighbors(board,curr[1])
for n in neigh:
board[n[0]][n[1]]=-1
q.append((curr[0]+1,n))
mod=1./(2**curr[0])
score+=len(neigh)*mod
if len(q)==0:
done=True
else:
curr=q.pop(0)
return score
def neighborFind(board,pos,func):#find the neighbor whose score is favored by func
#func must return the index of the favored score
neigh=neighbors(board,pos)
scores=[]
for n in neigh:
s=bfsScore(board,n)
scores.append(s)
ind=func(scores)
return neigh[ind]
def argmax(l):
m=max(l)
return l.index(m)
def argmin(l):
m=min(l)
return l.index(m)
def randRemove(board):
m=(-1,-1)
while not legal(board,m):
m=(randint(0,7),randint(0,7))
return m
def randMove(board,pos):
n=[]
moves=[(0,1),(1,0),(0,-1),(-1,0),(1,1),(-1,1),(-1,-1),(1,-1)]
for m in moves:
test=(pos[0]+m[0],pos[1]+m[1])
if legal(board,test):
n.append(test)
#print len(n)
return n[randint(0,len(n)-1)]
temp=[None,None]
board=[]
for i in xrange(7):
row=raw_input()
row=row.replace(' ',' ')
row=row.split(' ')
row=row[:7]
row=[int(x) for x in row]
board.append(row)
if temp[1]==None or temp[0]==None:
for j,n in enumerate(row):
if n>0:
temp[n-1]=(i,j)
pid=int(raw_input())
if pid==1:
player,enemy=temp
else:
enemy,player=temp
#move=randMove(board,player)
move=neighborFind(board,player,argmax)
board[move[0]][move[1]]=pid
board[player[0]][player[1]]=0
remove=neighborFind(board,enemy,argmax)
#remove=randRemove(board)
print str(move[0])+' '+str(move[1])
print str(remove[0])+' '+str(remove[1])
#print '5 3'
#print '0 0'
| [
"brycefore4@gmail.com"
] | brycefore4@gmail.com |
b087c7766a3e59b7abbbc7a25cb66a604aded1e7 | b85c0eb247ced711b6ea1a89e2a2878160b5ab80 | /camera/renameFile.py | 042018d04b9e151bbb5c95b01feccd05ea220b6a | [] | no_license | tianhz2/glimpsecam | 188ee863d9628b9f523b2383893c8561ba36c878 | da1427b4b5ea2cac6e274b7d5b315da4026d20ba | refs/heads/master | 2020-03-25T16:47:35.261834 | 2018-08-15T03:20:55 | 2018-08-15T03:20:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 274 | py | import glob, os
def rename(path, number):
list = glob.glob(path + '/*')
filename = max(list, key=os.path.getctime)
filepath = os.path.split(filename)
os.rename(filename, filepath[0] + '/%05d' % number + filepath[1])
return filepath[0] + '/%05d' % number + filepath[1]
| [
"jungo@uw.edu"
] | jungo@uw.edu |
e1e30f6764ae84523ceb90b72bfa3d571d25b9ad | 8bb4357ce54bdcc2ac98ec81d2afa344f5a9fcab | /qq/config_helper.py | 3c4d4a66faee1fd268fd06f657c39f59ae71d1e0 | [] | no_license | pfstudio/pf_bot | 8ed1627833916982e1f6de110cc00768bfd1a036 | 562a641cb96f59f740ed1da1fcd6b8ed1fe0974a | refs/heads/master | 2023-08-21T17:21:31.282863 | 2021-06-12T07:41:02 | 2021-06-12T07:41:02 | 376,000,264 | 1 | 0 | null | 2021-06-12T07:41:02 | 2021-06-11T11:17:58 | Python | UTF-8 | Python | false | false | 1,424 | py | # coding: utf-8
import json
from const import JobType
class Config(object):
config_name = None
request_url = None
qq_group_ids = None
template = None
data = None
job_type = None
class ConfigHelper(object):
# 通用获取配置字段
@classmethod
def get_config(cls, config_type):
"""
:param config_type:
:return: Config
"""
try:
with open('config.json', 'r') as f:
data = f.read()
except Exception as e:
# 兼容 python qq/qq_actions.py 场景
with open('qq/config.json', 'r') as f:
data = f.read()
all_config = json.loads(data)
base_url = all_config.get('base_url')
# 兼容 base_url 后缀没写 / 场景
if base_url[-1] != '/':
base_url += '/'
custom_config = {} if (isinstance(all_config, map)) else all_config.get('config').get(config_type)
conf = Config()
conf.request_url = base_url + custom_config.get('request_url', '')
conf.qq_group_ids = custom_config.get('qq_group_ids', [])
conf.template = custom_config.get('template', {})
conf.data = custom_config.get('data', {})
conf.job_type = custom_config.get('job_type', JobType.SEND_GROUP_MSG)
return conf
if __name__ == '__main__':
print(ConfigHelper.get_config('qq_duty_notify_config').__dict__)
| [
"yangfengchang@bytedance.com"
] | yangfengchang@bytedance.com |
eaa0908d459a075a301bd9ddf74dd8ace6758a06 | 9f637e68051d422eb48224a9283a304f64dacbb5 | /ex097.py | 5385f9c355ac7c08a125a454195760704dbbd260 | [] | no_license | rodrigolnaves/CursoemVideo | 85d8ff0a815047507c3d5eef87ae18660fb2a049 | 1c420426e2edc91589081cd7bddd874dc9458284 | refs/heads/master | 2023-04-21T14:18:52.240607 | 2021-05-08T17:30:39 | 2021-05-08T17:30:39 | 365,571,616 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 180 | py | def escreva(msg):
tam = len(msg) + 4
print('~' * tam)
print(f' {msg}')
print('~' * tam)
escreva('TESTE')
escreva('ESCREVENDO UM TEXTO BEM GRANDE')
escreva('Oi')
| [
"rodrigolnaves@hotmail.com"
] | rodrigolnaves@hotmail.com |
599353cfcafe9640d4cf07b868040b04a083b255 | 8dfee92f0a6aeceabe9aec77757e9b6155388be5 | /5-1.py | cfe8185096a393f9c870f7d6d59f4841fcd1b494 | [] | no_license | MaximeGoyette/adventOfCode2020 | 6c11ba54eb82be41837c3199194a9827b5176bb9 | 2efc36f162ffed2e317158008cf506bf5ccb886c | refs/heads/master | 2021-01-04T13:53:22.744417 | 2020-12-18T18:58:16 | 2020-12-18T18:58:16 | 322,681,088 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 255 | py | data = open('5.txt').read().split('\n')
m = 0
for seat in data:
row = int(seat[:7].replace('F', '0').replace('B', '1'), 2)
col = int(seat[-3:].replace('L', '0').replace('R', '1'), 2)
_id = row*8+col
if _id > m:
m = _id
print(m)
| [
"maxime.goyette@flare.systems"
] | maxime.goyette@flare.systems |
fe9df61a2e258863b6e2aee9719643e854ebe04c | 11ff5d1651b1a3972de8d7fe369943166cb1e8dd | /lab9/backend_squares/squares/squares_app/tests/e2e/test_e2e.py | 3c2864a8f70764ecee0fdd0d4badaa97762aeee1 | [] | no_license | ilyalevushkin/computer_networks | b0eb4fa1d20a381480b6b278c01a753a98bf23ee | 3fc63850ef27779404b8d3fd054f194b78c7ee21 | refs/heads/main | 2023-05-25T11:19:06.055725 | 2021-06-16T12:58:12 | 2021-06-16T12:58:12 | 316,938,267 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,684 | py | from http import HTTPStatus
from django.test import TestCase
import os
from copy import deepcopy
import json
from django.contrib.auth.models import User
from ...models import Users, PullPlayers, Games
class GameWithPoolUserTest(TestCase):
@classmethod
def setUpTestData(cls):
#arrange
cls.passed = 0
cls.user1_data = {'User': {
'user': {
'username': 'den',
'first_name': 'denis',
'last_name': 'reling',
'email': 'reling@reling.com',
'password': '123'
},
'phone': '1111111',
'about': 'infoooooo'
}}
cls.login_data1 = {'User_signin': {
'username': cls.user1_data['User']['user']['username'],
'password': cls.user1_data['User']['user']['password']
}}
cls.user2_data = {'User': {
'user': {
'username': 'den2',
'first_name': 'denis2',
'last_name': 'reling2',
'email': 'reling2@reling.com',
'password': '123'
},
'phone': '11111112',
'about': 'infoooooo2'
}}
cls.login_data2 = {'User_signin': {
'username': cls.user2_data['User']['user']['username'],
'password': cls.user2_data['User']['user']['password']
}}
cls.game_data = {'Game': {
'player_1_id': None,
'player_2_id': None,
'game_state': {
'turn': '1',
'columns': 1,
'rows': 2,
'table_with_chips': '00'
}
}}
cls.patch_data = {
'Game_state_update': {
'column_pos': 0,
'row_pos': None,
'value': ''
}
}
def passedPercent(self):
print(f'{self.passed}/{self.n}')
def create_user(self, person):
data = self.user1_data
if person == 2:
data = self.user2_data
response = self.client.post('/api/v1/users/signup', data=json.dumps(data),
content_type='application/json')
return response
def login_user(self, person):
data = self.login_data1
if person == 2:
data = self.login_data2
response = self.client.post('/api/v1/users/signin', data=json.dumps(data),
content_type='application/json')
return response
def get_user_info(self, person, token):
data = self.get_user_by_username(self.user1_data['User']['user']['username'])
if person == 2:
data = self.get_user_by_username(self.user2_data['User']['user']['username'])
response = self.client.get('/api/v1/users/' + str(data.pk), HTTP_AUTHORIZATION=('Token ' + token))
return response
def search_users_in_pull(self, token):
return self.client.get('/api/v1/pull_players', HTTP_AUTHORIZATION=('Token ' + token))
def add_user_in_pull(self, token):
return self.client.post('/api/v1/pull_players', HTTP_AUTHORIZATION=('Token ' + token))
def start_game(self, person_by, first_turn, token):
data = self.game_data
data['Game']['game_state']['turn'] = str(first_turn)
data['Game']['player_2_id'] = self.get_user_by_username(self.user1_data['User']['user']['username']).pk
data['Game']['player_1_id'] = self.get_user_by_username(self.user2_data['User']['user']['username']).pk
if person_by == 2:
data['Game']['player_2_id'], data['Game']['player_1_id'] = data['Game']['player_1_id'], \
data['Game']['player_2_id']
return self.client.post('/api/v1/games', data=json.dumps(data),
content_type='application/json', HTTP_AUTHORIZATION=('Token ' + token))
def get_game_by_user(self, person_by, token):
user = self.get_user_by_username(self.user1_data['User']['user']['username'])
if person_by == 2:
user = self.get_user_by_username(self.user2_data['User']['user']['username'])
return self.client.get('/api/v1/games/users/' + str(user.pk) + '?active=1', HTTP_AUTHORIZATION=('Token ' + token))
def make_turn(self, game_id, position, person, token):
data = self.patch_data
data['Game_state_update']['row_pos'] = position
data['Game_state_update']['value'] = str(person)
return self.client.patch('/api/v1/games/' + str(game_id), data=json.dumps(data),
content_type='application/json', HTTP_AUTHORIZATION=('Token ' + token))
def logout_user(self, token):
return self.client.get('/api/v1/users/signout', HTTP_AUTHORIZATION=('Token ' + token))
def get_user_by_username(self, username):
return Users.objects.get(user__username=username)
def test_live(self):
self.n = int(os.getenv('TEST_REPEATS', 100))
self.passed = 0
for i in range(self.n):
self.__test_live()
self.passedPercent()
def __test_live(self):
# create 2 users
# act
response = self.create_user(person=1)
#assert
self.assertEqual(response.status_code, HTTPStatus.CREATED)
self.assertEqual(self.get_user_by_username(self.user1_data['User']['user']['username']).user.username,
self.user1_data['User']['user']['username'])
#act
response = self.create_user(person=2)
# assert
self.assertEqual(response.status_code, HTTPStatus.CREATED)
self.assertEqual(self.get_user_by_username(self.user2_data['User']['user']['username']).user.username,
self.user2_data['User']['user']['username'])
# login user1 and user2
#act
response = self.login_user(person=1)
user1_token = response.data['Token']
#assert
self.assertEqual(response.status_code, HTTPStatus.OK)
#act
response = self.login_user(person=2)
user2_token = response.data['Token']
#assert
self.assertEqual(response.status_code, HTTPStatus.OK)
# search info about user1 and user2
#act
response = self.get_user_info(person=1, token=user1_token)
#assert
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertEqual(response.data['User']['user']['username'], self.user1_data['User']['user']['username'])
# act
response = self.get_user_info(person=2, token=user2_token)
# assert
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertEqual(response.data['User']['user']['username'], self.user2_data['User']['user']['username'])
# search users in pull by user1
#act
response = self.search_users_in_pull(token=user1_token)
#assert
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertEqual(len(response.data['Pull_players']), 0)
# add user1 to pull
# act
response = self.add_user_in_pull(token=user1_token)
# assert
self.assertEqual(response.status_code, HTTPStatus.CREATED)
# search users in pull by user2
# act
response = self.search_users_in_pull(token=user2_token)
# assert
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertEqual(len(response.data['Pull_players']), 1)
self.assertEqual(response.data['Pull_players'][0]['player']['user']['username'],
self.user1_data['User']['user']['username'])
# start game with user1 by user2
# act
response = self.start_game(person_by=2, first_turn=2, token=user2_token)
user2_game_id = response.data['Game']['id']
# assert
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertEqual(response.data['Game']['game_state']['table_with_chips'],
self.game_data['Game']['game_state']['table_with_chips'])
# get game_info by user1
# act
response = self.get_game_by_user(person_by=1, token=user1_token)
user1_game_id = response.data['Game']['id']
# assert
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertEqual(response.data['Game']['player_1']['user']['username'],
self.user1_data['User']['user']['username'])
self.assertEqual(response.data['Game']['player_2']['user']['username'],
self.user2_data['User']['user']['username'])
self.assertEqual(response.data['Game']['game_state']['turn'], '2')
self.assertEqual(user1_game_id, user2_game_id)
# user2 make turn
# act
response = self.make_turn(game_id=user2_game_id, position=0, person=2, token=user2_token)
# assert
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertEqual(response.data['Game']['game_state']['table_with_chips'], '20')
self.assertEqual(response.data['Game']['game_state']['turn'], '1')
self.assertEqual(response.data['Game']['game_state']['status'], '-1')
# user1 make turn and tied
# act
response = self.make_turn(game_id=user2_game_id, position=1, person=1, token=user1_token)
# assert
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertEqual(response.data['Game']['game_state']['table_with_chips'], '21')
self.assertEqual(response.data['Game']['game_state']['turn'], '2')
self.assertEqual(response.data['Game']['game_state']['status'], '0')
# logout user1 and user2
# act
response = self.logout_user(token=user1_token)
# assert
self.assertEqual(response.status_code, HTTPStatus.OK)
# act
response = self.logout_user(token=user2_token)
# assert
self.assertEqual(response.status_code, HTTPStatus.OK)
# проверка, вышли ли users
# act
response = self.logout_user(token=user1_token)
# assert
self.assertNotEqual(response.status_code, HTTPStatus.OK)
# act
response = self.logout_user(token=user2_token)
# assert
self.assertNotEqual(response.status_code, HTTPStatus.OK)
# Total
self.passed += 1
# Cleanup
Games.objects.all().delete()
PullPlayers.objects.all().delete()
Users.objects.all().delete()
User.objects.all().delete()
| [
"ilyalyov@mail.ru"
] | ilyalyov@mail.ru |
29a922186f04f76976f5e5ecca73dd93463543b9 | e0ad9016353b53372cc2129fd8e7b5518429f127 | /python/drawResolutionCFD.py | 26c77ad6da88ffb6d665d4265d7c350eb3c373b0 | [] | no_license | amartelli/iMCP_TB | 314bba87879f85d140140701c40520465514e38e | 7a90ee6f6e6007bc8998e447492d6eb89d169b25 | refs/heads/master | 2020-12-07T05:24:48.436877 | 2015-07-03T04:34:52 | 2015-07-03T04:34:52 | 38,692,771 | 0 | 0 | null | 2015-07-07T14:23:47 | 2015-07-07T14:23:47 | null | UTF-8 | Python | false | false | 771 | py | #!/usr/bin/python
import sys
import os
import commands
from commands import getstatusoutput
import datetime
import argparse
import string
if __name__ == '__main__':
os.system('./drawResolutionCFD.exe HV12')
os.system('./drawResolutionCFD.exe HV1')
os.system('./drawResolutionCFD.exe HV2')
os.system('./drawResolutionCFD.exe Extreme')
os.system('./drawResolutionCFD.exe Ang')
os.system('./drawResolutionCFD.exe X0_12')
os.system('./drawResolutionCFD.exe X0_1')
# os.system('./drawResolutionCFD.exe multiplicity1')
# os.system('./drawResolutionCFD.exe multiplicity2')
os.system('./drawResolutionCFD.exe LongScan2X0')
os.system('./drawResolutionCFD.exe saturated_HV12')
os.system('./drawResolutionCFD.exe saturated_X0_12')
| [
"brianza@hercules.mib.infn.it"
] | brianza@hercules.mib.infn.it |
a09adeed122ae58c69e4189c37b3aee9ca2aaeab | f5112d00a1068ea175ae4d44485b0c27970b85cb | /blog/urls.py | 5979a1bdbce68aaddcceab7df3166bb6dd481a78 | [] | no_license | nilanginexture/first-blog | 8261c15bbca1484e56c77dfe456f6e8e502f3e4e | 9a67945a1895c9a717167a32b6d254554fbf8018 | refs/heads/master | 2021-01-19T14:24:26.924701 | 2017-04-13T12:07:54 | 2017-04-13T12:07:54 | 88,159,048 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 404 | py | from django.conf.urls import url,include
from django.views.generic import ListView, DetailView
from blog.models import Post
urlpatterns = [
url(r'^$', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:25],
template_name="blog/blog.html")),
url(r'^(?P<pk>\d+)$', DetailView.as_view(model = Post,
template_name="blog/post.html")),
]
| [
"noreply@github.com"
] | nilanginexture.noreply@github.com |
38da11191a2e3dba557536e648c3a9195434ea0c | a9e200ca23b4da59cd8aa34d08d817a7810c7855 | /Sorting/Quicksort.py | 44ca7d09192d3230a666fcf1e610a82962ed4948 | [] | no_license | Abhijith250/Codes-DS | 602efbf97f0189dce55071d2346d1ea456e54fcd | 401aa68b5594a93944ac039f12fc02f3b640c1f4 | refs/heads/main | 2023-07-04T01:44:31.756165 | 2021-08-09T15:35:47 | 2021-08-09T15:35:47 | 303,723,443 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 595 | py | def partition(a,si,ei):
pivot=a[si]
c=0
for i in range(si,ei+1):
if a[i]<pivot:
c=c+1
a[si],a[si+c]=a[si+c],a[si]
index=si+c
i=si
j=ei
while i<j:
if a[i]<pivot:
i=i+1
elif a[j]>pivot:
j=j-1
else:
a[i],a[j]=a[j],a[i]
i=i+1
j=j-1
return index
def quicksort(a,si,ei):
if si>ei:
return
i=partition(a,si,ei)
quicksort(a,si,i-1)
quicksort(a,i+1,ei)
l=[2,4,5,1]
quicksort(l,0,len(l)-1)
print(l) | [
"noreply@github.com"
] | Abhijith250.noreply@github.com |
a646f736f2a7b33cfab0bd7bff97e2ca1026d8a6 | a83de5827c8ff594bb390fdcdf1ef5f65e6e6634 | /src/directconn/client.py | 1c2b9aad4d05b05ab52d619c3720f3ca46cb2d90 | [] | no_license | EthanBK/file_system_design | 29a7b6e8d95019fb78f2c54e3fd26d3066d38e71 | d2bea06b956bc62f90efa8163629a622f5f916d0 | refs/heads/master | 2020-05-02T10:46:32.414123 | 2019-03-20T19:14:31 | 2019-03-20T19:14:31 | 167,441,978 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 860 | py | #!/usr/bin/env python3
import os
import sys
import argparse
import rpyc
from threading import Thread
from fuse import FUSE
from fuseFunction import FuseOperation
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Distributed file system client")
parser.add_argument('-v','--virtual', required=True, help='Virtual mount point')
parser.add_argument('-r','--real', required=True, help='Physical mount directory')
parser.add_argument('-p','--port', required=True, help='Main server port number.')
parser.add_argument('-a', '--addr', required=False, help='(optional) Main server address, default: localhost')
args = parser.parse_args()
# controller = Controller() # Temply hard code
# Connect main server here
FUSE(FuseOperation(args.real, args.addr, args.port), args.virtual, foreground=True) | [
"chezhou@ucdavis.edu"
] | chezhou@ucdavis.edu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.