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 213
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 246
values | content
stringlengths 2
10.3M
| authors
listlengths 1
1
| author_id
stringlengths 0
212
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b25454882a873e407e6d6bad440f586462000189
|
c00dd2f4873f445dbc4dd0f01447207ce39a2878
|
/build/catkin_generated/order_packages.py
|
78bec3edd0aecd6043957b58f719c003cc969bd9
|
[] |
no_license
|
eataiwo/tommy_bot
|
a2c555e23e256f58e4d585f17641a5f1d671738f
|
f429656ed37415ac308e2ac15305bd8c72038cf0
|
refs/heads/master
| 2023-03-20T07:42:26.395342
| 2020-06-17T18:47:43
| 2020-06-17T18:47:43
| 273,044,446
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 385
|
py
|
# generated from catkin/cmake/template/order_packages.context.py.in
source_root_dir = '/home/pi/Github/Dexter_ROS/src'
whitelisted_packages = ''.split(';') if '' != '' else []
blacklisted_packages = ''.split(';') if '' != '' else []
underlay_workspaces = '/home/pi/Github/Dexter_ROS/devel;/opt/ros/noetic'.split(';') if '/home/pi/Github/Dexter_ROS/devel;/opt/ros/noetic' != '' else []
|
[
"t_taiwo@live.co.uk"
] |
t_taiwo@live.co.uk
|
134036bdd8ddfbd74afe5b7e1a657dfad7a57485
|
6df0d7a677129e9b325d4fdb4bbf72d512dd08b2
|
/PycharmProjects/my_python_v04/day12/m1.py
|
5a12ef3a487f579861fb99c81884f9b8d41bc8b2
|
[] |
no_license
|
yingxingtianxia/python
|
01265a37136f2ad73fdd142f72d70f7c962e0241
|
3e1a7617a4b6552bce4a7e15a182f30e1bae221e
|
refs/heads/master
| 2021-06-14T15:48:00.939472
| 2019-12-13T05:57:36
| 2019-12-13T05:57:36
| 152,200,507
| 0
| 0
| null | 2021-06-10T20:54:26
| 2018-10-09T06:40:10
|
Python
|
UTF-8
|
Python
| false
| false
| 468
|
py
|
#!/usr/bin/env python3
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP
message = MIMEText('Python test mail\r\n', 'plain', 'utf8')
message['From'] = Header('ljy', 'utf8')
message['To'] = Header('root', 'utf8')
message['Subject'] = Header('Test mail', 'utf8')
sender = 'ljy@tedu.cn'
receivers = ['root@localhost', 'zhangsan@localhost']
smtp = SMTP('192.168.4.11', 25)
smtp.sendmail(sender, receivers, message.as_string())
|
[
"903511044@qq.com"
] |
903511044@qq.com
|
a516870e93d89ca334c3ee99f38c49e041fa3a73
|
f210ccc90f9e091f10639f071c4e460fa4dafec1
|
/src/helper/get_delta_t_in_image_space.py
|
15883b83bbdb82e4ae0f65bc8dd2c79f96d54f3a
|
[
"MIT"
] |
permissive
|
qingchenkanlu/FlowPose6D
|
e21974bbbc73db8934e387943a002d009ac0b16f
|
2297ab5fa0afd0c247d59c2f1c7f899f078e2893
|
refs/heads/master
| 2023-01-20T13:43:59.737784
| 2020-11-22T10:52:23
| 2020-11-22T10:52:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,879
|
py
|
import torch
def get_delta_t_in_image_space(t_tar, t_src, fx, fy):
"""
only works for positive z values !
DeepIM equation 3
Inputs: target translation bs * [x,y,z]
source translation bs * [x,y,z]
fx bs * fx
fx bs * fy
Outputs: v_x v_y v_z
"""
v_x = (fx[:, 0] * (torch.true_divide(t_tar[:, 0], t_tar[:, 2]
) - torch.true_divide(t_src[:, 0], t_src[:, 2])))
v_y = (fy[:, 0] * (torch.true_divide(t_tar[:, 1], t_tar[:, 2]
) - torch.true_divide(t_src[:, 1], t_src[:, 2])))
print('log in', )
v_z = torch.true_divide(t_src[:, 2], t_tar[:, 2])
if torch.min(v_z) < 0:
print('Error negative number in log take abs but check input')
v_z = torch.abs(v_z)
v_z = torch.log(v_z)
return torch.stack([v_x, v_y, v_z], dim=1)
def get_delta_t_in_euclidean(v, t_src, fx, fy, device):
""" convert inital object pose and predicted image coordinates to euclidean translation
only works for positive z values !
Args:
v (torch.Tensor): bs x [x,y,z]
t_src (torch.Tensor): inital object position bs * [x,y,z]
fx (torch.Tensor): bs * fx
fy (torch.Tensor): bs * fy
Returns:
torch.Tensor: target object position bs * [x,y,z]
"""
# alternative implementation override t_src for intrinisc runtime capable or pass input tensor into function
t_pred_tar = torch.zeros(t_src.shape, device=device)
t_pred_tar[:, 2] = torch.div(
t_src.clone()[:, 2], torch.exp(v[:, 2]))
t_pred_tar[:, 0] = (torch.div(v.clone()[:, 0], fx.clone()[:, 0]) +
torch.div(t_src.clone()[:, 0], t_src.clone()[:, 2])) * t_pred_tar.clone()[:, 2]
t_pred_tar[:, 1] = (torch.div(v.clone()[:, 1], fy.clone()[:, 0]) +
torch.div(t_src.clone()[:, 1], t_src.clone()[:, 2])) * t_pred_tar.clone()[:, 2]
return t_pred_tar
if __name__ == "__main__":
# batch test
t_tar = torch.ones((100, 3))
t_src = torch.ones((100, 3))
fx = torch.ones((100, 1))
fy = torch.ones((100, 1))
v = get_delta_t_in_image_space(t_tar, t_src, fx, fy)
fx = torch.tensor([[1122.4123]], dtype=torch.float32)
fy = torch.tensor([[8813.123123]], dtype=torch.float32)
print('Test from global to image')
# sense checking
t_tar = torch.tensor([[0, 0, 1]], dtype=torch.float32)
t_src = torch.tensor([[0, 0, 1]], dtype=torch.float32)
v = get_delta_t_in_image_space(t_tar, t_src, fx, fy)
print('print not moveing', v)
t_src = torch.tensor([[0.1, 0, 1]], dtype=torch.float32)
v = get_delta_t_in_image_space(t_tar, t_src, fx, fy)
print('print move up', v)
t_src = torch.tensor([[-0.1, 0, 1]], dtype=torch.float32)
v = get_delta_t_in_image_space(t_tar, t_src, fx, fy)
print('print move down', v)
t_src = torch.tensor([[0, -0.1, 1]], dtype=torch.float32)
v = get_delta_t_in_image_space(t_tar, t_src, fx, fy)
print('print move left', v)
t_src = torch.tensor([[0, 0.1, 1]], dtype=torch.float32)
v = get_delta_t_in_image_space(t_tar, t_src, fx, fy)
print('print move right', v)
t_src = torch.tensor([[0.1, 0, 1.1]], dtype=torch.float32)
v = get_delta_t_in_image_space(t_tar, t_src, fx, fy)
print('print move up+ back', v)
t_src = torch.tensor([[-0.1, 0, 1.1]], dtype=torch.float32)
v = get_delta_t_in_image_space(t_tar, t_src, fx, fy)
print('print move down+ back', v)
t_src = torch.tensor([[0, -0.1, 1.1]], dtype=torch.float32)
v = get_delta_t_in_image_space(t_tar, t_src, fx, fy)
print('print move left+ back', v)
t_src = torch.tensor([[0, 0.1, 1.1]], dtype=torch.float32)
v = get_delta_t_in_image_space(t_tar, t_src, fx, fy)
print('print move right+ back', v)
# looks good to me. Maybe add some testing with real camera and images from object in different poses
print('Test image to global')
t_src = torch.tensor([[0.56, 0.12, 1.12]], dtype=torch.float32)
t_tar = torch.tensor([[0.99, .312, 0.127]], dtype=torch.float32)
v = get_delta_t_in_image_space(t_tar, t_src, fx, fy)
t_pred_tar = get_delta_t_in_euclidean(v, t_src, fx, fy)
print(f'input tar {t_tar}, output {t_pred_tar}')
bs = 100
t_src = torch.normal(mean=torch.zeros((bs, 3)), std=torch.ones((bs, 3)))
t_tar = torch.normal(mean=torch.zeros((bs, 3)), std=torch.ones((bs, 3)))
t_src[:, 2] = torch.abs(t_src[:, 2])
t_tar[:, 2] = torch.abs(t_tar[:, 2])
v = get_delta_t_in_image_space(
t_tar, t_src, fx.repeat((bs, 1)), fy.repeat((bs, 1)))
t_pred_tar = get_delta_t_in_euclidean(
v, t_src, fx.repeat((bs, 1)), fy.repeat((bs, 1)))
print('average error converting back and forward:',
torch.sum(t_tar - t_pred_tar, dim=0) / bs)
|
[
"frey.breitenbrunn@gmx.de"
] |
frey.breitenbrunn@gmx.de
|
baf23cf4353edab2fb5d498006315175e6785f2c
|
777cf9cb9a79a2510e4379ba08260714da00657f
|
/segmfriends/utils/various.py
|
63d84254dca0f2fc6c765379e2d3f09e4ef01900
|
[] |
no_license
|
abailoni/segmfriends
|
dbea3fd96d62a0f27687b9d87a93c07d656b58e4
|
d3919b48e45363735c696266f8890a9f5537ef1a
|
refs/heads/master
| 2022-04-30T19:43:45.771209
| 2022-03-25T10:13:06
| 2022-03-25T10:13:06
| 159,837,614
| 1
| 3
| null | 2021-04-29T14:56:17
| 2018-11-30T14:50:29
|
Python
|
UTF-8
|
Python
| false
| false
| 9,655
|
py
|
import numpy as np
import yaml
from itertools import repeat
import os
import h5py
import vigra
from scipy.ndimage import zoom
try:
import cremi
from cremi.evaluation import NeuronIds
from cremi import Volume
except ImportError:
cremi = None
def starmap_with_kwargs(pool, fn, args_iter, kwargs_iter):
"""
Wrapper around pool.starmap accepting args_iter and kwargs_iter. Example of usage:
args_iter = zip(repeat(project_name), api_extensions)
kwargs_iter = repeat(dict(payload={'a': 1}, key=True))
branches = starmap_with_kwargs(pool, fetch_api, args_iter, kwargs_iter)
"""
args_for_starmap = zip(repeat(fn), args_iter, kwargs_iter)
return pool.starmap(apply_args_and_kwargs, args_for_starmap)
def apply_args_and_kwargs(fn, args, kwargs):
return fn(*args, **kwargs)
def search_sorted(array, keys_to_search):
"""
Return the indices of the keys in array. If not found than the indices are masked.
"""
index = np.argsort(array)
sorted_x = array[index]
sorted_index = np.searchsorted(sorted_x, keys_to_search)
yindex = np.take(index, sorted_index, mode="clip")
mask = array[yindex] != keys_to_search
return np.ma.array(yindex, mask=mask)
def cantor_pairing_fct(int1, int2):
"""
Remarks:
- int1 and int2 should be positive (or zero), otherwise use f(n) = n * 2 if n >= 0; f(n) = -n * 2 - 1 if n < 0
- int1<=int2 to assure that cantor_pairing_fct(int1, int2)==cantor_pairing_fct(int2, int1)
It returns an unique integer associated to (int1, int2).
"""
return np.floor_divide((int1 + int2) * (int1 + int2 + 1), np.array(2, dtype='uint64')) + int2
# return (int1 + int2) * (int1 + int2 + 1) / 2 + int2
# @njit
def find_first_index(array, item):
for idx, val in np.ndenumerate(array):
if val == item:
return idx
return None
def parse_data_slice(data_slice):
"""Parse a dataslice as a list of slice objects."""
if data_slice is None:
return data_slice
elif isinstance(data_slice, (list, tuple)) and \
all([isinstance(_slice, slice) for _slice in data_slice]):
return list(data_slice)
else:
assert isinstance(data_slice, str)
# Get rid of whitespace
data_slice = data_slice.replace(' ', '')
# Split by commas
dim_slices = data_slice.split(',')
# Build slice objects
slices = []
for dim_slice in dim_slices:
indices = dim_slice.split(':')
if len(indices) == 2:
start, stop, step = indices[0], indices[1], None
elif len(indices) == 3:
start, stop, step = indices
else:
raise RuntimeError
# Convert to ints
start = int(start) if start != '' else None
stop = int(stop) if stop != '' else None
step = int(step) if step is not None and step != '' else None
# Build slices
slices.append(slice(start, stop, step))
# Done.
return tuple(slices)
# Yaml to dict reader
def yaml2dict(path):
if isinstance(path, dict):
# Forgivable mistake that path is a dict already
return path
with open(path, 'r') as f:
readict = yaml.load(f, Loader=yaml.FullLoader)
return readict
def check_dir_and_create(directory):
'''
if the directory does not exist, create it
'''
folder_exists = os.path.exists(directory)
if not folder_exists:
os.makedirs(directory)
return folder_exists
def compute_output_size_transp_conv(input_size,
padding=0,
stride=1,
dilation=1,
kernel_size=3):
return int((input_size-1)*stride -2*padding + dilation*(kernel_size-1) + 1)
def compute_output_size_conv(input_size,
padding=0,
stride=1,
dilation=1,
kernel_size=3):
return int((input_size + 2*padding - dilation * (kernel_size - 1) - 1) / stride + 1)
def readHDF5(path,
inner_path,
crop_slice=None,
dtype=None,
ds_factor=None,
ds_order=3,
run_connected_components=False,
):
if isinstance(crop_slice, str):
crop_slice = parse_data_slice(crop_slice)
elif crop_slice is not None:
assert isinstance(crop_slice, tuple), "Crop slice not recognized"
assert all([isinstance(sl, slice) for sl in crop_slice]), "Crop slice not recognized"
else:
crop_slice = slice(None)
with h5py.File(path, 'r') as f:
output = f[inner_path][crop_slice]
if run_connected_components:
assert output.dtype in [np.dtype("uint32")]
assert output.ndim == 3 or output.ndim == 2
output = vigra.analysis.labelVolumeWithBackground(output.astype('uint32'))
if dtype is not None:
output = output.astype(dtype)
if ds_factor is not None:
assert isinstance(ds_factor, (list, tuple))
assert output.ndim == len(ds_factor)
output = zoom(output, tuple(1./fct for fct in ds_factor), order=ds_order)
return output
def readHDF5_from_volume_config(
sample,
path,
inner_path,
crop_slice=None,
dtype=None,
ds_factor=None,
ds_order=3,
run_connected_components=False,
):
if isinstance(path, dict):
if sample not in path:
sample = eval(sample)
assert sample in path
path = path[sample] if isinstance(path, dict) else path
inner_path = inner_path[sample] if isinstance(inner_path, dict) else inner_path
crop_slice = crop_slice[sample] if isinstance(crop_slice, dict) else crop_slice
dtype = dtype[sample] if isinstance(dtype, dict) else dtype
return readHDF5(path, inner_path, crop_slice, dtype, ds_factor, ds_order, run_connected_components)
def writeHDF5(data, path, inner_path, compression='gzip'):
if os.path.exists(path):
write_mode = 'r+'
else:
write_mode = 'w'
with h5py.File(path, write_mode) as f:
if inner_path in f:
del f[inner_path]
f.create_dataset(inner_path, data=data, compression=compression)
def writeHDF5attribute(attribute_data, attriribute_name, file_path, inner_path_dataset):
if os.path.exists(file_path):
write_mode = 'r+'
else:
write_mode = 'w'
with h5py.File(file_path, write_mode) as f:
assert inner_path_dataset in f, "Dataset not present in file"
dataset = f[inner_path_dataset]
dataset.attrs.create(attriribute_name, attribute_data)
def get_hdf5_inner_paths(path, inner_path=None):
with h5py.File(path, 'r') as f:
if inner_path is None:
datasets = [dt for dt in f]
else:
datasets = [dt for dt in f[inner_path]]
return datasets
def cremi_score(gt, seg, return_all_scores=False, border_threshold=None,
run_connected_components=True):
if cremi is None:
raise ImportError("The cremi package is necessary to run cremi_score()")
# # the zeros must be kept in the gt since they are the ignore label
if run_connected_components:
gt = vigra.analysis.labelVolumeWithBackground(gt.astype(np.uint32))
seg = vigra.analysis.labelVolume(seg.astype(np.uint32))
seg = np.array(seg)
seg = np.require(seg, requirements=['C'])
# Make sure that all labels are strictly positive:
seg = seg.astype('uint32')
# FIXME: it seems to have some trouble with label 0 in the segmentation:
seg += 1
gt = np.array(gt)
gt = np.require(gt, requirements=['C'])
gt = (gt - 1).astype('uint32')
# assert gt.min() >= -1
gt_ = Volume(gt)
seg_ = Volume(seg)
metrics = NeuronIds(gt_, border_threshold=border_threshold)
arand = metrics.adapted_rand(seg_)
vi_s, vi_m = metrics.voi(seg_)
cs = np.sqrt(arand * (vi_s + vi_m))
# cs = (vi_s + vi_m + arand) / 3.
if return_all_scores:
return {'cremi-score': cs.item(), 'vi-merge': vi_m.item(), 'vi-split': vi_s.item(), 'adapted-rand': arand.item()}
else:
return cs
def memory_usage_psutil():
# return the memory usage in MB
import psutil
process = psutil.Process(os.getpid())
mem = process.memory_info()[0] / float(2 ** 20)
return mem
def make_dimensions_even(array):
"""Make sure that the dimensions are even"""
# TODO: generalize to general factors
for d, shp in enumerate(array.shape):
if shp % 2 != 0:
array = array[tuple(slice(0, -1 if i == d else None) for i in range(array.ndim))]
return array
def convert_array_from_float_to_uint(float_array, convert_to="uint16", rescale=False):
"""
By default, it requires values between 0 and 1. Otherwise it rescales both max and min to fit all
interval.
UInt16: from 0 to 65535
UInt32: from 0 to 4294967295
"""
if not rescale:
assert np.all(np.logical_and(float_array < 1.0, float_array > 0.))
else:
# Shift to zero:
min_array = float_array.min()
float_array -= min_array
# Normalize between 0 and 1:
max_array = float_array.max()
float_array /= max_array
if convert_to == "uint16":
max_uint = 65535
elif convert_to == "uint32":
max_uint = 4294967295
elif convert_to == "uint8":
max_uint = 255
else:
raise ValueError()
return (float_array * max_uint).astype(convert_to)
|
[
"bailoni.alberto@gmail.com"
] |
bailoni.alberto@gmail.com
|
c64012c61e5913f1f1d055db79ab4dbdcc8dfa3d
|
1b073f0e1e9ae3dfd218ad8d6b47a1dbe09362f3
|
/067.py
|
7c427ba3b4c428ea97c1b9e5f512f92bc6922467
|
[] |
no_license
|
dniku/project-euler
|
88e5fee191c35a1ac4ebc144c534c4aa59d24cb5
|
3156bd5c97c68249fb7235f8a0de326f6dd77365
|
refs/heads/master
| 2021-05-27T10:03:28.990822
| 2012-07-09T09:18:47
| 2012-07-09T09:18:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 303
|
py
|
s = open("067_triangle.txt", 'r').read()[:-1]
rows = s.split('\n')
arr = [map(int, row.split(' ')) for row in rows]
for i, row in enumerate(arr[1:]):
row[0] += arr[i][0]
row[-1] += arr[i][-1]
for j, val in enumerate(row[1:-1]):
row[j + 1] += max(arr[i][j], arr[i][j + 1])
print max(arr[-1])
|
[
"mr.pastafarianist@gmail.com"
] |
mr.pastafarianist@gmail.com
|
cea2e37800493b6df5d0fb7e0a0bf1c897580191
|
91085e175a60bc738bd9b614c99f0d8d15fb07cc
|
/class2.py
|
980eea494d8e91bb49d72d11a21540f7a3c44555
|
[] |
no_license
|
kumargaurav12/Python
|
1f5f8f748dbadf227025b8cbd7e30fd73660d99e
|
3f1304fd14e77536ec2ac6fa684d996d1e3362bf
|
refs/heads/master
| 2020-01-22T16:22:09.716431
| 2015-09-05T08:30:06
| 2015-09-05T08:30:06
| 37,358,913
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 632
|
py
|
#class Github(Object):
# def __init__(self,members):
# self.members =members
# self.code=code
#class Dinesh-sunny(Github):
# def __init__():
# super(Github.__init__())
#tuple is use for referece and update the value in a list.
print("-----------enemy class example-----------")
class Enemy:
life=3
def attack(self):
print("OOPs....")
self.life -=1
def checkLife(self):
if self.life<=0:
print("You are dead.")
else:
print(str(self.life)+ " left life")
enemy1=Enemy()
enemy1.attack()
enemy1.checkLife()
enemy2=Enemy()
enemy2.attack()
enemy2.checkLife()
enemy3=Enemy()
enemy3.attack()
enemy3.checkLife()
|
[
"kumargaurav2525@gmail.com"
] |
kumargaurav2525@gmail.com
|
7cd56a7929e474f131d4e29aa253a2090362b050
|
ffd583a7ae88ba510e02f8f5141506ec6d2071fd
|
/test/functional/test_framework/bignum.py
|
da965b9cf299b81cc6d36db343c960514f966147
|
[
"MIT"
] |
permissive
|
Coleganet/Clearcore-Project
|
37f90a797c8098c76f538f30125ce797fba9ebba
|
e1878cdff32ad14509c0950edf4cd428883e966b
|
refs/heads/master
| 2023-03-31T15:11:33.061970
| 2021-04-06T00:16:21
| 2021-04-06T00:16:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,910
|
py
|
#!/usr/bin/env python3
#
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Big number routines.
This file is copied from python-bitcoinlib.
"""
import struct
# generic big endian MPI format
def bn_bytes(v, have_ext=False):
ext = 0
if have_ext:
ext = 1
return ((v.bit_length()+7)//8) + ext
def bn2bin(v):
s = bytearray()
i = bn_bytes(v)
while i > 0:
s.append((v >> ((i-1) * 8)) & 0xff)
i -= 1
return s
def bin2bn(s):
l = 0
for ch in s:
l = (l << 8) | ch
return l
def bn2mpi(v):
have_ext = False
if v.bit_length() > 0:
have_ext = (v.bit_length() & 0x07) == 0
neg = False
if v < 0:
neg = True
v = -v
s = struct.pack(b">I", bn_bytes(v, have_ext))
ext = bytearray()
if have_ext:
ext.append(0)
v_bin = bn2bin(v)
if neg:
if have_ext:
ext[0] |= 0x80
else:
v_bin[0] |= 0x80
return s + ext + v_bin
def mpi2bn(s):
if len(s) < 4:
return None
s_size = bytes(s[:4])
v_len = struct.unpack(b">I", s_size)[0]
if len(s) != (v_len + 4):
return None
if v_len == 0:
return 0
v_str = bytearray(s[4:])
neg = False
i = v_str[0]
if i & 0x80:
neg = True
i &= ~0x80
v_str[0] = i
v = bin2bn(v_str)
if neg:
return -v
return v
# clr-specific little endian format, with implicit size
def mpi2vch(s):
r = s[4:] # strip size
r = r[::-1] # reverse string, converting BE->LE
return r
def bn2vch(v):
return bytes(mpi2vch(bn2mpi(v)))
def vch2mpi(s):
r = struct.pack(b">I", len(s)) # size
r += s[::-1] # reverse string, converting LE->BE
return r
def vch2bn(s):
return mpi2bn(vch2mpi(s))
|
[
"52296308+ClearNode@users.noreply.github.com"
] |
52296308+ClearNode@users.noreply.github.com
|
0ee116e9921ce9f47856f7cbe417f22360077a16
|
39abd3432a179a91473575d439e8cbe88db688a6
|
/test1/booktext/migrations/0001_initial.py
|
d4fd9519ca23b3e5fa382fcd1a4ce4ed360881c2
|
[] |
no_license
|
susky-zx/my-first-blog
|
3fd31e3d4e8693c968e8fa9ef891ab67abe6960e
|
c4e3d38654cba997ba42620ca15085b280662935
|
refs/heads/master
| 2023-03-18T12:52:52.156382
| 2021-03-04T10:22:53
| 2021-03-04T10:22:53
| 344,435,144
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 540
|
py
|
# Generated by Django 3.1.4 on 2021-01-26 06:42
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='BookInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('btitle', models.CharField(max_length=20)),
('bpub_date', models.DateField()),
],
),
]
|
[
"1348739561@qq.com"
] |
1348739561@qq.com
|
fa01aa6a1f850b5aa944195cf0c01c5eebb6bdd1
|
f85db9f20bbf99947681ec97083071dac79bddd8
|
/accounts/signals.py
|
a3d441e13ce2551b002721055883ca3898d15f0f
|
[] |
no_license
|
alxayeed/customer-management
|
c34247691d21d1ba18e9a2d54c2f810afc1546d5
|
23a18bcaa7ce1d5899bbb6a66b761c2c0abdd26e
|
refs/heads/master
| 2023-01-07T05:28:40.087220
| 2020-11-12T06:55:45
| 2020-11-12T06:55:45
| 280,801,654
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 536
|
py
|
from django.db.models.signals import post_save
from django.contrib.auth.models import User, Group
from .models import Customer
def customer_profile(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name='customer')
instance.groups.add(group)
# group.user_set(user) does the same thing
Customer.objects.create(
user=instance,
name= instance.username,
)
print('Profile is created')
post_save.connect(customer_profile,sender=User)
|
[
"alxayeed@gmail.com"
] |
alxayeed@gmail.com
|
fc46bf869b737429bb4275d39d72bd91ae474645
|
9970c423a0a63eb3657a5b3321057f1567c46102
|
/API/common/services/file_search/localfiles.py
|
55b79961c3694fcc63d4daf9a1e67de01545f0ef
|
[] |
no_license
|
HeainLee/Analytics-Module-DL
|
688107a1c985c66c5275962ba95b7db2d916cad1
|
9ba3447727883e8cd23049494b9a3f3b384b5c9a
|
refs/heads/master
| 2022-09-04T06:52:30.237167
| 2020-06-01T08:26:53
| 2020-06-01T08:26:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,037
|
py
|
# API/common/services/file_search.py
import os
import csv
import json
from shutil import rmtree
from datetime import datetime
from collections import OrderedDict
class InvalidPathContainedError(Exception):
def __str__(self):
return "Path couldn't contain " + "../ character"
class NotSupportedFileTypeError(Exception):
def __str__(self):
return "Supported File Type is only " + "json or csv"
class NotSupporteCommandError(Exception):
def __str__(self):
return "Command is failed"
class Localfiles:
def __init__(self):
self.sample_num = 5
def convert_date(self, timestamp):
date_obj = datetime.fromtimestamp(timestamp)
return date_obj
def case_get(self, case, path):
if path is None or "../" in path:
raise InvalidPathContainedError()
case_name = "case_" + str(case)
selected_function = getattr(self, case_name)
return selected_function(path)
def case_get_list(self, path):
file_list = [
file_name
for file_name in os.listdir(path)
if os.path.isfile(os.path.join(path, file_name))
and not file_name.startswith(".")
]
dir_list = [
dir_name
for dir_name in os.listdir(path)
if not os.path.isfile(os.path.join(path, dir_name))
and not dir_name.startswith(".")
]
return file_list, dir_list
def case_get_info(self, path):
mtime = self.convert_date(os.path.getmtime(path))
ctime = self.convert_date(os.path.getctime(path))
stsize = os.path.getsize(path)
return mtime, ctime, stsize
def case_get_sample(self, path):
if not (path.endswith(".json") or path.endswith(".csv")):
raise NotSupportedFileTypeError()
limit = self.sample_num
samples = []
if path.endswith(".json"):
with open(path) as f:
while True:
limit = limit - 1
line = f.readline()
if limit < 0 or not line:
break
samples.append(json.loads(line))
elif path.endswith(".csv"):
with open(path) as f:
line = csv.DictReader(f)
for row in line:
limit = limit - 1
if limit < 0 or not row:
break
get_row = json.dumps(row)
samples.append(json.loads(get_row))
return samples
def case_delete(self, path):
if os.path.isfile(path):
os.remove(path)
elif not os.path.isfile(path):
os.rmdir(path)
# rmtree(path) -> 기본은 폴더만 지울 수 있도록 처리하였으며,
# 재귀적으로 파일을 지우고 싶을 시 os.rmdir(path) 대신 rmtree(path)를 지움
def case_default(self, path):
raise NotSupporteCommandError
|
[
"hilee@daumsoft.com"
] |
hilee@daumsoft.com
|
1a51015987bc9abfc6de029b2d85adab52f247f4
|
c23238c0ad3ed362094505fdf35b57f26b256dfd
|
/operations/remove_virtual_router.py
|
b9521a4c02f65db8c7638c93601a5e6a76c42c21
|
[] |
no_license
|
JonathanArrance/OpenHCI
|
e6f80c3cfe140995b13bab797339212715f88159
|
94718f797f5a48ab2427dc230ff8a141cd8798b7
|
refs/heads/master
| 2021-01-23T15:57:24.697550
| 2018-07-15T20:01:45
| 2018-07-15T20:01:45
| 93,273,256
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,512
|
py
|
#!/usr/local/bin/python2.7
from fnmatch import fnmatch
from vpn_manager import delete_vpn_tunnel
import transcirrus.common.config as config
import transcirrus.common.util as util
import transcirrus.common.logger as logger
from transcirrus.component.neutron.layer_three import layer_three_ops
from transcirrus.component.neutron.vpn import vpn_ops
def remove_virt_router(auth_dict, input_dict):
"""
DESC: List the routers that are present in a project.
INPUT: input_dict - project_id
- router_id
auth_dict - authentication
OUTPUT: 'OK' - success
'ERROR' - fail
ACCESS: Admins can remove a router from any project, power users can only remove a router from their own project.
If any networks are attached an error will occure.
NOTE: none
"""
vo = vpn_ops(auth_dict)
lto = layer_three_ops(auth_dict)
#list the vpn tunnels in the project and find the ones attached to the router in question.
tunnels = vo.list_vpn_service(input_dict['project_id'])
if(len(tunnels['vpnservices']) >= 1):
for tunnel in tunnels['vpnservices']:
logger.sys_info('Deleting vpn tunnel %s'%(tunnel['id']))
if(tunnel['router_id'] == input_dict['router_id']):
delete_vpn_tunnel(auth_dict, input_dict['project_id'], tunnel['id'])
else:
logger.sys_info('No VPNaaS tunnels present.')
#remove the router
del_router = lto.delete_router(input_dict)
return del_router
|
[
"jonathan@transcirrus.com"
] |
jonathan@transcirrus.com
|
ea03199790d8cd02e3936392cbda8aeef3183cef
|
6e2041ba71caca8a823f3218d90cf21931d06865
|
/tests/test_graphvalues.py
|
3d93a5382f1974b90bf530c922430aff65803f40
|
[] |
no_license
|
Adeakim/web-scrapping
|
45ac6168df92822b7de27553ad62491de73d16d6
|
fa7f07b9ac32bb332df82c2ed07c9a27742cc980
|
refs/heads/main
| 2023-06-28T00:05:46.344913
| 2021-07-25T19:38:34
| 2021-07-25T19:38:34
| 389,426,583
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 114
|
py
|
import unittest
from graphvalues import GetGraphValues
class TestGetGraphValues(unittest.TestCase):
def test_
|
[
"decagon@Decagons-MacBook-Air.local"
] |
decagon@Decagons-MacBook-Air.local
|
53bf641f8a1a818bc927588c5e872a076f7e5c2e
|
394fad0dbb422a2996a3fe50b204338b665d8efd
|
/SGD_classifier.py
|
e635cd21b524be02e08e07b5f081ada2c128b064
|
[] |
no_license
|
strategist922/semEval_Task6_Text_Classification
|
32b0405a6b5cf9aa9fc0919592034f1228ed96ff
|
190d5340284b56e3dcae0bd0665538fe54c28dfb
|
refs/heads/master
| 2020-12-05T23:42:00.384463
| 2019-01-17T20:35:28
| 2019-01-17T20:35:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 317
|
py
|
from sklearn.linear_model import SGDClassifier
import numpy as np
def run(train,test,train_labels,test_labels):
sgd_clf = SGDClassifier(random_state=42,max_iter=1000)
sgd_clf.fit(train, train_labels)
p = sgd_clf.predict(test)
print("Stochastic gradient Descent Score : " ,np.mean(p == test_labels))
|
[
"ahmed.morsy1995@gmail.com"
] |
ahmed.morsy1995@gmail.com
|
8dda90afd4adbb6f1326ca5640bb4ccd347c9d8a
|
7ce56dc3a1110b61d0087565f02b4fe576cad58c
|
/lintcode/flattern_list/test.py
|
7817e8f9e3b9fceba772382267b95e57ae19297e
|
[] |
no_license
|
lssxfy123/PythonStudy
|
7c251961ce72217e83184853cb0c11dc773e4075
|
d5beba373b78c6c0276c413a44819d3084899d01
|
refs/heads/master
| 2022-11-28T17:25:36.957483
| 2021-11-26T09:55:32
| 2021-11-26T09:55:32
| 55,392,700
| 1
| 1
| null | 2022-11-22T01:39:12
| 2016-04-04T07:28:25
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 1,096
|
py
|
# Copyright(C) 2018 刘珅珅
# Environment: python 3.6.4
# Date: 2018.9.2
# lintcode:平面列表
import copy
def flatten(nestedList):
result = []
flag = False
while True:
for item in nestedList:
if isinstance(item, list):
flag = True
for child in item:
result.append(child)
else:
result.append(item)
if flag:
nestedList = copy.deepcopy(result)
result.clear()
flag = False
else:
return result
def flatten1(nestedList):
stack = [nestedList]
flatten_list = []
while stack:
top = stack.pop() # 移除最后一个元素
if isinstance(top, list):
for elem in reversed(top): # 反向遍历
stack.append(elem)
else:
flatten_list.append(top)
return flatten_list
if __name__ == '__main__':
nested_list = [1, 2, [1, 2, [1, 3]]]
result = flatten(nested_list)
print(result)
result = flatten1(nested_list)
print(result)
|
[
"liushenshenxfy@126.com"
] |
liushenshenxfy@126.com
|
451da8a8c6f8fb3a4cecebd145d5d6924c521ae7
|
a9e3f3ad54ade49c19973707d2beb49f64490efd
|
/Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/lib/license/wrapper.py
|
2d1701540820f68a0a9c09f087c53100816a01c2
|
[
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] |
permissive
|
luque/better-ways-of-thinking-about-software
|
8c3dda94e119f0f96edbfe5ba60ca6ec3f5f625d
|
5809eaca7079a15ee56b0b7fcfea425337046c97
|
refs/heads/master
| 2021-11-24T15:10:09.785252
| 2021-11-22T12:14:34
| 2021-11-22T12:14:34
| 163,850,454
| 3
| 1
|
MIT
| 2021-11-22T12:12:31
| 2019-01-02T14:21:30
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 462
|
py
|
"""
Code to wrap web fragments with a license.
"""
def wrap_with_license(block, view, frag, context): # pylint: disable=unused-argument
"""
In the LMS, display the custom license underneath the XBlock.
"""
license = getattr(block, "license", None) # pylint: disable=redefined-builtin
if license:
context = {"license": license}
frag.content += block.runtime.render_template('license_wrapper.html', context)
return frag
|
[
"rafael.luque@osoco.es"
] |
rafael.luque@osoco.es
|
df5a52c759c640fb283245fe58584533b0c81423
|
1953d9b702c61e28cdadcd69133242dfb4811ed2
|
/ants/run_tests.py
|
8aebf6b926225b999294bb6236876b2dbbd447a6
|
[] |
no_license
|
aleksandar-buha/lastmile
|
66c41926e1091ff1415684f5f6542b0e973ff15b
|
881d7b5c7285fcb109de6e3d51da751e7ba8d444
|
refs/heads/master
| 2023-08-03T17:12:05.546299
| 2010-01-07T23:49:55
| 2010-01-07T23:49:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 377
|
py
|
import unittest
from ants.tests.timing import *
from ants.tests.time_window import *
from ants.tests.gmaps import *
from ants.tests.engine import *
from ants.tests.engine_timing import *
from ants.tests.operations import *
from ants.tests.parameters import *
from ants.tests.routemap import *
from ants.tests.rootfinder import *
if __name__ == "__main__":
unittest.main()
|
[
"ekfriis@gmail.com"
] |
ekfriis@gmail.com
|
8d0401c94b30e4da791d9a20e92a17d3078ce03d
|
ed7a9902168b0a5340e1bd293d3fa93cedd73149
|
/libdemo/broken_links.py
|
ee0cc40084eb78d78d513899404abc28addbea36
|
[] |
no_license
|
srikanthpragada/PYTHON_07_SEP_2018_DEMO
|
ec15129de5118d0765dfe920942f78f5b903ab79
|
fe3782186d71a425df5f99f93e398bdc30716808
|
refs/heads/master
| 2020-03-28T10:10:26.637869
| 2018-10-16T03:31:51
| 2018-10-16T03:31:51
| 148,088,136
| 0
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 209
|
py
|
import requests
from bs4 import BeautifulSoup
html = "<html><a href='google.com'>google</a><a href='yahoo.com'>Yhaoo</a><a href='abcbbcxyz.com'>AbcBbcXyz</a>"
bs = BeautifulSoup(html,"html.parser")
|
[
"srikanthpragada@gmail.com"
] |
srikanthpragada@gmail.com
|
7a1f248d4325259473ec6e09daadaa9fb2496f56
|
7e2fdaec0741a79a78df9faec3b36c1a29693d56
|
/tests/test_day_one.py
|
5e3ead31eb745a1dba2653a14aaed7c8fccb0f6b
|
[] |
no_license
|
josefeg/adventofcode2017
|
983e727e34a2cb9aefb8017bb302cee0fce55ff2
|
9cb3a808550e945db13dfdab04f1fadb73dfdd7a
|
refs/heads/master
| 2021-10-01T01:03:11.450596
| 2018-01-14T09:55:28
| 2018-01-14T09:55:28
| 112,820,598
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 453
|
py
|
import src.day_one as day_one
def test_captcha():
assert day_one.captcha("1122") == 3
assert day_one.captcha("1111") == 4
assert day_one.captcha("1234") == 0
assert day_one.captcha("91212129") == 9
def test_captcha2():
assert day_one.captcha2("1212") == 6
assert day_one.captcha2("1221") == 0
assert day_one.captcha2("123425") == 4
assert day_one.captcha2("123123") == 12
assert day_one.captcha2("12131415") == 4
|
[
"josefeg@gmail.com"
] |
josefeg@gmail.com
|
4316a1a4b9807418a4f092d51450337a8dd64ff0
|
52957a949e511a6f445256112a4e0706edb64755
|
/psychsim/test/test_belief_update.py
|
62000134bfa2b71fc83d383a3957cf62b3f9def4
|
[
"MIT"
] |
permissive
|
ualiangzhang/psychsim
|
4bc98a612a01c911d8a2c163a9bf6811a31c985a
|
e615672e4785a54b2d5bc9dae74b743a6f10bd80
|
refs/heads/master
| 2023-01-19T14:15:10.643817
| 2020-11-26T01:20:35
| 2020-11-26T01:20:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,707
|
py
|
from psychsim.action import *
from psychsim.world import *
from psychsim.agent import Agent
from psychsim.pwl import *
from psychsim.reward import *
def setup_world():
# Create world
world = World()
# Create agents
tom = world.addAgent('Tom')
jerry = world.addAgent('Jerry')
return world
def add_state(world):
"""Create state features"""
world.defineState('Tom','health',int,lo=0,hi=100,
description='%s\'s wellbeing' % ('Tom'))
world.setState('Tom','health',50)
world.defineState('Jerry','health',int,lo=0,hi=100,
description='%s\'s wellbeing' % ('Jerry'))
world.setState('Jerry','health',50)
def add_actions(world,order=None):
"""Create actions"""
actions = {}
actions['chase'] = world.agents['Tom'].addAction({'verb': 'chase','object': 'Jerry'})
actions['hit'] = world.agents['Tom'].addAction({'verb': 'hit','object': 'Jerry'})
actions['nop'] = world.agents['Tom'].addAction({'verb': 'doNothing'})
actions['run'] = world.agents['Jerry'].addAction({'verb': 'run away'})
actions['trick'] = world.agents['Jerry'].addAction({'verb': 'trick','object': 'Tom'})
if order is None:
order = ['Tom','Jerry']
world.setOrder(order)
return actions
def add_dynamics(world,actions):
tree = makeTree({'distribution': [(approachMatrix(stateKey('Jerry','health'),0,.1),0.5),
(noChangeMatrix(stateKey('Jerry','health')),0.5)]})
world.setDynamics(stateKey('Jerry','health'),actions['hit'],tree)
tree = makeTree({'distribution': [(approachMatrix(stateKey('Tom','health'),0,.1),0.5),
(noChangeMatrix(stateKey('Tom','health')),0.5)]})
world.setDynamics(stateKey('Tom','health'),actions['hit'],tree)
def add_reward(world):
world.agents['Tom'].setReward(minimizeFeature(stateKey('Jerry','health'),'Tom'),1)
world.agents['Jerry'].setReward(maximizeFeature(stateKey('Jerry','health'),'Jerry'),1)
def add_models(world,rationality=1.):
model = next(iter(world.agents['Tom'].models.keys()))
world.agents['Tom'].addModel('friend',rationality=rationality,parent=model)
world.agents['Tom'].setReward(maximizeFeature(stateKey('Jerry','health'),'Jerry'),1,'friend')
world.agents['Tom'].addModel('foe',rationality=rationality,parent=model)
world.agents['Tom'].setReward(minimizeFeature(stateKey('Jerry','health'),'Jerry'),1,'foe')
def add_beliefs(world):
for agent in world.agents.values():
agent.resetBelief()
agent.omega = [key for key in world.state.keys() if not isModelKey(key) and not isRewardKey(key)]
def test_conjunction():
world = setup_world()
add_state(world)
actions = add_actions(world,['Tom'])
tree = makeTree({'if': thresholdRow(stateKey('Tom','health'),50) + thresholdRow(stateKey('Jerry','health'),50),
True: incrementMatrix(stateKey('Jerry','health'),-5),
False: noChangeMatrix(stateKey('Jerry','health'))})
world.setDynamics(stateKey('Jerry','health'),actions['hit'],tree)
health = [world.getState('Jerry','health',unique=True)]
world.step({'Tom': actions['hit']})
health.append(world.getState('Jerry','health',unique=True))
assert health[-1] == health[-2]
world.setState('Tom','health',51)
world.step({'Tom': actions['hit']})
health.append(world.getState('Jerry','health',unique=True))
assert health[-1] == health[-2]
world.setState('Jerry','health',51)
world.step({'Tom': actions['hit']})
health.append(world.getState('Jerry','health',unique=True))
assert health[-1] < health[-2]
def test_greater_than():
world = setup_world()
add_state(world)
actions = add_actions(world,['Tom'])
tree = makeTree({'if': thresholdRow(stateKey('Tom','health'),50),
True: incrementMatrix(stateKey('Jerry','health'),-5),
False: noChangeMatrix(stateKey('Jerry','health'))})
world.setDynamics(stateKey('Jerry','health'),actions['hit'],tree)
health = [world.getState('Jerry','health',unique=True)]
world.step({'Tom': actions['hit']})
health.append(world.getState('Jerry','health',unique=True))
assert health[-1] == health[-2]
world.setState('Tom','health',51)
world.step({'Tom': actions['hit']})
health.append(world.getState('Jerry','health',unique=True))
assert health[-1] < health[-2]
def dont_test_belief_update():
world = setup_world()
add_state(world)
actions = add_actions(world)
add_dynamics(world,actions)
add_reward(world)
add_beliefs(world)
add_models(world)
world.setMentalModel('Jerry','Tom',Distribution({'friend': 0.5,'foe': 0.5}))
world.step()
|
[
"david@pynadath.net"
] |
david@pynadath.net
|
c681972158638d22b8c388f1e98373a5d3201772
|
c11e28a535e50143dc4a3c4d82c3a8a2fc6d7ff5
|
/redirect/migrations/0004_auto_20201006_2247.py
|
30c7ff5b1e822013d520752a6a5c401914667923
|
[
"MIT"
] |
permissive
|
UWCS/uwcs-go
|
a493db01ff765185f4af379aef8191c742e2242c
|
3b74ee0457ba3b7c16f543f643599da17e52d995
|
refs/heads/main
| 2023-08-25T16:41:29.909202
| 2021-10-31T20:58:18
| 2021-10-31T20:58:18
| 301,833,077
| 0
| 1
|
MIT
| 2021-10-31T20:58:19
| 2020-10-06T19:26:19
|
Python
|
UTF-8
|
Python
| false
| false
| 548
|
py
|
# Generated by Django 2.2.16 on 2020-10-06 22:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('redirect', '0003_auto_20201006_1914'),
]
operations = [
migrations.AddField(
model_name='redirect',
name='usages',
field=models.PositiveIntegerField(default=0),
),
migrations.AlterField(
model_name='redirect',
name='sink',
field=models.URLField(max_length=250),
),
]
|
[
"44057980+the-Bruce@users.noreply.github.com"
] |
44057980+the-Bruce@users.noreply.github.com
|
12a39c80682008c88fe009157dcfff3354498887
|
309a85ce4d7bf6dd560334ec4774ecd88911f428
|
/src/SEIRcity/simulate/legacy.py
|
62d35a2e2d880022b1d07c0fbd385eb2d95f827e
|
[
"BSD-3-Clause-Clear"
] |
permissive
|
UT-Covid/compartmental_model_case_studies
|
c276e6b8b9bd552634409e70c70c55abf43f3184
|
324e2c92453c928e64c637d6e6fbe570fb714cdb
|
refs/heads/master
| 2023-01-08T16:59:14.655952
| 2020-11-08T19:12:24
| 2020-11-08T19:12:24
| 310,721,801
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 11,251
|
py
|
#!/usr/bin/env python
import os
import sys
import numpy as np
import pickle
import datetime as dt
from SEIRcity.scenario import BaseScenario as Scenario
from SEIRcity.get_scenarios import get_scenarios
from .simulate_one import simulate_one
from SEIRcity import param_parser
from SEIRcity import param as param_module
from SEIRcity import model, utils
# DEV
from SEIRcity import dev_utils
def school_date_from_arr(arr, interval_per_day, time_begin_sim, shift_week):
"""Converts school event dates from boolean arrays to time index
at which the event occurred. Used only for pytests.
"""
# for 2D currently
t_slice = arr[:, 0]
assert len(t_slice.shape) == 1, t_slice.shape
try:
time_idx = np.where(t_slice == 1.)[0][0]
time_idx = float(time_idx)
assert isinstance(time_idx, float), time_idx
except KeyError:
# legacy result
return "NA"
print("time_idx: ", time_idx)
# convert to datetime
date_begin = dt.datetime.strptime(np.str(time_begin_sim), '%Y%m%d') + \
dt.timedelta(weeks=shift_week)
days_from_t0 = np.floor((time_idx + 0.1) / interval_per_day)
t_date = date_begin + dt.timedelta(days=days_from_t0)
return t_date
def _legacy_simulate_multiple(yaml_fp, out_fp=None, verbosity=0):
# ------------------Get params from paramparser---------------------
params = param_module.aggregate_params_and_data(yaml_fp=yaml_fp)
DATA_FOLDER = params['DATA_FOLDER']
RESULTS_DIR = params['RESULTS_DIR']
GROWTH_RATE_LIST = params['GROWTH_RATE_LIST']
CONTACT_REDUCTION = params['CONTACT_REDUCTION']
CLOSE_TRIGGER_LIST = params['CLOSE_TRIGGER_LIST']
REOPEN_TRIGGER_LIST = params['REOPEN_TRIGGER_LIST']
NUM_SIM = params['NUM_SIM']
beta0_dict = params['beta0_dict']
n_age = params['n_age']
n_risk = params['n_risk']
CITY = params['CITY']
shift_week = params['shift_week']
time_begin_sim = params['time_begin_sim']
interval_per_day = params['interval_per_day']
total_time = params['total_time']
monitor_lag = params['monitor_lag']
report_rate = params['report_rate']
# START_CONDITION = 5
I0 = params['I0']
trigger_type = params['trigger_type']
deterministic = params['deterministic']
# from SEIR_get_data
metro_pop = params['metro_pop']
school_calendar = params['school_calendar']
time_begin = params['time_begin']
FallStartDate = params['FallStartDate']
# from SEIR_get_param
Phi = params['phi']
# ------------------------------------------------------------------
all_growth_rates = dict()
for g_rate in GROWTH_RATE_LIST:
beta0 = beta0_dict[g_rate] # * np.ones(n_age)
E2Iy_dict = {}
E2I_dict = {}
Iy2Ih_dict = {}
Ih2D_dict = {}
Ia_dict = {}
Iy_dict = {}
Ih_dict = {}
R_dict = {}
CloseDate_dict = {}
ReopenDate_dict = {}
R0_baseline = []
for c_reduction in CONTACT_REDUCTION:
E2Iy_dict_temp = {}
E2I_dict_temp = {}
Iy2Ih_dict_temp = {}
Ih2D_dict_temp = {}
Ia_dict_temp = {}
Iy_dict_temp = {}
Ih_dict_temp = {}
R_dict_temp = {}
CloseDate_dict_temp = {}
ReopenDate_dict_temp = {}
# parse to list of datetime points
DateVar = []
for t in range(0, total_time):
DateVar.append(dt.datetime.strptime(np.str(time_begin_sim), '%Y%m%d') + dt.timedelta(days=t))
# print(DateVar)
for c_trigger in CLOSE_TRIGGER_LIST:
close_trigger = c_trigger
for r_trigger in REOPEN_TRIGGER_LIST:
reopen_trigger = r_trigger
print(reopen_trigger)
# DEBUG: disable color cycling
# LineColor = COLOR_PALETTE[CLOSE_TRIGGER_LIST.index(close_trigger)][REOPEN_TRIGGER_LIST.index(reopen_trigger)]
LineColor = 'black'
E2Iy_list = []
E2I_list = []
Iy2Ih_list = []
Ih2D_list = []
Ia_list = []
Iy_list = []
Ih_list = []
R_list = []
CloseDate_list = []
ReopenDate_list = []
for sim in range(NUM_SIM):
assert all([k in Phi.keys() for k in
('phi_all', 'phi_school', 'phi_work', 'phi_home')])
# get epi params
assert 'initial_state' in params
Para = param_module.SEIR_get_param(config=params)
scenario = Scenario({
'n_age': n_age,
'n_risk': n_risk,
'total_time': total_time,
'interval_per_day': interval_per_day,
'c_reduction_date': params['sd_date'],
'shift_week': shift_week,
'time_begin': time_begin,
'time_begin_sim': time_begin_sim,
'initial_i': I0,
'trigger_type': trigger_type,
'close_trigger': close_trigger,
'reopen_trigger': reopen_trigger,
'monitor_lag': monitor_lag,
'report_rate': report_rate,
'g_rate': g_rate,
'c_reduction': c_reduction,
'beta0': beta0,
'phi': Phi,
'metro_pop': metro_pop,
'FallStartDate': FallStartDate,
'school_calendar': school_calendar,
'deterministic': deterministic,
'verbosity': verbosity,
'initial_state': params['initial_state'],
't_offset': params['t_offset'],
'config': params
})
scenario.update(Para)
# from pprint import pprint
# pprint(scenario)
# assert 0 == scenario
result = simulate_one(scenario)
# ----------------------------------------------
# convert school event times to legacy
# datetime.datetime
bool_to_dt_kwargs = {
'interval_per_day': interval_per_day,
'time_begin_sim': time_begin_sim,
'shift_week': shift_week}
SchoolCloseTime = utils.bool_arr_to_dt(
result[11], **bool_to_dt_kwargs)
SchoolReopenTime = utils.bool_arr_to_dt(
result[12], **bool_to_dt_kwargs)
# convert to legacy R0
R0 = utils.R0_arr_to_float(result[13])
if R0 is not None:
R0_baseline.append(R0)
# ----------------------------------------------
# DEBUG: we remove the first element (S compartment)
# because legacy code did not report it
E2Iy_list.append(result[1])
E2I_list.append(result[2])
Iy2Ih_list.append(result[3])
Ih2D_list.append(result[4])
Ia_list.append(result[5])
Iy_list.append(result[6])
Ih_list.append(result[7])
R_list.append(result[8])
CloseDate_list.append(SchoolCloseTime)
ReopenDate_list.append(SchoolReopenTime)
# ----------------------------------------------
# Aggregate sums from each replicate
E2Iy_dict_temp[close_trigger + '/' + reopen_trigger] = np.array(E2Iy_list)
E2I_dict_temp[close_trigger + '/' + reopen_trigger] = np.array(E2I_list)
Iy2Ih_dict_temp[close_trigger + '/' + reopen_trigger] = np.array(Iy2Ih_list)
Ih2D_dict_temp[close_trigger + '/' + reopen_trigger] = np.array(Ih2D_list)
Ia_dict_temp[close_trigger + '/' + reopen_trigger] = np.array(Ia_list)
Iy_dict_temp[close_trigger + '/' + reopen_trigger] = np.array(Iy_list)
Ih_dict_temp[close_trigger + '/' + reopen_trigger] = np.array(Ih_list)
R_dict_temp[close_trigger + '/' + reopen_trigger] = np.array(R_list)
CloseDate_dict_temp[close_trigger + '/' + reopen_trigger] = CloseDate_list
ReopenDate_dict_temp[close_trigger + '/' + reopen_trigger] = ReopenDate_list
if close_trigger.split('_')[-1] == '20220101':
break
# Aggregate compartment data into dict keyed by
# CONTACT_REDUCTION scenario
E2Iy_dict[c_reduction] = E2Iy_dict_temp
E2I_dict[c_reduction] = E2I_dict_temp
Iy2Ih_dict[c_reduction] = Iy2Ih_dict_temp
Ih2D_dict[c_reduction] = Ih2D_dict_temp
Ia_dict[c_reduction] = Ia_dict_temp
Iy_dict[c_reduction] = Iy_dict_temp
Ih_dict[c_reduction] = Ih_dict_temp
R_dict[c_reduction] = R_dict_temp
CloseDate_dict[c_reduction] = CloseDate_dict_temp
ReopenDate_dict[c_reduction] = ReopenDate_dict_temp
# Assemble dictionary for *.pckl file
data_for_pckl = {
'CITY': CITY,
'GROWTH_RATE': g_rate,
'CONTACT_REDUCTION': CONTACT_REDUCTION,
'time_begin_sim': time_begin_sim,
'beta0': beta0 * np.ones(n_age),
'Para': Para,
'metro_pop': metro_pop,
'CLOSE_TRIGGER_LIST': CLOSE_TRIGGER_LIST,
'REOPEN_TRIGGER_LIST': REOPEN_TRIGGER_LIST,
'E2Iy_dict': E2Iy_dict,
'E2I_dict': E2I_dict,
'Ia_dict': Ia_dict,
'Iy_dict': Iy_dict,
'Ih_dict': Ih_dict,
'R_dict': R_dict,
'Iy2Ih_dict': Iy2Ih_dict,
'Ih2D_dict': Ih2D_dict,
'CloseDate_dict': CloseDate_dict,
'ReopenDate_dict': ReopenDate_dict,
'R0_baseline': R0_baseline}
# Write results to *.pckl file in RESULTS_DIR
# pckl_fname = str(CITY + '-' + g_rate + str(time_begin_sim) + '_' + str(NUM_SIM) + '.pckl')
# if out_fp is None:
# pckl_fp = os.path.join(RESULTS_DIR, pckl_fname)
# else:
# pckl_fp = out_fp
# with open(pckl_fp, 'wb') as pckl_file:
# pickle.dump(data_for_pckl, pckl_file)
all_growth_rates[g_rate] = data_for_pckl
return all_growth_rates
|
[
"kellyannepierce@gmail.com"
] |
kellyannepierce@gmail.com
|
0e7d5a6eae05a22ad8fd1a204d91fcd011fcb1dd
|
3b0ccdc4a50a3d54ede0cf497a73cb342ae4952b
|
/src/global_path_follower.py
|
29c3918bba4a1bb5d2dfdae5369f33be34f61424
|
[] |
no_license
|
Aharobot/oculusprime_ros
|
4059d6224616248915293dfabf1fb835dea8faf5
|
d7ec0a66421614e74792ef43c21f5f6674adfe33
|
refs/heads/master
| 2020-04-05T23:42:52.712313
| 2015-02-24T21:37:27
| 2015-02-24T21:37:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,510
|
py
|
#!/usr/bin/env python
"""
on any new /initialpose, do full rotation, then delay (to hone in amcl)
follow something ~15th pose in global path for all moves (about 0.3m away?)
-maximum path length seems to be about 35*5 (45*5 max) for 2-3 meter path
-(longer if more turns -- go for 15th or 20th pose, or max if less, should be OK)
ignore local path, except for determining if at goal or not
if no recent local path, must be at goal: followpath = False, goalpose = true
requires dwa_base_controller, global path updated continuously as bot moves
"""
import rospy, tf
import oculusprimesocket
from nav_msgs.msg import Odometry
import math
from nav_msgs.msg import Path
from geometry_msgs.msg import PoseWithCovarianceStamped
from actionlib_msgs.msg import GoalStatusArray
from move_base_msgs.msg import MoveBaseActionGoal
listentime = 0.5 # allows odom + amcl to catch up
nextmove = 0
odomx = 0
odomy = 0
odomth = 0
targetx = 0
targety = 0
targetth = 0
followpath = False
goalth = 0
minturn = math.radians(6) # 0.21 minimum for pwm 255
lastpath = 0 # refers to localpath
goalpose = False
goalseek = False
linearspeed = 150
secondspermeter = 3.2 # calibration, automate? (do in java, faster)
turnspeed = 100
secondspertwopi = 4.2 # calibration, automate? (do in java, faster)
initth = 0
tfth = 0
globalpathposenum = 20 # just right
listener = None
def pathCallback(data): # local path
global goalpose, lastpath
lastpath = rospy.get_time()
goalpose = False
def globalPathCallback(data):
global targetx, targety, targetth , followpath
n = len(data.poses)
if n < 5:
return
if n-1 < globalpathposenum:
p = data.poses[n-1]
else:
p = data.poses[globalpathposenum]
targetx = p.pose.position.x
targety = p.pose.position.y
quaternion = ( p.pose.orientation.x, p.pose.orientation.y,
p.pose.orientation.z, p.pose.orientation.w )
targetth = tf.transformations.euler_from_quaternion(quaternion)[2]
followpath = True
def odomCallback(data):
global odomx, odomy, odomth
odomx = data.pose.pose.position.x
odomy = data.pose.pose.position.y
quaternion = ( data.pose.pose.orientation.x, data.pose.pose.orientation.y,
data.pose.pose.orientation.z, data.pose.pose.orientation.w )
odomth = tf.transformations.euler_from_quaternion(quaternion)[2]
# determine direction (angle) on map
global tfth, listener
try:
(trans,rot) = listener.lookupTransform('/map', '/odom', rospy.Time(0))
quaternion = (rot[0], rot[1], rot[2], rot[3])
tfth = tf.transformations.euler_from_quaternion(quaternion)[2]
except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):
pass
def intialPoseCallback(data):
# do full rotation on pose estimate, to hone-in amcl
rospy.sleep(0.5) # let amcl settle
oculusprimesocket.sendString("speed "+str(turnspeed) )
oculusprimesocket.sendString("move right")
rospy.sleep(secondspertwopi) # full rotation
oculusprimesocket.sendString("move stop")
oculusprimesocket.waitForReplySearch("<state> direction stop")
# rospy.sleep(1) # let amcl settle << TODO: this is in separate thread so does nothing!
def goalCallback(d):
global goalth, goalpose, lastpath
# to prevent immediately rotating wrongly towards new goal direction
lastpath = rospy.get_time()
goalpose = False
# set goal angle
data = d.goal.target_pose
quaternion = ( data.pose.orientation.x, data.pose.orientation.y,
data.pose.orientation.z, data.pose.orientation.w )
goalth = tf.transformations.euler_from_quaternion(quaternion)[2]
def goalStatusCallback(data):
global goalseek
goalseek = False
if len(data.status_list) == 0:
return
status = data.status_list[len(data.status_list)-1] # get latest status
if status.status == 1:
goalseek = True
def move(ox, oy, oth, tx, ty, tth, gth):
global followpath, goalpose, tfth, nextmove
global odomx, odomy, odomth
# determine xy deltas for move
distance = 0
if followpath:
dx = tx - ox
dy = ty - oy
distance = math.sqrt( pow(dx,2) + pow(dy,2) )
goalrotate = False
if distance > 0:
th = math.acos(dx/distance)
if dy <0:
th = -th
elif goalpose:
th = gth - tfth
goalrotate = True
else:
th = tth
# determine angle delta for move
dth = th - oth
if dth > math.pi:
dth = -math.pi*2 + dth
elif dth < -math.pi:
dth = math.pi*2 + dth
# force minimums
if distance > 0 and distance < 0.05:
distance = 0.05
# supposed to reduce zig zagging
if dth < minturn*0.3 and dth > -minturn*0.3:
dth = 0
elif dth >= minturn*0.3 and dth < minturn:
dth = minturn
elif dth <= -minturn*0.3 and dth > -minturn:
dth = -minturn
if dth > 0:
oculusprimesocket.sendString("speed "+str(turnspeed) )
oculusprimesocket.sendString("move left")
rospy.sleep(dth/(2.0*math.pi) * secondspertwopi)
oculusprimesocket.sendString("move stop")
oculusprimesocket.waitForReplySearch("<state> direction stop")
elif dth < 0:
oculusprimesocket.sendString("speed "+str(turnspeed) )
oculusprimesocket.sendString("move right")
rospy.sleep(-dth/(2.0*math.pi) * secondspertwopi)
oculusprimesocket.sendString("move stop")
oculusprimesocket.waitForReplySearch("<state> direction stop")
if distance > 0:
oculusprimesocket.sendString("speed "+str(linearspeed) )
oculusprimesocket.sendString("move forward")
rospy.sleep(distance*secondspermeter)
oculusprimesocket.sendString("move stop")
oculusprimesocket.waitForReplySearch("<state> direction stop")
if goalrotate:
rospy.sleep(1)
def cleanup():
oculusprimesocket.sendString("move stop")
oculusprimesocket.sendString("state delete navigationenabled")
# MAIN
rospy.init_node('dwa_base_controller', anonymous=False)
listener = tf.TransformListener()
oculusprimesocket.connect()
rospy.Subscriber("odom", Odometry, odomCallback)
rospy.Subscriber("move_base/DWAPlannerROS/local_plan", Path, pathCallback)
rospy.Subscriber("move_base/goal", MoveBaseActionGoal, goalCallback)
rospy.Subscriber("move_base/status", GoalStatusArray, goalStatusCallback)
rospy.Subscriber("move_base/DWAPlannerROS/global_plan", Path, globalPathCallback)
rospy.Subscriber("initialpose", PoseWithCovarianceStamped, intialPoseCallback)
rospy.on_shutdown(cleanup)
while not rospy.is_shutdown():
t = rospy.get_time()
if t >= nextmove:
# nextmove = t + listentime
if goalseek and (followpath or goalpose):
move(odomx, odomy, odomth, targetx, targety, targetth, goalth)
nextmove = rospy.get_time() + listentime
followpath = False
if t - lastpath > 3:
goalpose = True
rospy.sleep(0.01)
cleanup()
|
[
"colin@xaxxon.com"
] |
colin@xaxxon.com
|
d2c466843f5ca21ade743eddc9de1a04c01b44e8
|
32660e78b5180924b11bdf6755025cd62a92b600
|
/airtest脚本/快手极速版.air/快手极速版.py
|
d59ca10b47e12e9757e08f503ea6d7ceef277d60
|
[] |
no_license
|
HenryHuH/messageboard
|
205f6afe5ef5b331c3c8f9784767f5293127cbc0
|
f949bc3fe78d05f58be77e4d3df8e004ebb716fa
|
refs/heads/master
| 2020-08-13T09:50:09.564854
| 2019-10-10T16:37:31
| 2019-10-10T16:37:31
| 214,949,551
| 1
| 1
| null | 2019-10-14T04:42:41
| 2019-10-14T04:42:40
| null |
UTF-8
|
Python
| false
| false
| 2,474
|
py
|
# -*- encoding=utf8 -*-
__author__ = "Administrator"
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
import random
import time
import datetime
poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
auto_setup(__file__)
devs = device()
print(devs.list_app(third_only=True))
#================================公用函数=======================
#自定义滑动事件
def getSize():
s=poco.get_screen_size()
return (s[0], s[1])
#屏幕向上滑动
def swipeUp(t,percent):
l = getSize()
x1 = int(l[0] * 0.5)+ random.randint(0,20) #x坐标
y1 = int(l[1] * 1) #起始y坐标
y2 = int(l[1] * percent) #终点y坐标
swipe((x1, y1), (x1, y2),t+random.randint(0,20))
# ================================================
# 快手极速版
# 先关闭视频app
stop_app("com.kuaishou.nebula")
# 启动app 等待5秒
start_app("com.kuaishou.nebula",activity=None)
# 等待8秒启动加载
sleep(20)
file = r'D:\快手极速版.log'
f = open(file, 'a+')
# 1、左上角入口
flag=0
leftbtn = poco(name='com.kuaishou.nebula:id/left_btn',type='android.widget.ImageView')
if(leftbtn.exists()):
leftbtn.click()
sleep(8)
mkmoney = poco(name ='com.kuaishou.nebula:id/red_packet_text',text='去赚钱')
if(mkmoney.exists()):
mkmoney.click()
sleep(10)
swipeUp(1000,0.3)
sleep(8)
seemovie =poco(name='android.view.View',text='去赚钱')
if(seemovie.exists()):
sleep(3)
seemovie.click()
flag =1
else:
f.write("看视频去赚钱按钮不存在" + '\n')
else:
f.write("去赚钱按钮不存在" + '\n')
else:
f.write("主页左上角按钮不存在" + '\n')
# 查看次数
watch_num = 1
start = datetime.datetime.now()
if(flag==1):
#开始看视频
while(True):
sleep(8 +random.randint(0,8))
swipeUp(1000,0.1)
# 根据时间判断 三个小时结束
cur = datetime.datetime.now()
timeStyle=cur.strftime("%Y-%m-%d %H:%M:%S")
strlog = '查看一个快手极速视频,已看%d个' % watch_num
strlog =strlog +timeStyle+'\n'
f.write(strlog)
print(strlog)
watch_num += 1
f.flush()
if((cur-start).seconds >= 3600):
break
f.close()
# 关闭视频app
stop_app("com.kuaishou.nebula")
|
[
"826537273@qq.com"
] |
826537273@qq.com
|
7ad21d4c5b7176cc4b382b7aa2c195e2702f3abb
|
8fd6cb50ef3acd6cf9366b7fec7870d998d4d6f5
|
/test/test.py
|
fe2f3183a0f198103060e8c0358e52f29dc4c3cc
|
[] |
no_license
|
wuhuabushijie/regtest
|
d6c6c4fb5a2741d08a13f620e3d0d5681e171da2
|
f60bd4e123d23d667eb41cc272101be6116f2247
|
refs/heads/master
| 2020-04-01T07:09:31.875292
| 2018-10-14T14:15:26
| 2018-10-14T14:15:26
| 152,978,605
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 507
|
py
|
import re
# line = "aaaabooobabbby123"
# regex_str = ".*(babbb|babbby)"
#
# match = re.findall(regex_str,line)
# print(match)
# match_obj = re.match(regex_str,line)
# if match_obj:
# print(match_obj.group(3))
line = """
出生日期:
2016年10月6日
2016-10-6
2016/10/6
2016/10/06
2016年10月
2016/06
2016/6
2016-06
"""
regex_str = "\s*\S*?(\d{4}[年/-]\d{1,2}[月/-]{0,1}\d{0,2}日{0,})"
match = re.findall(regex_str,line)
for dates in match:
print(dates)
|
[
"214148402@qq.com"
] |
214148402@qq.com
|
5d3eba151a3de50aeadad21654eea9a63c346636
|
d3dbb8a0485e0bf7b096e38f0320b35d75b5105b
|
/mini-programs/tweet-using-python.py
|
b750f2ece436c4486f4fde954e8bbcb5f4461cb6
|
[
"MIT"
] |
permissive
|
fhansmann/coding-basics
|
e60a6694d807337f62a5881263868527ab791ffc
|
6cb8e8fb8ad7ac619dfdd068cfd70559b04e4b6a
|
refs/heads/master
| 2020-09-28T01:18:47.230776
| 2020-03-14T21:27:39
| 2020-03-14T21:27:39
| 226,654,015
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 510
|
py
|
from constants import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET
from twitter import OAuth, Twitter
consumer_key = CONSUMER_KEY
consumer_secret = CONSUMER_SECRET
access_token = ACCESS_TOKEN
access_token_secret = ACCESS_TOKEN_SECRET
# Authentication imformation
auth = OAuth(access_token,access_token_secret, consumer_key, consumer_secret)
t = Twitter(auth = auth)
#Tweet which is to be posted
tweet = "Twitter is awesome"
#Posting the tweet
t.statuses.update(status = tweet)
#done!
|
[
"noreply@github.com"
] |
fhansmann.noreply@github.com
|
5f352ba8d18d349b4b7b066a3829ba080b8c9195
|
9923e30eb99716bfc179ba2bb789dcddc28f45e6
|
/autorest/python/swagger/models/list_ok_response.py
|
474dacd75f58b920fa6a1f2154bd6c837af7f02d
|
[] |
no_license
|
silverspace/samsara-sdks
|
cefcd61458ed3c3753ac5e6bf767229dd8df9485
|
c054b91e488ab4266f3b3874e9b8e1c9e2d4d5fa
|
refs/heads/master
| 2020-04-25T13:16:59.137551
| 2019-03-01T05:49:05
| 2019-03-01T05:49:05
| 172,804,041
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 722
|
py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ListOKResponse(Model):
"""ListOKResponse.
:param vehicles:
:type vehicles: list[~swagger.models.VehicleMaintenance]
"""
_attribute_map = {
'vehicles': {'key': 'vehicles', 'type': '[VehicleMaintenance]'},
}
def __init__(self, vehicles=None):
super(ListOKResponse, self).__init__()
self.vehicles = vehicles
|
[
"greg@samsara.com"
] |
greg@samsara.com
|
98587add4acf6c959b65087c526976590381c6ee
|
566c1f097310fe8d38a64e911e0325071e3dce28
|
/read_statistics/models.py
|
215f729cf5680337f7d189f49d21ce29f20967a6
|
[] |
no_license
|
H-inXT/blogsite
|
96d67515c94deb279003293d716f4e503da5ae2b
|
c063125ac79eb78970f3bbfafe2da21911c92be9
|
refs/heads/master
| 2022-08-21T19:34:56.678394
| 2020-05-25T15:12:14
| 2020-05-25T15:12:14
| 266,797,015
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,406
|
py
|
from django.db import models
from django.db.models.fields import exceptions
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
# .工具
from django.utils import timezone
# Create your models here.
class ReadNum(models.Model): # 计数方法三
read_num = models.IntegerField(default=0)
# 此段信息可在官网查到-contenttypes
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class ReadNumExpandMethod():
def get_read_num(self):
try:
ct = ContentType.objects.get_for_model(self)# 获取到博客类, 这个是ContentType的一个方法
readnum = ReadNum.objects.get(content_type=ct, object_id=self.pk)
return readnum.read_num
except exceptions.ObjectDoesNotExist:
return 0
return readnum.read_num
class ReadDetail(models.Model):
date = models.DateField(default=timezone.now) #
read_num = models.IntegerField(default=0)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id') # 通用的外键 可以访问到相应的模型
pass
|
[
"3057314116@qq.com"
] |
3057314116@qq.com
|
a8e617cdd16508249e60ba84fe50b5924610960c
|
f859f2d94ee6dbd728870cf2d86a340f0ffd0e66
|
/tdf/core/xmlmenu.py
|
b539d29ac0c414f1f44c402d8782602adccf58ab
|
[] |
no_license
|
cms-l1-globaltrigger/tdf
|
744362d52b97c922263de521c16e6a124ce58b1f
|
a2564781ea6bb9af7450730ec7c0875933989ecc
|
refs/heads/master
| 2022-06-12T08:54:09.438619
| 2019-02-08T12:02:13
| 2019-02-08T12:02:13
| 168,487,371
| 0
| 0
| null | 2022-03-29T09:09:03
| 2019-01-31T08:08:23
|
Python
|
UTF-8
|
Python
| false
| false
| 11,045
|
py
|
# -*- coding: utf-8 -*-
#
# Copyright 2013-2017 Bernhard Arnold <bernahrd.arnold@cern.ch>
# Johannes Wittmann <johannes.wittmann@cern.ch>
#
"""This module provides a very basic XML menu reader making use of lmxl etree.
This class can be used for diagnostic output of algorithm params in TDF routines.
Load a menu from XML file:
>>> from xmlmenu import XmlMenu
>>> menu = XmlMenu("sample.xml")
Access menu meta information:
>>> menu.name
'L1Menu_Sample'
>>> menu.comment
'NO one expects the spanish inquisition!'
Iterate over algorithms:
>>> for algorithm in menu.algorithms:
... print algorithm.index, algorithm.name
Filter algorithms by attributes:
>>> for module in range(menu.n_modules):
... for algorithm in menu.algorithms.byModule(module):
... do_something(...)
To reduce execution time it is possible to disable parsing for algorithms and/or
external signals by using flags. To read only menu meta data disable parsing:
>>> from xmlmenu import XmlMenu
>>> menu = XmlMenu("sample.xml", parse_algorithms=False, parse_externals=False)
"""
import sys, os
try:
from lxml import etree
except ImportError:
raise RuntimeError("package lxml is missing, please install \"python-lxml\" by using your package manager")
__all__ = [ 'XmlMenu', '__doc__' ]
def filter_first(function, sequence):
"""Retruns first match of filter() result or None if nothing was found."""
return list(filter(function, sequence) or [None])[0]
def get_xpath(elem, path, fmt=str, default=None):
"""Easy access using etree elem xpath method. Returns value of 'default' if
element was not found (default is 'None').
"""
results = elem.xpath('{path}/text()'.format(path=path))
if results:
return fmt(results[0])
return default
def fast_iter(context, func, *args, **kwargs):
"""Fast XML iterator for huge XML files.
http://lxml.de/parsing.html#modifying-the-tree
Based on Liza Daly's fast_iter
http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
See also http://effbot.org/zone/element-iterparse.htm
"""
for event, elem in context:
func(elem, *args, **kwargs)
# It's safe to call clear() here because no descendants will be
# accessed
elem.clear()
# Also eliminate now-empty references from the root node to elem
for ancestor in elem.xpath('ancestor-or-self::*'):
while ancestor.getprevious() is not None:
del ancestor.getparent()[0]
del context
class Algorithm(object):
"""Algorithm container class."""
def __init__(self, index, name, expression, module_id=0, module_index=0, comment=None):
self.index = index
self.name = name
self.expression = expression
self.module_id = module_id
self.module_index = module_index
self.comment = comment or ""
def __repr__(self):
return "Algorithm(index={self.index}, " \
"name=\"{self.name}\", " \
"expression=\"{self.expression}\", " \
"module(id={self.module_id}, index={self.module_index}))".format(**locals())
class ExternalSignal(object):
"""External signal container class."""
def __init__(self, name, system, cable, channel, description=None, label=None):
self.name = name
self.system = system
self.cable = cable
self.channel = channel
self.description = description or ""
self.label = label or ""
def __repr__(self):
return \
"ExternalSignal(name=\"{self.name}\", " \
"system=\"{self.system}\", " \
"cable={self.cable}, " \
"channel={self.channel})".format(**locals())
class AlgorithmContainer(list):
"""List container with extended lookup methods for content."""
def byIndex(self, index):
"""Retruns algorithm by index or None if not found."""
return filter_first(lambda algorithm: algorithm.index == index, self)
def byModuleId(self, id):
"""Returns list of algorithms assigned to module id or empty list if none found."""
return filter(lambda algorithm: algorithm.module_id == id, self)
def byModuleIndex(self, index):
"""Returns list of algorithms assigned to module index or empty list if none found."""
return filter(lambda algorithm: algorithm.module_index == index, self)
def byName(self, name):
"""Retruns algorithm by name or None if not found."""
return filter_first(lambda algorithm: algorithm.name == name, self)
class ExternalSignalContainer(list):
"""External signal list container with extended lookup methods."""
def byName(self, name):
"""Retruns external signal by name or None if not found."""
return filter_first(lambda signal: signal.name == name, self)
def bySystem(self, system):
"""Returns list of external signals assigned to system or empty list if none found."""
return filter(lambda signal: signal.system == system, self)
def byCable(self, cable):
"""Returns list of external signals assigned to cable or empty list if none found."""
return filter(lambda signal: signal.cable == cable, self)
class XmlMenu(object):
"""Container holding some information of the XML menu.
Menu attributes:
*filename* holds the filename the menu was read from
*name* is the menu's name
*uuid_menu* is the menu's UUID
*uuid_firmware* is the menu's firmware UUID (set by the VHDL producer)
*algorithms* holds an instance of type AlgorithmContainer permitting a
convenient access to the loaded algorithms
*externals* holds an instance of type ExternalSignalContainer permitting a
convenient access to the loaded external signals.
Example:
>>> menu = XmlMenu("sample.xml")
>>> menu.name
'L1Menu_Sample'
>>> menu.algorithms.byModule(2)
[...]
"""
def __init__(self, filename=None, parse_algorithms=True, parse_externals=True):
self.filename = None
self.name = None
self.uuid_menu = None
self.uuid_firmware = None
self.grammar_version = ""
self.is_valid = False
self.is_obsolete = False
self.n_modules = 0
self.comment = ""
self.ext_signal_set = ""
self.algorithms = AlgorithmContainer()
self.externals = ExternalSignalContainer()
# Override parinsing options
self.parse_algorithms = parse_algorithms
self.parse_externals = parse_externals
if filename: self.read(filename)
def read(self, filename):
"""Read XML from file and parse its content."""
self.filename = os.path.abspath(filename)
self.algorithms = AlgorithmContainer()
self.externals = ExternalSignalContainer()
with open(self.filename, 'rb') as fp:
# Access meta data
context = etree.parse(fp)
self.name = get_xpath(context, 'name')
self.uuid_menu = get_xpath(context, 'uuid_menu')
self.uuid_firmware = get_xpath(context, 'uuid_firmware')
self.grammar_version = get_xpath(context, 'grammar_version')
self.is_valid = get_xpath(context, 'is_valid', bool)
self.is_obsolete = get_xpath(context, 'is_obsolete', bool)
self.n_modules = get_xpath(context, 'n_modules', int)
self.comment = get_xpath(context, 'comment', default="")
self.ext_signal_set = get_xpath(context, 'ext_signal_set/name', default="")
if self.parse_algorithms:
# Access list of algorithms
fp.seek(0) # Seek begin of file
context = etree.iterparse(fp, tag='algorithm')
fast_iter(context, self._load_algorithm)
if self.parse_externals:
# Access list of external signals
fp.seek(0) # Seek begin of file
context = etree.iterparse(fp, tag='ext_signal')
fast_iter(context, self._load_external)
def _load_algorithm(self, elem):
"""Fetch information from an algorithm tag and appends it to the list of algorithms."""
name = get_xpath(elem, 'name')
index = get_xpath(elem, 'index', int)
expression = get_xpath(elem, 'expression')
module_id = get_xpath(elem, 'module_id', int)
module_index = get_xpath(elem, 'module_index', int)
comment = get_xpath(elem, 'comment', default="")
algorithm = Algorithm(index, name, expression, module_id, module_index, comment)
self.algorithms.append(algorithm)
def _load_external(self, elem):
"""Fetch information from an algorithm tag and appends it to the list of algorithms."""
name = get_xpath(elem, 'name')
system = get_xpath(elem, 'system')
cable = get_xpath(elem, 'cable', int)
channel = get_xpath(elem, 'channel', int)
description = get_xpath(elem, 'description', default="")
label = get_xpath(elem, 'label', default="")
external = ExternalSignal(name, system, cable, channel, description, label)
self.externals.append(external)
if __name__ == '__main__':
"""Basic unittest..."""
import logging
logging.getLogger().setLevel(logging.DEBUG)
filename = sys.argv[1]
import time
t1 = time.time()
menu = XmlMenu(filename)
t2 = time.time()
logging.info("menu.filename : \"%s\"", menu.filename)
logging.info("menu.name : \"%s\"", menu.name)
logging.info("menu.uuid_menu : %s", menu.uuid_menu)
logging.info("menu.uuid_firmware : %s", menu.uuid_firmware)
logging.info("menu.n_modules : %s", menu.n_modules)
logging.info("menu.is_valid : %s", menu.is_valid)
logging.info("menu.is_obsolete : %s", menu.is_obsolete)
if menu.comment:
logging.info("menu.comment : \"%s\"", menu.comment)
logging.info("menu.ext_signal_set : \"%s\"", menu.ext_signal_set)
for algorithm in menu.algorithms:
logging.info("algorithm.name : \"%s\"", algorithm.name)
logging.info("algorithm.index : %s", algorithm.index)
logging.info("algorithm.module_id : %s", algorithm.module_id)
logging.info("algorithm.module_index : %s", algorithm.module_index)
if algorithm.comment:
logging.info("algorithm.comment : \"%s\"", algorithm.comment)
for external in menu.externals:
logging.info("ext_signal.name : \"%s\"", external.name)
logging.info("ext_signal.system : \"%s\"", external.system)
logging.info("ext_signal.cable : %s", external.cable)
logging.info("ext_signal.channel : %s", external.channel)
if external.label:
logging.info("ext_signal.label : \"%s\"", external.label)
if external.description:
logging.info("ext_signal.description : \"%s\"", external.description)
logging.info("XML parsed in %.03f seconds.", (t2 - t1))
|
[
"Bernhard.Arnold@cern.ch"
] |
Bernhard.Arnold@cern.ch
|
b3698d8f8556fdfef9636a3e6e038e36765962b9
|
1f4b84ebc42c04e192ecdeebf44848dcfb16aa22
|
/Card_value_items.py
|
c12d50bff18b53b8e8872b96fffb8e8871a3b3a1
|
[] |
no_license
|
MakubexZ/Legends-of-Code-Magic
|
05a9a18f8cb5a467111f280ef3632bf0c158dabd
|
c7938ef9b1d92624d22bbb735ff1e35c75dc33c9
|
refs/heads/master
| 2021-05-18T11:12:09.802855
| 2020-03-31T05:18:00
| 2020-03-31T05:18:00
| 251,222,357
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,255
|
py
|
# -*- coding: utf-8 -*-
import sys
import numpy as np
from collections import Counter
d = open("D:\Python\CCG\GameCoding\Card_items.txt", "r")
line = d.readline()
value_list = {}
# Analyze each line of one item
# Calculate value of each item based on empirical formula
while line:
item = line.split(";")
# For Green item calculate strength of basic and special abilities
if 'Green' in item[2]:
strength = int(item[4]) + int(item[5])
if 'B' in item[6]:
strength += 2
elif 'C' in item[6]:
strength += 2.5
elif 'D' in item[6]:
strength += 2
elif 'G' in item[6]:
strength += 2
elif 'L' in item[6]:
strength += 4
elif 'W' in item[6]:
strength += 3
if int(item[7]) != 0:
strength += int(item[7])*0.5
if int(item[9]) != 0:
strength += int(item[9])*2
# For Red item calculate strength of basic and special abilities
elif 'Red' in item[2]:
strength = abs(int(item[4]) + int(item[5]))
if 'B' in item[6]:
strength += 2
elif 'C' in item[6]:
strength += 2.5
elif 'D' in item[6]:
strength += 2
elif 'G' in item[6]:
strength += 2
elif 'L' in item[6]:
strength += 4
elif 'W' in item[6]:
strength += 3
if int(item[8]) != 0:
strength -= int(item[8])*1.5
if int(item[9]) != 0:
strength += int(item[9])*2
# For Blue item calculate strength of basic and special abilities
elif 'Blue' in item[2]:
strength = abs(int(item[4]) + int(item[5]))
if int(item[7]) != 0:
strength += int(item[7])*0.5
if int(item[8]) != 0:
strength -= int(item[8])*1.5
if int(item[9]) != 0:
strength += int(item[9])*2
# Calculate value via dividing strength by 2*cost+1
# 'COST' is the consumption of using this card
value = strength/(int(item[3])*2 + 1)
iden = item[0].strip()
value_list[iden] = value
line = d.readline()
print(value_list)
d.close()
|
[
"shakamakubex@gmail.com"
] |
shakamakubex@gmail.com
|
86062cd52085d2ec4039080aa3ef86ea5a569b5d
|
5a8f080b8d277b5b657d0afef7c4206056f1202e
|
/py2copyp/settings.py
|
8ea89859be14a80c38c84e9a0a9a22595cec12d8
|
[] |
no_license
|
AccountOfLom/py2copyp
|
d5cb299e416a7046463a5925003def9df0ce24a1
|
afcae2054501e3d7bf323a50bdb298c8030bc506
|
refs/heads/master
| 2023-04-07T08:20:12.309331
| 2021-04-12T08:03:31
| 2021-04-12T08:03:31
| 354,258,789
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,106
|
py
|
"""
Django settings for py2copyp project.
Generated by 'django-admin startproject' using Django 1.11.29.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!+1b#6k_ic48dv4by^))xvtvx2(wy3k-z3o0chl*#ef$)+(7u$'
# 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',
]
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 = 'py2copyp.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 = 'py2copyp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/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.11/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/1.11/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.11/howto/static-files/
STATIC_URL = '/static/'
|
[
"ez@happys.online"
] |
ez@happys.online
|
2b5f5537744462032e8fc7b724f169d52fdc7e8f
|
abf16e8c114a2eaf91ac7021acd336a4a0aacb4e
|
/DataVisualization/MatplotlibTutorial.py
|
7afc41bd5f237e0cde0f4ab093e5efa82c15287c
|
[] |
no_license
|
giangnn-bkace/ml
|
f24293d63bcee2907412378527eb382fa1710d8f
|
605e444a58e830ae3f4d1ea1b3a0dd733dd70efb
|
refs/heads/master
| 2021-05-03T23:05:10.787691
| 2018-02-06T03:27:31
| 2018-02-06T03:27:31
| 120,396,510
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,334
|
py
|
# Imports
import numpy as np
import matplotlib.pyplot as plt
# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(10,6), dpi=100)
# Create a new subplot from a grid of 1x1
plt.subplot(111)
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)
# Plot cosine using blue color with a continuous line of width 1 (pixels)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label='cosine')
# Plot sine using green color with a continuous line of width 1 (pixels)
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label='sin')
# Set x limits
plt.xlim(X.min()*1.1, X.max()*1.1)
# Set x ticks
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$\pi/2$',r'$\pi$'])
# Set y limits
plt.ylim(C.min()*1.1, C.max()*1.1)
# Set y ticks
plt.yticks([-1, 0, 1], [r'$-1$',r'$0$',r'$+1$'])
# Move spines
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
# Adding legend
plt.legend(loc='upper left', frameon=True)
# Save figure using 72 dots per inch
#plt.savefig("./figures/helloMatplotlib.png",dpi=600)
# Show result on screen
plt.show()
|
[
"giangnn.bkace@gmail.com"
] |
giangnn.bkace@gmail.com
|
f05c731e5c5fbdbdd0c7a1ba5cde32ea92da2bd0
|
5df9472558247d43edd993409d78f6ada6a27cec
|
/plingback/plingback/input/tests.py
|
fd9580a83cb43fbf312e9a42748bd8a1b02318a8
|
[] |
no_license
|
neontribe/PlingBack
|
f7cd77cc3e7086293014e4a0eac05e7b2afa7c56
|
fb79de819003789c3106eb1cca7a06c24336d30c
|
refs/heads/master
| 2021-01-13T02:05:52.454900
| 2011-03-17T12:54:44
| 2011-03-17T12:54:44
| 1,267,528
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,197
|
py
|
import unittest
from webob.multidict import MultiDict
from pyramid.config import Configurator
from pyramid import testing
from pyramid.registry import Registry
from pyramid.mako_templating import MakoLookupTemplateRenderer, renderer_factory as mako_renderer_factory
from pyramid.exceptions import NotFound, Forbidden
from plingback.resources import TripleStore
from plingback.input.views import *
import rdflib
rdflib.plugin.register('sparql', rdflib.query.Processor,
'rdfextras.sparql.processor', 'Processor')
rdflib.plugin.register('sparql', rdflib.query.Result,
'rdfextras.sparql.query', 'SPARQLQueryResult')
class InputControllerTests(unittest.TestCase):
use_jsapi = False
def setUp(self):
reg = Registry()
reg.settings = {'store_type':'rdflib',
'debug_sparql':True}
self.config = testing.setUp(reg)
self.config.add_settings({'mako.directories':'plingback.sparql:templates'})
self.config.add_renderer(None, mako_renderer_factory)
self.config.begin()
def tearDown(self):
testing.tearDown()
def mock_request(self, path, params, method='GET', feedback_id=None):
matchdict = {}
if feedback_id:
matchdict.update({'feedback_id':feedback_id})
if not self.use_jsapi:
request = testing.DummyRequest(path=path,
params=MultiDict(params),
post= (method=='POST') and params or None,
method = method,
matchdict = matchdict)
else:
matchdict.update({'method':method})
jspath = path.split('/')
jspath.insert(2, method.lower())
jspath = '/'.join(jspath)
request = testing.DummyRequest(path=jspath,
params=MultiDict(params),
method = 'GET',
matchdict = matchdict)
request.context = TripleStore(request)
return request
def mock_params(self, initial={}):
initial.update({'pling_id':'5678',
'plingbackType':'automated_testing'})
return initial
def test_misplaced_feedback_id(self):
params = self.mock_params({'feedback_id':'888999000'})
request = self.mock_request('/api/plingbacks',
params,
'PUT')
self.assertRaises(HTTPBadRequest, create, request)
def test_missing_feedback_id(self):
params = self.mock_params()
request = self.mock_request('/api/plingbacks',
params,
'PUT')
self.assertRaises(HTTPBadRequest, create, request)
def test_create(self):
params = self.mock_params()
request = self.mock_request('/api/plingbacks',
params,
'POST')
res = create(request)
self.assertEqual(request.response_status, '201 Created')
self.assertEqual(len([x for x in request.context.store]), 6)
def test_create_with_attribute(self):
params = self.mock_params({'feedback_attribute':'rating',
'rating_value':'70'})
request = self.mock_request('/api/plingbacks',
params,
'POST')
res = create(request)
self.assertEqual(request.response_status, '201 Created')
self.assertEqual(len([x for x in request.context.store]), 7)
def test_create_missing_pling_id(self):
params = self.mock_params()
del params['pling_id']
request = self.mock_request('/api/plingbacks',
params,
'POST')
self.assertRaises(HTTPBadRequest, create, request)
def test_put_attribute(self):
params = self.mock_params({'feedback_attribute':'rating',
'rating_value':'70'})
request = self.mock_request('/api/plingbacks/888-999-111/rating',
params,
'PUT',
'888-999-111')
res = attribute_handler(request)
self.failUnless('888-999-111' in str(res))
self.assertEqual(len([x for x in request.context.store]), 1)
def test_delete_attribute(self):
self.config.add_settings({'enable_delete':True})
params = self.mock_params({})
request = self.mock_request('/api/plingbacks/999-999-111',
params,
'DELETE',
'999-999-111')
res = delete(request)
self.failUnless(res.status == '204 No Content')
def test_delete_disabled(self):
params = self.mock_params({})
request = self.mock_request('/api/plingbacks/999-999-111',
params,
'DELETE',
'999-999-111')
self.assertRaises(Forbidden, delete, request)
class JSAPITests(InputControllerTests):
""" Repeat all the input api test through the JSAPI layer"""
use_jsapi = True
def test_create_bad_method(self):
params = self.mock_params()
request = self.mock_request('/api/plingbacks',
params,
'HEAD')
self.assertRaises(HTTPBadRequest, create, request)
def test_attribute_bad_method(self):
params = self.mock_params()
request = self.mock_request('/api/plingbacks/888-999-111/rating',
params,
'HEAD')
self.assertRaises(HTTPBadRequest, attribute_handler, request)
|
[
"rupert@neontribe.co.uk"
] |
rupert@neontribe.co.uk
|
3ab77a485659577c19b71433cec2d2d97b292a8d
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03473/s350397845.py
|
d3b8ca0a69b57b9e581c2cd75495443833037f5a
|
[] |
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
| 28
|
py
|
x = int(input())
print(48-x)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
5948aa5ed3e4653b4271bd30ae04f23dcb7cc92a
|
dc382bba161dd09594b0c2601dbe822e487c0690
|
/utils/scraper.py
|
d63e9ebd113ed5651afdcd2bef0f1ce2932c2bfc
|
[
"MIT"
] |
permissive
|
IIIT-Programming-Club/Lockout-Bot
|
68e7607da0d540399878328b496a5f62846c34e2
|
2d1edaad3fe9f3432005bb4da80aec2209902826
|
refs/heads/master
| 2023-07-16T03:18:26.617515
| 2021-08-25T18:55:03
| 2021-08-25T18:55:03
| 399,890,530
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 965
|
py
|
import json
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
def run():
dict = {}
for pp in range(1, 16):
url = f"https://codeforces.com/contests/page/{pp}"
uClient = uReq(url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
container = page_soup.find("div", {"class": "contests-table"})
items = container.findAll("tr")
for i in items[1:]:
td_content = i.findAll("td")
contest_id = td_content[0].find("a")["href"].split("/")[-1]
a_tags = td_content[1].findAll("a")
authors = []
for x in a_tags:
authors.append(x["href"].split("/")[-1])
if "vovuh" in authors:
authors.append("pikmike")
dict[contest_id] = authors
with open("./data/authors.json", "w") as json_file:
json.dump(dict, json_file)
|
[
"groverkss@gmail.com"
] |
groverkss@gmail.com
|
f92202f5030cf1aa6ae1426c42d010f3d46de545
|
1a246b687b2b42bb8c38932bf538572041e88f27
|
/file/migrations/0001_initial.py
|
c5eb5edb11e1b1bf3d6b3e24ce081d586f4ff469
|
[] |
no_license
|
kamiwana/apolo
|
02aa89045eff93a3a3aee4c9ad5e9f4b1d8b31ed
|
47a6830dd8a77d16fa4b11162c9c872361c5a943
|
refs/heads/master
| 2020-03-30T03:32:01.561826
| 2019-07-02T12:06:26
| 2019-07-02T12:06:26
| 150,692,365
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,251
|
py
|
# Generated by Django 2.0.6 on 2018-06-12 02:44
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import file.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('project', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='File',
fields=[
('timestamp', models.DateTimeField(auto_created=True, verbose_name='등록일')),
('file_key', models.CharField(max_length=32, primary_key=True, serialize=False)),
('file_name', models.CharField(max_length=100)),
('file_path', models.FileField(upload_to=file.models.get_upload_path)),
('expire_min', models.IntegerField()),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='file', to='project.Project')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='file', to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'file',
},
),
]
|
[
"kamiwana@gmail.com"
] |
kamiwana@gmail.com
|
d6b95e67106d3596c8a253af1bf9df93a2f8736d
|
65ac0e5714a96a8b0267152b0401371f635db453
|
/create-drop_user_oracledb.py
|
90ff99030d3c1da51d14b0998a24d57d979b442c
|
[] |
no_license
|
vhernandomartin/Python-scripts
|
09a305bbefd740dc779b0e39d5b6da3ec3e22f98
|
46ac1bd647b105c737fdbc39aeb8b4a379c82f92
|
refs/heads/master
| 2021-04-27T16:32:31.268047
| 2018-03-09T10:38:28
| 2018-03-09T10:38:28
| 122,304,402
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,921
|
py
|
#!/usr/bin/python
import getopt
import sys
import cx_Oracle
def printf (format,*args):
sys.stdout.write (format % args)
def printException (exception):
error, = exception.args
printf ("Error code = %s\n",error.code);
printf ("Error message = %s\n",error.message);
class DBConnection:
global myPrintf
global myprintException
myPrintf = printf
myprintException = printException
def __init__(self, database, username, password):
self.database = database
self.username = username
self.password = password
def imprime(self):
return self.database
return self.username
return self.password
def add_connection(self):
try:
username = self.username
password = self.password
database = self.database
connection = cx_Oracle.connect (username,password,database)
#ver = connection.version.split(":")
#print ver
except cx_Oracle.DatabaseError, exception:
myiPrintf ('Failed to connect to %s\n',database)
myprintException (exception)
exit (1)
cursor = connection.cursor()
return cursor
def execute_query(self, cursor):
#cursor = connection.cursor()
try:
cursor.execute ('select count(*) from dba_objects')
except cx_Oracle.DatabaseError, exception:
myPrintf ('Failed to select from EMP\n')
myprintException (exception)
exit (1)
count = cursor.fetchone ()[0]
print count
#cursor.close ()
#connection.close ()
def create_user(self, cursor, new_user, new_user_pwd):
sql = "CREATE USER " + new_user + " identified by " + new_user_pwd
try:
cursor.execute (sql)
#cursor.execute ('CREATE USER TESTUSR identified by TESTUSR')
except cx_Oracle.DatabaseError, exception:
myPrintf ('Failed to prepare cursor\n')
myprintException (exception)
exit (1)
def drop_user(self, cursor):
try:
cursor.execute ('DROP USER TEST cascade')
except cx_Oracle.DatabaseError, exception:
myPrintf ('Failed to prepare cursor\n')
myprintException (exception)
exit (1)
def close_cursor(self, cursor):
cursor.close ()
def help():
print 'Usage: ' + sys.argv[0] + ' -s <ORACLE_SID> -u <DB_ADM_USR> -p <DB_ADM_PWD> -U <NEW_USER> -P <NEW_USER_PWD>'
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "hs:u:p:U:P:", ["help", "sid=", "db_adm_usr=", "db_adm_pwd=", "new_user=", "new_user_pwd="])
if not opts:
print 'No options supplied'
help()
sys.exit(1)
except getopt.GetoptError as err:
print err
help()
sys.exit(2)
for opt, arg in opts:
if len(opts) < 5:
print 'ERROR: Missing required arguments!'
help()
sys.exit(2)
if opt in ("-h", "--help"):
help()
sys.exit(2)
elif opt in ("-s", "--sid"):
sid = arg
elif opt in ("-u", "--user"):
user = arg
elif opt in ("-p", "--password"):
password = arg
elif opt in ("-U", "--new_user"):
new_user = arg
elif opt in ("-P", "--new_user_pwd"):
new_user_pwd = arg
# Stablish new connection to database
con = DBConnection(sid,user,password)
# Open new cursor on database
cursor = con.add_connection()
# Execute query
#con.execute_query(cursor)
# Create user function
con.create_user(cursor,new_user,new_user_pwd)
#con.drop_user(cursor)
# Closing database cursor
con.close_cursor(cursor)
## MAIN ##
if __name__=='__main__':
main()
## END MAIN ##
|
[
"vhernandomartin@gmail.com"
] |
vhernandomartin@gmail.com
|
1fb0b9a4310638e5a03d75d2861117263c815b12
|
bf0f1207d7a3c76b4f51f1392d2eb607eb12f948
|
/account_report/models/models.py
|
0b168905254de668aedba1525236b05080758c03
|
[] |
no_license
|
DevMohamedFci/Account-Report
|
65456c7690064c398060b4099344dc7b5e296b97
|
587dbc37c3f2cb2eae51b9109e39fd17d9e0e8c0
|
refs/heads/master
| 2020-03-29T02:17:36.423790
| 2018-09-19T10:27:17
| 2018-09-19T10:27:17
| 149,428,755
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 23,540
|
py
|
# -*- coding: utf-8 -*-
from odoo import models, fields, api
# class account_report(models.Model):
# _name = 'account_report.account_report'
# name = fields.Char()
# value = fields.Integer()
# value2 = fields.Float(compute="_value_pc", store=True)
# description = fields.Text()
#
# @api.depends('value')
# def _value_pc(self):
# self.value2 = float(self.value) / 100
import time
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.exceptions import UserError
# Journal Transaction Report
class account_journalcartreport(models.TransientModel):
_name = 'account.journalcartreport'
_description = 'Account Aged Trial balance Report'
date_from = fields.Date(string="start date", required=True, default=lambda *a: time.strftime('%Y-%m-%d'))
date_end = fields.Date(string="end date", required=True, default=lambda *a: time.strftime('%Y-%m-%d'))
account_move=fields.Many2one('account.journal',"account journal")
nid=fields.Integer(related="account_move.id")
name=fields.Char(related="account_move.display_name")
@api.multi
@api.onchange('account_move')
def product_id_change(self):
self.nid=self.account_move.id
self.name=self.account_move.display_name
def print_report(self, data,context=None):
data['form']=self.read(['nid','name','date_from','date_end'])[0]
return self.env['report'].with_context(landscape=True).get_action(self, 'account_report.report_journalcartreport', data=data)
class journalcartreport(models.AbstractModel):
_name = 'report.account_report.report_journalcartreport'
def _get_partner_move_lines(self,nid, date_from, date_end,target_move):
res = []
totalinval = 0.0
totaloutval = 0.0
netval=0.0
cr = self.env.cr
#select records before date_from
cr.execute("select \
CASE \
WHEN AM.payment_type='inbound' THEN Am.Amount ELSE 0 END AS InVal, \
CASE \
WHEN AM.payment_type='outbound' THEN Am.Amount ELSE 0 END as OutVal"
" FROM account_payment AM where state ='posted' and journal_id=%s and payment_date < %s;",
(str(nid), date_from))
# ,(str(nid),date_from,date_end)
beforeleads = cr.dictfetchall()
beforetotalinval=0.0
beforetotaloutval=0.0
for ld in beforeleads:
beforetotalinval += float(ld['inval'])
beforetotaloutval += float(ld['outval'])
beforenetval=beforetotalinval-beforetotaloutval
#select all record between tow date
cr.execute("select \
AM.payment_date,AM.payment_type,AM.Name, \
CASE \
WHEN AM.payment_type='inbound' THEN Am.Amount ELSE 0 END AS InVal, \
CASE \
WHEN AM.payment_type='outbound' THEN Am.Amount ELSE 0 END as OutVal"
" FROM account_payment AM where state ='posted' and journal_id=%s and payment_date between %s and %s;",(str(nid),date_from,date_end))
#,(str(nid),date_from,date_end)
leads = cr.dictfetchall()
for ld in leads:
value= { }
value['payment_date'] = ld['payment_date']
value['payment_type'] = ld['payment_type']
value['name'] = ld['name']
value['inval'] = ld['inval']
value['outval'] = ld['outval']
totalinval += float(ld['inval'])
totaloutval += float(ld['outval'])
value['netval']=beforenetval+ totalinval-totaloutval
res.append(value)
return res,totalinval,totaloutval,beforenetval
def render_html(self, docids, data=None):
if not data.get('form') or not self.env.context.get('active_model') or not self.env.context.get('active_id'):
raise UserError(_("Form content is missing, this report cannot be printed."))
if not data.get('form') or not self.env.context.get('active_model') or not self.env.context.get('active_id'):
raise UserError(_("Form content is missing, this report cannot be printed."))
total = []
model = self.env.context.get('active_model')
docs = self.env[model].browse(self.env.context.get('active_id'))
target_move = data['form'].get('target_move', 'all')
date_from = data['form'].get('date_from', time.strftime('%Y-%m-%d'))
date_end = data['form'].get('date_end', time.strftime('%Y-%m-%d'))
nid = data['form'].get('nid')
movelines,totalinval,totaloutval,beforenetval = self._get_partner_move_lines(nid, date_from, date_end,target_move)
docargs = {
'doc_model': model,
'data': data['form'],
'docs': docs,
'get_lead_lines': movelines,
'totalinval':totalinval,
'totaloutval':totaloutval,
'totalnetval':beforenetval+totalinval-totaloutval,
'beforenetval':beforenetval,
}
return self.env['report'].render('account_report.report_journalcartreport', docargs)
# Customer Tnasaction Report
class account_CutomerTransactionreport(models.TransientModel):
_name = 'account.cutomertransactionreport'
_description = 'Account Aged Trial balance Report'
date_from = fields.Date(string="start date", required=True, default=lambda *a: time.strftime('%Y-%m-%d'))
date_end = fields.Date(string="end date", required=True, default=lambda *a: time.strftime('%Y-%m-%d'))
account_Customer=fields.Many2one('res.partner',"Customer")
nid=fields.Integer(related="account_Customer.id")
name=fields.Char(related="account_Customer.name")
@api.multi
@api.onchange('account_Customer')
def product_id_change(self):
self.nid=self.account_Customer.id
self.name=self.account_Customer.name
def print_report(self, data,context=None):
data['form']=self.read(['nid','name','date_from','date_end'])[0]
return self.env['report'].with_context(landscape=True).get_action(self, 'account_report.report_cutomertransactionreport', data=data)
class CutomerTransactionreport(models.AbstractModel):
_name = 'report.account_report.report_cutomertransactionreport'
def _get_partner_move_lines(self,nid, date_from, date_end,target_move):
res = []
TotInvoice = 0.0
PaymentTo = 0.0
PaymentFrom = 0.0
FirstBal = 0.0
totaldebit = 0.0
totalcredit = 0.0
cr = self.env.cr
#calc FirstBal before date_from
cr.execute("select amount_total as TotInvoice \
from account_invoice \
where \
partner_id = %s and \
date_invoice < %s",
(str(nid), date_from))
# ,(str(nid),date_from,date_end)
beforeleads1 = cr.dictfetchall()
for ld in beforeleads1:
TotInvoice += float( (ld['totinvoice']))
cr.execute("select amount as PaymentTo \
from account_payment \
where \
partner_id = %s and \
payment_date < %s and \
state = 'posted' and \
payment_type = 'inbound';",
(str(nid), date_from))
# ,(str(nid),date_from,date_end)
beforeleads2 = cr.dictfetchall()
for ld in beforeleads2:
PaymentTo += float(ld['paymentto'])
cr.execute("select amount as PaymentFrom \
from account_payment \
where \
partner_id = %s and \
payment_date < %s and \
state = 'posted' and \
payment_type = 'outbound';",
(str(nid), date_from))
# ,(str(nid),date_from,date_end)
beforeleads3 = cr.dictfetchall()
for ld in beforeleads3:
PaymentFrom += float(ld['paymentfrom'])
FirstBal = TotInvoice - PaymentTo + PaymentFrom
#select all record between tow date
cr.execute("select Q_Trans.* from \
(select \
date_invoice as TransDate, \
create_date as TransDateTime, 'Invoice' as TransType, \
number as TransNumber, \
amount_total as Debit, \
0 as Credit, \
0 as NetBal, \
'' as Desciption \
from \
account_invoice \
where \
partner_id = %s and \
date_invoice between %s and %s \
union \
select \
AP.payment_date as TransDate, \
Ap.create_date as TransDateTime, \
'Payment' as TransType, \
AP.name as TransNumber, \
0 as Debit, \
AP.amount as Credit, \
0 as NetBal, \
'Payed to ' || AJ.name as Description \
from \
account_payment AP \
INNER JOIN account_Journal AJ ON AJ.id = AP.journal_id \
where \
partner_id = %s and \
payment_date between %s and %s and \
state = 'posted' and \
payment_type = 'inbound' \
union \
select \
AP.payment_date as TransDate, \
Ap.create_date as TransDateTime, \
'Payment' as TransType, \
AP.name as TransNumber, \
AP.amount as Debit, \
0 as Credit, \
0 as NetBal, \
'Payed from ' || AJ.name as Description \
from \
account_payment AP \
INNER JOIN account_Journal AJ ON AJ.id = AP.journal_id \
where \
partner_id = %s and \
payment_date between %s and %s and \
state = 'posted' and \
payment_type = 'outbound' \
) \
as Q_Trans \
Order by TransDateTime;",(str(nid),date_from,date_end,str(nid),date_from,date_end,str(nid),date_from,date_end))
#,(str(nid),date_from,date_end)
leads = cr.dictfetchall()
for ld in leads:
value= { }
value['transdate'] = ld['transdate']
value['transdatetime'] = ld['transdatetime']
value['transtype'] = ld['transtype']
value['transnumber'] = ld['transnumber']
value['debit'] = ld['debit']
value['credit'] = ld['credit']
totaldebit += float(ld['debit'])
totalcredit += float(ld['credit'])
value['netbal']=FirstBal+ totaldebit-totalcredit
res.append(value)
return res,totaldebit,totalcredit,FirstBal
def render_html(self, docids, data=None):
if not data.get('form') or not self.env.context.get('active_model') or not self.env.context.get('active_id'):
raise UserError(_("Form content is missing, this report cannot be printed."))
if not data.get('form') or not self.env.context.get('active_model') or not self.env.context.get('active_id'):
raise UserError(_("Form content is missing, this report cannot be printed."))
total = []
model = self.env.context.get('active_model')
docs = self.env[model].browse(self.env.context.get('active_id'))
target_move = data['form'].get('target_move', 'all')
date_from = data['form'].get('date_from', time.strftime('%Y-%m-%d'))
date_end = data['form'].get('date_end', time.strftime('%Y-%m-%d'))
nid = data['form'].get('nid')
movelines,totaldebit,totalcredit,FirstBal = self._get_partner_move_lines(nid, date_from, date_end,target_move)
docargs = {
'doc_model': model,
'data': data['form'],
'docs': docs,
'get_lead_lines': movelines,
'totaldebit':totaldebit,
'totalcredit':totalcredit,
'totalnetbal':FirstBal+totaldebit-totalcredit,
'FirstBal':FirstBal,
}
return self.env['report'].render('account_report.report_cutomertransactionreport', docargs)
class account_customerbalancereport(models.TransientModel):
_name = 'account.customerbalancereport'
_description = 'customer balance Report'
date_from = fields.Date(string="select start date", required=True, default=lambda *a: time.strftime('%Y-%m-%d'))
date_end = fields.Date(string="select end date", required=True, default=lambda *a: time.strftime('%Y-%m-%d'))
def print_report(self, data,context=None):
data['form']=self.read(['date_from','date_end'])[0]
return self.env['report'].with_context(landscape=True).get_action(self, 'account_report.report_cbr', data=data)
class customerbalancereport(models.AbstractModel):
_name = 'report.account_report.report_cbr'
def _get_partner_move_lines(self,nid, date_from, date_end,target_move):
res = []
netval=0.0
cr = self.env.cr
#select all record between tow date
cr.execute("select id, name, \
(COALESCE(dbt_first_invoice, 0) + COALESCE(dbt_payment_first, 0) - COALESCE(crd_payment_first, 0)) first_bal, \
(COALESCE(dbt_invoice, 0) + COALESCE(dbt_payment, 0)) dbt, \
(COALESCE(crd_Payment, 0)) crd, \
(COALESCE(dbt_first_invoice, 0) + COALESCE(dbt_payment_first, 0) - COALESCE(crd_payment_first, 0) + COALESCE(dbt_invoice, 0) + COALESCE(dbt_payment, 0) - COALESCE(crd_Payment, 0)) Net \
from \
( \
select RP.id, RP.name, (select sum(amount_total) from account_invoice AI \
where AI.partner_id = RP.id \
and AI.date_invoice < %s \
and state <> 'draft') as dbt_first_invoice, \
(select sum(amount) from account_payment AP \
where AP.partner_id = RP.id \
and AP.payment_date < %s and payment_type = 'outbound' and state = 'posted') as dbt_Payment_first, (select sum(amount) from account_payment AP \
where AP.partner_id = RP.id \
and AP.payment_date < %s and payment_type = 'inbound' and state = 'posted') as crd_Payment_first, \
(select sum(amount_total) \
from account_invoice AI \
where AI.partner_id = RP.id \
and AI.date_invoice between %s and %s and state <> 'draft') as dbt_invoice, \
(select sum(amount) \
from account_payment AP \
where AP.partner_id = RP.id \
and AP.payment_date between %s and %s and payment_type = 'outbound' and state = 'posted') as dbt_Payment, \
(select sum(amount) \
from account_payment AP \
where AP.partner_id = RP.id \
and AP.payment_date between %s and %s and payment_type = 'inbound' \
and state = 'posted') as crd_Payment \
from res_partner RP \
where customer = true \
and active = true \
)as Q_Bal \
order by id;"
,(date_from,date_from,date_from,date_from,date_end,date_from,date_end,date_from,date_end))
#,(str(nid),date_from,date_end)
leads = cr.dictfetchall()
for ld in leads:
value= { }
value['id'] = ld['id']
value['name'] = ld['name']
value['first_bal'] = ld['first_bal']
value['dbt'] = ld['dbt']
value['crd'] = ld['crd']
value['net'] = ld['net']
netval += float(ld['net'])
res.append(value)
return res,netval
def render_html(self, docids, data=None):
if not data.get('form') or not self.env.context.get('active_model') or not self.env.context.get('active_id'):
raise UserError(_("Form content is missing, this report cannot be printed."))
if not data.get('form') or not self.env.context.get('active_model') or not self.env.context.get('active_id'):
raise UserError(_("Form content is missing, this report cannot be printed."))
total = []
model = self.env.context.get('active_model')
docs = self.env[model].browse(self.env.context.get('active_id'))
target_move = data['form'].get('target_move', 'all')
date_from = data['form'].get('date_from', time.strftime('%Y-%m-%d'))
date_end = data['form'].get('date_end', time.strftime('%Y-%m-%d'))
nid = data['form'].get('nid')
movelines,netval = self._get_partner_move_lines(nid, date_from, date_end,target_move)
docargs = {
'doc_model': model,
'data': data['form'],
'docs': docs,
'get_lead_lines': movelines,
'netval':netval,
}
return self.env['report'].render('account_report.report_cbr', docargs)
#vendor balance report
class account_vendorbalancereport(models.TransientModel):
_name = 'account.vendorbalancereport'
_description = 'vendor balance Report'
date_from = fields.Date(string="select start date", required=True, default=lambda *a: time.strftime('%Y-%m-%d'))
date_end = fields.Date(string="select end date", required=True, default=lambda *a: time.strftime('%Y-%m-%d'))
def print_report(self, data,context=None):
data['form']=self.read(['date_from','date_end'])[0]
return self.env['report'].with_context(landscape=True).get_action(self, 'account_report.report_vbr', data=data)
class vendorbalancereport(models.AbstractModel):
_name = 'report.account_report.report_vbr'
def _get_partner_move_lines(self,nid, date_from, date_end,target_move):
res = []
netval=0.0
cr = self.env.cr
#select all record between tow date
cr.execute("select id, name, \
(COALESCE(crd_first_invoice, 0) + COALESCE(crd_payment_first, 0) - COALESCE(dbt_payment_first, 0)) first_bal, \
(COALESCE(dbt_Payment, 0)) dbt, \
(COALESCE(crd_invoice, 0) + COALESCE(crd_payment, 0)) crd, \
(COALESCE(crd_first_invoice, 0) + COALESCE(crd_payment_first, 0) - COALESCE(dbt_payment_first, 0) + COALESCE(crd_invoice, 0) + COALESCE(crd_payment, 0) - COALESCE(dbt_Payment, 0)) Net \
from ( select RP.id, RP.name, (select sum(amount_total) from account_invoice AI \
where AI.partner_id = RP.id \
and AI.date_invoice < %s \
and state <> 'draft') as crd_first_invoice, \
(select sum(amount) \
from account_payment AP \
where AP.partner_id = RP.id \
and AP.payment_date < %s and payment_type = 'outbound' \
and state = 'posted') as dbt_Payment_first, \
(select sum(amount) \
from account_payment AP \
where AP.partner_id = RP.id \
and AP.payment_date < %s and payment_type = 'inbound' and state = 'posted') as crd_Payment_first, \
(select sum(amount_total) \
from account_invoice AI \
where AI.partner_id = RP.id \
and AI.date_invoice between %s and %s and state <> 'draft') as crd_invoice, \
(select sum(amount) \
from account_payment AP \
where AP.partner_id = RP.id \
and AP.payment_date between %s and %s and payment_type = 'outbound' and state = 'posted') as dbt_Payment, \
(select sum(amount) \
from account_payment AP \
where AP.partner_id = RP.id \
and AP.payment_date between %s and %s and payment_type = 'inbound' and state = 'posted') as crd_Payment \
from res_partner RP \
where supplier = true \
and active = true \
)as Q_Bal \
order by id;"
,(date_from,date_from,date_from,date_from,date_end,date_from,date_end,date_from,date_end))
#,(str(nid),date_from,date_end)
leads = cr.dictfetchall()
for ld in leads:
value= { }
value['id'] = ld['id']
value['name'] = ld['name']
value['first_bal'] = ld['first_bal']
value['dbt'] = ld['dbt']
value['crd'] = ld['crd']
value['net'] = ld['net']
netval += float(ld['net'])
res.append(value)
return res,netval
def render_html(self, docids, data=None):
if not data.get('form') or not self.env.context.get('active_model') or not self.env.context.get('active_id'):
raise UserError(_("Form content is missing, this report cannot be printed."))
if not data.get('form') or not self.env.context.get('active_model') or not self.env.context.get('active_id'):
raise UserError(_("Form content is missing, this report cannot be printed."))
total = []
model = self.env.context.get('active_model')
docs = self.env[model].browse(self.env.context.get('active_id'))
target_move = data['form'].get('target_move', 'all')
date_from = data['form'].get('date_from', time.strftime('%Y-%m-%d'))
date_end = data['form'].get('date_end', time.strftime('%Y-%m-%d'))
nid = data['form'].get('nid')
movelines,netval = self._get_partner_move_lines(nid, date_from, date_end,target_move)
docargs = {
'doc_model': model,
'data': data['form'],
'docs': docs,
'get_lead_lines': movelines,
'netval':netval,
}
return self.env['report'].render('account_report.report_vbr', docargs)
|
[
"41862946+DevMohamedFci@users.noreply.github.com"
] |
41862946+DevMohamedFci@users.noreply.github.com
|
9e9069ab87e69b895301d4832b3bae10dcd8850e
|
27046afbe5337e6a246249c54fe96ccc0a4cac1f
|
/bin/bin_onePT/mvir-0-gather-measurements.py
|
f75eff93f54b5d68816941bda0e5bfe951ee62f4
|
[
"CC0-1.0"
] |
permissive
|
Jravis/nbody-npt-functions
|
d08863dbe2ad8a0c4fbb0785ebbb17256f39a9e7
|
a034db4e5a9b2f87dc42eeb6059c4dd280589e4a
|
refs/heads/master
| 2021-09-28T21:06:10.099374
| 2018-11-20T16:37:36
| 2018-11-20T16:37:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,768
|
py
|
import glob
from os.path import join
import numpy as n
import astropy.io.fits as fits
import lib_functions_1pt as lib
import os
import sys
#Quantity studied
version = 'v4'
qty = "mvir"
# one point function lists
fileC = n.array(glob.glob( join(os.environ['MD_DIR'], "MD_*Gpc*", version, qty,"out_*_Central_JKresampling.pkl")))
fileB = n.array(glob.glob( join( os.environ['MD_DIR'], "MD_*Gpc*", version, qty,"out_*_"+qty+"_JKresampling.bins")))
fileS = n.array(glob.glob( join( os.environ['MD_DIR'], "MD_*Gpc*", version, qty,"out_*_Satellite_JKresampling.pkl")))
fileC.sort()
fileS.sort()
fileB.sort()
print len(fileC), len(fileB), len(fileS)
print "considers ",len(fileC), qty , " function files"
for ii, el in enumerate(fileC):
print el
print fileS[ii]
print fileB[ii]
lib.convert_pkl_mass(fileC[ii], fileS[ii], fileB[ii], qty)
fileC = n.array(glob.glob( join(os.environ['DS_DIR'], version, qty,"ds*_Central_JKresampling.pkl")))
fileB = n.array(glob.glob( join( os.environ['DS_DIR'], version, qty,"ds*_"+qty+"_JKresampling.bins")))
fileS = n.array(glob.glob( join( os.environ['DS_DIR'], version, qty,"ds*_Satellite_JKresampling.pkl")))
fileC.sort()
fileS.sort()
fileB.sort()
print len(fileC), len(fileB), len(fileS)
print "considers ",len(fileC), qty , " function files"
for ii, el in enumerate(fileC):
print el
print fileS[ii]
print fileB[ii]
lib.convert_pkl_mass(fileC[ii], fileS[ii], fileB[ii], qty)
print qty
af = n.array(glob.glob(join(os.environ['MVIR_DIR'], "data", "*_"+qty+".fits") ) )
print af[0]
d0 = fits.open(af[0])[1].data
#print len(d0['log_mvir']), d0['log_mvir']
for ii in range(1,len(af),1):
d1 = fits.open(af[ii])[1].data
d0 = n.hstack((d0,d1))
hdu2 = fits.BinTableHDU.from_columns(d0)
writeName = join(os.environ['MVIR_DIR'], qty+"_summary.fits")
if os.path.isfile(writeName):
os.remove(writeName)
hdu2.writeto( writeName )
"""
sys.exit()
# rebinning here
#solve bins = 0 problem
n.arange()
n.hstack((n.arange(8,14,0.25), n.arange(14,16,0.05)))
#if logmvir < 14 :
Nrb = 5.
idSplit = int(n.searchsorted(d0['log_mvir'],14)/Nrb)*Nrb
split_array= lambda array: [array[:idSplit], array[idSplit:]]
#variables :
#
def rebinMe(trb, mod, Nrb = 5):
# split
part1, part2 = split_array(trb)
# rebin
take_middle_val = lambda part: part[2::Nrb]
take_mean_val = lambda part: (part[0::Nrb] + part[1::Nrb] + part[2::Nrb] + part[3::Nrb] + part[4::Nrb])/Nrb.
take_sum_val = lambda part: part[0::Nrb] + part[1::Nrb] + part[2::3] + part[3::Nrb] + part[4::Nrb]
if mode == 'middle' :
part1b = take_middle_val(part1)
if mode == 'mean' :
part1b = take_mean_val(part1)
if mode == 'sum' :
part1b = take_sum_val(part1)
return n.hstack((part1b, part2))
trb = d0['log_mvir']
mode = 'middle'
trb_o = rebinMe(trb, mode)
"""
|
[
"johan.comparat@gmail.com"
] |
johan.comparat@gmail.com
|
24fa475f4d63a9f4044e917f0bda01aeeb74b12e
|
aa1c9b140230edc1d52bff4045c64258b04e8daf
|
/boxUpdate/boxUpdate.py
|
1c2df23cd27c41834a1e60dfbcd69a296561cd37
|
[
"Apache-2.0"
] |
permissive
|
Vast-Stars/Mohou_Box-master
|
4846071126f7d84947b382fe714d7cc2023db360
|
3d1c320a6258422406e2ba2f96ec7986beba1330
|
refs/heads/master
| 2021-01-13T03:46:35.015561
| 2016-08-22T02:11:19
| 2016-08-22T02:11:19
| 77,207,490
| 3
| 0
| null | 2016-12-23T07:35:51
| 2016-12-23T07:35:51
| null |
UTF-8
|
Python
| false
| false
| 19,795
|
py
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
#sys.path.append("/home/pi/oprint/lib/python2.7/site-packages/tornado-4.0.1-py2.7-linux-armv7l.egg/")
#sys.path.append("/home/pi/oprint/lib/python2.7/site-packages/backports.ssl_match_hostname-3.4.0.2-py2.7.egg/")
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import uuid
import hashlib
import time
import logging
import os
import urllib
import httplib
import json
import md5
from tornado.httpclient import HTTPClient
from tornado.escape import json_decode
from tornado.options import define, options
from common import Application
from network_api import get_allwifi_info, get_network_info, get_dns_info, set_wifi, set_network, machine_is_online, get_serial_number, set_serial_number
from user_api import md5, get_user_info, set_user_info, bind_box_api, unbind_box_api, init_box_config_info
from update_api import getLatestVer, getCurrentVer, getUpdateMeta, netUpdate, initUpdateInfo, clearUpdateInfoBegin, getUpdatePkgDesc
import settings as WebConfig
from machine_api import update_machine_config, update_setting_gcode, update_preferences_file_info, get_current_activity_print_machine, get_active_machine_print_info, \
get_default_machine_print_info, write_print_info, restart_web_service
define("host", default="*", help="run on the given host")
define("port", default=8092, help="run on the given port", type=int)
app = Application()
WebConfig.settings(True);
logger = logging.getLogger("__name__")
bind_messages = ["绑定成功".encode("utf8"),
"绑定失败,请重试".encode("utf8"),
"数据读取失败,配置文件丢失".encode("utf8"),
"连接认证服务器网络失败".encode("utf8")]
unbind_messages = ["解除绑定成功".encode("utf8"),
"解除绑定失败,请重试".encode("utf8"),
"数据读取失败,配置文件丢失".encode("utf8"),
"连接认证服务器网络失败".encode("utf8")]
machine_config_messages = ["设定成功".encode("utf8"),
"设定失败".encode("utf8")]
@app.route(r"/bind")
class bind(tornado.web.RequestHandler):
def post(self):
username = self.get_argument("username")
password = md5(self.get_argument("password"))
result = None
is_on_line = machine_is_online()
if is_on_line:
user_info = get_user_info()
if user_info["device_id"]:
response = bind_box_api(username, password, user_info["device_id"], user_info["box_name"])
if response and response["code"] in [1, 81]:
user_info["username"] = username
user_info["password"] = password
user_info["user_token"] = response["data"]["token"]
user_info["remember_information"] = 1
user_info["binding_mohou"] = 1
user_info["is_login"] = 1
set_user_info(user_info);
result = 0
else:
result = 1
else:
result = 2
else:
result = 3
return self.write({"result" : result, "msg" : bind_messages[result]})
@app.route(r"/unbind")
class unbind(tornado.web.RequestHandler):
def post(self):
result = None
is_on_line = machine_is_online()
if is_on_line:
user_info = get_user_info()
if user_info and user_info["user_token"] and user_info["device_id"]:
response = unbind_box_api(user_info["user_token"], user_info["device_id"])
if response and response["code"] == 1:
user_info_default = {
"username" : "",
"password" : "",
"user_token" : "",
"remember_information" : 0,
"binding_mohou" : 0,
"is_login" : 0
}
set_user_info(user_info_default);
result = 0
else:
result = 1
else:
result = 2
else:
result = 3
return self.write({"result" : result, "msg" : unbind_messages[result]})
@app.route(r"/update")
class update(tornado.web.RequestHandler):
def get(self):
clearUpdateInfoBegin()
initUpdateInfo()
return self.render(
"update.jinja2",
update_mode=self.get_argument("mode"),
latest_ver=getLatestVer(),
current_ver=getCurrentVer(),
update_desc=getUpdatePkgDesc(),
update_meta=getUpdateMeta()
)
@app.route(r"/pre_update")
class pre_update(tornado.web.RequestHandler):
def get(self):
result = "0"
clearUpdateInfoBegin()
initUpdateInfo()
return self.write(result)
@app.route(r"/netupdate_ajax")
class netupdate_ajax(tornado.web.RequestHandler):
def post(self):
result = "0"
clearUpdateInfoBegin()
initUpdateInfo()
netUpdate()
return self.write(result)
def get(self):
type = self.get_argument("type", default="meta")
retContent = {}
if type == "meta":
retContent=getUpdateMeta()
elif type == "cur_ver":
retContent = {"current_ver" : getCurrentVer()}
#retContent = {"current_ver" : "1.1"}
else:
pass
return self.write(retContent)
@app.route(r"/")
class moWifi(tornado.web.RequestHandler):
def get(self):
wifi_info = get_network_info("wlan0")
wire_info = get_network_info("eth0")
dns_info = get_dns_info()
serial_number = get_serial_number()
#user_info = get_user_info()
#print_info = get_active_machine_print_info()
return self.render(
"mowifi.jinja2",
wifi_info = wifi_info,
wire_info = wire_info,
dns_info = dns_info,
sn=serial_number
#user_info = user_info,
#print_info = print_info
)
@app.route(r"/setserialnumber")
class SerialNumber(tornado.web.RequestHandler):
def post(self):
serial_number = self.get_argument("sn", None)
if serial_number:
if set_serial_number(serial_number) == 0:
return self.write("0")
return self.write("1")
@app.route(r"/wifi")
class WifiSetting(tornado.web.RequestHandler):
def get(self):
wifissid = self.get_argument("ssid", None)
wifi_list = get_allwifi_info()
if wifissid:
wifi_list = filter(lambda x: x[0]==wifissid and x or False , wifi_list)
if wifi_list:
return self.write({'code': 0, 'msg': 'Success', 'data': {'ssid': wifi_list[0][0], 'state': wifi_list[0][1], 'lock': wifi_list[0][2], 'signal': wifi_list[0][3]}})
else:
return self.write({'code': 1, 'msg': 'SSID error.', 'data': {'wifi_list': []}})
else:
return self.write({'code': 0, 'msg': 'Success', 'data': {'wifi_list': wifi_list}})
def post(self):
wifissid = self.get_argument("ssid")
wifipwd = self.get_argument("pwd")
set_wifi(wifissid, wifipwd)
return self.write({'code': 0, 'msg': 'Success', 'data': {}})
@app.route(r"/isaccesscloud")
class AccessCloud(tornado.web.RequestHandler):
def get(self):
is_on_line = machine_is_online()
cur_client = HTTPClient()
response = cur_client.fetch("http://127.0.0.1:5000/status", request_timeout=10)
if response.error:
logger.warn("Failed to get current box info. error=%s", response.error)
is_on_line = False
res = json_decode(response.body)
if res["code"] != 0:
logger.warn("Failed to get current box info. ret_value=%d", res["ret_value"])
is_on_line = False
if is_on_line:
boxid = res["data"]["boxid"]
params=urllib.urlencode({
"token": "box_setting",
"boxid": boxid,
"progress": 2
})
headers = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Connection": "Keep-Alive"}
conn = httplib.HTTPConnection("yun.mohou.com")
conn.request(method="POST", url="/api/box/init-setting", body=params, headers=headers)
response = conn.getresponse()
response_json = response.read()
conn.close()
logger.info("Box setting result: " + str(response_json))
is_access_cloud = True
else:
is_access_cloud = False
return self.write({'code': 0, 'msg': 'Success', 'data': {'is_access_cloud': is_access_cloud}})
@app.route(r"/mowifiinfoajax")
class moWifiAjax(tornado.web.RequestHandler):
def get(self):
return self.render(
"wifiinfo.jinja2",
wifi_list=get_allwifi_info()
)
def post(self):
result = "0"
type = int(self.get_argument("type"))
if type == 1:
#connect wifi
wifissid = self.get_argument("wifissid")
wifipwd = self.get_argument("wifipwd")
set_wifi(wifissid, wifipwd)
return self.write(result)
elif (type == 2) or (type == 3):
#set ip address
if type == 2:
iface_name = "wlan0"
else:
iface_name = "eth0"
result = "0"
iface_info = {}
dns_info = {}
iface_info["dhcp"] = self.get_argument("dhcp")
iface_info["ip"] = ""
iface_info["netmask"] = ""
iface_info["gateway"] = ""
dns_info["dns"] = ""
if iface_info["dhcp"] == "0":
iface_info["ip"] = self.get_argument("ip")
iface_info["netmask"] = self.get_argument("mask")
iface_info["gateway"] = self.get_argument("gateway")
dns_info["dns"] = self.get_argument("dns")
set_network(iface_name, iface_info, dns_info)
return self.write(result)
else:
#Log incorrect type
pass
@app.route(r"/settings/machines")
class MachineDefaultConfig(tornado.web.RequestHandler):
def post(self):
json_strings = self.request.body
data = json.loads(json_strings)
alter_machine_info = get_default_machine_print_info(data["machine_name"], data["machine_type"])
return self.write({"result" : 0, "msg" : machine_config_messages[0],"data": alter_machine_info})
@app.route(r"/settings/machines/edit")
class MachineConfig(tornado.web.RequestHandler):
def post(self):
json_strings = self.request.body
data = json.loads(json_strings)
set_user_info({ "box_name": data["add_machine_data"]["box_name"] })
del data["add_machine_data"]["box_name"]
if data["machine_type_changed"] == "1":
write_print_info(data["add_machine_data"]["machine_name"], data["add_machine_data"]["machine_type"])
web_config = WebConfig.settings()
#保存打印机信息和切片参数
write_result_update=update_machine_config(data["machine_type_name"],data)
if write_result_update == 0:
return self.write({"result" : 1, "msg" : machine_config_messages[1]})
#如果是活动打印机的话还得更新CuraConfig.ini中的信息
current_activity_print_machine = get_current_activity_print_machine()
if current_activity_print_machine:
if data["machine_type_name"]:
if current_activity_print_machine==data["machine_type_name"]:
#如果是激活的打印机则更新CuraConfig
update_setting_gcode(current_activity_print_machine)
#更新preferences.ini中的machine_n节点信息
write_results=update_preferences_file_info(data["add_machine_data"])
if write_results==0:
return self.write({"result" : 1, "msg" : machine_config_messages[1]})
#
# if "api" in data.keys():
# if "enabled" in data["api"].keys(): web_config.set(["api", "enabled"], data["api"]["enabled"])
# if "key" in data["api"].keys(): web_config.set(["api", "key"], data["api"]["key"], True)
#
# if "appearance" in data.keys():
# if "name" in data["appearance"].keys(): web_config.set(["appearance", "name"], data["appearance"]["name"])
# if "color" in data["appearance"].keys(): web_config.set(["appearance", "color"], data["appearance"]["color"])
#
# if "printer" in data.keys():
# if "movementSpeedX" in data["printer"].keys(): web_config.setInt(["printerParameters", "movementSpeed", "x"], data["printer"]["movementSpeedX"])
# if "movementSpeedY" in data["printer"].keys(): web_config.setInt(["printerParameters", "movementSpeed", "y"], data["printer"]["movementSpeedY"])
# if "movementSpeedZ" in data["printer"].keys(): web_config.setInt(["printerParameters", "movementSpeed", "z"], data["printer"]["movementSpeedZ"])
# if "movementSpeedE" in data["printer"].keys(): web_config.setInt(["printerParameters", "movementSpeed", "e"], data["printer"]["movementSpeedE"])
# if "invertAxes" in data["printer"].keys(): web_config.set(["printerParameters", "invertAxes"], data["printer"]["invertAxes"])
#
# if "webcam" in data.keys():
# if "streamUrl" in data["webcam"].keys(): web_config.set(["webcam", "stream"], data["webcam"]["streamUrl"])
# if "snapshotUrl" in data["webcam"].keys(): web_config.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
# if "ffmpegPath" in data["webcam"].keys(): web_config.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
# if "bitrate" in data["webcam"].keys(): web_config.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
# if "watermark" in data["webcam"].keys(): web_config.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
# if "flipH" in data["webcam"].keys(): web_config.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
# if "flipV" in data["webcam"].keys(): web_config.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
#
# if "feature" in data.keys():
# if "gcodeViewer" in data["feature"].keys(): web_config.setBoolean(["feature", "gCodeVisualizer"], data["feature"]["gcodeViewer"])
# if "temperatureGraph" in data["feature"].keys(): web_config.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
# if "waitForStart" in data["feature"].keys(): web_config.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
# if "alwaysSendChecksum" in data["feature"].keys(): web_config.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
# if "sdSupport" in data["feature"].keys(): web_config.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
# if "sdAlwaysAvailable" in data["feature"].keys(): web_config.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
# if "swallowOkAfterResend" in data["feature"].keys(): web_config.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
if "serial" in data.keys():
# if "autoconnect" in data["serial"].keys(): web_config.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
if "port" in data["serial"].keys(): web_config.set(["serial", "port"], data["serial"]["port"])
if "baudrate" in data["serial"].keys():
if data["serial"]["baudrate"] == "AUTO":
web_config.set(["serial", "baudrate"], "AUTO")
else:
web_config.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
else:
web_config.set(["serial", "baudrate"], "AUTO")
# if "timeoutConnection" in data["serial"].keys(): web_config.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
# if "timeoutDetection" in data["serial"].keys(): web_config.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
# if "timeoutCommunication" in data["serial"].keys(): web_config.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
#
# oldLog = web_config.getBoolean(["serial", "log"])
# if "log" in data["serial"].keys(): web_config.setBoolean(["serial", "log"], data["serial"]["log"])
# if oldLog and not web_config.getBoolean(["serial", "log"]):
# # disable debug logging to serial.log
# logging.getLogger("SERIAL").debug("Disabling serial logging")
# logging.getLogger("SERIAL").setLevel(logging.CRITICAL)
# elif not oldLog and web_config.getBoolean(["serial", "log"]):
# # enable debug logging to serial.log
# logging.getLogger("SERIAL").setLevel(logging.DEBUG)
# logging.getLogger("SERIAL").debug("Enabling serial logging")
# if "folder" in data.keys():
# if "uploads" in data["folder"].keys(): web_config.setBaseFolder("uploads", data["folder"]["uploads"])
# if "timelapse" in data["folder"].keys(): web_config.setBaseFolder("timelapse", data["folder"]["timelapse"])
# if "timelapseTmp" in data["folder"].keys(): web_config.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
# if "logs" in data["folder"].keys(): web_config.setBaseFolder("logs", data["folder"]["logs"])
#
# if "temperature" in data.keys():
# if "profiles" in data["temperature"].keys(): web_config.set(["temperature", "profiles"], data["temperature"]["profiles"])
#
# if "terminalFilters" in data.keys():
# web_config.set(["terminalFilters"], data["terminalFilters"])
# cura = data.get("cura", None)
# if cura:
# path = cura.get("path")
# if path:
# web_config.set(["cura", "path"], path)
#
# config = cura.get("config")
# if config:
# web_config.set(["cura", "config"], config)
#
# # Enabled is a boolean so we cannot check that we have a result
# enabled = cura.get("enabled")
# web_config.setBoolean(["cura", "enabled"], enabled)
web_config.save()
restart_web_service()
return self.write({"result" : 0, "msg" : machine_config_messages[0]})
#~~ startup code
if __name__ == "__main__":
pid = os.fork()
if pid > 0:
sys.exit(0)
os.chdir("/")
os.setsid()
os.umask(0)
pid = os.fork()
if pid > 0:
sys.exit(0)
tornado.options.parse_command_line()
logger.info("Box management server start.")
app = app.instance()
server = tornado.httpserver.HTTPServer(app)
server.listen(options.port, options.host)
tornado.ioloop.IOLoop.instance().start() # start the tornado ioloop to
|
[
"xk@edeng.com"
] |
xk@edeng.com
|
c7d4f559b071a6305943bfc4d91e7588b85d7e56
|
0064d4b6f3908b2989a7965e49afa3f4bf65d095
|
/leetcode+牛客/数对.py
|
5b72a3cc93b41043b93a7ddfa04f1c54b3e5d8e2
|
[] |
no_license
|
MyHiHi/myLeetcode
|
d7a5c1c3a3a30ba517183f97369ed6c95e90cae3
|
ca36041af7f73d91c95cdbe9599ac5ec15a1243c
|
refs/heads/master
| 2021-05-20T08:29:37.017725
| 2020-05-03T05:17:05
| 2020-05-03T05:17:05
| 252,196,933
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,605
|
py
|
# -*- encoding: utf-8 -*-
'''
@File : 数对.py
@Time : 2020/02/06 16:41:42
@Author : Zhang tao
@Version : 1.0
@Desc : None
'''
'''
题目描述
牛牛以前在老师那里得到了一个正整数数对(x, y), 牛牛忘记他们具体是多少了。
但是牛牛记得老师告诉过他x和y均不大于n, 并且x除以y的余数大于等于k。
牛牛希望你能帮他计算一共有多少个可能的数对。
输入描述:
输入包括两个正整数n,k(1 <= n <= 10^5, 0 <= k <= n - 1)。
输出描述:
对于每个测试用例, 输出一个正整数表示可能的数对数量。
示例1
输入
5 2
输出
7
'''
'''
假设 n=13,k=3; 则
y取值[4,13],当y取值[0,3]时,x%y<3;
当y=5时,符合条件的是:
第e组(e:[1,n//y]) [x,y]
1[1--5] [3,5]
1 [4,5]
2[6--10] [8,5]
2 [9,5]
3 [13,5]
我们将上述结果分两种来计算:
1)在n/y=2次循环内,x=[0-5]和x=[6-10]中分别有y-k个是余数>=k的,因此是n/y*(y-k)
2)在2次循环外,x=[11-13],x有n%y=3种取值,其中有n%y-k+1个余数>=k;如果没有余数>=k的则count=0
'''
import sys;
n,k=map(int,sys.stdin.readline().split());
co=0;
if k==0:
co=n*n;
else:
for i in range(k+1,n+1):
a1=n//i;
a2=(i-k);
a3=max(n%i-k+1,0);
co+=a1*a2+a3;
print(co)
|
[
"909535692@qq.com"
] |
909535692@qq.com
|
f278355a25a49f4b0c27147692f22f1be13b9bbb
|
a4e1392bbd5ce36b0525adb9fd2ce799f9bd9a9c
|
/elmutube/asgi.py
|
077f86a1fe3ae002277f3b33298c6f776a217cc5
|
[] |
no_license
|
jenadiusnicholaus/ET
|
61855e02ba7322088457467101be169c69017582
|
649b6b77ca40647cc566f31ac07186d11fde459f
|
refs/heads/master
| 2023-08-06T05:59:47.040317
| 2020-08-14T14:07:49
| 2020-08-14T14:07:49
| 282,652,578
| 0
| 0
| null | 2021-09-22T19:30:43
| 2020-07-26T13:11:02
|
Python
|
UTF-8
|
Python
| false
| false
| 393
|
py
|
"""
ASGI config for elmutube project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'elmutube.settings')
application = get_asgi_application()
|
[
"ucode888@gmail.com"
] |
ucode888@gmail.com
|
626430580438a2b07deb1e0d86c6fb5a51533788
|
f58a9043915a6c4933b9d8a4d6bf9e43d1ee03b2
|
/day05/solution.py
|
10ee9413c537e1cee2c7fccb7b01ecaf65210cfc
|
[] |
no_license
|
tormobr/advent_of_code_2018
|
f8098cf05aa04ec12661f96b07b64bfdc194a10b
|
62f82642364e23e96abbfe52291fa8daa29af6cb
|
refs/heads/master
| 2021-07-13T20:29:49.440455
| 2020-12-09T02:15:12
| 2020-12-09T02:15:12
| 226,742,024
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,008
|
py
|
def part1(data):
result = data
current_length = len(data)
i = 0
while True:
if abs(ord(result[i]) - ord(result[i+1])) == 32:
result = result[:i] + result[i+2:]
current_length -= 2
i -= 2
i += 1
if i == len(result)-1:
break
return len(result)-1
def part2(data):
distinct = set([c.lower() for c in data.strip()])
results = []
data = [c for c in data.strip()]
for d in distinct:
result = list(filter(lambda x: x != d and x != d.upper(), data))
i = 0
while True:
if abs(ord(result[i]) - ord(result[i+1])) == 32:
result = result[:i] + result[i+2:]
i -= 2
i += 1
if i == len(result)-1:
break
results.append((d, len(result)))
return min(results, key=lambda x: x[1])
if __name__ =="__main__":
data = open("input.txt", "r").read()
print(part1(data))
print(part2(data))
|
[
"tormod.brandshoi@gmail.com"
] |
tormod.brandshoi@gmail.com
|
34a78ba79013ca413e0317e60bb94d1a72ce8dac
|
27c75711bbe10b3120c158971bb4e830af0c33e8
|
/AsZ/2015.10.05/G.py
|
fd3f46f380ce9ea4e3d0ba80ef0f8c5e3d305f5b
|
[] |
no_license
|
yl3i/ACM
|
9d2f7a6f3faff905eb2ed6854c2dbf040a002372
|
29bb023cb13489bda7626f8105756ef64f89674f
|
refs/heads/master
| 2021-05-22T02:00:56.486698
| 2020-04-04T05:45:10
| 2020-04-04T05:45:10
| 252,918,033
| 0
| 0
| null | 2020-04-04T05:36:11
| 2020-04-04T05:36:11
| null |
UTF-8
|
Python
| false
| false
| 1,466
|
py
|
from decimal import *
import sys
#sys.stdin = open("G.in", "r")
sys.stdin = open("game.in", "r")
sys.stdout = open("game.out", "w")
getcontext().prec = 100
dp, A, B, p, q = [[Decimal(0) for i in xrange(55)] for j in xrange(5)]
n, k = map(int, raw_input().split())
tmp = map(Decimal, raw_input().split())
for i in xrange(len(tmp)):
p[i + 1] = tmp[i]
q[i + 1] = Decimal(1) - p[i + 1]
def solve(a, b):
dp[a], dp[b] = Decimal(1), Decimal(0)
A[1], B[1] = Decimal(0), dp[1]
A[2], B[2] = Decimal(1), Decimal(0)
for i in xrange(2, n - 1):
A[i + 1] = (A[i] - A[i - 1] * q[i]) / p[i]
B[i + 1] = (B[i] - B[i - 1] * q[i]) / p[i]
dp[2] = (dp[n - 1] - B[n - 1]) / A[n - 1]
for i in xrange(3, n - 1):
dp[i] = A[i] * dp[2] + B[i]
key = dp[k]
return key
key = solve(1, n - 1)
ans = Decimal(0)
dp[n - 1], dp[n] = Decimal(1), Decimal(0)
A[0], B[0] = Decimal(0), dp[n]
A[1], B[1] = Decimal(1), Decimal(0)
for i in xrange(1, n - 1):
A[i + 1] = (A[i] - A[i - 1] * q[i]) / p[i]
B[i + 1] = (B[i] - B[i - 1] * q[i]) / p[i]
dp[1] = (dp[n - 1] - B[n - 1]) / A[n - 1]
ans += key * dp[1]
dp[1], dp[n] = Decimal(1), Decimal(0)
A[n], B[n] = Decimal(0), dp[n]
A[n - 1], B[n - 1] = Decimal(1), Decimal(0)
for i in xrange(n - 1, 1, -1):
A[i - 1] = (A[i] - A[i + 1] * p[i]) / q[i]
B[i - 1] = (B[i] - B[i + 1] * p[i]) / q[i]
dp[n - 1] = (dp[1] - B[1]) / A[1]
ans += (Decimal(1) - key) * dp[n - 1]
print float(ans)
|
[
"yuzhou627@gmail.com"
] |
yuzhou627@gmail.com
|
98f252e0b525235c53fd61d51c11cae7b33421bf
|
7323b8039f47c0457ae90173c963549b7d1e6823
|
/resolve/misc/combine.py
|
a70488376b9059fb42e2b8d13a7ffcaa9d2c88bc
|
[
"BSD-2-Clause"
] |
permissive
|
sniemi/SamPy
|
abce0fb941f011a3264a8d74c25b522d6732173d
|
e048756feca67197cf5f995afd7d75d8286e017b
|
refs/heads/master
| 2020-05-27T18:04:27.156194
| 2018-12-13T21:19:55
| 2018-12-13T21:19:55
| 31,713,784
| 5
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 873
|
py
|
'''
Simple script to median combine FITS files.
'''
import pyfits as PF
import numpy as np
import glob as g
def combineFITS(files,
exstension=0):
'''
A simple function that median combines FITS files
'''
#get data, ignore missing END
fhs = [PF.open(x, ignore_missing_end=True) for x in files]
datalist = [x[extension].data for x in fhs]
#check that the files are of the same size
if len(set(x.shape for x in datalist)) > 1:
print 'Images not of same size! Aborted!'
import sys;
sys.exit()
#median combine
median = np.median(datalist, axis=0)
#write an output
hdu = PF.PrimaryHDU(median)
hdulist = PF.HDUList([hdu])
hdulist.writeto('combined.fits')
if __name__ == '__main__':
#find all fits files
files = g.glob('*.fits')
#combine files
combineFITS(files)
|
[
"sniemi@tuonela.physics.unc.edu"
] |
sniemi@tuonela.physics.unc.edu
|
2cd959d3662b2ceba07b0ed259e5f3adf0a6b108
|
7a445fd4e0fa4f4d07964b7c7797ab6ebd15b3cf
|
/vidly/urls.py
|
1bfb6d379873a8c9ae63f01e4e0cc62b94b8e981
|
[] |
no_license
|
GrisoFandango/Django-Vidly-Tutorial
|
cd76e67536d4d6312f8501f8f42b154d0230d45f
|
6e8dbfa662930b1f5e24ff2145be28e280a93098
|
refs/heads/master
| 2021-06-23T22:40:11.563448
| 2019-11-26T23:29:25
| 2019-11-26T23:29:25
| 224,303,351
| 0
| 0
| null | 2021-06-10T22:23:36
| 2019-11-26T23:17:09
|
Python
|
UTF-8
|
Python
| false
| false
| 993
|
py
|
"""vidly URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from api.models import MovieResource
from . import views
movie_resource = MovieResource()
urlpatterns = [
path("", views.home),
path('admin/', admin.site.urls),
path("movies/", include("movies.urls")),
path("api/", include(movie_resource.urls))
]
|
[
"noreply@github.com"
] |
GrisoFandango.noreply@github.com
|
c3956894de35f8abca722c5e8bfc3bcd1b39489a
|
e4d89b96605c9f5aa081296e524868bc49a23034
|
/lyricsmaster/providers.py
|
812bdeb0631d7cb786abdded8aafd9dc9b7e1ba3
|
[
"MIT"
] |
permissive
|
soualid/lyricsmaster
|
2d8e35fc6f0c304aa50569149b10bea0757e6395
|
30bab8432d2801d7061a98076a8f0a9874d3c890
|
refs/heads/master
| 2020-03-26T10:55:01.493308
| 2018-08-01T04:02:08
| 2018-08-01T04:02:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 36,702
|
py
|
# -*- coding: utf-8 -*-
"""Main module.
This module defines the Api interface for the various Lyrics providers.
All lyrics providers inherit from the base class LyricsProvider.
"""
# We use abstract methods to ensure that all future classes inheriting from LyricsProvider will
# implement the required methods in order to have a nice and consistent API.
from abc import ABCMeta, abstractmethod
import re
import urllib3
import certifi
from bs4 import BeautifulSoup
# We use gevent in order to make asynchronous http requests while downloading lyrics.
# It is also used to patch the socket module to use SOCKS5 instead to interface with the Tor controller.
import gevent.monkey
from gevent.pool import Pool
# Python 2.7 compatibility
# Works for Python 2 and 3
try:
from importlib import reload
except ImportError:
try:
from imp import reload
except:
pass
# Importing the app models and utilities
from .models import Song, Album, Discography
from .utils import normalize
class LyricsProvider:
"""
This is the base class for all Lyrics Providers. If you wish to subclass this class, you must implement all
the methods defined in this class to be compatible with the LyricsMaster API.
Requests to fetch songs are executed asynchronously for better performance.
Tor anonymisation is provided if tor is installed on the system and a TorController is passed at instance creation.
:param tor_controller: TorController Object.
"""
__metaclass__ = ABCMeta
name = ''
def __init__(self, tor_controller=None):
if not self.__socket_is_patched():
gevent.monkey.patch_socket()
self.tor_controller = tor_controller
if not self.tor_controller:
user_agent = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
self.session = urllib3.PoolManager(maxsize=10, cert_reqs='CERT_REQUIRED', ca_certs=certifi.where(),
headers=user_agent)
else:
self.session = self.tor_controller.get_tor_session()
self.__tor_status__()
def __repr__(self):
return '{0}.{1}({2})'.format(__name__, self.__class__.__name__, self.tor_controller.__repr__())
def __tor_status__(self):
"""
Informs the user of the Tor status.
"""
if not self.tor_controller:
print('Anonymous requests disabled. The connexion will not be anonymous.')
elif self.tor_controller and not self.tor_controller.controlport:
print('Anonymous requests enabled. The Tor circuit will change according to the Tor network defaults.')
else:
print('Anonymous requests enabled. The Tor circuit will change for each album.')
def __socket_is_patched(self):
"""
Checks if the socket is patched or not.
:return: bool.
"""
return gevent.monkey.is_module_patched('socket')
@abstractmethod
def _has_lyrics(self, page):
"""
Must be implemented by children classes conforming to the LyricsMaster API.
Checks if the lyrics provider has the lyrics for the song or not.
:param page:
:return: bool.
"""
pass
@abstractmethod
def _has_artist(self, page):
"""
Must be implemented by children classes conforming to the LyricsMaster API.
Check if the artist is in the lyrics provider's database.
:param page:
:return: bool.
"""
pass
@abstractmethod
def _make_artist_url(self, artist):
"""
Must be implemented by children classes conforming to the LyricsMaster API.
Builds an url for the artist page of the lyrics provider.
:param artist:
:return: string or None.
"""
pass
@abstractmethod
def _clean_string(self, text):
"""
Must be implemented by children classes conforming to the LyricsMaster API.
Formats the text to conform to the lyrics provider formatting.
:param text:
:return: string or None.
"""
pass
def get_page(self, url):
"""
Fetches the supplied url and returns a request object.
:param url: string.
:return: urllib3.response.HTTPResponse Object or None.
"""
if not self.__socket_is_patched():
gevent.monkey.patch_socket()
try:
req = self.session.request('GET', url)
except Exception as e:
print(e)
req = None
print('Unable to download url ' + url)
return req
def get_lyrics(self, artist, album=None, song=None):
"""
This is the main method of this class.
Connects to the Lyrics Provider and downloads lyrics for all the albums of the supplied artist and songs.
Returns a Discography Object or None if the artist was not found on the Lyrics Provider.
:param artist: string
Artist name.
:return: models.Discography object or None.
"""
raw_html = self.get_artist_page(artist)
if not raw_html:
print('{0} was not found on {1}'.format(artist, self.name))
return None
albums = self.get_albums(raw_html)
if album:
# If user supplied a specific album
albums = [elmt for elmt in albums if album.lower() in self.get_album_infos(elmt)[0].lower()]
album_objects = []
for elmt in albums:
album_title, release_date = self.get_album_infos(elmt)
song_links = self.get_songs(elmt)
if song:
# If user supplied a specific song
song_links = [link for link in song_links if song.lower() in link.text.lower()]
if self.tor_controller and self.tor_controller.controlport:
# Renew Tor circuit before starting downloads.
self.tor_controller.renew_tor_circuit()
self.session = self.tor_controller.get_tor_session()
print('Downloading {0}'.format(album_title))
pool = Pool(25) # Sets the worker pool for async requests. 25 is a nice value to not annoy site owners ;)
results = [pool.spawn(self.create_song, *(link, artist, album_title)) for link in song_links]
pool.join() # Gathers results from the pool
songs = [song.value for song in results]
album_obj = Album(album_title, artist, songs, release_date)
album_objects.append(album_obj)
print('{0} succesfully downloaded'.format(album_title))
discography = Discography(artist, album_objects)
return discography
def get_artist_page(self, artist):
"""
Fetches the web page for the supplied artist.
:param artist: string.
Artist name.
:return: string or None.
Artist's raw html page. None if the artist page was not found.
"""
artist = self._clean_string(artist)
url = self._make_artist_url(artist)
if not url:
return None
raw_html = self.get_page(url).data
artist_page = BeautifulSoup(raw_html, 'lxml')
if not self._has_artist(artist_page):
return None
return raw_html
def get_lyrics_page(self, url):
"""
Fetches the web page containing the lyrics at the supplied url.
:param url: string.
Lyrics url.
:return: string or None.
Lyrics's raw html page. None if the lyrics page was not found.
"""
raw_html = self.get_page(url).data
lyrics_page = BeautifulSoup(raw_html, 'lxml')
if not self._has_lyrics(lyrics_page):
return None
return raw_html
@abstractmethod
def get_albums(self, raw_artist_page):
"""
Must be implemented by children classes conforming to the LyricsMaster API.
Fetches the albums section in the supplied html page.
:param raw_artist_page: Artist's raw html page.
:return: list.
List of BeautifulSoup objects.
"""
pass
@abstractmethod
def get_album_infos(self, tag):
"""
Must be implemented by children classes conforming to the LyricsMaster API.
Extracts the Album informations from the tag
:param tag: BeautifulSoup object.
:return: tuple(string, string).
Album title and release date.
"""
pass
@abstractmethod
def get_songs(self, album):
"""
Must be implemented by children classes conforming to the LyricsMaster API.
Fetches the links to the songs of the supplied album.
:param album: BeautifulSoup object.
:return: List of BeautifulSoup Link objects.
"""
pass
@abstractmethod
def create_song(self, link, artist, album_title):
"""
Must be implemented by children classes conforming to the LyricsMaster API.
Creates a Song object.
:param link: BeautifulSoup Link object.
:param artist: string.
:param album_title: string.
:return: models.Song object or None.
"""
pass
@abstractmethod
def extract_lyrics(self, song):
"""
Must be implemented by children classes conforming to the LyricsMaster API.
Extracts the lyrics from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string or None.
Formatted lyrics.
"""
pass
@abstractmethod
def extract_writers(self, lyrics_page):
"""
Must be implemented by children classes conforming to the LyricsMaster API.
Extracts the writers from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string or None.
Song writers.
"""
pass
class LyricWiki(LyricsProvider):
"""
Class interfacing with http://lyrics.wikia.com .
This class is used to retrieve lyrics from LyricWiki.
"""
base_url = 'http://lyrics.wikia.com'
name = 'LyricWiki'
def _has_lyrics(self, lyrics_page):
"""
Checks if the lyrics provider has the lyrics for the song or not.
:param lyrics_page:
:return: bool.
"""
return not lyrics_page.find("div", {'class': 'noarticletext'})
_has_artist = _has_lyrics
def _make_artist_url(self, artist):
"""
Builds an url for the artist page of the lyrics provider.
:param artist:
:return: string.
"""
url = self.base_url + '/wiki/' + artist
return url
def get_album_page(self, artist, album):
"""
Fetches the album page for the supplied artist and album.
:param artist: string.
Artist name.
:param album: string.
Album title.
:return: string or None.
Album's raw html page. None if the album page was not found.
"""
artist = self._clean_string(artist)
album = self._clean_string(album)
url = self.base_url + '/wiki/' + artist + ':' + album
raw_html = self.get_page(url).data
album_page = BeautifulSoup(raw_html, 'lxml')
if album_page.find("div", {'class': 'noarticletext'}):
return None
return raw_html
def get_albums(self, raw_artist_page):
"""
Fetches the albums section in the supplied html page.
:param raw_artist_page: Artist's raw html page.
:return: list.
List of BeautifulSoup objects.
"""
artist_page = BeautifulSoup(raw_artist_page, 'lxml')
albums = [tag for tag in artist_page.find_all("span", {'class': 'mw-headline'}) if
tag.attrs['id'] not in ('Additional_information', 'External_links')]
return albums
def get_album_infos(self, tag):
"""
Extracts the Album informations from the tag
:param tag: BeautifulSoup object.
:return: tuple(string, string).
Album title and release date.
"""
i = tag.text.index(' (')
album_title = tag.text[:i]
release_date = re.findall(r'\(([^()]+)\)', tag.text)[0]
return album_title, release_date
def get_songs(self, album):
"""
Fetches the links to the songs of the supplied album.
:param album: BeautifulSoup object.
:return: List of BeautifulSoup Link objects.
"""
parent_node = album.parent
while parent_node.name != 'ol':
parent_node = parent_node.next_sibling
song_links = [elmt.find('a') for elmt in parent_node.find_all('li')]
return song_links
def create_song(self, link, artist, album_title):
"""
Creates a Song object.
:param link: BeautifulSoup Link object.
:param artist: string.
:param album_title: string.
:return: models.Song object or None.
"""
if not link.attrs['href'].startswith(self.base_url):
song_url = self.base_url + link.attrs['href']
else:
song_url = link.attrs['href']
song_title = link.attrs['title']
song_title = song_title[song_title.index(':') + 1:]
if '(page does not exist' in song_title:
return None
raw_lyrics_page = self.get_lyrics_page(song_url)
if not raw_lyrics_page:
return None
lyrics_page = BeautifulSoup(raw_lyrics_page, 'lxml')
lyrics = self.extract_lyrics(lyrics_page)
writers = self.extract_writers(lyrics_page)
song = Song(song_title, album_title, artist, lyrics, writers)
return song
def extract_lyrics(self, lyrics_page):
"""
Extracts the lyrics from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string or None.
Formatted lyrics.
"""
lyric_box = lyrics_page.find("div", {'class': 'lyricbox'})
lyrics = '\n'.join(lyric_box.strings)
return lyrics
def extract_writers(self, lyrics_page):
"""
Extracts the writers from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string or None.
Song writers.
"""
writers_box = lyrics_page.find("table", {'class': 'song-credit-box'})
if writers_box:
writers = writers_box.find_all('p')[-1].text.strip()
else:
writers = None
return writers
def _clean_string(self, text):
"""
Cleans the supplied string and formats it to use in a url.
:param text: string.
Text to be cleaned.
:return: string.
Cleaned text.
"""
for elmt in [('#', 'Number_'), ('[', '('), (']', ')'), ('{', '('), ('}', ')'), (' ', '_')]:
text = text.replace(*elmt)
return text
class AzLyrics(LyricsProvider):
"""
Class interfacing with https://azlyrics.com .
This class is used to retrieve lyrics from AzLyrics.
"""
base_url = 'https://www.azlyrics.com'
search_url = 'https://search.azlyrics.com/search.php?q='
name = 'AzLyrics'
def _has_lyrics(self, lyrics_page):
"""
Checks if the lyrics provider has the lyrics for the song or not.
:param lyrics_page:
:return: bool.
"""
if lyrics_page.find("div", {'class': 'lyricsh'}):
return True
else:
return False
def _has_artist(self, page):
"""
Check if the artist is in the lyrics provider's database.
:param lyrics_page:
:return: bool.
"""
if page.find("div", {'id': 'listAlbum'}):
return True
else:
return False
def _has_artist_result(self, page):
"""
Checks if the lyrics provider has the lyrics for the song or not.
:param lyrics_page:
:return: bool.
"""
artist_result = page.find("div", {'class': 'panel-heading'})
if artist_result.find('b').text == 'Artist results:':
return True
else:
return False
def _make_artist_url(self, artist):
"""
Builds an url for the artist page of the lyrics provider.
:param artist:
:return: string.
"""
return self.search(artist)
def search(self, artist):
"""
Searches for the artist in the supplier's database.
:param artist: Artist's name.
:return: url or None.
Url to the artist's page if found. None if not Found.
"""
artist = artist.replace(' ', '+')
if artist.lower().startswith('the'):
artist = artist[4:]
url = self.search_url + artist
search_results = self.get_page(url).data
results_page = BeautifulSoup(search_results, 'lxml')
if not self._has_artist_result(results_page):
return None
target_node = results_page.find("div", {'class': 'panel-heading'}).find_next_sibling("table")
artist_url = target_node.find('a').attrs['href']
if not artist_url:
return None
if not artist_url.startswith(self.base_url):
artist_url = self.base_url + artist_url
return artist_url
def get_albums(self, raw_artist_page):
"""
Fetches the albums section in the supplied html page.
:param raw_artist_page: Artist's raw html page.
:return: list.
List of BeautifulSoup objects.
"""
artist_page = BeautifulSoup(raw_artist_page, 'lxml')
albums = [tag for tag in artist_page.find_all("div", {'id': 'listAlbum'})]
return albums
def get_album_infos(self, tag):
"""
Extracts the Album informations from the tag
:param tag: BeautifulSoup object.
:return: tuple(string, string).
Album title and release date.
"""
album_infos = tag.find("div", {'class': 'album'}).text
album_title = re.findall(r'"([^"]*)"', album_infos)[0]
release_date = re.findall(r'\(([^()]+)\)', tag.text)[0]
return album_title, release_date
def get_songs(self, album):
"""
Fetches the links to the songs of the supplied album.
:param album: BeautifulSoup object.
:return: List of BeautifulSoup Link objects.
"""
song_links = album.find_all('a')
song_links = [song for song in song_links if 'href' in song.attrs]
return song_links
def create_song(self, link, artist, album_title):
"""
Creates a Song object.
:param link: BeautifulSoup Link object.
:param artist: string.
:param album_title: string.
:return: models.Song object or None.
"""
song_title = link.text
raw_lyrics_page = self.get_lyrics_page(self.base_url + link.attrs['href'].replace('..', ''))
if not raw_lyrics_page:
return None
lyrics_page = BeautifulSoup(raw_lyrics_page, 'lxml')
lyrics = self.extract_lyrics(lyrics_page)
writers = self.extract_writers(lyrics_page)
song = Song(song_title, album_title, artist, lyrics, writers)
return song
def extract_lyrics(self, lyrics_page):
"""
Extracts the lyrics from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string.
Formatted lyrics.
"""
lyric_box = lyrics_page.find("div", {"class": None, "id": None})
lyrics = ''.join(lyric_box.strings)
return lyrics
def extract_writers(self, lyrics_page):
"""
Extracts the writers from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string or None.
Song writers or None.
"""
writers_box = lyrics_page.find("div", {'class': 'smt'})
if writers_box:
writers = writers_box.text.strip()
else:
writers = None
return writers
def _clean_string(self, text):
"""
Cleans the supplied string and formats it to use in a url.
:param text: string.
Text to be cleaned.
:return: string.
Cleaned text.
"""
return text
class Genius(LyricsProvider):
"""
Class interfacing with https://genius.com .
This class is used to retrieve lyrics from Genius.
"""
base_url = 'https://genius.com'
search_url = base_url + '/search?q='
name = 'Genius'
def _has_lyrics(self, page):
"""
Checks if the lyrics provider has the lyrics for the song or not.
:param lyrics_page:
:return: bool.
"""
if page.find("div", {'class': 'song_body-lyrics'}):
return True
else:
return False
def _has_artist(self, page):
"""
Check if the artist is in the lyrics provider's database.
:param lyrics_page:
:return: bool.
"""
if not page.find("div", {'class': 'render_404'}):
return True
else:
return False
def _make_artist_url(self, artist):
"""
Builds an url for the artist page of the lyrics provider.
:param artist:
:return: string.
"""
url = self.base_url + '/artists/' + artist
return url
def get_albums(self, raw_artist_page):
"""
Fetches the albums section in the supplied html page.
:param raw_artist_page: Artist's raw html page.
:return: list.
List of BeautifulSoup objects.
"""
artist_page = BeautifulSoup(raw_artist_page, 'lxml')
albums_link = artist_page.find("a", {'class': 'full_width_button'})
albums_link = albums_link.attrs['href'].replace('songs?', 'albums?')
albums_page = BeautifulSoup(self.get_page(self.base_url + albums_link).data, 'lxml')
albums = [tag for tag in albums_page.find_all("a", {'class': 'album_link'})]
return albums
def get_album_infos(self, tag):
"""
Extracts the Album informations from the tag
:param tag: BeautifulSoup object.
:return: tuple(string, string).
Album title and release date.
"""
album_title = tag.text
album_page = BeautifulSoup(self.get_page(self.base_url + tag.attrs['href']).data, 'lxml')
info_box = album_page.find("div", {'class': 'header_with_cover_art-primary_info'})
metadata = [elmt for elmt in info_box.find_all("div", {'class': 'metadata_unit'}) if elmt.text.startswith('Released')]
if metadata:
release_date = metadata[0].text
else:
release_date = ''
return album_title, release_date
def get_songs(self, album):
"""
Fetches the links to the songs of the supplied album.
:param album: BeautifulSoup object.
:return: List of BeautifulSoup Link objects.
"""
album_page = BeautifulSoup(self.get_page(self.base_url + album.attrs['href']).data, 'lxml')
song_links = album_page.find_all("div", {'class': 'chart_row chart_row--light_border chart_row--full_bleed_left chart_row--align_baseline chart_row--no_hover'})
song_links = [song.find('a') for song in song_links]
return song_links
def create_song(self, link, artist, album_title):
"""
Creates a Song object.
:param link: BeautifulSoup Link object.
:param artist: string.
:param album_title: string.
:return: models.Song object or None.
"""
if not link.attrs['href'].startswith(self.base_url):
song_url = self.base_url + link.attrs['href']
else:
song_url = link.attrs['href']
song_title = link.text.strip('\n').split('\n')[0].lstrip()
raw_lyrics_page = self.get_lyrics_page(song_url)
if not raw_lyrics_page:
return None
lyrics_page = BeautifulSoup(raw_lyrics_page, 'lxml')
lyrics = self.extract_lyrics(lyrics_page)
writers = self.extract_writers(lyrics_page)
song = Song(song_title, album_title, artist, lyrics, writers)
return song
def extract_lyrics(self, lyrics_page):
"""
Extracts the lyrics from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string.
Formatted lyrics.
"""
lyric_box = lyrics_page.find("div", {"class": 'lyrics'})
lyrics = ''.join(lyric_box.strings)
return lyrics
def extract_writers(self, lyrics_page):
"""
Extracts the writers from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string.
Song writers or None.
"""
writers_box = [elmt for elmt in lyrics_page.find_all("span", {'class': 'metadata_unit-label'}) if elmt.text == "Written By"]
if writers_box:
target_node = writers_box[0].find_next_sibling("span", {'class': 'metadata_unit-info'})
writers = target_node.text.strip()
else:
writers = None
return writers
def _clean_string(self, text):
"""
Cleans the supplied string and formats it to use in a url.
:param text: string.
Text to be cleaned.
:return: string.
Cleaned text.
"""
text = normalize(text).lower().capitalize()
return text
class Lyrics007(LyricsProvider):
"""
Class interfacing with https://www.lyrics007.com .
This class is used to retrieve lyrics from Lyrics007.
"""
base_url = 'https://www.lyrics007.com'
search_url = base_url + '/search.php?category=artist&q='
name = 'Lyrics007'
def _has_lyrics(self, page):
"""
Checks if the lyrics provider has the lyrics for the song or not.
:param lyrics_page:
:return: bool.
"""
if page.find("div", {'class': 'lyrics'}):
return True
else:
return False
def _has_artist(self, page):
"""
Check if the artist is in the lyrics provider's database.
:param lyrics_page:
:return: bool.
"""
if page.find("ul", {'class': 'song_title'}):
return True
else:
return False
def _has_artist_result(self, page):
"""
Check if the artist is in the lyrics provider's database.
:param lyrics_page:
:return: bool.
"""
artist_link = page.find("div", {'id': 'search_result'}).find('a')
if artist_link:
return True
else:
return False
def _make_artist_url(self, artist):
"""
Builds an url for the artist page of the lyrics provider.
:param artist:
:return: string.
"""
return self.search(artist)
def search(self, artist):
"""
Searches for the artist in the supplier's database.
:param raw_artist_page: Artist's raw html page.
:return: string or None.
Artist's url page.
"""
artist = "".join([c if (c.isalnum() or c == '.') else "+" for c in artist])
url = self.search_url + artist
search_results = self.get_page(url).data
results_page = BeautifulSoup(search_results, 'lxml')
if not self._has_artist_result(results_page):
return None
artist_url = results_page.find("div", {'id': 'search_result'}).find('a').attrs['href']
if not artist_url:
return None
if not artist_url.startswith(self.base_url):
artist_url = self.base_url + artist_url
return artist_url
def get_albums(self, raw_artist_page):
"""
Fetches the albums section in the supplied html page.
:param raw_artist_page: Artist's raw html page.
:return: list.
List of BeautifulSoup objects.
"""
artist_page = BeautifulSoup(raw_artist_page, 'lxml')
albums = [tag for tag in artist_page.find_all('li') if tag.find('b')]
return albums
def get_album_infos(self, tag):
"""
Extracts the Album informations from the tag
:param tag: BeautifulSoup object.
:return: tuple(string, string).
Album title and release date.
"""
release_date, album_title = tag.text.split(': ')
return album_title, release_date
def get_songs(self, album):
"""
Fetches the links to the songs of the supplied album.
:param album: BeautifulSoup object.
:return: List of BeautifulSoup Link objects.
"""
target_node = album.find_next_sibling("ul")
song_links = [elmt.find('a') for elmt in target_node.find_all('li') if elmt.find('a')]
return song_links
def create_song(self, link, artist, album_title):
"""
Creates a Song object.
:param link: BeautifulSoup Link object.
:param artist: string.
:param album_title: string.
:return: models.Song object or None.
"""
if not link.attrs['href'].startswith(self.base_url):
song_url = self.base_url + link.attrs['href']
else:
song_url = link.attrs['href']
song_title = link.text
raw_lyrics_page = self.get_lyrics_page(song_url)
if not raw_lyrics_page:
return None
lyrics_page = BeautifulSoup(raw_lyrics_page, 'lxml')
lyrics = self.extract_lyrics(lyrics_page)
writers = self.extract_writers(lyrics_page)
song = Song(song_title, album_title, artist, lyrics, writers)
return song
def extract_lyrics(self, lyrics_page):
"""
Extracts the lyrics from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string.
Formatted lyrics.
"""
lyric_box = lyrics_page.find("div", {'class': 'lyrics'})
lyrics = '\n'.join(lyric_box.strings)
return lyrics
def extract_writers(self, lyrics_page):
"""
Extracts the writers from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string.
Song writers or None.
"""
writers_box = [elmt for elmt in lyrics_page.strings if
elmt.lower().startswith('writers:') or elmt.lower().startswith('writer:')]
if writers_box:
writers = writers_box[0].strip()
else:
writers = None
return writers
def _clean_string(self, text):
"""
Cleans the supplied string and formats it to use in a url.
:param text: string.
Text to be cleaned.
:return: string.
Cleaned text.
"""
return text
class MusixMatch(LyricsProvider):
"""
Class interfacing with https://www.musixmatch.com .
This class is used to retrieve lyrics from MusixMatch.
"""
base_url = 'https://www.musixmatch.com'
search_url = base_url + '/search/{0}/artists'
name = 'MusixMatch'
def _has_lyrics(self, page):
"""
Checks if the lyrics provider has the lyrics for the song or not.
:param lyrics_page:
:return: bool.
"""
if page.find("p", {'class': 'mxm-lyrics__content '}):
return True
else:
return False
def _has_artist(self, page):
"""
Check if the artist is in the lyrics provider's database.
:param lyrics_page:
:return: bool.
"""
if page.find("div", {'class': 'artist-page main-wrapper'}):
return True
else:
return False
def _make_artist_url(self, artist):
"""
Builds an url for the artist page of the lyrics provider.
:param artist:
:return: string.
"""
return self.base_url + '/artist/' + artist
def get_albums(self, raw_artist_page):
"""
Fetches the albums section in the supplied html page.
:param raw_artist_page: Artist's raw html page.
:return: list.
List of BeautifulSoup objects.
"""
artist_page = BeautifulSoup(raw_artist_page, 'lxml')
albums_link = artist_page.find("li", {'id': 'albums'})
albums_link = albums_link.find('a').attrs['href']
albums_page = BeautifulSoup(self.get_page(self.base_url + albums_link).data, 'lxml')
albums = [tag for tag in albums_page.find_all("div", {'class': 'media-card-text'})]
return albums
def get_album_infos(self, tag):
"""
Extracts the Album informations from the tag
:param tag: BeautifulSoup object.
:return: tuple(string, string).
Album title and release date.
"""
album_title = tag.find('h2').text
release_date = tag.find('h3').text
return album_title, release_date
def get_songs(self, album):
"""
Fetches the links to the songs of the supplied album.
:param album: BeautifulSoup object.
:return: List of BeautifulSoup Link objects.
"""
album_page = BeautifulSoup(self.get_page(self.base_url + album.find('a').attrs['href']).data, 'lxml')
album_div = album_page.find("div", {'class': 'mxm-album__tracks mxm-collection-container'})
song_links = album_div.find_all("li", {'class': re.compile("^mui-collection__item")})
song_links = [song.find('a') for song in song_links]
return song_links
def create_song(self, link, artist, album_title):
"""
Creates a Song object.
:param link: BeautifulSoup Link object.
:param artist: string.
:param album_title: string.
:return: models.Song object or None.
"""
if not link.attrs['href'].startswith(self.base_url):
song_url = self.base_url + link.attrs['href']
else:
song_url = link.attrs['href']
song_title = link.text
raw_lyrics_page = self.get_lyrics_page(song_url)
if not raw_lyrics_page:
return None
lyrics_page = BeautifulSoup(raw_lyrics_page, 'lxml')
lyrics = self.extract_lyrics(lyrics_page)
writers = self.extract_writers(lyrics_page)
song = Song(song_title, album_title, artist, lyrics, writers)
return song
def extract_lyrics(self, lyrics_page):
"""
Extracts the lyrics from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string.
Formatted lyrics.
"""
lyric_box = lyrics_page.find("p", {'class': re.compile("^mxm-lyrics__content")})
lyrics = '\n'.join(lyric_box.strings)
return lyrics
def extract_writers(self, lyrics_page):
"""
Extracts the writers from the lyrics page of the supplied song.
:param lyrics_page: BeautifulSoup Object.
BeautifulSoup lyrics page.
:return: string.
Song writers or None.
"""
writers_box = lyrics_page.find("p", {'class': re.compile("^mxm-lyrics__copyright")})
if writers_box:
writers = writers_box.text.strip()
else:
writers = None
return writers
def _clean_string(self, text):
"""
Cleans the supplied string and formats it to use in a url.
:param text: string.
Text to be cleaned.
:return: string.
Cleaned text.
"""
text = text.replace(' ', '-').replace('.', '-')
if text[-1] == '-':
text = text[:-1]
return text
if __name__ == "__main__":
pass
|
[
"sekou.diao@gmail.com"
] |
sekou.diao@gmail.com
|
62d60cdddcf39f00ac2ccab8f6af6efc0d40a9e5
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_204/87.py
|
7018c11415bc4175318f2b8b39eb1e9f6df5c51a
|
[] |
no_license
|
dr-dos-ok/Code_Jam_Webscraper
|
c06fd59870842664cd79c41eb460a09553e1c80a
|
26a35bf114a3aa30fc4c677ef069d95f41665cc0
|
refs/heads/master
| 2020-04-06T08:17:40.938460
| 2018-10-14T10:12:47
| 2018-10-14T10:12:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,950
|
py
|
# python 3.6
import numpy as np
import math
import networkx as nx
import fractions
from functools import reduce
import time
import fileinput
import multiprocessing
def read():
n, p = next_int()
r = [int(s) for s in next_line().split()]
q = []
for i in range(n):
q.append([int(s) for s in next_line().split()])
return n, p, r, q
def solve(inp):
n, p, r, q = inp
for row in q:
row.sort()
q1 = []
for i, row in enumerate(q):
q1.append([])
for x in row:
y = (math.ceil(x/r[i]/1.1), math.floor(x/r[i]/0.9))
if y[0]<=y[1]:
q1[len(q1)-1].append(y)
if len(q1) == 1:
return len(q1[0])
res = 0
for x in q1[0]:
can = [True] + [False] * (n-1)
for i,row in enumerate(q1):
if i==0:
continue
for y in row:
if is_pair(x, y):
can[i] = True
if can == [True] * n:
res += 1
for i, row in enumerate(q1):
if i == 0:
continue
for y in row:
if is_pair(x, y):
row.remove(y)
break
#res = ""
return res
def is_pair(a,b):
return a[0]<=b[1] and a[1]>=b[0]
def main():
t = next_int() # read a line with a single integer
inputs = []
for case_number in range(1, t + 1):
inputs.append(read())
k = multiprocessing.cpu_count()
p = multiprocessing.Pool(k)
outputs = list(map(solve, inputs))
for case_number, res in enumerate(outputs):
print("Case #{}: {}".format(case_number + 1, res))
def is_in_map(i, j, m, n):
return 0 <= i < m and 0 <= j < n
def create_file_line_iterator():
for line in fileinput.input():
yield line
def next_line():
return next(fileLineIterator).strip()
def next_int():
next_ints_line = next_line().split()
return [int(s) for s in next_ints_line] if len(next_ints_line) > 1 else int(next_ints_line[0])
class MyFraction(object):
def __init__(self, n, d):
if d == 0:
self.npa = np.nan
else:
gcd = math.gcd(n, d)
gcd *= 1 if d > 0 else -1
n1, d1 = n // gcd, d // gcd
self.npa = np.array([n1, d1], dtype=np.int64)
def __eq__(self, other):
return self.npa[0] == other.npa[0] and self.npa[1] == other.npa[1]
def __cmp__(self, other):
r = self.npa[0] * other.npa[1] - self.npa[1] * other.npa[0]
if r < 0:
return -1
if r > 0:
return 1
return 0
def __lt__(self, other):
return self.npa[0] * other.npa[1] - self.npa[1] * other.npa[0] < 0
def __le__(self, other):
return self.npa[0] * other.npa[1] - self.npa[1] * other.npa[0] <= 0
fileLineIterator = create_file_line_iterator()
if __name__ == '__main__':
main()
|
[
"miliar1732@gmail.com"
] |
miliar1732@gmail.com
|
5d6e84335ad50ff1132b4f8f2258e5acb91cd14c
|
9827269c84a2afc599a8ac8ac88027b25ef74d78
|
/02_40333_wsd_test.py
|
5be79c7280ecff968ea4e0631acd5e4185d1312a
|
[] |
no_license
|
caonlp/wsd_bert_tensorflow_version
|
2dbb7883d8a1bc5cedbe0d69a04a8cdda3ce757f
|
7cf786d1803ac6e49292469b1afdf71838295b25
|
refs/heads/main
| 2023-03-13T22:45:26.361832
| 2021-03-04T06:35:06
| 2021-03-04T06:35:06
| 344,372,725
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,309
|
py
|
import tensorflow as tf
import numpy as np
import codecs
from keras.utils import to_categorical
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def load_wsd_train_x():
wsd_train_x = codecs.open('40333_train_data', mode = 'r', encoding= 'utf-8')
line = wsd_train_x.readline()
list1 = []
while line:
a = line.split()
b = a[3:]
list1.append(b)
line = wsd_train_x.readline()
return np.array(list1)
wsd_train_x.close()
def load_wsd_test_x():
wsd_test_x = codecs.open('40333_test_data', mode = 'r', encoding= 'utf-8')
line = wsd_test_x.readline()
list1 = []
while line:
a = line.split()
b = a[3:]
list1.append(b)
line = wsd_test_x.readline()
return np.array(list1)
wsd_test_x.close()
def load_wsd_train_y():
wsd_train_y = codecs.open('40333_train_target', mode = 'r', encoding = 'utf-8')
line = wsd_train_y.readline()
list1 = []
while line:
a = line.split()
b = a[1:2]
list1.append(b)
line = wsd_train_y.readline()
return (np.array(list1)).reshape(50,)
wsd_train_y.close()
def load_wsd_test_y():
wsd_test_y = codecs.open('40333_test_target', mode = 'r', encoding = 'utf-8')
line = wsd_test_y.readline()
list1 = []
while line:
a = line.split()
b = a[1:2]
list1.append(b)
line = wsd_test_y.readline()
return (np.array(list1)).reshape(50,)
wsd_test_y.close()
b = np.zeros(50)
wsd_train_x = load_wsd_train_x()
wsd_test_x = load_wsd_test_x()
wsd_train_y = load_wsd_train_y()
wsd_train_y = to_categorical(wsd_train_y)
#wsd_train_y = np.c_[wsd_train_y, b]
wsd_test_y = load_wsd_test_y()
wsd_test_y = to_categorical(wsd_test_y)
#wsd_test_y = np.c_[wsd_test_y, b]
max_epoch = 100
train_size = wsd_train_x.shape[0]
batch_size = 10
n_batch = train_size // batch_size
layer_num = 2
gogi_num = 3
if layer_num == 3:
x = tf.placeholder(tf.float32, [None, 768])
y = tf.placeholder(tf.float32, [None, gogi_num])
W1 = tf.Variable(tf.zeros([768, 50]))
b1 = tf.Variable(tf.zeros([50]))
L1 = tf.nn.sigmoid(tf.matmul(x, W1) + b1)
W2 = tf.Variable(tf.zeros([50, gogi_num]))
b2 = tf.Variable(tf.zeros[gogi_num])
predict = tf.nn.softmax(tf.matmul(L1, W2) + b2)
if layer_num == 2:
x = tf.placeholder(tf.float32, [None, 768])
y = tf.placeholder(tf.float32, [None, gogi_num])
W = tf.Variable(tf.zeros([768, gogi_num]))
b = tf.Variable(tf.zeros([gogi_num]))
predict = tf.nn.softmax(tf.matmul(x, W) + b)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=predict))
train_step = tf.train.AdamOptimizer().minimize(loss)
init = tf.global_variables_initializer()
correct_predict = tf.equal(tf.argmax(y, 1), tf.argmax(predict, 1))
accuracy = tf.reduce_mean(tf.cast(correct_predict, tf.float32))
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
saver.restore(sess, 'model/40333_wsd_model.ckpt')
print("40333(normal) : " + str(sess.run(accuracy, feed_dict={x:wsd_test_x, y:wsd_test_y})))
|
[
"noreply@github.com"
] |
caonlp.noreply@github.com
|
2eaec93aa62c8791797660c5d6df1b3f7f536b76
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_267/ch132_2020_04_01_10_51_00_770814.py
|
3618f607a3f1c5924205b5948b23e593ff000985
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 90
|
py
|
import math
def calcula_trabalho(F,theta,s):
trabalho=F*math.cos(math.radians(theta)*s
|
[
"you@example.com"
] |
you@example.com
|
6fd8711ad825f854f934a8cf6f2d64d1901e4138
|
bf4f7f73a642cb018c8ab507d40360454a9e58a1
|
/approaches/networkx-graph/source_words_only.py
|
0f85c0cd2f3eddb123a1f5ea6aac56243f903f3e
|
[
"MIT"
] |
permissive
|
athityakumar/btp
|
b17ee3c53488b990a274c94d01ef467b7b6f6943
|
a1bdad0ed6162faa482673347707c09228d6cd9c
|
refs/heads/master
| 2021-01-20T02:48:13.919021
| 2018-04-06T08:01:50
| 2018-04-06T08:01:50
| 101,335,911
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 10,288
|
py
|
from helper_methods import *
def recursive_fetch_next_character(G, node, word_id, lpos):
neighbors = G[node]
required_uid = str(word_id)+"_"+str(lpos)
for neighbor in neighbors:
if required_uid in G[node][neighbor]['uid']:
return(neighbor + recursive_fetch_next_character(G, neighbor, word_id, lpos+1))
return('')
def fetch_exact_words_from_graph(G):
guess_words = list()
beginnings = dict(G['start'])
for key in beginnings:
word_ids = beginnings[key]['uid']
for word_id in word_ids:
guess_words.append(key + recursive_fetch_next_character(G, key, word_id, 0))
return(guess_words)
def generate_exact_graph_from_words(words):
letters = set()
G = nx.DiGraph()
for word in words:
for letter in list(word):
letters.add(letter)
G.add_nodes_from(letters)
G.add_node('start')
G.add_node('stop')
for i, word in enumerate(words):
G = force_add_uid(G, 'start', word[0], i)
G = force_add_uid(G, word[-1], 'stop', i)
for lpos in range(0, len(word)-1):
from_node = word[lpos]
to_node = word[lpos+1]
uniq_id = str(i) + "_" + str(lpos)
G = force_add_uid(G, from_node, to_node, uniq_id)
return(G)
def generate_guess_graph_from_words(words, start_weight, stop_weight, node_weight):
letters = set()
G = nx.DiGraph()
for word in words:
for letter in list(word):
letters.add(letter)
G.add_nodes_from(letters)
G.add_node('start')
G.add_node('stop')
for i, word in enumerate(words):
G = force_add_weight(G, 'start', word[0], start_weight)
G = force_add_weight(G, word[-1], 'stop', stop_weight)
# G = force_add_weight(G, word[0], 'start', marker_weight)
# G = force_add_weight(G, 'stop', word[-1], marker_weight)
for lpos in range(0, len(word)-1):
from_node = word[lpos]
to_node = word[lpos+1]
G = force_add_weight(G, from_node, to_node, node_weight)
# G = force_add_weight(G, to_node, from_node, node_weight)
return(G)
def fetch_guess_words_from_graph(G, node, prefix=''):
sort = sorted(G.edges([node], data=True), key=lambda data : -1*data[2]['weight'])
if sort[0][1] == 'stop' and sort[0][2] == sort[1][2]:
max_weighed_neighbor = sort[1][1]
else:
max_weighed_neighbor = sort[0][1]
# print(max_weighed_neighbor)
G[node][max_weighed_neighbor]['weight'] -= 1
if max_weighed_neighbor == 'stop':
return(G, prefix + '')
else:
return(fetch_guess_words_from_graph(G, max_weighed_neighbor, prefix=prefix+max_weighed_neighbor))
def guess_words_from_graph(G):
words = list()
nodes = list()
return(words)
def inverse_weight(graph, weight='weight'):
copy_graph = graph.copy()
for n in copy_graph:
eds = copy_graph[n]
for ed, eattr in eds.items():
copy_graph[n][ed][weight] = eattr[weight] * -1
return(copy_graph)
def longest_path_and_length(graph, s, t, weight='weight'):
i_w_graph = inverse_weight(graph, weight)
length, path = nx.bidirectional_dijkstra(i_w_graph, s, t)
# path = nx.dijkstra_path(i_w_graph, s, t)
# length = nx.dijkstra_path_length(i_w_graph, s, t) * -1
# path = nx.astar_path(i_w_graph, s, t)
# length = nx.astar_path_length(i_w_graph, s, t)
return(path, length)
def map_weights_to_probability(G):
for node in G:
sum_of_all_weights = 0
for neighbor in G[node]:
sum_of_all_weights += G[node][neighbor]['weight']
for neighbor in G[node]:
G[node][neighbor]['weight'] /= sum_of_all_weights
return(G)
def map_weights_to_probability_with_weights(G):
for node in G:
sum_of_all_weights = 0
for neighbor in G[node]:
sum_of_all_weights += G[node][neighbor]['weight']
for neighbor in G[node]:
G[node][neighbor]['probability'] = G[node][neighbor]['weight'] / sum_of_all_weights
return(G)
def simple_cycles(G):
return(list(nx.simple_cycles(G)))
def remove_cycles(G):
G.add_node('loop_from')
G.add_node('loop_to')
while not len(simple_cycles(G)) == 0:
cycle = simple_cycles(G)[0]
print(cycle)
min_weight_from_node = cycle[-1]
min_weight_to_node = cycle[0]
min_weight = G[min_weight_from_node][min_weight_to_node]['weight']
for i in range(0, len(cycle)-1):
weight = G[cycle[i]][cycle[i+1]]['weight']
if weight < min_weight:
min_weight = weight
min_weight_from_node = cycle[i]
min_weight_to_node = cycle[i+1]
print(min_weight, min_weight_from_node, min_weight_to_node, G[min_weight_from_node][min_weight_to_node])
G.remove_edge(min_weight_from_node, min_weight_to_node)
G = force_add_weight(G, min_weight_from_node, 'loop_from', min_weight)
G = force_add_weight(G, 'loop_to', min_weight_to_node, min_weight)
# G = force_add_weight(min_weight_from_node, 'stop', 1)
G = map_weights_to_probability_with_weights(G)
if not cycle[-1] == min_weight_from_node and not cycle[0] == min_weight_to_node:
G[cycle[i]][cycle[i+1]]['weight'] -= min_weight
for i in range(0, len(cycle)-1):
if not cycle[i] == min_weight_from_node and not cycle[i+1] == min_weight_to_node:
G[cycle[i]][cycle[i+1]]['weight'] -= min_weight
# edges_to_remove.add((min_weight_from_node, min_weight_to_node))
return(G)
# def djikstra_algo(G, source):
# # 3 create vertex set Q
# Q = set()
# infinity = 100000
# # 4
# # 5 for each vertex v in Graph: // Initialization
# # 6 dist[v] ← INFINITY // Unknown distance from source to v
# # 7 prev[v] ← UNDEFINED // Previous node in optimal path from source
# # 8 add v to Q // All nodes initially in Q (unvisited nodes)
# prev = dict()
# dist = dict()
# for node in G:
# dist[node] = 0
# prev[node] = None
# Q.add(node)
# # 9
# # 10 dist[source] ← 0 // Distance from source to source
# dist[source] = infinity
# # 11
# # 12 while Q is not empty:
# while not len(Q) == 0:
# print(Q)
# # 13 u ← vertex in Q with min dist[u] // Node with the least distance
# # 14 // will be selected first
# # 15 remove u from Q
# u = list(dist.keys())[list(dist.values()).index(min([dist[vertex] for vertex in Q]))]
# print(u)
# Q.remove(u)
# # 16
# # 17 for each neighbor v of u: // where v is still in Q.
# # 18 alt ← dist[u] + length(u, v)
# # 19 if alt < dist[v]: // A shorter path to v has been found
# # 20 dist[v] ← alt
# # 21 prev[v] ← u
# for v in G[u]:
# alt = dist[u] + G[u][v]['weight']
# if alt > dist[v]:
# dist[v] = alt
# prev[v] = u
# # 22
# # 23 return dist[], prev[]
# return(list(dist) + list(prev))
def open_loops(G):
G = force_add_weight(G, 'loop_from', 'loop_to', 0)
return(G)
if __name__ == '__main__':
# words = ['flatten', 'tantrum', 'rum', 'drum', 'drama']
# words = ['flatten', 'flatter']
words = ['rum', 'drum', 'drambler', 'drain']
# wordpairs = read_wordpairs('../btp/spec/fixtures/polish/polish-train-high')
# words = [word for word in wordpairs]
# words = words[0:20]
start_weight = 1
stop_weight = 1
node_weight = 1
source_G = generate_guess_graph_from_words(words, start_weight, stop_weight, node_weight)
# source_G = map_weights_to_probability(source_G)
source_G = map_weights_to_probability_with_weights(source_G)
source_G = remove_cycles(source_G)
if len(source_G.edges) < (len(source_G.nodes) * len(source_G.nodes)) / 5 or len(source_G.nodes) < 10:
pretty_print_graph(source_G)
# visualize_graph(source_G, 'weight')
# visualize_network(source_G, 'weight')
# try:
# sp=nx.shortest_path(source_G, 'start', 'stop')
# for n in sp:
# print(n)
# except nx.NetworkXNoPath:
# print("None")
# brute_force_guess_words = list()
# for path in nx.all_simple_paths(source_G, source='start', target='stop'):
# brute_force_guess_words.append(''.join(path[1:-1]))
# print("Words back from the graph are", brute_force_guess_words)
# compare(words, brute_force_guess_words)
# brute_force_guess_words = list()
# for path in nx.all_simple_paths(source_G, source='start', target='stop'):
# brute_force_guess_words.append(''.join(path[1:-1]))
# print("Words back from the graph are", brute_force_guess_words)
# compare(words, brute_force_guess_words)
guess_words = list()
while not empty_graph(source_G):
try:
max_weighted_path, weights = longest_path_and_length(source_G, 'start', 'stop')
# max_weighted_path, weights = longest_path_and_length(source_G, 'start', 'stop')
# max_weighted_path, weights = longest_path_and_length(source_G, 'stop', 'start')
max_weighted_path_nodes = max_weighted_path[1:-1]
# print(''.join(max_weighted_path_nodes)[::-1])
# print(''.join(max_weighted_path_nodes))
guess_words.append(''.join(max_weighted_path_nodes))
print(''.join(max_weighted_path_nodes))
for i in range(0, len(max_weighted_path)-1):
from_node = max_weighted_path[i]
to_node = max_weighted_path[i+1]
weight = source_G[from_node][to_node]['weight']
if from_node == 'start':
if weight == start_weight:
source_G.remove_edge(from_node, to_node)
else:
source_G[from_node][to_node]['weight'] -= start_weight
elif to_node == 'stop':
if weight == stop_weight:
source_G.remove_edge(from_node, to_node)
else:
source_G[from_node][to_node]['weight'] -= stop_weight
else:
if weight == node_weight:
source_G.remove_edge(from_node, to_node)
else:
source_G[from_node][to_node]['weight'] -= node_weight
except nx.NetworkXNoPath:
source_G = open_loops(source_G)
pretty_print_graph(source_G)
break
compare(words, guess_words)
# guessed_words = guess_words_from_graph(source_G)
# print("Words back from the graph are", guessed_words)
# compare(words, guessed_words)
|
[
"athityakumar@gmail.com"
] |
athityakumar@gmail.com
|
5715da2b5a81be41b88e605097abb5ebabc3a9a0
|
737e1496e76cc351e93cabb2112f34e00016e6f0
|
/HuffmanEncoding/Huffman.py
|
e4cca03dd73d8cb1d66ecfbfe5d0b6069f99d360
|
[] |
no_license
|
ZLeopard/Python_Works
|
19e2fe9c6e794a96a136d70766bbca81f38c815a
|
75d5eaf2573ecd54778716f759c8dddbfa66d911
|
refs/heads/master
| 2021-01-21T21:05:45.193174
| 2017-05-24T15:34:03
| 2017-05-24T15:34:03
| 92,305,453
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,856
|
py
|
# Huffman Encoding
import math
class Node:
def __init__(self, freq):
self.left = None
self.right = None
self.father = None
self.freq = freq
def Is_Left(self):
return self.father.left == self
def CreateNodes(freqs):
return [Node(freq) for freq in freqs]
def CreateHuffmanTree(nodes):
queue = nodes[:]
while len(queue) > 1:
queue.sort(key=lambda nodes: nodes.freq) # 按概率大小排序
node_left = queue.pop(0)
node_right = queue.pop(0) # 删除要结合的两结点
node_father = Node(node_left.freq + node_right.freq)
node_father.right = node_right
node_father.left = node_left
node_right.father = node_father
node_left.father = node_father # 建立每个结点的逻辑关系
queue.append(node_father) # 添加结合后的新结点
queue[0].father = None
return queue[0]
def HuffmanEncoding(nodes, root):
codes = [''] * len(nodes)
for i in range(len(nodes)):
temp_node = nodes[i]
while temp_node != root: # 从叶结点遍历到根结点
if temp_node.Is_Left(): # 判断是否为左儿子
codes[i] = '0' + codes[i]
else:
codes[i] = '1' + codes[i]
temp_node = temp_node.father
return codes
if __name__ == '__main__':
ii = 0
chars_freqs = {'I': 2, 'l': 1, 'o': 7, 'v': 1}
nodes = CreateNodes([chars_freqs[i] for i in chars_freqs.keys()])
root = CreateHuffmanTree(nodes)
codes = HuffmanEncoding(nodes, root)
code_AveLength = len("".join(codes)) / len(codes)
print(math.log2(8))
for item in chars_freqs.keys():
print('Character:%s freq:%-2d encoding: %s' % (item, chars_freqs[item], codes[ii]))
ii += 1
print(code_AveLength)
|
[
"599707567@qq.com"
] |
599707567@qq.com
|
e5a640db26fe1149142d488afce147437d682f0b
|
07c46730e218c2f42a8516defbdbfc2fc484c006
|
/account.py
|
15f4a9881c6c71a415e92f33bbb022781bfefe45
|
[] |
no_license
|
adrianmatkowski01/Account
|
d21297d0f71d09042838d9bf185eb1961c84da0e
|
558e9d41d338667f16c23681b2d534454ebba805
|
refs/heads/master
| 2020-07-15T01:02:15.153835
| 2019-09-08T17:00:26
| 2019-09-08T17:00:26
| 205,443,521
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,079
|
py
|
import utils
import gui
utils.generate_key()
data_file = "data.json"
utils.check_file(data_file)
def login_variable(var):
global login_entry_variable
login_entry_variable = var
def password_variable(var):
global password_entry_variable
password_entry_variable = var
def register_login_variable(var):
global login_register_entry_variable
login_register_entry_variable = var
def register_password_variable(var):
global password_register_entry_variable
password_register_entry_variable = var
def register_repassword_variable(var):
global repassword_register_entry_variable
repassword_register_entry_variable = var
def login():
# Login function
log_in = login_entry_variable
password = password_entry_variable
data = utils.load_file(data_file)
encrypted_log_in = "".join(data.keys())
encrypted_password = "".join(data.values())
friendly_decrypted_log_in = utils.decrypt_credential_make_friendly(encrypted_log_in)
friendly_decrypted_password = utils.decrypt_credential_make_friendly(encrypted_password)
if log_in == friendly_decrypted_log_in and password == friendly_decrypted_password:
# Login success
gui.label_text_variable = "Login successful"
else:
# Login bad
gui.label_text_variable = "Wrong Login or Password!"
def register():
# Register function
log_in = login_register_entry_variable
password = password_register_entry_variable
re_password = repassword_register_entry_variable
if password == re_password:
encrypted_login = utils.encrypt_credential(log_in)
encrypted_password = utils.encrypt_credential(password)
json_friendly_login = utils.make_json_friendly(encrypted_login)
json_friendly_password = utils.make_json_friendly(encrypted_password)
data = {}
data[json_friendly_login] = json_friendly_password
utils.write_file(data_file, data)
gui.label_text_variable = "Registered!"
else:
gui.label_text_variable = "Your Passwords dont match!\nTry again!"
|
[
"unconfigured@null.spigotmc.org"
] |
unconfigured@null.spigotmc.org
|
5ecb0a9aedfee8b912fee96c26bc3d92853035c6
|
f9dbabe8a68da8b5c296096896f1f6b76608ba9d
|
/bill/migrations/0002_remove_category_name.py
|
1ddf14b66e43ece72cbbaa824ba226980fc87341
|
[] |
no_license
|
shawnloong/zst_online_server
|
c47d3a5756fdce21ccdd93ccc12f279ab7661484
|
f7acf082b8e05787ea98c56656f1ae9a871bfb2c
|
refs/heads/master
| 2023-06-14T04:57:17.046294
| 2021-05-09T08:10:50
| 2021-05-09T08:10:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 314
|
py
|
# Generated by Django 2.2.5 on 2020-10-07 14:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bill', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='category',
name='name',
),
]
|
[
"text.zwb@gmail.com"
] |
text.zwb@gmail.com
|
7b3209cc9ac515e70c9d42ef7ed82ccab0aebf29
|
253decb99c6d058537118b36da2b63ab0ee9225a
|
/9_1.py
|
15b04abe326a1f1078fbb17812e902bcedd482e5
|
[] |
no_license
|
Adityashah2003/PY4E
|
730ca263579a65f3c852c12c13cbe2134580d3fb
|
4523f60ed5098419303e1e64380a9e0c7ac681aa
|
refs/heads/main
| 2023-07-18T12:20:11.601524
| 2021-09-07T08:34:10
| 2021-09-07T08:34:10
| 368,843,889
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 224
|
py
|
count = 0
dictionary_words = dict() # Initializes the dictionary
fhand = open('9.txt')
user_word = input("Enter the word")
if user_word in dictionary_words:
print('True')
else:
print('False')
|
[
"noreply@github.com"
] |
Adityashah2003.noreply@github.com
|
e9895ee2613f447320c901c82b8253a7824b37fb
|
f0fa2d6ae033cecf655e5b4163c3d10008eb66de
|
/model.py
|
be387574b51ba16055f6202bd2b49beb82027b60
|
[] |
no_license
|
MChoi-git/Mel-Spectro-Phonemes
|
7c480afcac84f0b1944237375226f077d0ca2acf
|
b0d6d16dc3072c017971729425fc11f9ca8c38b6
|
refs/heads/main
| 2023-07-07T07:35:24.070785
| 2021-08-12T20:50:12
| 2021-08-12T20:50:12
| 394,769,748
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 982
|
py
|
import torch
import torch.nn as nn
import torch.nn.functional as F
MODELS = {}
# Register model decorator
def register(func=None, *, name=None):
def wrapper(func):
MODELS[func.__name__ if name is None else name] = func
return func
if func is None:
return wrapper
return wrapper(func)
def get_model(name, *args):
func = MODELS.get(name, None)
return func(*args) if func is not None else func
# Define neural net
@register
class SimpleNet(nn.Module):
def __init__(self, data_size):
super().__init__()
self.fc1 = nn.Linear(40, 120)
self.fc2 = nn.Linear(120, 200)
self.fc3 = nn.Linear(200, 71)
def forward(self, input_example):
input_example = self.fc1(input_example)
input_example = F.relu(input_example)
input_example = self.fc2(input_example)
input_example = F.relu(input_example)
input_example = self.fc3(input_example)
return input_example
|
[
"mattchoi427@gmail.com"
] |
mattchoi427@gmail.com
|
b9abbb0cc253ae0226bcb8e42d4ee3681efaf908
|
f8906e9963593db723111a473d221a383074319c
|
/1.py
|
187f98a32bd318398d94f36c9906a1a73c485af3
|
[] |
no_license
|
OpportunV/test_tasks
|
10e8667454b29f02ac618fc0b6267a881adbb937
|
85d33120eba2c862349eb49e74f344a0879e1ad8
|
refs/heads/master
| 2022-11-14T14:41:50.523580
| 2020-06-25T12:23:15
| 2020-06-25T12:23:15
| 274,835,790
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,993
|
py
|
import sqlite3
def create_tables(cur):
cur.execute('''CREATE TABLE orders (
id INTEGER PRIMARY KEY,
promocode_id INTEGER);''')
cur.execute('''CREATE TABLE promocodes (
id INTEGER PRIMARY KEY,
name TEXT,
discount INTEGER NOT NULL);''')
def add_order(cur, promocode_id):
cur.execute('''INSERT INTO orders(promocode_id)
VALUES(?)''', (promocode_id,))
def add_promocode(cur, name, discount):
cur.execute('''INSERT INTO promocodes(name, discount)
VALUES(?,?)''', (name, discount))
def show_table(cur, table):
print(f'---------------{table}------------------')
for row in cur.execute(f'SELECT * FROM {table}'):
print(row)
print('-------------------------------------------')
def task_one(cur):
for i in cur.execute('''SELECT AVG(promocode_id IS NOT NULL)
FROM orders;'''):
print(i)
for i in cur.execute('''SELECT 1.0 * COUNT(promocode_id) / COUNT(*)
FROM orders;'''):
print(i)
def task_two(cur):
for i in cur.execute('''SELECT name
FROM
(SELECT discount, name
FROM promocodes
JOIN orders
ON orders.promocode_id = promocodes.id)
GROUP BY name
ORDER BY SUM(discount) DESC
LIMIT 1
'''):
print(i)
def main():
con = sqlite3.connect('1.sqlite3')
cur = con.cursor()
con.commit()
show_table(cur, 'promocodes')
show_table(cur, 'orders')
task_one(cur)
task_two(cur)
if __name__ == '__main__':
main()
|
[
"RsTGear@gmail.com"
] |
RsTGear@gmail.com
|
7d72f10b1c541b7796e81e007603ba329d97791e
|
70c661b810d6b6b791ce6a9a1648e33bfc7da669
|
/securityheaders.py
|
05762073f9cbdacbe786587674bf2c3c93a7b837
|
[] |
no_license
|
Cr1nc/Header-Scripts
|
9928b01b8175f1824728a08fe87d08252f0ab9c8
|
26da8c0944181093b9b596ddc88be9d104199cc5
|
refs/heads/master
| 2020-05-20T17:23:29.416498
| 2020-02-16T23:25:40
| 2020-02-16T23:25:40
| 185,687,063
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,037
|
py
|
import requests
import sys
import colored
hostname = sys.argv[1]
response = requests.get(hostname)
response.headers
if "X-XSS-Protection" in response.headers:
print("\033[1;32;49m")
print "[+] XSS header is present"
else:
print("\033[1;31;49m")
print "[-] XSS header is not present"
if "x-frame-options" in response.headers:
print("\033[1;32;49m")
print "[+] X-Frame header is present"
else:
print("\033[1;31;49m")
print "[-] X-Frame header is not present"
if "x-content-type" in response.headers:
print("\033[1;32;49m")
print "[+] X-Content-Type header is present"
else:
print("\033[1;31;49m")
print "[-] C-Content-Type header is not present"
if "Public-Key-Pins" in response.headers:
print("\033[1;32;49m")
print "[+] Public-Key-Pins is present"
else:
print("\033[1;31;49m")
print "[-] Public-Key-Pins header is not present"
if "X-Content-Type-Options" in response.headers:
print("\033[1;32;49m")
print "[+] X-Content-Type-Options is present"
else:
print("\033[1;31;49m")
print "[-] X-Content-Type-Options header is not present"
if "X-Permitted-Cross-Domain-Policies" in response.headers:
print("\033[1;32;49m")
print "[+] X-Permitted-Cross-Domain-Policies is present"
else:
print("\033[1;31;49m")
print "[-] X-Permitted-Cross-Domain-Policies header is not present"
if "Content-Security-Policy" in response.headers:
print("\033[1;32;49m")
print "[+] Referrer-Policy is present"
else:
print("\033[1;31;49m")
print "[-] Referrer-Policy header is not present"
if "Content-Security-Policy" and "X-Content-Type-Options" not in response.headers:
print ("\033[1;32;49m")
print "[!] Site may be vulnerable to Clickjacking"
if "X-XSS-Protection" not in response.headers:
print "[!] Check site with XSS payloads"
print("\033[1;31;49m")
print ("\033[1;32;49m")
print ("Completed")
print ("\033[0;0m")
|
[
"noreply@github.com"
] |
Cr1nc.noreply@github.com
|
6cb6bc2c8cca71612ccd4aff20a540639c588bda
|
99b2cee110db28b1d3dde95b2f8745efbe3844bb
|
/orders/urls.py
|
01066e4f0da5aac31c4fec116ff3d6d41d15ba32
|
[] |
no_license
|
Peniella/kart-django
|
a39c5eb48a28e9a03d9ee3ca8e2482c6090197fd
|
e96831181a83f8b3e4b86e95467211554e446a3b
|
refs/heads/main
| 2023-07-26T20:34:33.058616
| 2021-09-08T08:01:22
| 2021-09-08T08:01:22
| 396,990,989
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 248
|
py
|
from django.urls import path
from . import views
urlpatterns=[
path('place_order/', views.place_order,name='place_order'),
path('payments/', views.payments,name='payments'),
path('order_complete/', views.order_complete,name='order_complete'),
]
|
[
"babatundeblessing7@gmail.com"
] |
babatundeblessing7@gmail.com
|
adfd908fd1fc88eb5097627cadcf5b1a5bd25fe6
|
4a6b30c04e37bb0ad2c2593544916b85642f48e3
|
/research/meo/mlp_baseline/losses.py
|
306f31b2ad8ad9870652b6aca10bcf26ecad6d33
|
[
"Apache-2.0"
] |
permissive
|
jango-blockchained/neural-structured-learning
|
519e8b757eede408d12b15282e5cfcf78e8875cc
|
aaa9d3e4733f3b551823b86f67cf8a572acfeb7d
|
refs/heads/master
| 2023-08-15T06:00:53.439094
| 2023-07-31T19:30:57
| 2023-07-31T19:32:05
| 224,641,017
| 0
| 0
|
Apache-2.0
| 2023-07-13T14:54:23
| 2019-11-28T11:43:56
|
Python
|
UTF-8
|
Python
| false
| false
| 4,115
|
py
|
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Custom loss functions.
This file contains custom losses used for our models.
"""
from typing import Optional
import tensorflow as tf
def vae_kl_divergence(
z_mean: tf.Tensor,
z_log_var: tf.Tensor,
) -> tf.Tensor:
"""Compute the KL divergence loss for the VAE model.
This function computes the KL divergence of the distribution generated by the
VAE encoder and the gaussian. This is used as part of the training for
the VAE model.
Args:
z_mean: Mean of the conditional distribution generated by the encoder.
z_log_var: Log variance of the conditional distribution generated by the
encoder.
Returns:
The loss tensor for the provided input.
"""
kl_divergence = -0.5 * (1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var))
loss = tf.reduce_sum(kl_divergence)
return loss
def reconstruction_loss(
real_embed: tf.Tensor,
generated_embed: tf.Tensor,
loss_type: str,
) -> tf.Tensor:
"""Calculate the reconstruction loss in multiple views/obfuscations.
This function is used to calculate the quality of the reconstructed
embeddings, using the real obfuscated embeddings as ground truth.
Args:
real_embed: Given embeddigns from obfuscated images. This must be a
tensor of shape (batch_size, number_of_obfuscations, embedding_size).
generated_embed: Generated embeddings from obfuscated images. This must
have the same shape as real_embed.
loss_type: The embedding loss to be used, currently one of
[MSE, Contrastive].
Returns:
The embedding loss of the AutoEncoder.
"""
# TODO(smyrnisg): add back contrastive loss.
if loss_type == 'MSE':
embed_loss = tf.reduce_mean(
tf.keras.metrics.mean_squared_error(
real_embed, generated_embed
)
)
else:
raise ValueError(
'Embedding loss type not understood: {}'.format(loss_type)
)
return embed_loss
def weighted_crossentropy_loss(
labels: tf.Tensor,
real_logits: tf.Tensor,
generated_logits: tf.Tensor,
gen_loss_weight: tf.float32,
gen_labels: Optional[tf.Tensor] = None
) -> tf.Tensor:
"""Calculate a paired cross-entropy loss which includes a weight factor.
This function calculates a paired cross-entropy loss, using logits derived
from both real and generated embeddings. The total loss is a sum of the
two crossentropy losses between the logits of the real embeddings and the
labels, and the logits between the generated logits and the labels. Since the
latter are trained jointly with the classifier, their loss is scaled by a
weight factor. This weight factor should ramp up during training (so the loss
due to the generated embeddings isn't as important in the beginning).
Args:
labels: The labels for the given batch.
real_logits: The logits the classifier provides for the real embeddings.
generated_logits: The logits the classifier provides for the generated
embeddings.
gen_loss_weight: The factor with which to multiply the loss between
generated_logits and labels.
gen_labels: Optional labels for extra generated samples.
Returns:
The paired crossentropy loss as described.
"""
loss_real = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels, real_logits
)
loss_gen = tf.nn.sparse_softmax_cross_entropy_with_logits(
gen_labels if gen_labels is not None else labels, generated_logits
)
total_loss = tf.reduce_mean(tf.concat(
[loss_real, gen_loss_weight * loss_gen], axis=0
))
return total_loss
|
[
"tensorflow.copybara@gmail.com"
] |
tensorflow.copybara@gmail.com
|
17e3f6d893e21fd37b22c2db73250c3ce6181866
|
1a72fecd2a4461f0c81587429203519d8e4f175b
|
/main.py
|
138d1add000e0ec0f5e640419b9e202e906b7bd8
|
[
"MIT"
] |
permissive
|
ForXample/02-Text-adventure
|
75e4772eb8128b35fb094fd25aae4000432d441f
|
c8581a49a4baae5456a8fa39d45744f7cb56840b
|
refs/heads/master
| 2020-12-29T09:02:11.454059
| 2020-02-13T05:24:45
| 2020-02-13T05:24:45
| 238,547,835
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,901
|
py
|
#!/usr/bin/env python3
import sys, os, json
# Check to make sure we are running the correct version of Python
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
# The game and item description files (in the same folder as this script)
game_file = 'game.json'
# Load the contents of the files into the game and items dictionaries. You can largely ignore this
# Sorry it's messy, I'm trying to account for any potential craziness with the file location
def load_files():
try:
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
with open(os.path.join(__location__, game_file)) as json_file: game = json.load(json_file)
return game
except:
print("There was a problem reading either the game or item file.")
os._exit(1)
def render(game,current):
c = game[current]
print("You are at the " + c["name"])
print(c["desc"])
def get_input():
response = input("Which direction are you heading to? (North or South) ")
response = response.upper().strip()
return response
def update(game,current,response):
c = game[current]
for e in c["exits"]:
if response == e["exit"]:
return e["target"]
return current
# The main function for the game
def main():
current = 'START' # The starting location
end_game = ['END'] # Any of the end-game locations
game = load_files()
while True:
render(game,current)
for e in end_game:
if current == e:
print("You win!")
break #break out of the while loop
response = get_input()
if response == "QUIT" or response == "Q":
break #break out of the while loop
current = update(game,current,response)
print("Thanks for playing!")
# run the main function
if __name__ == '__main__':
main()
|
[
"59849551+ForXample@users.noreply.github.com"
] |
59849551+ForXample@users.noreply.github.com
|
3b7411fbe3d5f7145dff21fa430bb8761233d726
|
5683a76d2a7134539e847fbe23a0040828a079e4
|
/magic8Ball.py
|
3d9a0360f1dde6cb57b2d66466733a56c1b9a743
|
[] |
no_license
|
tambulkerasha/codetolearn
|
41b5a345f922a6cda753f821e6fdc827d431bc79
|
9b74df487ed4e94e885004ed6548d34c8884c540
|
refs/heads/master
| 2020-08-16T12:30:37.652373
| 2019-12-20T08:54:00
| 2019-12-20T08:54:00
| 215,502,019
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 688
|
py
|
import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Reply hazy try again'
elif answerNumber == 5:
return 'Ask again later'
elif answerNumber == 6:
return 'Concentrate and ask again'
elif answerNumber == 7:
return 'My reply is no'
elif answerNumber == 8:
return 'Outlook is not good'
elif answerNumber == 9:
return 'Very doubtful'
r = random.randint(1,9)
fortunate = getAnswer(r)
print(fortunate)
|
[
"noreply@github.com"
] |
tambulkerasha.noreply@github.com
|
80500b0aafc98304b8d4abcf0c5bfc9578091c0e
|
579f3bf8e30af4d4f7576a9b9090e29f94a5c731
|
/CookiesPool/login/login_weibo_selenium.py
|
f60fa9aac62e4f38243e928a30f9ea1f970db780
|
[] |
no_license
|
JaveyYu/Myspider
|
021b1eaca5340cac4b724758a3080b8b2dfae084
|
0dfde94028affa193c277c45c54850d6c2b26671
|
refs/heads/master
| 2021-06-12T10:39:19.750020
| 2021-04-06T07:54:55
| 2021-04-06T07:54:55
| 147,939,923
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 12,736
|
py
|
import os
import time
import random
import pymongo
import pytesseract
import numpy as np
from io import BytesIO
from PIL import Image, ImageEnhance
from cookiespool import util
from cookiespool.config import *
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.alert import Alert
from login.chaojiying import Chaojiying_Client
class CookiesGenerate(object):
def __init__(self, username, password):
self.url = 'https://xueqiu.com/'
self.username = username
self.password = password
self.__init__chrome_option()
def __init__chrome_option(self):
self.option = webdriver.ChromeOptions()
#chrome 配置
self.option.add_argument("--window-size=1920x1080")
self.option.add_argument("--start-maximized")
self.option.add_argument('--headless')
self.option.add_argument('user-agent=' + random.choice(USER_AGENTS))
def open(self):
self.browser = webdriver.Chrome(chrome_options=self.option)
self.browser.delete_all_cookies()
self.browser.get(self.url)
self.wait = WebDriverWait(self.browser, 5)
#找到首页上的登录按钮并点击
self.wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="app"]/nav/div[1]/div[2]/div/div'))).click()
#找到登录界面的微博登录按钮并点击
self.wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[3]/div[1]/div/div/div[2]/div[5]/ul/li[3]/a/i'))).click()
#找到账号密码登录按钮并点击
time.sleep(0.5)
self.browser.switch_to.window(self.browser.window_handles[1])
input_u = self.browser.find_element_by_id('userId')
input_u.send_keys(self.username)
input_p = self.browser.find_element_by_id('passwd')
input_p.send_keys(self.password)
###################-----------OCR验证码------------------------#####################
def ocr_main(self):
# 获取验证码图片并下载到本地
time.sleep(1)
scimg = self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="outer"]/div/div[2]/form/div/div[1]/div[1]/p[3]/span/img')))
self.browser.save_screenshot(self.Imgpath)
top = 207
bottom = top + 35
left = 513.75
right = left + 75
img = Image.open(self.Imgpath).crop((left,top,right,bottom))
img = img.convert('L')
img.save(self.Imgpath)
# 用超极鹰识别出图片张的文字
text = self.captcha_identify()
if text:
input_c = self.wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="outer"]/div/div[2]/form/div/div[1]/div[1]/p[3]/input')))
input_c.send_keys(text)
self.wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="outer"]/div/div[2]/form/div/div[2]/div/p/a[1]'))).click()
else:
self.wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="outer"]/div/div[2]/form/div/div[1]/div[1]/p[3]/a'))).click()
self.ocr_main()
def input_captcha(self, captcha_text):
input_c = self.browser.find_element_by_xpath('//*[@id="outer"]/div/div[2]/form/div/div[1]/div[1]/p[3]/input')
input_c.send_keys(captcha_text)
self.wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="outer"]/div/div[2]/form/div/div[2]/div/p/a[1]'))).click()
def get_file_content(self, filePath):
with open(filePath, 'rb') as fp:
return fp.read()
def captcha_identify(self):
'''用超极鹰进行识别'''
img = open(self.Imgpath, 'rb').read()
chaojiying = Chaojiying_Client('kingdatalab', 'zju211root', '96001')
result = chaojiying.PostPic(img, 1902)
if result['err_no'] == -1005:
print('无可用题分,请给超极鹰充值')
text = result['pic_str']
return text
###################-----------滑块验证码------------------------#####################
#获取原图
def get_position(self, xpath):
img = self.wait.until(EC.presence_of_element_located((By.XPATH, xpath)))
location = img.location
size = img.size
top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size['width']
return (top, bottom, left, right)
def get_screenshot(self):
screenshot = self.browser.get_screenshot_as_png()
screenshot = Image.open(BytesIO(screenshot))
return screenshot
def get_image(self):
#(top, bottom, left, right) = self.get_position('/html/body/div/div[2]/div[6]/div/div[1]/div[1]/div/a/div[1]/div')
# 根据网页实际情况,这里手动定义位置,确保抓下来图片大小一样,此处为非headless模式下的位置
#top = 129
#bottom = top+160
#left = 247
#right =left +260
# headless下的位置
top = 182
bottom = top+160
left = 255
right =left +260
screenshot = self.get_screenshot()
captcha = screenshot.crop((left, top, right, bottom))
return captcha
def get_distance(self, image1,image2):
'''
拿到滑动验证码需要移动的距离
:param image1:没有缺口的图片对象
:param image2:带缺口的图片对象
:return:需要移动的距离
'''
threshold=100
left=50
for i in range(left,image1.size[0]):
for j in range(image1.size[1]):
rgb1=image1.load()[i,j]
rgb2=image2.load()[i,j]
res1=abs(rgb1[0]-rgb2[0])
res2=abs(rgb1[1]-rgb2[1])
res3=abs(rgb1[2]-rgb2[2])
if not (res1 < threshold and res2 < threshold and res3 < threshold):
return i - 8.9
return i - 8.9
def get_tracks(self, distance):
'''
拿到移动轨迹,模仿人的滑动行为,先匀加速后匀减速
匀变速运动基本公式:
①v=v0+at
②s=v0t+½at²
③v²-v0²=2as
:param distance: 需要移动的距离
:return: 存放每0.3秒移动的距离
'''
#初速度
v=0
#单位时间为0.2s来统计轨迹,轨迹即0.2内的位移
t=0.3
#位移/轨迹列表,列表内的一个元素代表0.2s的位移
tracks=[]
#当前的位移
current=0
#到达mid值开始减速
mid=distance*4/5
while current < distance:
if current < mid:
# 加速度越小,单位时间的位移越小,模拟的轨迹就越多越详细
a= 7 #+ random.random()
else:
a=-9 #+ random.random()
#初速度
v0=v
#0.2秒时间内的位移
s=v0*t+0.5*a*(t**2)
#当前的位置
current+=s
#添加到轨迹列表
tracks.append(round(s))
#速度已经达到v,该速度作为下次的初速度
v=v0+a*t
return tracks
def move_to_gap(self, slider, tracks):
# 实例化一个action对象
time.sleep(0.5)
ActionChains(self.browser).click_and_hold(slider).perform()
for x in tracks:
ActionChains(self.browser).move_by_offset(xoffset=x, yoffset=random.randint(-1,1)).perform()
captcha = self.get_image()
captcha.save('login/template/test.png')
time.sleep(0.5)
ActionChains(self.browser).release().perform()
def verify_successfully(self):
if len(self.browser.window_handles) == 2:
return False
else:
print('注册成功')
return True
def error_test(self):
'''在点击刷新后可能会出现错误提示,要点击后才能继续刷新'''
try:
error_button = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_panel_error_content'))).click()
time.sleep(1)
except:
print('Geetest no error')
return
def geetest_main(self):
#while True:
# 获取有缺口的图片
element = self.wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div/div[2]/div[6]/div/div[1]/div[1]/div/a/div[1]/div/canvas[2]')))
self.browser.execute_script("arguments[0].setAttribute('style', 'display:none')", element)
time.sleep(1)
captcha_cut = self.get_image()
captcha_cut.save('login/template/cut.png')
self.browser.execute_script("arguments[0].setAttribute('style', 'display:block')", element)
#将缺口图片还原出原图
element = self.wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div/div[2]/div[6]/div/div[1]/div[1]/div/a/div[1]/canvas')))
self.browser.execute_script("arguments[0].setAttribute('style', 'display:block')", element)
time.sleep(1)
captcha_full = self.get_image()
captcha_full.save('login/template/full.png')
self.browser.execute_script("arguments[0].setAttribute('style', 'display:none')", element)
#获取移动轨迹
distance = self.get_distance(captcha_full, captcha_cut)
tracks=self.get_tracks(distance)
#滑动验证
slider = self.wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div/div[2]/div[6]/div/div[1]/div[2]/div[2]')))
self.move_to_gap(slider, tracks)
# 判断是否验证成功
#time.sleep(2)
#if self.verify_successfully():
# break
#else:
# self.alert_box()
# #判断是否有报错
# self.error_test()
# # 点击刷新图片按钮
# self.wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div/div[2]/div[6]/div/div[2]/div/a[2]'))).click()
# time.sleep(2)
def alert_box(self):
try:
prompt = Alert(self.browser)
time.sleep(1)
prompt.accept()
except:
return
###################-----------获取cookies------------------------#####################
def get_cookie(self):
cookies = self.browser.get_cookies()
cookie = {}
for item in cookies:
if item['name']=='xq_r_token':
cookie[item['name']] = item['value']
return cookie
def main(self):
count = 1
while True:
try:
self.open()
#OCR验证码识别
self.Imgpath = 'login/template/screenImg.png'
self.wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="outer"]/div/div[2]/form/div/div[2]/div/p/a[1]'))).click()
while True:
self.ocr_main()
time.sleep(2)
if self.browser.current_url == 'https://api.weibo.com/oauth2/authorize':
try:
self.wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="outer"]/div/div[2]/form/div/div[2]/div/p/a[1]'))).click()
except:
print('已连接雪球')
# 点击允许授权
self.wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="outer"]/div/div[2]/div/div[2]/div[2]/p/a[1]'))).click()
break
else:
# 点击换一换按钮,换验证码图片
self.wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="outer"]/div/div[2]/form/div/div[1]/div[1]/p[3]/a'))).click()
self.alert_box()
##########滑块验证码
if len(self.browser.window_handles) == 2:
self.geetest_main()
time.sleep(1)
self.browser.switch_to.window(self.browser.window_handles[0])
cookie = self.get_cookie()
self.browser.quit()
print('登录成功')
return cookie
except:
print('登录失败')
self.browser.quit()
if count <= 5:
count += 1
else:
cookie = None
return cookie
if __name__ == '__main__':
CookiesGenerate.main()
|
[
"yujiawei96@yeah.net"
] |
yujiawei96@yeah.net
|
87d154de566f59b78edb6f26d569ed2a9fa19af5
|
b4780737a985edde2f517591a4eacfd215ef2791
|
/json-transfer-poc/main.py
|
beb321e501506dde3db47a588076c1efeed1ddb5
|
[] |
no_license
|
gabrielSpassos/python-sandbox
|
f4c38046ba14e3ae53e75c7b1b33c3b1da2bb4dc
|
faa3bc2909aa3733c9bf55b858f9948c0942687c
|
refs/heads/master
| 2023-09-01T18:16:15.812991
| 2023-08-30T18:14:34
| 2023-08-30T18:14:34
| 196,250,657
| 1
| 0
| null | 2021-09-22T19:36:48
| 2019-07-10T17:46:21
|
Python
|
UTF-8
|
Python
| false
| false
| 251
|
py
|
import json;
f=open('input.json');
config=json.load(f);
f.close();
config['data']['aws']['aws_access_key_id_2'] = 'new key';
config['data']['aws']['aws_secret_access_key_2'] = 'new secret';
f=open('output.json','w');
json.dump(config,f);
f.close()
|
[
"gabriel.passos@agibank.com.br"
] |
gabriel.passos@agibank.com.br
|
1c1b81d0a54b7f2bd8ccb3e549c7af36380ec4a9
|
0101b46765c76991e8108cb1d417f739162184c3
|
/App/views.py
|
d610a25c5505c3f189abdbf3f4249b5fc8585663
|
[] |
no_license
|
vijithDevops/voip-gulf
|
5d890e56c8b7bdadb9a53ecc201fb406bd954c7b
|
317506fc1289bd4ed79354d4381675671208c653
|
refs/heads/master
| 2020-05-19T22:42:00.621945
| 2019-05-07T05:03:51
| 2019-05-07T05:03:51
| 185,248,252
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 736,497
|
py
|
from django.shortcuts import render,render_to_response,redirect,get_object_or_404
from django.http import HttpResponse, HttpResponseNotFound, Http404, HttpResponseRedirect, JsonResponse
from App.forms import *
from django.contrib import messages
from App.models import *
from App.serializers import *
from django.core import serializers
from django.forms.models import model_to_dict
from decimal import Decimal
from django.db.models import Sum, Count
import json
import hashlib
from django.shortcuts import render,render_to_response,redirect,get_object_or_404
from django.http import HttpResponse, HttpResponseNotFound, Http404, HttpResponseRedirect, JsonResponse
from App.forms import *
from django.contrib import messages
from django.utils.formats import localize
from App.models import *
from App.serializers import *
from django.core import serializers
from django.forms.models import model_to_dict
from decimal import Decimal
from django.db.models import Sum, Count
import json
import hashlib
from django.db import connection
from itertools import groupby
from operator import itemgetter
import itertools
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from django.conf import settings
from datetime import datetime, timedelta, date
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, renderers, response, schemas
from wsgiref.util import FileWrapper
import os, Project.settings
import mimetypes
from django.contrib.auth import authenticate
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view, permission_classes, renderer_classes, schema
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.status import (
HTTP_400_BAD_REQUEST,
HTTP_404_NOT_FOUND,
HTTP_200_OK,
HTTP_405_METHOD_NOT_ALLOWED,
HTTP_204_NO_CONTENT,
HTTP_302_FOUND,
HTTP_406_NOT_ACCEPTABLE,
HTTP_202_ACCEPTED,
HTTP_403_FORBIDDEN,
HTTP_401_UNAUTHORIZED,
HTTP_500_INTERNAL_SERVER_ERROR,
)
from rest_framework.response import Response
import coreapi, coreschema
from rest_framework.schemas import AutoSchema, ManualSchema
from django.db.models import Q
import pytz
def PageNotFound(request):
response = render_to_response('404.html')
response.status_code = 404
return response
def ServerError(request):
response = render_to_response('500.html')
response.status_code = 505
return response
# Create your views here.
def LoginPage(request):
if request.session.has_key("user"):
usertype=request.session['usertype']
if(usertype=="Admin"):
return redirect(vcloudhomePage)
#return redirect(databasefix)
elif(usertype=="Reseller"):
return redirect(resellervcloudStore)
elif(usertype=="Sub_Reseller"):
return redirect(subresellervcloudStore)
elif(usertype=="User"):
return redirect(uservcloudStore)
else:
return render(request,"index.html",{'form':UserLoginForm})
else:
return render(request,"index.html",{'form':UserLoginForm})
def LoginSubmit(request):
if request.method == "POST":
form = UserLoginForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
if(user.status):
request.session["user"] = user.username
request.session["usertype"] = user.postId
print(user)
if(user.postId=="Admin"):
return redirect(vcloudhomePage)
elif(user.postId=="Reseller"):
return redirect(resellervcloudStore)
elif(user.postId=="Sub_Reseller"):
return redirect(subresellervcloudStore)
else:
return redirect(uservcloudStore)
else:
messages.warning(request, 'You Are Blocked By Someone, Contact with your Administrator')
return redirect(LoginPage)
else:
messages.warning(request, 'Incorrect Username Or Password')
return redirect(LoginPage)
else:
form = UserLoginForm()
return render(request,"index.html",{'form':UserLoginForm})
else:
form = UserLoginForm()
return render(request,"index.html",{'form':UserLoginForm})
def logoutclick(request):
for sesskey in list(request.session.keys()):
del request.session[sesskey]
return redirect(LoginPage)
#________________________________________________________________Admin_______________________________________________________________
#________________VCLOUD_______________
def vcloudhomePage(request):
if request.session.has_key("user"):
last_month = datetime.today() - timedelta(days=1)
username = request.session["user"]
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(list(reseller[0]))
type = request.session["usertype"]
try:
user = UserData.objects.get(username = username, postId = type)
except UserData.DoesNotExist:
return redirect(LoginPage)
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser1__username=username,type="Vcloud").order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":(i.margin1*i.quantity),"rtype":i.rtype}
data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
topuser.append(data3)
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+(i.margin1*i.quantity)
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand=vcloudBrands.objects.all()
product=list()
for j in brand:
prdcts=vcloudProducts.objects.filter(brand__id=j.id,status=True).order_by("brand__brand").values("brand").annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__denomination')
if(prdcts):
for k in prdcts:
totalcost=k['productcount']*k['brand__denomination']
data2={"brand":k['brand__brand'],"count":k['productcount'],"denomination":k['brand__denomination'],'totalcost':totalcost}
product.append(data2)
else:
totalcost=0
count=0
tdenomination=j.denomination
data2={"brand":j.brand,"count":count,"denomination":tdenomination,'totalcost':totalcost}
product.append(data2)
#print(topuser)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"admin/vcloud/dashboard-vcloud.html",{'filterform':vcloudDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':user,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filtervcloudhomepage(request):
if request.session.has_key("user"):
if request.method == "POST":
form = vcloudDashboardfilter(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
uuusername=form.cleaned_data.get("username")
print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
reseller = UserData.objects.filter(sponserId=currentuser,postId="Reseller")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(username)
userdetails = UserData.objects.get(username=request.session["user"])
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,sponser1__username=currentuser,type="Vcloud",sponser2__username=uuusername).order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":(i.margin1*i.quantity),"rtype":i.rtype}
data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
topuser.append(data3)
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+(i.margin1*i.quantity)
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand=vcloudBrands.objects.all()
product=list()
for j in brand:
prdcts=vcloudProducts.objects.filter(brand__id=j.id,status=True).order_by("brand__brand").values("brand").annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__denomination')
#print(prdcts)
if(prdcts):
for k in prdcts:
totalcost=k['productcount']*k['brand__denomination']
data2={"brand":k['brand__brand'],"count":k['productcount'],"denomination":k['brand__denomination'],'totalcost':totalcost}
product.append(data2)
else:
totalcost=0
count=0
tdenomination=j.denomination
data2={"brand":j.brand,"count":count,"denomination":tdenomination,'totalcost':totalcost}
product.append(data2)
#print(topuser)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"admin/vcloud/dashboard-vcloud.html",{'filterform':vcloudDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':userdetails,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(vcloudhomePage)
else:
return(vcloudhomePage)
else:
return redirect(LoginPage)
def vcloudaddReseller(request):
if request.session.has_key("user"):
username = request.session["user"]
user = UserData.objects.get(username = username)
return render(request,"admin/vcloud/addReseller.html",{'form':AddUserDataForm,'user':user})
else:
return redirect(LoginPage)
def vcloudnewReseller(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="Reseller"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(vcloudaddReseller)
else:
username = request.session["user"]
user = UserData.objects.get(username = username)
form = AddUserDataForm()
messages.warning(request, 'Internal Error Occur')
return render(request,"admin/vcloud/addReseller.html",{'form':AddUserDataForm,'user':user})
else:
username = request.session["user"]
user = UserData.objects.get(username = username)
form = AddUserDataForm()
return render(request,"admin/vcloud/addReseller.html",{'form':AddUserDataForm,'user':user})
else:
return redirect(LoginPage)
def vcloudviewReseller(request):
if request.session.has_key("user"):
resellers = UserData.objects.filter(postId="Reseller")
username = request.session["user"]
user = UserData.objects.get(username = username)
return render(request,"admin/vcloud/viewResellers.html",{'resellers':resellers,'user':user})
else:
return redirect(LoginPage)
def vcloudaddUser(request):
if request.session.has_key("user"):
username = request.session["user"]
user = UserData.objects.get(username = username)
return render(request,"admin/vcloud/addUser.html",{'form':AddUserDataForm,'user':user})
else:
return redirect(LoginPage)
def vcloudnewUser(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
print(username)
print(password)
print(hash)
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="User"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(vcloudaddUser)
else:
username = request.session["user"]
user = UserData.objects.get(username = username)
messages.warning(request, 'Internal Error Occured')
form = AddUserDataForm()
return render(request,"admin/vcloud/addUser.html",{'form':AddUserDataForm,'user':user})
else:
username = request.session["user"]
user = UserData.objects.get(username = username)
form = AddUserDataForm()
return render(request,"admin/vcloud/addUser.html",{'form':AddUserDataForm,'user':user})
else:
return redirect(LoginPage)
def vcloudviewUser(request):
if request.session.has_key("user"):
user = request.session["user"]
userdet = UserData.objects.get(username = user)
resellers = UserData.objects.filter(postId="User",sponserId=user)
#request.session['_old_post'] = request.GET
return render(request,"admin/vcloud/viewUser.html",{'resellers':resellers,'user':userdet})
else:
return redirect(LoginPage)
def vcloudprofile(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"admin/vcloud/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def vcloudeditProfile(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(vcloudprofile)
else:
messages.warning(request,'Internal Error Occured')
return redirect(vcloudprofile)
else:
return redirect(LoginPage)
def vcloudbalanceTransfer(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
bthist=balanceTransactionReport.objects.filter(source=userdetails,category="BT").order_by('-date')
#print(bthist)
return render(request,"admin/vcloud/balanceTransfer.html",{'bthist':bthist,'user':userdetails})
else:
return redirect(LoginPage)
def validate_username(request):
username = request.GET.get('username', None)
data = {
'is_taken': UserData.objects.filter(username__iexact=username).exists()
}
return JsonResponse(data)
def getReseller_UserList(request):
if request.session.has_key("user"):
usertype = request.GET.get('usertype', None)
user = request.session['user']
userlist = UserData.objects.filter(sponserId=user,postId=usertype)
data = serializers.serialize('json', userlist)
return HttpResponse(data, content_type="application/json")
else:
return redirect(LoginPage)
def getBrandWithTypes(request):
type = request.GET.get('type', None)
if(type=="Vcloud"):
brandlist = vcloudBrands.objects.all()
data = serializers.serialize('json', brandlist)
return HttpResponse(data, content_type="application/json")
elif(type=="Dcard"):
brandlist = dcardBrands.objects.all()
data = serializers.serialize('json', brandlist)
return HttpResponse(data, content_type="application/json")
else:
brandlist = rcardBrands.objects.all()
data = serializers.serialize('json', brandlist)
return HttpResponse(data, content_type="application/json")
def getCreditBalance(request):
try:
user = request.GET.get('users', None)
credit=UserData.objects.get(username=user)
return JsonResponse(model_to_dict(credit))
except:
return redirect(LoginPage)
def vcloudSubmitBalanceTransfer(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
userdet = UserData.objects.get(username=user)
bal = userdet.balance
newbal=bal+Decimal(amount)
cdbal = userdet.targetAmt
newcdbal = cdbal-Decimal(amount)
userdet.targetAmt = newcdbal
userdet.balance = newbal
userdet.save()
userdetails = UserData.objects.get(username=request.session["user"])
btreport = balanceTransactionReport()
btreport.source = userdetails
btreport.destination = userdet
btreport.category = "BT"
btreport.pbalance = bal
btreport.nbalance = newbal
btreport.cramount = newcdbal
btreport.amount = amount
btreport.remarks = 'Added To Balance'
btreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(vcloudbalanceTransfer)
#userdata=UserData.objects.get(username=)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(vcloudbalanceTransfer)
else:
return redirect(LoginPage)
def vcloudaddPayment(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
phist=fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"admin/vcloud/addPayment.html",{'phist':phist,'user':userdetails})
else:
return redirect(LoginPage)
def vcloudsubmitPayment(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
remarks = request.POST.get('remarks', None)
userdet = UserData.objects.get(username=user)
obalance = userdet.targetAmt
cdbal = userdet.targetAmt
newcdbal = cdbal+Decimal(amount)
userdet.targetAmt = newcdbal
userdet.save()
closeuser = UserData.objects.get(username=user)
userdetails = UserData.objects.get(username=request.session["user"])
ftreport=fundTransactionReport()
ftreport.source = userdetails
ftreport.destination = userdet
ftreport.obalance = obalance
ftreport.cbalance = closeuser.targetAmt
ftreport.role = userType
ftreport.amount = amount
ftreport.balance = newcdbal
ftreport.remarks = remarks
ftreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(vcloudaddPayment)
else:
messages.warning(request, 'Internal error Occured')
return redirect(vcloudaddPayment)
else:
return redirect(LoginPage)
def vcloudbalanceTransferReport(request):
if request.session.has_key("user"):
username = request.session["user"]
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
sum = balanceTransactionReport.objects.filter(source=userdetails,category='BT').aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"admin/vcloud/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'sum':sum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filtervcloudbtreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
#fuser=UserData.objects.get(username=susername)
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
sum=None
bthist=None
try:
if(usertype == "All" and susername == "All"):
sum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(usertype!="All" and susername == "All"):
sum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype)
else:
sum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"admin/vcloud/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'sum':sum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(vcloudbalanceTransferReport)
else:
return redirect(vcloudbalanceTransferReport)
else:
return redirect(LoginPage)
def vcloudpaymentReport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=request.session["user"],postId="Reseller")
phist = fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
bsum = fundTransactionReport.objects.filter(source=userdetails).aggregate(Sum('amount'))
return render(request,"admin/vcloud/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filtervcloudpaymentreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
#fuser=UserData.objects.get(username=susername)
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
sum=None
bthist=None
try:
if(usertype == "All" and susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(usertype!="All" and susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype)
else:
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"admin/vcloud/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(vcloudpaymentReport)
else:
return redirect(vcloudpaymentReport)
else:
return redirect(LoginPage)
def addVcloudBrand(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/vcloud/addVcloudBrand.html",{'form':AddVcloudBrands,'user':userdetails})
else:
return redirect(LoginPage)
def vcloudeditResellerView(request):
user = request.GET.get('username', None)
userdet=UserData.objects.get(username=user)
return JsonResponse(model_to_dict(userdet))
def adminVcloudDashboard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"dashboard-vcloud.html",{'user':userdetails})
else:
return redirect(LoginPage)
def submitVcloudBrands(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddVcloudBrands(request.POST, request.FILES)
#print(form.errors)
if form.is_valid():
branddata=form.save()
messages.success(request, 'Successfully Added The Brands')
return redirect(addVcloudBrand)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(addVcloudBrand)
else:
return redirect(addVcloudBrand)
else:
return redirect(LoginPage)
def manageVcloudBrands(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
brands = vcloudBrands.objects.all()
return render(request,"admin/vcloud/manageVcloudBrand.html",{'brands':brands,'user':userdetails})
else:
return redirect(LoginPage)
def assignVcloudBrands(request):
if request.session.has_key("user"):
brands = vcloudBrands.objects.all()
#brands = vcloudProducts.objects.filter(status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('brand__id','brand__brand','brand__denomination','count','brand__description','brand__logo','brand__currency','brand__category')
print(brands)
userdetails = UserData.objects.get(username=request.session["user"])
resellers = UserData.objects.filter(postId="Reseller")
return render(request,"admin/vcloud/assignVcloudBrands.html",{'brands':brands,'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def addVcloudProduct(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
brands = vcloudBrands.objects.filter()
return render(request,"admin/vcloud/addVcloudProduct.html",{'productform':AddVcloudProducts,'brandform':AddVcloudBrands,'user':userdetails,'brands':brands})
else:
return redirect(LoginPage)
def submitVcloudProducts(request):
if request.session.has_key("user"):
if request.method == "POST":
try:
form = AddVcloudProducts(request.POST or None)
if form.is_valid():
brandid = form.cleaned_data.get("brand")
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
res=vcloudProducts.objects.filter(username = username).exists()
print(res)
res1=vcloudupproducts.objects.filter(username = username).exists()
print(res1)
if(res or res1):
messages.warning(request, 'Product is alreday updated in Csv log. Go and spent the product')
else:
product = vcloudProducts()
branddet = vcloudBrands.objects.get(id=brandid)
product.brand = branddet
product.username = username
product.password = password
product.denomination = branddet.denomination
product.save()
messages.success(request, 'Successfully Added The Products')
return redirect(addVcloudProduct)
else:
messages.warning(request, form.errors)
return redirect(addVcloudProduct)
except:
return redirect(addVcloudProduct)
else:
return redirect(addVcloudProduct)
else:
return redirect(LoginPage)
def getBrandDetails(request):
id = request.GET.get('id', None)
brdet = vcloudBrands.objects.get(id=id)
data={"id":brdet.id,"brand":brdet.brand,"logo":brdet.logo.url,"rate":brdet.denomination,"desc":brdet.description}
return JsonResponse(data)
def getProductDetails(request):
id = request.GET.get('id', None)
brdet = vcloudProducts.objects.get(id=id)
data={"id":brdet.id,"brand":brdet.brand.brand,"logo":brdet.brand.logo.url,"rate":brdet.brand.denomination,"desc":brdet.brand.description,"username":brdet.username,"password":brdet.password,"status":brdet.status}
#print(data)
return JsonResponse(data)
def getDatacardProductDetails(request):
id = request.GET.get('id', None)
brdet = datacardproducts.objects.get(id=id)
data={"id":brdet.id,"brand":brdet.brand.brand,"logo":brdet.brand.logo.url,"rate":brdet.brand.denomination,"desc":brdet.brand.description,"username":brdet.username,"status":brdet.status}
#print(data)
return JsonResponse(data)
def getRcardProductDetails(request):
id = request.GET.get('id', None)
brdet = rcardProducts.objects.get(id=id)
data={"id":brdet.id,"brand":brdet.brand.brand,"logo":brdet.brand.logo.url,"rate":brdet.brand.denomination,"desc":brdet.brand.description,"username":brdet.username,"status":brdet.status}
#print(data)
return JsonResponse(data)
def submitManageBrands(request):
if request.session.has_key("user"):
if request.method == "POST":
form = editVcloudBrands(request.POST, request.FILES)
if form.is_valid():
id = form.cleaned_data.get("id")
brandname = form.cleaned_data.get("brand")
flag=True;
brand = vcloudBrands.objects.get(id=id)
try:
logo = request.FILES['logo']
brand.logo = logo
print(logo)
except:
flag=False;
description = form.cleaned_data.get("desc")
denomination = form.cleaned_data.get("rate")
brand.brand = brandname
brand.description = description
brand.denomination = denomination
brand.save()
print(brand)
return redirect(manageVcloudBrands)
else:
print(form.errors)
return redirect(manageVcloudBrands)
else:
return redirect(manageVcloudBrands)
else:
return redirect(LoginPage)
def editsubmitManageProducts(request):
if request.session.has_key("user"):
if request.method == "POST":
form = EditVcloudProducts(request.POST, request.FILES)
if form.is_valid():
id = form.cleaned_data.get("id")
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
flag=True;
brand = vcloudProducts.objects.get(id=id)
brand.username = username
brand.password = password
brand.save()
print(brand)
return redirect(vcloudmanageProduct)
else:
print(form.errors)
return redirect(vcloudmanageProduct)
else:
return redirect(vcloudmanageProduct)
else:
return redirect(LoginPage)
def editsubmitManagedcardProducts(request):
if request.session.has_key("user"):
if request.method == "POST":
form = EditCardProducts(request.POST, request.FILES)
if form.is_valid():
id = form.cleaned_data.get("id")
username = form.cleaned_data.get("username")
#password = form.cleaned_data.get("password")
flag=True;
brand = datacardproducts.objects.get(id=id)
brand.username = username
#brand.password = password
brand.save()
print(brand)
return redirect(dcardmanageProduct)
else:
print(form.errors)
return redirect(dcardmanageProduct)
else:
return redirect(dcardmanageProduct)
else:
return redirect(LoginPage)
def editsubmitManagercardProducts(request):
if request.session.has_key("user"):
if request.method == "POST":
form = EditCardProducts(request.POST, request.FILES)
if form.is_valid():
id = form.cleaned_data.get("id")
username = form.cleaned_data.get("username")
#password = form.cleaned_data.get("password")
flag=True;
brand = rcardProducts.objects.get(id=id)
brand.username = username
#brand.password = password
brand.save()
print(brand)
return redirect(rcardmanageProduct)
else:
print(form.errors)
return redirect(rcardmanageProduct)
else:
return redirect(rcardmanageProduct)
else:
return redirect(LoginPage)
def editReseller(request):
username = request.GET.get('username', None)
usrdet = UserData.objects.get(username=username)
print(username)
data = {"username":usrdet.username,"name":usrdet.name,"address":usrdet.address,"email":usrdet.email, "mobile":usrdet.mobileno, "retailerLimit":usrdet.retailerLimit ,"balance":usrdet.balance,"margin":usrdet.margin,"ior":usrdet.recharge_status,"vcloud":usrdet.vcloud_status,"status":usrdet.status}
return JsonResponse(data)
def submitEditUsers(request):
name = request.GET.get('name', None)
username = request.GET.get('username', None)
email = request.GET.get('email', None)
mobileno = request.GET.get('mobileno', None)
balance = request.GET.get('balance', None)
margin = request.GET.get('margin', None)
transactionlimit = request.GET.get('transactionlimit', None)
recharge_status = request.GET.get('recharge_status', None)
vcloud_status = request.GET.get('vcloud_status', None)
usrdet = UserData.objects.get(username=username)
usrdet.name = name
usrdet.email = email
usrdet.mobileno = mobileno
usrdet.balance = balance
usrdet.margin = margin
usrdet.retailerLimit = transactionlimit
if(recharge_status=="true"):
usrdet.recharge_status = True
else:
usrdet.recharge_status = False
if(vcloud_status=="false"):
usrdet.vcloud_status = False
else:
usrdet.vcloud_status = True
usrdet.save()
data = {"status":"Success"}
return JsonResponse(data)
def vcloudStore(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
pdcts = vcloudProducts.objects.filter(status=True,brand__category="card with cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
ads = adverisements.objects.filter(adtype="Image",ctype="Vcloud").order_by('-id')[:10]
buttonlist=["Cutting","Non Cutting"]
buttonclass=["btn-warning","btn-success"]
btnlist = zip(buttonlist, buttonclass)
return render(request,"admin/vcloud/vcloudStore.html",{'pdcts':pdcts,'btnlist':btnlist,'user':userdetails,'ads':ads})
else:
return redirect(LoginPage)
def filteredvcloudstore(request,brandtype):
if request.session.has_key("user"):
ads = adverisements.objects.filter(adtype="Image",ctype="Vcloud").order_by('-id')[:10]
buttonclass=[]
userdetails = UserData.objects.get(username=request.session["user"])
if(brandtype=="Cutting"):
pdcts = vcloudProducts.objects.filter(status=True,brand__category="card with cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
buttonclass=["btn-warning","btn-success"]
else:
pdcts = vcloudProducts.objects.filter(status=True,brand__category="card without cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
buttonclass=["btn-success","btn-warning"]
buttonlist=["Cutting","Non Cutting"]
btnlist = zip(buttonlist, buttonclass)
return render(request,"admin/vcloud/vcloudStore.html",{'pdcts':pdcts,'btnlist':btnlist,'user':userdetails,'ads':ads})
else:
return redirect(LoginPage)
def saveassignVcloudBrands(request):
if request.session.has_key("user"):
if request.method == "POST":
try:
reseller = request.POST.get('username', None)
values = request.POST.get('values', None)
states = request.POST.get('states', None)
brands = request.POST.get('brands', None)
margins = request.POST.get('margins', None)
v = values.split(',')
s = states.split(',')
b = brands.split(',')
m = margins.split(',')
username = request.session["user"]
assignedby = UserData.objects.get(username=username)
assignedto = UserData.objects.get(username=reseller)
#print(len(s))
for i in range(0,len(s)):
if(int(s[i])==0):
print(True)
brandid=b[i]
brdet=vcloudBrands.objects.get(id=brandid)
print(brdet)
try:
vdt = vcloudAssignments.objects.get(brand=brdet,assignedby=assignedby,assignedto=assignedto)
print(vdt)
vdt.delete()
print(assignedto)
vadt = vcloudAssignments.objects.filter(brand=brdet,assignedby=assignedto)
print(vadt)
for i in vadt:
try:
ud = vcloudAssignments.objects.filter(brand=brdet,assignedby=i.assignedto)
ud.delete()
except Exception as e:
print("inner "+str(e))
print(vadt)
vadt.delete()
except Exception as e:
print("Outer "+str(e))
else:
print(False)
brandid=b[int(i)]
brdet=vcloudBrands.objects.get(id=brandid)
try:
assdet = vcloudAssignments.objects.get(brand=brdet,assignedby=assignedby,assignedto=assignedto)
assdet.margin = Decimal(v[int(i)])
assdet.save()
except vcloudAssignments.DoesNotExist:
vass = vcloudAssignments()
vass.brand=brdet
vass.assignedto=assignedto
vass.assignedby=assignedby
vass.margin = Decimal(v[int(i)])
vass.save()
data={"status":"Success"}
return JsonResponse(data)
except Exception as e:
print("Outer Most"+str(e))
return JsonResponse({"status":"Error"})
else:
return JsonResponse({"status":"Error"})
else:
return redirect(LoginPage)
def vcloudmanageProduct(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
product = vcloudProducts.objects.all().order_by('-cdate')[:5000]
return render(request,"admin/vcloud/manageProduct.html",{'products':product,'user':userdetails})
else:
return redirect(LoginPage)
def getSponserDeT(user):
#print(user)
usdet=UserData.objects.get(username=user)
#print(usdet)
return usdet
def vcloudreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser1__username=username).order_by('-date')
#vcloudtxns = vcloudtransactions.objects.all().order_by('-date')
reseller=UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":(i.margin1*i.quantity),"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+(i.margin1*i.quantity)
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"admin/vcloud/vcloudreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filtervcloud_report(request):
if request.session.has_key("user"):
if request.method=="POST":
form = vcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
print(usertype)
fusername=form.cleaned_data.get("username")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
userdetails = UserData.objects.get(username=request.session["user"])
fuser=''
if(fusername!='All'):
filterdata=UserData.objects.get(username=fusername)
fuser=filterdata.name
else:
fuser=fusername
filter={'ffdate':fromdate,'ttdate':todate,'fuser':fuser}
reseller=UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords = 0
productsum = 0
quantitysum = 0
profitsum = 0
vcloudtxns=vcloudtransactions()
try:
print(usertype)
print(fusername)
print(type)
print(brand)
if(usertype=="All" and fusername=="All" and type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username).order_by('-date')
print("One")
elif(usertype=="All" and fusername=="All" and type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, type=type).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand !="All"):
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername!="All" and type !="All" and brand !="All"):
print('five')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, type=type, sponser1__username=username, sponser2__username=fusername, brand=brand).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand !="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__type=usertype, sponser1__username=username).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__postId=usertype).order_by('-date')
elif(usertype =="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__username=fusername).order_by('-date')
elif(usertype !="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__username=fusername).order_by('-date')
else:
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__username=fusername,brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":(i.margin1*i.quantity),"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+(i.margin1*i.quantity)
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"admin/vcloud/vcloudreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(vcloudreport)
else:
return redirect(vcloudreport)
else:
return redirect(LoginPage)
def get_product_details(request):
if request.session.has_key("user"):
if request.method == 'POST':
id = request.POST.get('id', None)
print(id)
vcloudtxns=vcloudtransactions.objects.get(id=id)
print(vcloudtxns)
type = vcloudtxns.type
productid=vcloudtxns.product_id
result = productid.rstrip(',')
pdid = result.split(',')
print(pdid)
pdlist=list()
content=list()
if(type=="Vcloud"):
for i in pdid:
pddet=vcloudProducts.objects.get(id=i)
data={"id":pddet.id,"brand":pddet.brand.brand,"username":pddet.username,"password":pddet.password}
pdlist.append(data)
elif(type=="Dcard"):
for i in pdid:
pddet=datacardproducts.objects.get(id=i)
data={"id":pddet.id,"brand":pddet.brand.brand,"username":pddet.username}
pdlist.append(data)
else:
for i in pdid:
pddet=rcardProducts.objects.get(id=i)
data={"id":pddet.id,"brand":pddet.brand.brand,"username":pddet.username}
pdlist.append(data)
content.append(pdlist)
content.append({"type":type})
return JsonResponse(content,safe=False)
else:
pass
else:
return redirect(LoginPage)
#________________DCARD______________
def adminDcardDashboard(request):
if request.session.has_key("user"):
last_month = datetime.today() - timedelta(days=1)
username = request.session["user"]
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(list(reseller[0]))
type = request.session["usertype"]
try:
user = UserData.objects.get(username = username, postId = type)
except UserData.DoesNotExist:
return redirect(LoginPage)
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser1__username=username,type="Dcard").order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":(i.margin1*i.quantity),"rtype":i.rtype}
data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
topuser.append(data3)
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+(i.margin1*i.quantity)
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand=dcardBrands.objects.all()
product=list()
for j in brand:
prdcts=datacardproducts.objects.filter(brand__id=j.id,status=True).order_by("brand__brand").values("brand").annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__denomination')
#print(prdcts)
if(prdcts):
for k in prdcts:
totalcost=k['productcount']*k['brand__denomination']
data2={"brand":k['brand__brand'],"count":k['productcount'],"denomination":k['brand__denomination'],'totalcost':totalcost}
product.append(data2)
else:
totalcost=0
data2={"brand":j.brand,"count":0,"denomination":j.denomination,'totalcost':totalcost}
product.append(data2)
#print(topuser)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"admin/dcard/dashboard-dcard.html",{'filterform':dcardDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':user,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filterdcardhomepage(request):
if request.session.has_key("user"):
if request.method == "POST":
form = dcardDashboardfilter(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
uuusername=form.cleaned_data.get("username")
#mffromdate=datetime.strptime(fromdate, '%b %d %Y %I:%M%p')
#print(type(fromdate))
print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
reseller = UserData.objects.filter(sponserId=currentuser,postId="Reseller")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(username)
userdetails = UserData.objects.get(username=request.session["user"])
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,sponser1__username=currentuser,type="Dcard",sponser2__username=uuusername).order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":(i.margin1*i.quantity),"rtype":i.rtype}
data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
topuser.append(data3)
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+(i.margin1*i.quantity)
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand=vcloudBrands.objects.all()
product=list()
for j in brand:
prdcts=vcloudProducts.objects.filter(brand__id=j.id,status=True).order_by("brand__brand").values("brand").annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__denomination')
#print(prdcts)
if(prdcts):
for k in prdcts:
totalcost=k['productcount']*k['brand__denomination']
data2={"brand":k['brand__brand'],"count":k['productcount'],"denomination":k['brand__denomination'],'totalcost':totalcost}
product.append(data2)
else:
totalcost=0
data2={"brand":j.brand,"count":0,"denomination":j.denomination,'totalcost':totalcost}
product.append(data2)
#print(topuser)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"admin/dcard/dashboard-dcard.html",{'filterform':vcloudDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':userdetails,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(adminDcardDashboard)
else:
return(adminDcardDashboard)
else:
return redirect(LoginPage)
def dcardaddReseller(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def dcardaddUser(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def dcardnewReseller(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="Reseller"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(dcardaddReseller)
else:
userdetails = UserData.objects.get(username=request.session["user"])
messages.warning(request, 'Internal Error Occured')
form = AddUserDataForm()
return render(request,"admin/dcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"admin/dcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def dcardviewReseller(request):
if request.session.has_key("user"):
resellers = UserData.objects.filter(postId="Reseller")
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/viewResellers.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def dcardnewUser(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="User"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(dcardaddUser)
else:
userdetails = UserData.objects.get(username=request.session["user"])
messages.warning(request, form.errors)
form = AddUserDataForm()
return render(request,"admin/dcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"admin/dcard/addUser.html",{'form':AddUserDataForm,'user':username})
else:
return redirect(LoginPage)
def dcardviewUser(request):
if request.session.has_key("user"):
user = request.session["user"]
resellers = UserData.objects.filter(postId="User",sponserId=user)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/viewUser.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def dcardprofile(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"admin/dcard/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def dcardeditProfile(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(dcardprofile)
else:
messages.warning(request,'Internal Error Occured')
return redirect(dcardprofile)
else:
return redirect(LoginPage)
def dcardbalanceTransfer(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
bthist=balanceTransactionReport.objects.filter(source=userdetails,category="BT").order_by('-date')
#print(bthist)
return render(request,"admin/dcard/balanceTransfer.html",{'bthist':bthist,'user':userdetails})
else:
return redirect(LoginPage)
def dcardSubmitBalanceTransfer(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
userdet = UserData.objects.get(username=user)
bal = userdet.balance
newbal=bal+Decimal(amount)
cdbal = userdet.targetAmt
newcdbal = cdbal-Decimal(amount)
userdet.targetAmt = newcdbal
userdet.balance = newbal
userdet.save()
userdetails = UserData.objects.get(username=request.session["user"])
btreport = balanceTransactionReport()
btreport.source = userdetails
btreport.destination = userdet
btreport.category = "BT"
btreport.amount = amount
btreport.pbalance = bal
btreport.nbalance = newbal
btreport.cramount = newcdbal
btreport.remarks = 'Added To Balance'
btreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(dcardbalanceTransfer)
#userdata=UserData.objects.get(username=)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(dcardbalanceTransfer)
else:
return redirect(LoginPage)
def dcardaddPayment(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
phist=fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"admin/dcard/addPayment.html",{'phist':phist})
else:
return redirect(LoginPage)
def dcardsubmitPayment(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
remarks = request.POST.get('remarks', None)
userdet = UserData.objects.get(username=user)
obalance =userdet.targetAmt
cdbal = userdet.targetAmt
newcdbal = cdbal+Decimal(amount)
userdet.targetAmt = newcdbal
userdet.save()
closeuser = UserData.objects.get(username=user)
userdetails = UserData.objects.get(username=request.session["user"])
ftreport=fundTransactionReport()
ftreport.source = userdetails
ftreport.destination = userdet
ftreport.obalance = obalance
ftreport.cbalance = closeuser.targetAmt
ftreport.role = userType
ftreport.amount = amount
ftreport.balance = newcdbal
ftreport.remarks = remarks
ftreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(dcardaddPayment)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(dcardaddPayment)
else:
return redirect(LoginPage)
def dcardbalanceTransferReport(request):
if request.session.has_key("user"):
username = request.session["user"]
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
sum = balanceTransactionReport.objects.filter(source=userdetails,category='BT').aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"admin/dcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'sum':sum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filterdcardbtreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
sum=list()
bthist=None
try:
if(usertype == "All" and susername == "All"):
sum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(usertype!="All" and susername == "All"):
sum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype)
else:
sum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"admin/dcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'sum':sum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(dcardbalanceTransferReport)
else:
return redirect(dcardbalanceTransferReport)
else:
return redirect(LoginPage)
def dcardpaymentReport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=request.session["user"],postId="Reseller")
phist = fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
bsum = fundTransactionReport.objects.filter(source=userdetails).aggregate(Sum('amount'))
return render(request,"admin/dcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filterdcardpaymentreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
sum=None
bthist=None
try:
if(usertype == "All" and susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(usertype!="All" and susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype)
else:
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"admin/dcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(dcardpaymentReport)
else:
return redirect(dcardpaymentReport)
else:
return redirect(LoginPage)
def addDCardBrand(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/adddcardbrand.html",{'form':AddDCardBrands,'user':userdetails})
else:
return redirect(LoginPage)
def submitDCardBrands(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddDCardBrands(request.POST, request.FILES)
#print(form.errors)
if form.is_valid():
branddata=form.save()
messages.success(request, 'Successfully Added The Brands')
return redirect(addDCardBrand)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(addDCardBrand)
else:
return redirect(addDCardBrand)
else:
return redirect(LoginPage)
def manageDCardBrands(request):
if request.session.has_key("user"):
brands = dcardBrands.objects.all()
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/managedcardbrand.html",{'brands':brands,'user':userdetails})
else:
return redirect(LoginPage)
def assignDCardBrands(request):
if request.session.has_key("user"):
brands=dcardBrands.objects.all()
#brands = datacardproducts.objects.filter(status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('brand__id','brand__brand','brand__denomination','count','brand__description','brand__logo','brand__currency')
print(brands)
resellers = UserData.objects.filter(postId="Reseller")
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/assignDcardbrand.html",{'brands':brands,'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def getDCardBrandDetails(request):
id = request.GET.get('id', None)
brdet = dcardBrands.objects.get(id=id)
data={"id":brdet.id,"brand":brdet.brand,"logo":brdet.logo.url,"rate":brdet.denomination,"desc":brdet.description}
#print(data)
return JsonResponse(data)
def submitDcardManageBrands(request):
if request.session.has_key("user"):
if request.method == "POST":
form = editDcardBrands(request.POST, request.FILES)
if form.is_valid():
id = form.cleaned_data.get("id")
brandname = form.cleaned_data.get("brand")
flag=True;
brand = dcardBrands.objects.get(id=id)
try:
logo = request.FILES['logo']
brand.logo = logo
print(logo)
except:
flag=False;
description = form.cleaned_data.get("desc")
denomination = form.cleaned_data.get("rate")
brand.brand = brandname
brand.description = description
brand.denomination = denomination
brand.save()
print(brand)
return redirect(manageDCardBrands)
else:
print(form.errors)
return redirect(manageDCardBrands)
else:
return redirect(manageDCardBrands)
else:
return redirect(LoginPage)
def adddcardProduct(request):
if request.session.has_key("user"):
choices=dcardBrands.objects.all().values('id', 'brand')
print(choices)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/addDcardProduct.html",{'productform':AddDcardProducts,'brandform':AddDCardBrands,'choices':choices,'user':userdetails})
else:
return redirect(LoginPage)
def submitdcardProducts(request):
if request.session.has_key("user"):
if request.method == "POST":
try:
form = AddDcardProducts(request.POST or None)
if form.is_valid():
brandid = form.cleaned_data.get("brand")
username = form.cleaned_data.get("username")
res=datacardproducts.objects.filter(username = username).exists()
print(res)
res1=dcardupproducts.objects.filter(username = username).exists()
print(res1)
if(res or res1):
messages.warning(request, 'Product is alreday updated in Csv log. Go and spent the product')
else:
product = datacardproducts()
branddet = dcardBrands.objects.get(id=brandid)
product.brand = branddet
product.username = username
product.denomination = branddet.denomination
product.save()
messages.success(request, 'Successfully Added The Products')
return redirect(adddcardProduct)
else:
messages.warning(request, form.errors)
return redirect(adddcardProduct)
except:
return redirect(adddcardProduct)
else:
return redirect(adddcardProduct)
else:
return redirect(LoginPage)
def dcardmanageProduct(request):
if request.session.has_key("user"):
product = datacardproducts.objects.all().order_by('-cdate')[:5000]
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/manageProduct.html",{'products':product,'user':userdetails})
else:
return redirect(LoginPage)
def saveassignDCardBrands(request):
if request.session.has_key("user"):
if request.method == "POST":
try:
reseller = request.POST.get('username', None)
values = request.POST.get('values', None)
states = request.POST.get('states', None)
brands = request.POST.get('brands', None)
margins = request.POST.get('margins', None)
v = values.split(',')
s = states.split(',')
b = brands.split(',')
m = margins.split(',')
username = request.session["user"]
assignedby = UserData.objects.get(username=username)
assignedto = UserData.objects.get(username=reseller)
for i in range(0,len(s)):
if(int(s[i])==0):
print(True)
brandid=b[int(i)]
brdet=dcardBrands.objects.get(id=brandid)
print(brdet)
try:
vdt = datacardAssignments.objects.get(brand=brdet,assignedby=assignedby,assignedto=assignedto)
vdt.delete()
vadt = datacardAssignments.objects.filter(brand=brdet,assignedby=assignedto)
print(vadt)
for j in vadt:
try:
ud = datacardAssignments.objects.filter(brand=brdet,assignedby=j.assignedto)
print(ud)
ud.delete()
except Exception as e:
print(e)
pass;
#print(vadt)
vadt.delete()
except Exception as e:
print (e)
print("Error")
else:
print(False)
brandid=b[int(i)]
brdet=dcardBrands.objects.get(id=brandid)
try:
assdet = datacardAssignments.objects.get(brand=brdet,assignedby=assignedby,assignedto=assignedto)
assdet.margin = Decimal(v[int(i)])
assdet.save()
except datacardAssignments.DoesNotExist:
vass = datacardAssignments()
vass.brand=brdet
vass.assignedto=assignedto
vass.assignedby=assignedby
vass.margin = Decimal(v[int(i)])
vass.save()
data={"status":"Success"}
return JsonResponse(data)
except Exception as e:
print(e)
return JsonResponse({"status":"Error"})
else:
pass
else:
return redirect(LoginPage)
def dcardstore(request):
if request.session.has_key("user"):
ads = adverisements.objects.filter(adtype="Image",ctype="Dcard").order_by('-id')[:10]
dcardproducts = datacardproducts.objects.filter(status=True).order_by('brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
some_list = []
data = dict()
for i in dcardproducts:
brandname=i["brand__brand"]
bd=brandname.split(' ')
bname=bd[0]
print(bname)
if any(bname in s for s in some_list):
pass
else:
some_list.append(bname)
totalfil=len(some_list)
print(totalfil)
if(totalfil!=0):
classlist=[]
for j in range(0,totalfil):
if(j==0):
classlist.append("btn-warning")
else:
classlist.append("btn-success")
btnlist = zip(some_list, classlist)
print(btnlist)
userdetails = UserData.objects.get(username=request.session["user"])
item=datacardproducts.objects.filter(status=True,brand__brand__contains=some_list[0]).order_by('brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
else:
item=None
btnlist=None
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/datastore.html",{'dcardproducts':item,'btnlist':btnlist,'user':userdetails,'ads':ads})
else:
return redirect(LoginPage)
def filtereddatastore(request,brand):
if request.session.has_key("user"):
ads = adverisements.objects.filter(adtype="Image",ctype="Dcard").order_by('-id')[:10]
dcardproducts = datacardproducts.objects.filter(status=True).order_by('brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
some_list = []
data = dict()
for i in dcardproducts:
brandname=i["brand__brand"]
bd=brandname.split(' ')
bname=bd[0]
#print(bname)
if any(bname in s for s in some_list):
pass
else:
some_list.append(bname)
totalfil=len(some_list)
position=0
for index, inbrand in enumerate(some_list):
print(inbrand)
#print(bname)
if inbrand == brand:
position=index
print(position)
classlist=[]
for j in range(0,totalfil):
if(j==position):
classlist.append("btn-warning")
else:
classlist.append("btn-success")
print(classlist)
btnlist = zip(some_list, classlist)
#print(btnlist)
item=datacardproducts.objects.filter(status=True,brand__brand__contains=brand).order_by('brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/datastore.html",{'dcardproducts':item,'btnlist':btnlist,'totalfil':totalfil,'user':userdetails,'ads':ads})
else:
return redirect(LoginPage)
def datacardreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser1__username=username).order_by('-date')
#vcloudtxns = vcloudtransactions.objects.all().order_by('-date')
reseller=UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":(i.margin1*i.quantity),"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+(i.margin1*i.quantity)
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"admin/dcard/dcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filterdcard_report(request):
if request.session.has_key("user"):
if request.method=="POST":
form = vcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
print(usertype)
fusername=form.cleaned_data.get("username")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
userdetails = UserData.objects.get(username=request.session["user"])
fuser=''
if(fusername!='All'):
filterdata=UserData.objects.get(username=fusername)
fuser=filterdata.name
else:
fuser=fusername
filter={'ffdate':fromdate,'ttdate':todate,'fuser':fuser}
reseller=UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords = 0
productsum = 0
quantitysum = 0
profitsum = 0
vcloudtxns=vcloudtransactions()
try:
print(usertype)
print(fusername)
print(type)
print(brand)
if(usertype=="All" and fusername=="All" and type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username).order_by('-date')
print("One")
elif(usertype=="All" and fusername=="All" and type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, type=type).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand !="All"):
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername!="All" and type !="All" and brand !="All"):
print('five')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, type=type, sponser1__username=username, sponser2__username=fusername, brand=brand).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand !="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__type=usertype, sponser1__username=username).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__postId=usertype).order_by('-date')
elif(usertype =="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__username=fusername).order_by('-date')
elif(usertype !="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__username=fusername).order_by('-date')
else:
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__username=fusername,brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":(i.margin1*i.quantity),"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+(i.margin1*i.quantity)
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"admin/dcard/dcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(dcardreport)
else:
return redirect(dcardreport)
else:
return redirect(LoginPage)
#________________RCARD_______________
def adminRcardDashboard(request):
if request.session.has_key("user"):
last_month = datetime.today() - timedelta(days=1)
username = request.session["user"]
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(list(reseller[0]))
type = request.session["usertype"]
try:
user = UserData.objects.get(username = username, postId = type)
except UserData.DoesNotExist:
return redirect(LoginPage)
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser1__username=username,type="Rcard").order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":(i.margin1*i.quantity),"rtype":i.rtype}
data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
topuser.append(data3)
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+(i.margin1*i.quantity)
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand=rcardBrands.objects.all()
product=list()
for j in brand:
prdcts=rcardProducts.objects.filter(brand__id=j.id,status=True).order_by("brand__brand").values("brand").annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__denomination')
#print(prdcts)
if(prdcts):
for k in prdcts:
totalcost=k['productcount']*k['brand__denomination']
data2={"brand":k['brand__brand'],"count":k['productcount'],"denomination":k['brand__denomination'],"totalcost":totalcost}
product.append(data2)
else:
totalcost=0
data2={"brand":j.brand,"count":0,"denomination":j.denomination,"totalcost":totalcost}
product.append(data2)
#print(topuser)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"admin/rcard/dashboard-rcard.html",{'filterform':rcardDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':user,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filterrcardhomepage(request):
if request.session.has_key("user"):
if request.method == "POST":
form = rcardDashboardfilter(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
uuusername=form.cleaned_data.get("username")
#mffromdate=datetime.strptime(fromdate, '%b %d %Y %I:%M%p')
#print(type(fromdate))
print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
reseller = UserData.objects.filter(sponserId=currentuser,postId="Reseller")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(username)
userdetails = UserData.objects.get(username=request.session["user"])
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,sponser1__username=currentuser,type="Vcloud",sponser2__username=uuusername).order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":(i.margin1*i.quantity),"rtype":i.rtype}
data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
topuser.append(data3)
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+(i.margin1*i.quantity)
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand=rcardBrands.objects.all()
product=list()
for j in brand:
prdcts=rcardProducts.objects.filter(brand__id=j.id,status=True).order_by("brand__brand").values("brand").annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__denomination')
if(prdcts):
for k in prdcts:
totalcost=k['productcount']*k['brand__denomination']
data2={"brand":k['brand__brand'],"count":k['productcount'],"denomination":k['brand__denomination'],"totalcost":totalcost}
product.append(data2)
else:
totalcost=0
data2={"brand":j.brand,"count":0,"denomination":j.denomination,"totalcost":totalcost}
product.append(data2)
#print(topuser)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"admin/rcard/dashboard-rcard.html",{'filterform':rcardDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':userdetails,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(adminRcardDashboard)
else:
return(adminRcardDashboard)
else:
return redirect(LoginPage)
def rcardaddReseller(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/rcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def rcardaddUser(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/rcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def getRCardBrandDetails(request):
id = request.GET.get('id', None)
brdet = rcardBrands.objects.get(id=id)
data={"id":brdet.id,"brand":brdet.brand,"logo":brdet.logo.url,"rate":brdet.denomination,"desc":brdet.description}
#print(data)
return JsonResponse(data)
def submitRcardManageBrands(request):
if request.session.has_key("user"):
if request.method == "POST":
form = editRcardBrands(request.POST, request.FILES)
if form.is_valid():
id = form.cleaned_data.get("id")
brandname = form.cleaned_data.get("brand")
flag=True;
brand = rcardBrands.objects.get(id=id)
try:
logo = request.FILES['logo']
brand.logo = logo
print(logo)
except:
flag=False;
description = form.cleaned_data.get("desc")
denomination = form.cleaned_data.get("rate")
brand.brand = brandname
brand.description = description
brand.denomination = denomination
brand.save()
print(brand)
return redirect(manageRCardBrands)
else:
print(form.errors)
return redirect(manageRCardBrands)
else:
return redirect(manageRCardBrands)
else:
return redirect(LoginPage)
def rcardnewReseller(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="Reseller"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(rcardaddReseller)
else:
userdetails = UserData.objects.get(username=request.session["user"])
messages.warning(request, 'Internal Error Occured')
form = AddUserDataForm()
return render(request,"admin/rcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"admin/rcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def rcardviewReseller(request):
if request.session.has_key("user"):
resellers = UserData.objects.filter(postId="Reseller")
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/rcard/viewResellers.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def rcardnewUser(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="User"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(rcardaddUser)
else:
userdetails = UserData.objects.get(username=request.session["user"])
messages.warning(request, 'Internal Error Occured')
form = AddUserDataForm()
return render(request,"admin/rcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"admin/rcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def rcardviewUser(request):
if request.session.has_key("user"):
user = request.session["user"]
userdetails = UserData.objects.get(username=request.session["user"])
resellers = UserData.objects.filter(postId="User",sponserId=user)
return render(request,"admin/rcard/viewUser.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def rcardprofile(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"admin/rcard/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def rcardeditProfile(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(rcardprofile)
else:
messages.warning(request,'Internal Error Occured')
return redirect(rcardprofile)
else:
return redirect(LoginPage)
def rcardbalanceTransfer(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
bthist=balanceTransactionReport.objects.filter(source=userdetails,category="BT").order_by('-date')
#print(bthist)
return render(request,"admin/rcard/balanceTransfer.html",{'bthist':bthist,'user':userdetails})
else:
return redirect(LoginPage)
def rcardSubmitBalanceTransfer(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
userdet = UserData.objects.get(username=user)
bal = userdet.balance
newbal=bal+Decimal(amount)
cdbal = userdet.targetAmt
newcdbal = cdbal-Decimal(amount)
userdet.targetAmt = newcdbal
userdet.balance = newbal
userdet.save()
userdetails = UserData.objects.get(username=request.session["user"])
btreport = balanceTransactionReport()
btreport.source = userdetails
btreport.destination = userdet
btreport.category = "BT"
btreport.amount = amount
btreport.pbalance = bal
btreport.nbalance = newbal
btreport.cramount = newcdbal
btreport.remarks = 'Added To Balance'
btreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(rcardbalanceTransfer)
#userdata=UserData.objects.get(username=)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(rcardbalanceTransfer)
else:
return redirect(LoginPage)
def rcardaddPayment(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
phist=fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"admin/rcard/addPayment.html",{'phist':phist,'user':userdetails})
else:
return redirect(LoginPage)
def rcardsubmitPayment(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
remarks = request.POST.get('remarks', None)
userdet = UserData.objects.get(username=user)
obalance = userdet.targetAmt
cdbal = userdet.targetAmt
newcdbal = cdbal+Decimal(amount)
userdet.targetAmt = newcdbal
userdet.save()
closeuser = UserData.objects.get(username=user)
userdetails = UserData.objects.get(username=request.session["user"])
ftreport=fundTransactionReport()
ftreport.source = userdetails
ftreport.destination = userdet
ftreport.obalance = obalance
ftreport.cbalance = closeuser.targetAmt
ftreport.role = userType
ftreport.amount = amount
ftreport.balance = newcdbal
ftreport.remarks = remarks
ftreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(rcardaddPayment)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(rcardaddPayment)
else:
return redirect(LoginPage)
def rcardbalanceTransferReport(request):
if request.session.has_key("user"):
username = request.session["user"]
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
sum = balanceTransactionReport.objects.filter(source=userdetails,category='BT').aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"admin/rcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'sum':sum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filterrcardbtreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
#fuser=UserData.objects.get(username=susername)
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
sum=list()
bthist=None
try:
if(usertype == "All" and susername == "All"):
sum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(usertype!="All" and susername == "All"):
sum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype)
else:
sum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"admin/rcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'sum':sum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(rcardbalanceTransferReport)
else:
return redirect(rcardbalanceTransferReport)
else:
return redirect(LoginPage)
def rcardpaymentReport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=request.session["user"],postId="Reseller")
phist = fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
bsum = fundTransactionReport.objects.filter(source=userdetails).aggregate(Sum('amount'))
return render(request,"admin/rcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filterrcardpaymentreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Reseller")
sum=None
bthist=None
try:
if(usertype == "All" and susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(usertype!="All" and susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype)
else:
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"admin/rcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(rcardpaymentReport)
else:
return redirect(rcardpaymentReport)
else:
return redirect(LoginPage)
def addRCardBrand(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/rcard/addrcardbrand.html",{'form':AddRCardBrands,'user':userdetails})
else:
return redirect(LoginPage)
def submitRCardBrands(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddRCardBrands(request.POST, request.FILES)
#print(form.errors)
if form.is_valid():
branddata=form.save()
messages.success(request, 'Successfully Added The Brands')
return redirect(addRCardBrand)
else:
messages.warning(request, form.errors)
return redirect(addRCardBrand)
else:
return redirect(addRCardBrand)
else:
return redirect(LoginPage)
def manageRCardBrands(request):
if request.session.has_key("user"):
brands = rcardBrands.objects.all()
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/rcard/managercardbrand.html",{'brands':brands,'user':userdetails})
else:
return redirect(LoginPage)
def assignRCardBrands(request):
if request.session.has_key("user"):
brands = rcardBrands.objects.all()
#brands = rcardProducts.objects.filter(status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('brand__id','brand__brand','brand__denomination','count','brand__description','brand__logo','brand__currency')
print(brands)
resellers = UserData.objects.filter(postId="Reseller")
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/rcard/assignRcardbrand.html",{'brands':brands,'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def addrcardProduct(request):
if request.session.has_key("user"):
choices=rcardBrands.objects.all().values('id', 'brand')
userdetails = UserData.objects.get(username=request.session["user"])
#print(choices)
return render(request,"admin/rcard/addrcardproduct.html",{'productform':AddRcardProducts,'brandform':AddRCardBrands,'choices':choices,'user':userdetails})
else:
return redirect(LoginPage)
def submitrcardProducts(request):
if request.session.has_key("user"):
if request.method == "POST":
try:
form = AddRcardProducts(request.POST or None)
if form.is_valid():
brandid = form.cleaned_data.get("brand")
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
res=rcardProducts.objects.filter(username = username).exists()
print(res)
res1=rcardupproducts.objects.filter(username = username).exists()
print(res1)
if(res or res1):
messages.warning(request, 'Product is alreday updated in Csv log. Go and spent the product')
else:
product = rcardProducts()
branddet = rcardBrands.objects.get(id=brandid)
product.brand = branddet
product.username = username
product.denomination = branddet.denomination
product.save()
messages.success(request, 'Successfully Added The Products')
return redirect(addrcardProduct)
else:
messages.warning(request, form.errors)
return redirect(addrcardProduct)
except:
return redirect(addrcardProduct)
else:
return redirect(addrcardProduct)
else:
return redirect(LoginPage)
def rcardmanageProduct(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
product = rcardProducts.objects.all().order_by('-cdate')[:5000]
return render(request,"admin/rcard/manageProduct.html",{'products':product,'user':userdetails})
else:
return redirect(LoginPage)
def saveassignRCardBrands(request):
if request.session.has_key("user"):
if request.method == "POST":
try:
reseller = request.POST.get('username', None)
values = request.POST.get('values', None)
states = request.POST.get('states', None)
brands = request.POST.get('brands', None)
margins = request.POST.get('margins', None)
v = values.split(',')
s = states.split(',')
b = brands.split(',')
m = margins.split(',')
username = request.session["user"]
assignedby = UserData.objects.get(username=username)
assignedto = UserData.objects.get(username=reseller)
for i in range(0,len(s)):
if(int(s[i])==0):
print(True)
brandid=b[int(i)]
brdet=rcardBrands.objects.get(id=brandid)
print(brdet)
try:
vdt = rcardAssignments.objects.get(brand=brdet,assignedby=assignedby,assignedto=assignedto)
vdt.delete()
vadt = rcardAssignments.objects.filter(brand=brdet,assignedby=assignedto)
for i in vadt:
try:
ud = rcardAssignments.objects.filter(brand=brdet,assignedby=i.assignedto)
ud.delete()
except rcardAssignments.DoesNotExist:
pass;
print(vadt)
vadt.delete()
except:
print("Error")
else:
print(False)
brandid=b[int(i)]
brdet=rcardBrands.objects.get(id=brandid)
try:
assdet = rcardAssignments.objects.get(brand=brdet,assignedby=assignedby,assignedto=assignedto)
assdet.margin = Decimal(v[int(i)])
assdet.save()
except rcardAssignments.DoesNotExist:
vass = rcardAssignments()
vass.brand=brdet
vass.assignedto=assignedto
vass.assignedby=assignedby
vass.margin = Decimal(v[int(i)])
vass.save()
data={"status":"Success"}
return JsonResponse(data)
except:
return redirect({"status":"Error"})
else:
pass
else:
return redirect(LoginPage)
def rcardstore(request):
if request.session.has_key("user"):
try:
ads = adverisements.objects.filter(adtype="Image",ctype="Rcard").order_by('-id')[:10]
rcardproducts = rcardProducts.objects.filter(status=True).order_by('brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
some_list = []
data = dict()
for i in rcardproducts:
brandname=i["brand__brand"]
bd=brandname.split(' ')
bname=bd[0]
print(bname)
if any(bname in s for s in some_list):
pass
else:
some_list.append(bname)
totalfil=len(some_list)
if(totalfil != 0):
classlist=[]
for j in range(0,totalfil):
if(j==0):
classlist.append("btn-warning")
else:
classlist.append("btn-success")
btnlist = zip(some_list, classlist)
print(btnlist)
item=rcardProducts.objects.filter(status=True,brand__brand__contains=some_list[0]).order_by('brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
userdetails = UserData.objects.get(username=request.session["user"])
else:
item=None
btnlist=None
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/rcard/rcardstore.html",{'rcardproducts':item,'btnlist':btnlist,'user':userdetails,'ads':ads})
except:
pass
else:
return redirect(LoginPage)
def filteredrcardstore(request,brand):
if request.session.has_key("user"):
try:
ads = adverisements.objects.filter(adtype="Image",ctype="Rcard").order_by('-id')[:10]
rcardproducts = rcardProducts.objects.filter(status=True).order_by('brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
some_list = []
data = dict()
for i in rcardproducts:
brandname=i["brand__brand"]
bd=brandname.split(' ')
bname=bd[0]
#print(bname)
if any(bname in s for s in some_list):
pass
else:
some_list.append(bname)
totalfil=len(some_list)
position=0
for index, inbrand in enumerate(some_list):
if inbrand == brand:
position=index
classlist=[]
for j in range(0,totalfil):
if(j==position):
classlist.append("btn-warning")
else:
classlist.append("btn-success")
print(classlist)
btnlist = zip(some_list, classlist)
#print(btnlist)
item=rcardProducts.objects.filter(status=True,brand__brand__contains=brand).order_by('brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"admin/rcard/rcardstore.html",{'rcardproducts':item,'btnlist':btnlist,'totalfil':totalfil,'user':userdetails,'ads':ads})
except:
pass;
else:
return redirect(LoginPage)
def rcardreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser1__username=username).order_by('-date')
#vcloudtxns = vcloudtransactions.objects.all().order_by('-date')
reseller=UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":i.margin1,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+i.margin1
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"admin/rcard/rcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filterrcard_report(request):
if request.session.has_key("user"):
if request.method=="POST":
try:
form = vcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
print(usertype)
fusername=form.cleaned_data.get("username")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
userdetails = UserData.objects.get(username=request.session["user"])
fuser=''
if(fusername!='All'):
filterdata=UserData.objects.get(username=fusername)
fuser=filterdata.name
else:
fuser=fusername
filter={'ffdate':fromdate,'ttdate':todate,'fuser':fuser}
reseller=UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords = 0
productsum = 0
quantitysum = 0
profitsum = 0
vcloudtxns=vcloudtransactions()
try:
print(usertype)
print(fusername)
print(type)
print(brand)
if(usertype=="All" and fusername=="All" and type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username).order_by('-date')
print("One")
elif(usertype=="All" and fusername=="All" and type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, type=type).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand !="All"):
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername!="All" and type !="All" and brand !="All"):
print('five')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, type=type, sponser1__username=username, sponser2__username=fusername, brand=brand).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand !="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__type=usertype, sponser1__username=username).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__postId=usertype).order_by('-date')
elif(usertype =="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__username=fusername).order_by('-date')
elif(usertype !="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__username=fusername).order_by('-date')
else:
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser1__username=username, sponser2__username=fusername,brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.denominations*i.quantity),"profit":i.margin1,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.denominations*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+i.margin1
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"admin/rcard/rcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(rcardreport)
except:
return redirect(rcardreport)
else:
return redirect(rcardreport)
else:
return redirect(LoginPage)
#________________________________________________________________Reseller_______________________________________________________________
#________________VCLOUD_______________
def resellervcloudhomePage(request):
if request.session.has_key("user"):
try:
username = request.session["user"]
#print(last_month)
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
username = request.session["user"]
type = request.session["usertype"]
try:
user = UserData.objects.get(username = username, postId = type)
except UserData.DoesNotExist:
return redirect(LoginPage)
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser2__username=username,type="Vcloud").order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin2*i.quantity
data3={'user':i.sponser3.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = vcloudAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
#print(brand)
for i in brand:
print(i['brand__id'])
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
print(username)
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
print(username)
userdet2=UserData.objects.get(username=username)
print("username:"+userdet2.username)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2.postId=="Admin"):
break;
else:
#print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
#print(productcost)
username=userdet2.sponserId.username
print(username)
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"reseller/vcloud/dashboard-vcloud.html",{'filterform':vcloudDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':user,'topuser':list3,'last_month':last_month,'boxval':box_data})
except Exception as e:
print(e);
#return render(request,"reseller/vcloud/dashboard-vcloud.html",{'filterform':vcloudDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':user,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filterresellervcloudhomepage(request):
if request.session.has_key('user'):
if request.method == "POST":
try:
form = vcloudDashboardfilter(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
uuusername=form.cleaned_data.get("username")
#mffromdate=datetime.strptime(fromdate, '%b %d %Y %I:%M%p')
print(type(fromdate))
print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
reseller = UserData.objects.filter(sponserId=currentuser,postId="Sub_Reseller")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(username)
userdetails = UserData.objects.get(username=request.session["user"])
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,sponser2__username=currentuser,type="Vcloud",sponser3__username=uuusername).order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin2*i.quantity
data3={'user':i.sponser3.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = vcloudAssignments.objects.filter(assignedto=currentuser).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"reseller/vcloud/dashboard-vcloud.html",{'filterform':vcloudDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':userdetails,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
print("Haiii0")
return redirect(resellervcloudhomePage)
except:
print("Haiii1")
return redirect(resellervcloudhomePage)
else:
print("Haiii2")
return(resellervcloudhomePage)
else:
return redirect(LoginPage)
def resellervcloudaddReseller(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/vcloud/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def resellervcloudnewReseller(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="Sub_Reseller"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(resellervcloudaddReseller)
else:
userdetails = UserData.objects.get(username=request.session["user"])
messages.warning(request, form.errors)
form = AddUserDataForm()
return render(request,"reseller/vcloud/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"reseller/vcloud/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def resellervcloudviewReseller(request):
if request.session.has_key("user"):
username = request.session["user"]
userdet = UserData.objects.get(username=username)
print(userdet)
try:
resellers = UserData.objects.filter(postId="Sub_Reseller",sponserId=username)
except UserData.DoesNotExist:
resellers = None
return render(request,"reseller/vcloud/viewResellers.html",{'resellers':resellers,'user':userdet})
else:
return redirect(LoginPage)
def resellervcloudaddUser(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/vcloud/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def resellervcloudnewUser(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
print(username)
print(password)
print(hash)
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="User"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(resellervcloudaddUser)
else:
userdetails = UserData.objects.get(username=request.session["user"])
messages.warning(request, form.errors)
form = AddUserDataForm()
return render(request,"reseller/vcloud/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"reseller/vcloud/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def resellervcloudviewUser(request):
if request.session.has_key("user"):
username = request.session["user"]
resellers = UserData.objects.filter(postId="User",sponserId=username)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/vcloud/viewUser.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def resellervcloudprofile(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"reseller/vcloud/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def resellervcloudeditProfile(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(resellervcloudprofile)
else:
messages.warning(request,'Internal Error Occured')
return redirect(resellervcloudprofile)
else:
return redirect(LoginPage)
def resellervcloudbalanceTransfer(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
bthist=balanceTransactionReport.objects.filter(source=userdetails,category="BT").order_by('-date')
#print(bthist)
return render(request,"reseller/vcloud/balanceTransfer.html",{'bthist':bthist,'user':userdetails})
else:
return redirect(LoginPage)
def resellervcloudSubmitBalanceTransfer(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
userdet = UserData.objects.get(username=user)
bal = userdet.balance
newbal=bal+Decimal(amount)
cdbal = userdet.targetAmt
newcdbal = cdbal-Decimal(amount)
userdet.targetAmt = newcdbal
userdet.balance = newbal
userdet.save()
userdetails = UserData.objects.get(username=request.session["user"])
btreport = balanceTransactionReport()
btreport.source = userdetails
btreport.destination = userdet
btreport.category = "BT"
btreport.amount = amount
btreport.pbalance = bal
btreport.nbalance = newbal
btreport.cramount = newcdbal
btreport.remarks = 'Added To Balance'
btreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(resellervcloudbalanceTransfer)
#userdata=UserData.objects.get(username=)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(resellervcloudbalanceTransfer)
else:
return redirect(LoginPage)
def resellervcloudaddPayment(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
phist=fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"reseller/vcloud/addPayment.html",{'phist':phist,'user':userdetails})
else:
return redirect(LoginPage)
def resellervcloudsubmitPayment(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
remarks = request.POST.get('remarks', None)
userdet = UserData.objects.get(username=user)
obalance = userdet.targetAmt
cdbal = userdet.targetAmt
newcdbal = cdbal+Decimal(amount)
userdet.targetAmt = newcdbal
userdet.save()
closeuser = UserData.objects.get(username=user)
userdetails = UserData.objects.get(username=request.session["user"])
ftreport=fundTransactionReport()
ftreport.source = userdetails
ftreport.destination = userdet
ftreport.obalance = obalance
ftreport.cbalance = closeuser.targetAmt
ftreport.role = userType
ftreport.amount = amount
ftreport.balance = newcdbal
ftreport.remarks = remarks
ftreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(resellervcloudaddPayment)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(resellervcloudaddPayment)
else:
return redirect(LoginPage)
def resellervcloudbalanceTransferReport(request):
if request.session.has_key("user"):
username = request.session["user"]
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
fromsum = balanceTransactionReport.objects.filter(source=userdetails,category='BT').aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(destination=userdetails,category='BT').aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(source=userdetails) | balanceTransactionReport.objects.filter(destination=userdetails).order_by('-date')
return render(request,"reseller/vcloud/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filterresellervcloudbtreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
#fuser=UserData.objects.get(username=susername)
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
fromsum=None
tosum=None
bthist=None
try:
if(usertype == "Self"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
elif(usertype == "All" and susername == "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(usertype!="All" and susername == "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__postId=usertype).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__postId=usertype)
else:
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"reseller/vcloud/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(resellervcloudbalanceTransferReport)
else:
return redirect(resellervcloudbalanceTransferReport)
else:
return redirect(LoginPage)
def resellervcloudpaymentReport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=request.session["user"],postId="Sub_Reseller")
phist = fundTransactionReport.objects.filter(source=userdetails).order_by('-date') | fundTransactionReport.objects.filter(destination=userdetails).order_by('-date')
bsum = fundTransactionReport.objects.filter(source=userdetails).aggregate(Sum('amount'))
return render(request,"reseller/vcloud/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filterresellervcloudpaymentreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
print(usertype)
bsum=None
phist=None
try:
if(usertype == "Self" ):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
elif(usertype == "All" and susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
print(phist)
print("phist")
elif(usertype!="All" and susername == "All"):
print(usertype)
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype)
print("Haiii")
else:
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except Exception as e:
print(e)
pass
return render(request,"reseller/vcloud/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(resellervcloudpaymentReport)
else:
return redirect(resellervcloudpaymentReport)
else:
return redirect(LoginPage)
def resellervcloudreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser2__username=username).order_by('-date')
#vcloudtxns = vcloudtransactions.objects.all().order_by('-date')
reseller=UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
cost=0
for i in vcloudtxns:
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin2*i.quantity)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"reseller/vcloud/vcloudreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filterresellervcloud_report(request):
if request.session.has_key("user"):
if request.method=="POST":
form = vcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
fusername=form.cleaned_data.get("username")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
fuser=''
if(fusername!='All'):
filterdata=UserData.objects.get(username=fusername)
fuser=filterdata.name
else:
fuser=fusername
filter={'ffdate':fromdate,'ttdate':todate,'fuser':fuser}
reseller=UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
print(usertype)
fusername=form.cleaned_data.get("username")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
userdetails = UserData.objects.get(username=request.session["user"])
fuser=''
if(fusername!='All'):
filterdata=UserData.objects.get(username=fusername)
fuser=filterdata.name
else:
fuser=fusername
filter={'ffdate':fromdate,'ttdate':todate,'fuser':fuser}
reseller=UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords = 0
productsum = 0
quantitysum = 0
profitsum = 0
vcloudtxns=vcloudtransactions()
try:
print(usertype)
print(fusername)
print(type)
print(brand)
if(usertype=="All" and fusername=="All" and type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username).order_by('-date')
print("One")
elif(usertype=="All" and fusername=="All" and type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, type=type).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand !="All"):
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername!="All" and type !="All" and brand !="All"):
print('five')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, type=type, sponser2__username=username, sponser3__username=fusername, brand=brand).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand !="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__postId=usertype, sponser2__username=username).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__postId=usertype).order_by('-date')
elif(usertype =="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__username=fusername).order_by('-date')
elif(usertype !="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__username=fusername).order_by('-date')
else:
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__username=fusername,brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin2*i.quantity)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"reseller/vcloud/vcloudreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(resellervcloudreport)
else:
return redirect(resellervcloudreport)
else:
return redirect(LoginPage)
def resellervcloudStore(request):
if request.session.has_key("user"):
username=request.session["user"]
ads = adverisements.objects.filter(adtype="Image",usertype="Reseller",ctype="Vcloud").order_by('-id')[:10]
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card with cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
#print(pdcts)
data=dict()
content = []
for i in pdcts:
#print(i['brand__id'])
lpd=vcloudProducts.objects.filter(brand__id=i['brand__id'],status = True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
count=0
if not lpd:
pass
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
#print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
#print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
#print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
#print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand_id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'productcount':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'brand__denomination':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
buttonlist=["Cutting","Non Cutting"]
buttonclass=["btn-warning","btn-success"]
btnlist = zip(buttonlist, buttonclass)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/vcloud/vcloudStore.html",{'pdcts':content,'btnlist':btnlist,'user':userdetails,'ads':ads})
else:
return redirect(LoginPage)
def resellerfilteredvcloudstore(request,brandtype):
if request.session.has_key("user"):
username=request.session["user"]
buttonclass=[]
ads = adverisements.objects.filter(adtype="Image",usertype="Reseller",ctype="Vcloud").order_by('-id')[:10]
if(brandtype=="Cutting"):
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card with cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
data=dict()
content = []
for i in pdcts:
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
#print(lpd)
#print(productcost)
count=0
if not lpd:
#break;
pass;
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
#print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
#print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
#print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand_id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'productcount':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'brand__denomination':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
#print(content)
buttonclass=["btn-warning","btn-success"]
else:
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card without cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
data=dict()
content = []
for i in pdcts:
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
#print(lpd)
#print(productcost)
count=0
if not lpd:
#break;
#print("Haiii")
pass
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
#print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
#print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
#print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand_id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'productcount':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'brand__denomination':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
#print(content)
buttonclass=["btn-success","btn-warning"]
buttonlist=["Cutting","Non Cutting"]
btnlist = zip(buttonlist, buttonclass)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/vcloud/vcloudStore.html",{'pdcts':content,'btnlist':btnlist,'user':userdetails,'ads':ads})
else:
return redirect(LoginPage)
def resellersaveassignVcloudBrands(request):
if request.session.has_key("user"):
if request.method == "POST":
try:
reseller = request.POST.get('username', None)
values = request.POST.get('values', None)
states = request.POST.get('states', None)
brands = request.POST.get('brands', None)
margins = request.POST.get('margins', None)
v = values.split(',')
s = states.split(',')
b = brands.split(',')
m = margins.split(',')
username = request.session["user"]
assignedby = UserData.objects.get(username=username)
assignedto = UserData.objects.get(username=reseller)
for i in range(0,len(s)):
if(int(s[i])==0):
print(True)
brandid=b[int(i)]
brdet=vcloudBrands.objects.get(id=brandid)
print(brdet)
try:
vdt = vcloudAssignments.objects.get(brand=brdet,assignedby=assignedby,assignedto=assignedto)
vdt.delete()
vadt = vcloudAssignments.objects.filter(brand=brdet,assignedby=assignedto)
print(vadt)
for i in vadt:
try:
ud = vcloudAssignments.objects.filter(brand=brdet,assignedby=i.assignedto)
ud.delete()
except Exception as e:
print("inner "+str(e))
vadt.delete()
except vcloudAssignments.DoesNotExist:
print("Error")
else:
print(False)
brandid=b[int(i)]
brdet=vcloudBrands.objects.get(id=brandid)
try:
assdet = vcloudAssignments.objects.get(brand=brdet,assignedby=assignedby,assignedto=assignedto)
assdet.margin = Decimal(v[int(i)])
assdet.save()
except vcloudAssignments.DoesNotExist:
vass = vcloudAssignments()
vass.brand=brdet
vass.assignedto=assignedto
vass.assignedby=assignedby
vass.margin = Decimal(v[int(i)])
vass.save()
data={"status":"Success"}
return JsonResponse(data)
except:
return JsonResponse({"status":"Error"})
else:
pass
else:
return redirect(LoginPage)
def getvcloudproductcost(brand,username):
print(brand)
prdcts=vcloudBrands.objects.get(brand=brand)
prdctcost = Decimal(prdcts.denomination)
print(prdcts)
margins=0
while(True):
userdet = UserData.objects.filter(username=username).values('sponserId','postId')
pdct = vcloudAssignments.objects.filter(assignedto=username, brand__brand=brand).values('margin')
if(pdct):
if(userdet[0]['postId']=="Admin"):
break
else:
prdctcost = prdctcost+Decimal(pdct[0]['margin'])
username=userdet[0]['sponserId']
else:
break;
return prdctcost
def resellerassignVcloudBrands(request):
if request.session.has_key("user"):
print("Haiii")
brands = vcloudAssignments.objects.filter(assignedto=request.session["user"]).values('brand','brand__brand')
print(brands)
username=request.session["user"]
costlist=list()
brandlist=list()
for j in brands:
prdcts=vcloudBrands.objects.get(brand=j['brand__brand'])
print(prdcts.brand)
print(prdcts.logo.url)
if(prdcts):
print("Haiiii")
cost=subgetvcloudproductcost(j['brand__brand'],username)
data={'brand':prdcts.id,'brand__brand':prdcts.brand,'brand__id':prdcts.id,'brand__denomination':prdcts.denomination,'brand__logo':prdcts.logo.url,'barnd__description':prdcts.description,'brand__currency':prdcts.currency,'brand__category':prdcts.category,'cost':cost}
print(data)
brandlist.append(data)
resellers = UserData.objects.filter(postId="Sub_Reseller",sponserId=request.session["user"])
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/vcloud/assignVcloudBrands.html",{'brands':brands,'products':brandlist,'resellers':resellers,'user':userdetails})
#return render(request,"reseller/vcloud/assignVcloudBrands.html",{'brands':brands,'products':list(db),'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def resellerviewbrands(request):
if request.session.has_key("user"):
username = request.session["user"]
vcdprod=vcloudBrands.objects.all()
resultlist=list()
statuslist=list()
for i in vcdprod:
vca=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i.brand)
if not vca:
statuslist.append(False)
else:
statuslist.append(True)
vcd=list(vcdprod)
print(vcd)
print(statuslist)
#print(data)
ldb=zip(vcd,statuslist)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/vcloud/viewBrands.html",{'pdcts':list(ldb),'user':userdetails})
else:
return redirect(LoginPage)
def buy_vcloud_brands(request):
if request.session.has_key("user"):
if request.method == "POST":
username=request.session["user"]
brand = request.POST.get('brandid', None)
quantity = request.POST.get('quantity', None)
amt = request.POST.get('amt', None)
branddet=vcloudBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=request.session["user"])
#checkqty = vcloudProducts.objects.filter(brand__brand=brand, status=True).exclude(productstatus=1).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('productcount')
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=vcloudProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
content=dict()
licheckqty=list(checkqty)
brand_id=0
deno=0
if(licheckqty[0]['productcount'] >= int(quantity)):
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = vcloudProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
#print(prdctcost)
#print(cost)
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
print(flag)
break;
username=userdet2[0]['sponserId']
if(flag):
try:
prdctcddet=vcloudProducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
#print(h.username)
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'brand':h.brand.brand,'brand_logo':h.brand.logo.url,'password':h.password,'status':h.status,'suser':username,'sdate':h.sdate}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Vcloud"
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.quantity = quantity
vcrep.amount = amt
vcrep.rtype = "Web"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
print(ms)
print(admin)
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
obj = vcloudtransactions.objects.latest('id')
print(obj.id)
content["data"] = result
content["res_status"]="success"
content["trid"]=obj.id
except:
content["res_status"]="Failed"
else:
for i in prdctdet:
i.suser=None
i.save()
content["res_status"]="Failed"
return JsonResponse(content,safe=False)
else:
return redirect(resellervcloudStore)
else:
return redirect(LoginPage)
def printLayout(request):
return render(request,"reseller/printLayout.html")
def downloadvcloudresellercards(request,trid):
print(trid)
trdet=vcloudtransactions.objects.get(id=trid)
print(trdet)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
type=trdet.type
productid=trdet.product_id
result = productid.rstrip(',')
pdid = result.split(',')
for i in pdid:
pddet=vcloudProducts.objects.get(id=i)
imagelogo=pddet.brand.logo.url
str=imagelogo.replace("%20", " ")
print(str)
logo = str.lstrip('/')
print(image)
print(logo)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
draw.text((100, 290),"Password : "+pddet.password,(0,0,0),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
return redirect(resellervcloudStore)
def downloaddcardresellercards(request,trid):
print(trid)
trdet=vcloudtransactions.objects.get(id=trid)
print(trdet)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
type=trdet.type
productid=trdet.product_id
result = productid.rstrip(',')
pdid = result.split(',')
for i in pdid:
pddet=datacardproducts.objects.get(id=i)
print(image)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
return redirect(resellerdcardstore)
def downloaddcardsubresellercards(request,trid):
print(trid)
trdet=vcloudtransactions.objects.get(id=trid)
print(trdet)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
type=trdet.type
productid=trdet.product_id
result = productid.rstrip(',')
pdid = result.split(',')
for i in pdid:
pddet=datacardproducts.objects.get(id=i)
print(image)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
return redirect(subresellerdcardstore)
def downloaddcardusercards(request,trid):
print(trid)
trdet=vcloudtransactions.objects.get(id=trid)
print(trdet)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
type=trdet.type
productid=trdet.product_id
result = productid.rstrip(',')
pdid = result.split(',')
for i in pdid:
pddet=datacardproducts.objects.get(id=i)
print(image)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
return redirect(userdcardstore)
def downloadvcloudsubresellercards(request,trid):
print(trid)
trdet=vcloudtransactions.objects.get(id=trid)
print(trdet)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
type=trdet.type
productid=trdet.product_id
result = productid.rstrip(',')
pdid = result.split(',')
for i in pdid:
pddet=vcloudProducts.objects.get(id=i)
imagelogo=pddet.brand.logo.url
str=imagelogo.replace("%20", " ")
print(str)
logo = str.lstrip('/')
print(image)
print(logo)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
draw.text((100, 290),"Password : "+pddet.password,(0,0,0),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
return redirect(subresellervcloudStore)
def downloadvcloudusercards(request,trid):
print(trid)
trdet=vcloudtransactions.objects.get(id=trid)
print(trdet)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
type=trdet.type
productid=trdet.product_id
result = productid.rstrip(',')
pdid = result.split(',')
for i in pdid:
pddet=vcloudProducts.objects.get(id=i)
imagelogo=pddet.brand.logo.url
str=imagelogo.replace("%20", " ")
print(str)
logo = str.lstrip('/')
print(image)
print(logo)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
draw.text((100, 290),"Password : "+pddet.password,(0,0,0),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
return redirect(uservcloudStore)
def downloadrcardresellercards(request,trid):
print(trid)
trdet=vcloudtransactions.objects.get(id=trid)
print(trdet)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
type=trdet.type
productid=trdet.product_id
result = productid.rstrip(',')
pdid = result.split(',')
for i in pdid:
pddet=rcardProducts.objects.get(id=i)
print(image)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
return redirect(resellerrcardstore)
def downloadrcardsubresellercards(request,trid):
print(trid)
trdet=vcloudtransactions.objects.get(id=trid)
print(trdet)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
type=trdet.type
productid=trdet.product_id
result = productid.rstrip(',')
pdid = result.split(',')
for i in pdid:
pddet=rcardProducts.objects.get(id=i)
print(image)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
return redirect(subresellerrcardstore)
def downloadrcardusercards(request,trid):
print(trid)
trdet=vcloudtransactions.objects.get(id=trid)
print(trdet)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
type=trdet.type
productid=trdet.product_id
result = productid.rstrip(',')
pdid = result.split(',')
for i in pdid:
pddet=rcardProducts.objects.get(id=i)
print(image)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
return redirect(userrcardstore)
#________________DCARD_______________
def resellerDcardDashboard(request):
if request.session.has_key("user"):
last_month = datetime.today() - timedelta(days=1)
username = request.session["user"]
#print(last_month)
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
username = request.session["user"]
type = request.session["usertype"]
try:
user = UserData.objects.get(username = username, postId = type)
except UserData.DoesNotExist:
return redirect(LoginPage)
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser2__username=username,type="Dcard").order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin2*i.quantity
data3={'user':i.sponser3.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = datacardAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
for i in brand:
pd=datacardproducts.objects.filter(brand=i['brand__id'], status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass;
#break;
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=datacardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"reseller/dcard/dashboard-dcard.html",{'filterform':dcardDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':user,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filterresellerDcardDashboard(request):
if request.session.has_key("user"):
if request.method == "POST":
form = dcardDashboardfilter(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
uuusername=form.cleaned_data.get("username")
#mffromdate=datetime.strptime(fromdate, '%b %d %Y %I:%M%p')
#print(type(fromdate))
#print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
reseller = UserData.objects.filter(sponserId=currentuser,postId="Sub_Reseller")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(username)
userdetails = UserData.objects.get(username=request.session["user"])
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,sponser2__username=currentuser,type="Dcard",sponser3__username=uuusername).order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin2*i.quantity
data3={'user':i.sponser3.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = datacardAssignments.objects.filter(assignedto=currentuser).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=datacardproducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=datacardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"reseller/dcard/dashboard-dcard.html",{'filterform':vcloudDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':userdetails,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(resellerDcardDashboard)
else:
return(resellerDcardDashboard)
else:
return redirect(LoginPage)
def resellerprofiledcard(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"reseller/dcard/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def reselleraddResellerDcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/dcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def reselleraddUserDcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/dcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def resellerviewResellerDcard(request):
if request.session.has_key("user"):
resellers = UserData.objects.filter(sponserId=request.session["user"],postId="Sub_Reseller")
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/dcard/viewResellers.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def resellerviewUserDcard(request):
if request.session.has_key("user"):
user = request.session["user"]
resellers = UserData.objects.filter(postId="User",sponserId=user)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/dcard/viewUser.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def resellerbalanceTransferDcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
bthist=balanceTransactionReport.objects.filter(source=userdetails,category="BT").order_by('-date')
#print(bthist)
return render(request,"reseller/dcard/balanceTransfer.html",{'bthist':bthist,'user':userdetails})
else:
return redirect(LoginPage)
def reselleraddPaymentDcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
phist=fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"reseller/dcard/addPayment.html",{'phist':phist})
else:
return redirect(LoginPage)
def resellerdatacardreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser2__username=username).order_by('-date')
#vcloudtxns = vcloudtransactions.objects.all().order_by('-date')
reseller=UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
cost=0
for i in vcloudtxns:
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin2*i.quantity)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"reseller/dcard/dcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filterresellerdcard_report(request):
if request.session.has_key("user"):
if request.method=="POST":
form = vcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
fusername=form.cleaned_data.get("username")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
fuser=''
if(fusername!='All'):
filterdata=UserData.objects.get(username=fusername)
fuser=filterdata.name
else:
fuser=fusername
filter={'ffdate':fromdate,'ttdate':todate,'fuser':fuser}
#print(brand,fusername)
reseller=UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
resellerlist=list()
userdetails = UserData.objects.get(username=request.session["user"])
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords = 0
productsum = 0
quantitysum = 0
profitsum = 0
vcloudtxns=vcloudtransactions()
try:
print(usertype)
print(fusername)
print(type)
print(brand)
if(usertype=="All" and fusername=="All" and type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username).order_by('-date')
print("One")
elif(usertype=="All" and fusername=="All" and type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, type=type).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand !="All"):
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername!="All" and type !="All" and brand !="All"):
print('five')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, type=type, sponser2__username=username, sponser3__username=fusername, brand=brand).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand !="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__postId=usertype, sponser2__username=username).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__postId=usertype).order_by('-date')
elif(usertype =="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__username=fusername).order_by('-date')
elif(usertype !="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__username=fusername).order_by('-date')
else:
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__username=fusername,brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin2*i.quantity)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"reseller/dcard/dcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(resellerdatacardreport)
else:
return redirect(resellerdatacardreport)
else:
return redirect(LoginPage)
def resellerbTReportDcard(request):
if request.session.has_key("user"):
username = request.session["user"]
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
fromsum = balanceTransactionReport.objects.filter(source=userdetails,category='BT').aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(destination=userdetails,category='BT').aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(source=userdetails).order_by("-date") | balanceTransactionReport.objects.filter(destination=userdetails).order_by("-date")
return render(request,"reseller/dcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filterresellerdcardbtreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username=request.session["user"]
#fuser=UserData.objects.get(username=susername)
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
fromsum=None
tosum=None
bthist=None
try:
if(usertype == "Self"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
elif(usertype == "All" and susername == "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(usertype!="All" and susername == "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__postId=usertype).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__postId=usertype)
else:
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"reseller/dcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(resellerbTReportDcard)
else:
return redirect(resellerbTReportDcard)
else:
return redirect(LoginPage)
def resellerpaymentReportDcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=request.session["user"],postId="Sub_Reseller")
phist = fundTransactionReport.objects.filter(source=userdetails).order_by('-date')|fundTransactionReport.objects.filter(destination=userdetails).order_by('-date')
bsum = fundTransactionReport.objects.filter(source=userdetails).aggregate(Sum('amount'))
return render(request,"reseller/dcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filterresellerdcardpaymentreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
bsum=None
phist=None
try:
if(usertype == "Self" ):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
elif(usertype == "All" and susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
#print(phist)
#print("phist")
elif(usertype!="All" and susername == "All"):
#print(usertype)
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype)
#print("Haiii")
else:
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except Exception as e:
print(e)
pass
return render(request,"reseller/dcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(resellerpaymentReportDcard)
else:
return redirect(resellerpaymentReportDcard)
else:
return redirect(LoginPage)
def resellerassignDCardBrands(request):
if request.session.has_key("user"):
brands = datacardAssignments.objects.filter(assignedto=request.session["user"]).values('brand','brand__brand','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
username = request.session["user"]
bd=list(brands)
prdcts=list()
costs=list()
for i in brands:
prd=dcardBrands.objects.get(brand=i['brand__brand'])
#prd=datacardproducts.objects.filter(brand__brand=i['brand__brand'], status=True).order_by('brand').values('brand').annotate(productcount=Count('brand')).values('brand','brand__brand','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
#print(prd)
if(prd):
cost=getDatacardProductCost(username,i["brand__brand"])
data={'brand__brand':prd.brand,'brand__logo':prd.logo.url,'brand__id':prd.id,'cost':cost,'brand__currency':prd.currency,'brand__description':prd.description}
prdcts.append(data)
else:
pass;
#print(pddata[0])
resellers = UserData.objects.filter(postId="Sub_Reseller",sponserId=request.session["user"])
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/dcard/assignDcardbrand.html",{'brands':bd,'products':prdcts,'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def resellerdcardstore(request):
if request.session.has_key("user"):
username=request.session["user"]
user = UserData.objects.get(username=username)
ads = adverisements.objects.filter(adtype="Image",usertype="Reseller",ctype="Dcard").order_by('-id')[:10]
btnlist=list()
dproducts = datacardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
content=list()
if(len(btnlist)!=0):
dcardproducts = datacardAssignments.objects.filter(assignedto=username,brand__brand__contains=btnlist[0]).order_by('brand').values('brand__brand','margin')
for i in dcardproducts:
dcp=datacardproducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getDatacardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
else:
pass
else:
pass
print(content)
return render(request,"reseller/dcard/datastore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def getDatacardProductCost(username,brand):
prdcts=dcardBrands.objects.get(brand=brand)
prdctcost=0
if(prdcts):
prdctcost = Decimal(prdcts.denomination)
margins=0
while(True):
userdet = UserData.objects.filter(username=username).values('sponserId','postId')
pdct = datacardAssignments.objects.filter(assignedto=username, brand__brand=brand).values('margin')
if(pdct):
if(userdet[0]['postId']=="Admin"):
break;
else:
prdctcost = prdctcost+Decimal(pdct[0]['margin'])
username=userdet[0]['sponserId']
else:
break;
return prdctcost
def getRcardProductCost(username,brand):
prdcts=rcardBrands.objects.get(brand=brand)
prdctcost=0
prdctcost = Decimal(prdcts.denomination)
margins=0
while(True):
userdet = UserData.objects.filter(username=username).values('sponserId','postId')
pdct = rcardAssignments.objects.filter(assignedto=username, brand__brand=brand).values('margin')
if(userdet[0]['postId']=="Admin"):
break;
else:
prdctcost = prdctcost+Decimal(pdct[0]['margin'])
username=userdet[0]['sponserId']
print(prdctcost)
return prdctcost
def viewfiltereddatastore(brand):
brands=datacardproducts.objects.filter(brand__brand__contains=brand,status=True).order_by('brand').values('brand').annotate(productcount=Count('brand')).values('productcount','brand__brand','brand__id','brand__description','brand__denomination','brand__logo','brand__currency')
return brands
def resellerfilterdcardstore(request,brand):
if request.session.has_key("user"):
#print(brand)
username=request.session["user"]
user = UserData.objects.get(username=username)
btnlist=list()
ads = adverisements.objects.filter(adtype="Image",usertype="Reseller",ctype="Dcard").order_by('-id')[:10]
dproducts = datacardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
dcardproducts = datacardAssignments.objects.filter(assignedto=username,brand__brand__contains=brand).order_by('brand').values('brand__brand','margin')
content=list()
#print(buttons)
for i in dcardproducts:
dcp=datacardproducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if not dcp:
pass
else:
cost=getDatacardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
print(content)
return render(request,"reseller/dcard/datastore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def editresellerProfileDcard(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(resellerprofiledcard)
else:
messages.warning(request,'Internal Error Occured')
return redirect(resellerprofiledcard)
else:
return redirect(LoginPage)
def resellerdcardsubmitReseller(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
print(username)
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="Sub_Reseller"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request,'Successfully Added')
return redirect(reselleraddResellerDcard)
else:
userdetails = UserData.objects.get(username=request.session["user"])
messages.warning(request, 'Internal Error Occured')
form = AddUserDataForm()
return render(request,"reseller/dcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"reseller/dcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def resellersubmitUser(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="User"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(reselleraddUserDcard)
else:
userdetails = UserData.objects.get(username=request.session["user"])
messages.warning(request, 'Internal Error Occured')
form = AddUserDataForm()
return render(request,"reseller/dcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"reseller/dcard/addUser.html",{'form':AddUserDataForm,'user':username})
else:
return redirect(LoginPage)
def resellersubBalTransDcard(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
userdet = UserData.objects.get(username=user)
bal = userdet.balance
newbal=bal+Decimal(amount)
cdbal = userdet.targetAmt
newcdbal = cdbal-Decimal(amount)
userdet.targetAmt = newcdbal
userdet.balance = newbal
userdet.save()
userdetails = UserData.objects.get(username=request.session["user"])
btreport = balanceTransactionReport()
btreport.source = userdetails
btreport.destination = userdet
btreport.category = "BT"
btreport.pbalance = bal
btreport.nbalance = newbal
btreport.cramount = newcdbal
btreport.amount = amount
btreport.remarks = 'Added To Balance'
btreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(resellerbalanceTransferDcard)
#userdata=UserData.objects.get(username=)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(resellerbalanceTransferDcard)
else:
return redirect(LoginPage)
def resellersubPayTrans(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
remarks = request.POST.get('remarks', None)
userdet = UserData.objects.get(username=user)
obalance = userdet.targetAmt
cdbal = userdet.targetAmt
newcdbal = cdbal+Decimal(amount)
userdet.targetAmt = newcdbal
userdet.save()
closeuser = UserData.objects.get(username=user)
userdetails = UserData.objects.get(username=request.session["user"])
ftreport=fundTransactionReport()
ftreport.source = userdetails
ftreport.destination = userdet
ftreport.obalance = obalance
ftreport.cbalance = closeuser.targetAmt
ftreport.role = userType
ftreport.amount = amount
ftreport.balance = newcdbal
ftreport.remarks = remarks
ftreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(resellervcloudaddPayment)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(resellervcloudaddPayment)
else:
return redirect(LoginPage)
def resellerdcardsubPayTrans(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
remarks = request.POST.get('remarks', None)
userdet = UserData.objects.get(username=user)
obalance = userdet.targetAmt
cdbal = userdet.targetAmt
newcdbal = cdbal+Decimal(amount)
userdet.targetAmt = newcdbal
userdet.save()
closeuser = UserData.objects.get(username=user)
userdetails = UserData.objects.get(username=request.session["user"])
ftreport=fundTransactionReport()
ftreport.source = userdetails
ftreport.destination = userdet
ftreport.obalance = obalance
ftreport.cbalance = closeuser.targetAmt
ftreport.role = userType
ftreport.amount = amount
ftreport.balance = newcdbal
ftreport.remarks = remarks
ftreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(reselleraddPaymentDcard)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(reselleraddPaymentDcard)
else:
return redirect(LoginPage)
def buy_datacard_brands(request):
if request.session.has_key("user"):
if request.method == "POST":
username=request.session["user"]
brand = request.POST.get('brandid', None)
quantity = request.POST.get('quantity', None)
amt = request.POST.get('amt', None)
branddet=dcardBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=request.session["user"])
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=datacardproducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
content=dict()
licheckqty=list(checkqty)
brand_id=0
deno=0
if(licheckqty[0]['productcount'] >= int(quantity)):
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = datacardproducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=datacardAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
#print(prdctcost)
#print(cost)
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
print(flag)
break;
username=userdet2[0]['sponserId']
if(flag):
try:
prdctcddet=datacardproducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'brand':h.brand.brand,'brand_logo':h.brand.logo.url, 'status':h.status,'suser':username,'sdate':h.sdate}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Dcard"
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.quantity = quantity
vcrep.amount = amt
vcrep.rtype = "Web"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
obj = vcloudtransactions.objects.latest('id')
print(obj.id)
content["data"] = result
content["res_status"]="success"
content["trid"]=obj.id
except:
content["res_status"]="Failed"
else:
for i in prdctdet:
i.suser=None
i.save()
content["res_status"]="Failed"
return JsonResponse(content,safe=False)
else:
return redirect(resellerdcardstore)
else:
return redirect(LoginPage)
def resellerdcardviewbrands(request):
if request.session.has_key("user"):
if request.session.has_key("user"):
username = request.session["user"]
vcdprod=dcardBrands.objects.all()
resultlist=list()
statuslist=list()
for i in vcdprod:
vca=datacardAssignments.objects.filter(assignedto=username,brand__brand=i.brand)
if not vca:
statuslist.append(False)
else:
statuslist.append(True)
vcd=list(vcdprod)
print(vcd)
print(statuslist)
#print(data)
ldb=zip(vcd,statuslist)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/dcard/viewBrands.html",{'pdcts':list(ldb),'user':userdetails})
else:
return redirect(LoginPage)
#________________RCARD_______________
def resellerRcardDashboard(request):
if request.session.has_key("user"):
last_month = datetime.today() - timedelta(days=1)
username = request.session["user"]
#print(last_month)
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
username = request.session["user"]
type = request.session["usertype"]
try:
user = UserData.objects.get(username = username, postId = type)
except UserData.DoesNotExist:
return redirect(LoginPage)
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser2__username=username,type="Rcard").order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin2*i.quantity
data3={'user':i.sponser3.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = rcardAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=rcardProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=rcardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"reseller/rcard/dashboard-rcard.html",{'filterform':rcardDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':user,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filterresellerrcardhomepage(request):
if request.session.has_key("user"):
if request.method == "POST":
form = rcardDashboardfilter(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
uuusername=form.cleaned_data.get("username")
#mffromdate=datetime.strptime(fromdate, '%b %d %Y %I:%M%p')
#print(type(fromdate))g
print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
reseller = UserData.objects.filter(sponserId=currentuser,postId="Sub_Reseller")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(username)
userdetails = UserData.objects.get(username=request.session["user"])
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,sponser2__username=currentuser,type="Rcard",sponser3__username=uuusername).order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin2*i.quantity
data3={'user':i.sponser3.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = rcardAssignments.objects.filter(assignedto=currentuser).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=rcardProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=rcardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"reseller/rcard/dashboard-rcard.html",{'filterform':rcardDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':userdetails,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(resellerRcardDashboard)
else:
return(resellerRcardDashboard)
else:
return redirect(LoginPage)
def resellerprofilercard(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"reseller/rcard/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def reselleraddResellerRcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/rcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def reselleraddUserRcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/rcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def resellerviewResellerRcard(request):
if request.session.has_key("user"):
resellers = UserData.objects.filter(sponserId=request.session["user"],postId="Sub_Reseller")
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/rcard/viewResellers.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def resellerviewUserRcard(request):
if request.session.has_key("user"):
user = request.session["user"]
resellers = UserData.objects.filter(postId="User",sponserId=user)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/rcard/viewUser.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def resellerbalanceTransferRcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
bthist=balanceTransactionReport.objects.filter(source=userdetails,category="BT").order_by('-date')
#print(bthist)
return render(request,"reseller/rcard/balanceTransfer.html",{'bthist':bthist,'user':userdetails})
else:
return redirect(LoginPage)
def reselleraddPaymentRcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
phist=fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"reseller/rcard/addPayment.html",{'phist':phist})
else:
return redirect(LoginPage)
def resellerrcardreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser2__username=username).order_by('-date')
#vcloudtxns = vcloudtransactions.objects.all().order_by('-date')
reseller=UserData.objects.filter(sponserId=username,postId="Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
cost=0
for i in vcloudtxns:
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin2*i.quantity)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"reseller/rcard/rcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filterresellerrcard_report(request):
if request.session.has_key("user"):
if request.method=="POST":
form = vcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
fusername=form.cleaned_data.get("username")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
#print(brand,fusername)
fuser=''
if(fusername!='All'):
filterdata=UserData.objects.get(username=fusername)
fuser=filterdata.name
else:
fuser=fusername
filter={'ffdate':fromdate,'ttdate':todate,'fuser':fuser}
userdetails = UserData.objects.get(username=request.session["user"])
reseller=UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords = 0
productsum = 0
quantitysum = 0
profitsum = 0
vcloudtxns=vcloudtransactions()
try:
print(usertype)
print(fusername)
print(type)
print(brand)
if(usertype=="All" and fusername=="All" and type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username).order_by('-date')
print("One")
elif(usertype=="All" and fusername=="All" and type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, type=type).order_by('-date')
elif(usertype=="All" and fusername=="All" and type !="All" and brand !="All"):
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, brand=brand).order_by('-date')
elif(usertype=="All" and fusername!="All" and type !="All" and brand !="All"):
print('five')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, type=type, sponser2__username=username, sponser3__username=fusername, brand=brand).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand !="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__postId=usertype, sponser2__username=username).order_by('-date')
elif(usertype !="All" and fusername =="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__postId=usertype).order_by('-date')
elif(usertype =="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__username=fusername).order_by('-date')
elif(usertype !="All" and fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__username=fusername).order_by('-date')
else:
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser2__username=username, sponser3__username=fusername,brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin2*i.quantity)
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"reseller/rcard/rcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(resellerrcardreport)
else:
return redirect(resellerrcardreport)
else:
return redirect(LoginPage)
def resellerbTReportRcard(request):
if request.session.has_key("user"):
username = request.session["user"]
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
fromsum = balanceTransactionReport.objects.filter(source=userdetails,category='BT').aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(destination=userdetails,category='BT').aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(source=userdetails).order_by('-date') | balanceTransactionReport.objects.filter(destination=userdetails).order_by('-date')
return render(request,"reseller/rcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filterresellerrcardbtreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
fromsum=None
tosum=None
bthist=None
try:
if(usertype == "Self"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
elif(usertype == "All" and susername == "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(usertype!="All" and susername == "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__postId=usertype).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__postId=usertype)
else:
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"reseller/dcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(resellerbTReportRcard)
else:
return redirect(resellerbTReportRcard)
else:
return redirect(LoginPage)
def resellerpaymentReportRcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=request.session["user"],postId="Sub_Reseller")
phist = fundTransactionReport.objects.filter(source=userdetails).order_by('-date')|fundTransactionReport.objects.filter(destination=userdetails).order_by('-date')
bsum = fundTransactionReport.objects.filter(source=userdetails).aggregate(Sum('amount'))
return render(request,"reseller/rcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filterresellerrcardpaymentreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
bsum=None
phist=None
try:
if(usertype == "Self" ):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
elif(usertype == "All" and susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
#print(phist)
#print("phist")
elif(usertype!="All" and susername == "All"):
#print(usertype)
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails, destination__postId=usertype)
#print("Haiii")
else:
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except Exception as e:
print(e)
pass
return render(request,"reseller/rcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(resellerpaymentReportRcard)
else:
return redirect(resellerpaymentReportRcard)
else:
return redirect(LoginPage)
def getReachargeProductCost(username,brand):
prdcts=rcardBrands.objects.get(brand=brand)
prdctcost=0
prdctcost = Decimal(prdcts.denomination)
margins=0
print("helloo")
while(True):
userdet = UserData.objects.filter(username=username).values('sponserId','postId')
pdct = rcardAssignments.objects.filter(assignedto=username, brand__brand=brand).values('margin')
if(pdct):
if(userdet[0]['postId']=="Admin"):
break;
else:
prdctcost = prdctcost+Decimal(pdct[0]['margin'])
username=userdet[0]['sponserId']
else:
break;
#print(prdctcost)
return prdctcost
def resellerassignRCardBrands(request):
if request.session.has_key("user"):
brands = rcardAssignments.objects.filter(assignedto=request.session["user"]).values('brand','brand__brand','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
username=request.session["user"]
bd=list(brands)
prdcts=list()
costs=list()
for i in brands:
prd=rcardBrands.objects.get(brand=i['brand__brand'])
#prd=rcardProducts.objects.filter(brand__brand=i['brand__brand'], status=True).order_by('brand').values('brand').annotate(productcount=Count('brand')).values('brand','brand__brand','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
if(prd):
cost=getReachargeProductCost(username,i["brand__brand"])
data={'brand__brand':prd.brand,'brand__logo':prd.logo.url,'brand__id':prd.id,'cost':cost,'brand__currency':prd.currency,'brand__description':prd.description}
prdcts.append(data)
else:
pass
#print(pddata[0])
resellers = UserData.objects.filter(postId="Sub_Reseller",sponserId=request.session["user"])
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/rcard/assignRcardbrand.html",{'brands':bd,'products':prdcts,'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def resellerrcardstore(request):
if request.session.has_key("user"):
username=request.session["user"]
user = UserData.objects.get(username=username)
ads = adverisements.objects.filter(adtype="Image",usertype="Reseller",ctype="Rcard").order_by('-id')[:10]
btnlist=list()
content=list()
dproducts = rcardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
if(len(btnlist)!=0):
dcardproducts = rcardAssignments.objects.filter(assignedto=username,brand__brand__contains=btnlist[0]).order_by('brand').values('brand__brand','margin')
for i in dcardproducts:
dcp=rcardProducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getRcardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
else:
pass
else:
pass
print(content)
return render(request,"reseller/rcard/rcardstore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def getVcloudCost(id,username):
prdctcost=0
prdcts=vcloudtransactions.objects.get(id=id)
prdctcost = Decimal(prdcts.denominations)
margins=0
if(prdcts.type == "Vcloud"):
while(True):
try:
userdet = UserData.objects.filter(username=username).values('sponserId','postId')
pdct = vcloudAssignments.objects.filter(assignedto=username, brand__brand=prdcts.brand).values('margin')
if(userdet[0]['postId']=="Admin"):
break;
else:
prdctcost = prdctcost+Decimal(pdct[0]['margin'])
username=userdet[0]['sponserId']
except:
pass
elif(prdcts.type == "Dcard"):
while(True):
try:
userdet = UserData.objects.filter(username=username).values('sponserId','postId')
pdct = datacardAssignments.objects.filter(assignedto=username, brand__brand=prdcts.brand).values('margin')
if(userdet[0]['postId']=="Admin"):
break;
else:
prdctcost = prdctcost+Decimal(pdct[0]['margin'])
username=userdet[0]['sponserId']
except:
pass
else:
while(True):
try:
userdet = UserData.objects.filter(username=username).values('sponserId','postId')
pdct = rcardAssignments.objects.filter(assignedto=username, brand__id=prdcts.brand_id).values('margin')
if(userdet[0]['postId']=="Admin"):
break;
else:
prdctcost = prdctcost+Decimal(pdct[0]['margin'])
username=userdet[0]['sponserId']
except:
pass
return prdctcost
def viewfilteredreachargestore(brand):
brands=rcardProducts.objects.filter(brand__brand__contains=brand,status=True).order_by('brand').values('brand').annotate(productcount=Count('brand')).values('productcount','brand__brand','brand__id','brand__description','brand__denomination','brand__logo','brand__currency')
return brands
def resellerfilterrcardstore(request,brand):
if request.session.has_key("user"):
#print(brand)
username=request.session["user"]
user = UserData.objects.get(username=username)
ads = adverisements.objects.filter(adtype="Image",usertype="Reseller",ctype="Rcard").order_by('-id')[:10]
btnlist=list()
dproducts = rcardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
dcardproducts = rcardAssignments.objects.filter(assignedto=username,brand__brand__contains=brand).order_by('brand').values('brand__brand','margin')
content=list()
#print(buttons)
for i in dcardproducts:
dcp=rcardProducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
buttons=(dcp[0]["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
cost=getRcardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
else:
pass;
print(content)
return render(request,"reseller/rcard/rcardstore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def editresellerProfileRcard(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(resellerprofilercard)
else:
messages.warning(request,'Internal Error Occured')
return redirect(resellerprofilercard)
else:
return redirect(LoginPage)
def resellerrcardsubmitReseller(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
print(username)
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="Sub_Reseller"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request,'Successfully Added')
return redirect(reselleraddResellerRcard)
else:
userdetails = UserData.objects.get(username=request.session["user"])
messages.warning(request, form.errors)
form = AddUserDataForm()
return render(request,"reseller/rcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"reseller/rcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def resellerrcardsubmitUser(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="User"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(reselleraddUserRcard)
else:
userdetails = UserData.objects.get(username=request.session["user"])
messages.warning(request, form.errors)
form = AddUserDataForm()
return render(request,"reseller/rcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"reseller/rcard/addUser.html",{'form':AddUserDataForm,'user':username})
else:
return redirect(LoginPage)
def resellersubBalTransRcard(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
userdet = UserData.objects.get(username=user)
bal = userdet.balance
newbal=bal+Decimal(amount)
cdbal = userdet.targetAmt
newcdbal = cdbal-Decimal(amount)
userdet.targetAmt = newcdbal
userdet.balance = newbal
userdet.save()
userdetails = UserData.objects.get(username=request.session["user"])
btreport = balanceTransactionReport()
btreport.source = userdetails
btreport.destination = userdet
btreport.category = "BT"
btreport.pbalance = bal
btreport.nbalance = newbal
btreport.cramount = newcdbal
btreport.amount = amount
btreport.remarks = 'Added To Balance'
btreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(resellerbalanceTransferRcard)
#userdata=UserData.objects.get(username=)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(resellerbalanceTransferRcard)
else:
return redirect(LoginPage)
def resellerrcardsubPayTrans(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
remarks = request.POST.get('remarks', None)
userdet = UserData.objects.get(username=user)
obalance = userdet.targetAmt
cdbal = userdet.targetAmt
newcdbal = cdbal+Decimal(amount)
userdet.targetAmt = newcdbal
userdet.save()
closeuser = UserData.objects.get(username=user)
userdetails = UserData.objects.get(username=request.session["user"])
ftreport=fundTransactionReport()
ftreport.source = userdetails
ftreport.destination = userdet
ftreport.obalance = obalance
ftreport.cbalance = closeuser.targetAmt
ftreport.role = userType
ftreport.amount = amount
ftreport.balance = newcdbal
ftreport.remarks = remarks
ftreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(reselleraddPaymentRcard)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(reselleraddPaymentRcard)
else:
return redirect(LoginPage)
def buy_rcard_brands(request):
if request.session.has_key("user"):
if request.method == "POST":
username=request.session["user"]
brand = request.POST.get('brandid', None)
quantity = request.POST.get('quantity', None)
amt = request.POST.get('amt', None)
branddet=rcardBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=request.session["user"])
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=rcardProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
content=dict()
licheckqty=list(checkqty)
brand_id=0
deno=0
if(licheckqty[0]['productcount'] >= int(quantity)):
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = rcardProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=rcardAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
#print(prdctcost)
#print(cost)
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
print(flag)
break;
username=userdet2[0]['sponserId']
if(flag):
try:
prdctcddet=rcardProducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'brand':h.brand.brand,'brand_logo':h.brand.logo.url, 'status':h.status,'suser':username,'sdate':h.sdate}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Rcard"
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.quantity = quantity
vcrep.amount = amt
vcrep.rtype = "Web"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
obj = vcloudtransactions.objects.latest('id')
print(obj.id)
content["data"] = result
content["res_status"]="success"
content["trid"]=obj.id
except:
content["res_status"]="Failed"
else:
for i in prdctdet:
i.suser=None
i.save()
content["res_status"]="Failed"
return JsonResponse(content,safe=False)
else:
return redirect(resellerrcardstore)
else:
return redirect(LoginPage)
def resellerrcardviewbrands(request):
if request.session.has_key("user"):
if request.session.has_key("user"):
username = request.session["user"]
vcdprod=rcardBrands.objects.all()
resultlist=list()
statuslist=list()
for i in vcdprod:
vca=rcardAssignments.objects.filter(assignedto=username,brand__brand=i.brand)
if not vca:
statuslist.append(False)
else:
statuslist.append(True)
vcd=list(vcdprod)
print(vcd)
print(statuslist)
#print(data)
ldb=zip(vcd,statuslist)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"reseller/rcard/viewBrands.html",{'pdcts':list(ldb),'user':userdetails})
else:
return redirect(LoginPage)
#________________________________________________________________Sub_Reseller_______________________________________________________________
#________________VCLOUD_______________
def subresellervcloudhomePage(request):
if request.session.has_key("user"):
last_month = datetime.today() - timedelta(days=1)
username = request.session["user"]
#print(last_month)
reseller = UserData.objects.filter(sponserId=username,postId="User")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
username = request.session["user"]
type = request.session["usertype"]
try:
user = UserData.objects.get(username = username, postId = type)
except UserData.DoesNotExist:
return redirect(LoginPage)
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser3__username=username,type="Vcloud").order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin3*i.quantity
data3={'user':i.sponser4.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = vcloudAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"sub_reseller/vcloud/dashboard-vcloud.html",{'filterform':vcloudDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':user,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filtersubresellervcloudhomepage(request):
if request.session.has_key("user"):
if request.method == "POST":
form = vcloudDashboardfilter(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
uuusername=form.cleaned_data.get("username")
#mffromdate=datetime.strptime(fromdate, '%b %d %Y %I:%M%p')
print(type(fromdate))
print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
reseller = UserData.objects.filter(sponserId=currentuser,postId="User")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(username)
userdetails = UserData.objects.get(username=request.session["user"])
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,sponser3__username=currentuser,type="Vcloud",sponser4__username=uuusername).order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin3*i.quantity
data3={'user':i.sponser4.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = vcloudAssignments.objects.filter(assignedto=currentuser).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"sub_reseller/vcloud/dashboard-vcloud.html",{'filterform':vcloudDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':userdetails,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(subresellervcloudhomePage)
else:
return(subresellervcloudhomePage)
else:
return redirect(LoginPage)
def subresellervcloudaddUser(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/vcloud/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def subresellervcloudnewUser(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
print(username)
print(password)
print(hash)
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="User"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(subresellervcloudaddUser)
else:
messages.warning(request, form.errors)
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"sub_reseller/vcloud/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"sub_reseller/vcloud/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def subresellervcloudviewUser(request):
if request.session.has_key("user"):
username = request.session["user"]
resellers = UserData.objects.filter(postId="User",sponserId=username)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/vcloud/viewUser.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def subresellervcloudprofile(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"sub_reseller/vcloud/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def subresellervcloudeditProfile(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(subresellervcloudprofile)
else:
messages.warning(request,'Internal Error Occured')
return redirect(subresellervcloudprofile)
else:
return redirect(LoginPage)
def subresellervcloudbalanceTransfer(request):
if request.session.has_key("user"):
username = request.session["user"]
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
fromsum = balanceTransactionReport.objects.filter(source=userdetails,category='BT').aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(destination=userdetails,category='BT').aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(source=userdetails).order_by('-date') | balanceTransactionReport.objects.filter(destination=userdetails).order_by('-date')
return render(request,"sub_reseller/vcloud/balanceTransfer.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filtersubresellervcloudbtreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="User")
fromsum=None
tosum=None
bthist=None
try:
if(susername == "Self"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
elif(susername == "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(susername != "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"sub_reseller/vcloud/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(subresellervcloudbalanceTransferReport)
else:
return redirect(subresellervcloudbalanceTransferReport)
else:
return redirect(LoginPage)
def subresellervcloudSubmitBalanceTransfer(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
userdet = UserData.objects.get(username=user)
bal = userdet.balance
newbal=bal+Decimal(amount)
cdbal = userdet.targetAmt
newcdbal = cdbal-Decimal(amount)
userdet.targetAmt = newcdbal
userdet.balance = newbal
userdet.save()
userdetails = UserData.objects.get(username=request.session["user"])
btreport = balanceTransactionReport()
btreport.source = userdetails
btreport.destination = userdet
btreport.category = "BT"
btreport.pbalance = bal
btreport.nbalance = newbal
btreport.cramount = newcdbal
btreport.amount = amount
btreport.remarks = 'Added To Balance'
btreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(subresellervcloudbalanceTransfer)
#userdata=UserData.objects.get(username=)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(subresellervcloudbalanceTransfer)
else:
return redirect(LoginPage)
def subresellervcloudaddPayment(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
phist=fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"sub_reseller/vcloud/addPayment.html",{'phist':phist,'user':userdetails})
else:
return redirect(LoginPage)
def subresellervcloudsubmitPayment(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
remarks = request.POST.get('remarks', None)
userdet = UserData.objects.get(username=user)
obalance = userdet.targetAmt
cdbal = userdet.targetAmt
newcdbal = cdbal+Decimal(amount)
userdet.targetAmt = newcdbal
userdet.save()
closeuser = UserData.objects.get(username=user)
userdetails = UserData.objects.get(username=request.session["user"])
ftreport=fundTransactionReport()
ftreport.source = userdetails
ftreport.destination = userdet
ftreport.role = userType
ftreport.obalance = obalance
ftreport.cbalance = closeuser.targetAmt
ftreport.amount = amount
ftreport.balance = newcdbal
ftreport.remarks = remarks
ftreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(subresellervcloudaddPayment)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(subresellervcloudaddPayment)
else:
return redirect(LoginPage)
def subresellervcloudbalanceTransferReport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=request.session["user"],postId="User")
fromsum = balanceTransactionReport.objects.filter(source=userdetails,category='BT').aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(destination=userdetails,category='BT').aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(source=userdetails).order_by('-date') | balanceTransactionReport.objects.filter(destination=userdetails).order_by('-date')
return render(request,"sub_reseller/vcloud/balanceTransferReport.html",{'form':balancetransferfilterform,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails,'reseller':reseller})
else:
return redirect(LoginPage)
def subresellervcloudpaymentReport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=request.session["user"],postId="User")
phist = fundTransactionReport.objects.filter(source=userdetails).order_by('-date')|fundTransactionReport.objects.filter(destination=userdetails).order_by('-date')
bsum = fundTransactionReport.objects.filter(source=userdetails).aggregate(Sum('amount'))
return render(request,"sub_reseller/vcloud/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filtersubresellervcloudpaymentreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="User")
bsum=None
phist=None
try:
if(susername=="Self"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
#print(phist)
elif(susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
print(phist)
elif(susername != "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except Exception as e:
print(e)
pass
return render(request,"sub_reseller/vcloud/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(subresellervcloudpaymentReport)
else:
return redirect(subresellervcloudpaymentReport)
else:
return redirect(LoginPage)
def subresellervcloudreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser3__username=username).order_by('-date')
#vcloudtxns = vcloudtransactions.objects.all().order_by('-date')
reseller=UserData.objects.filter(sponserId=username,postId="User")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
cost=0
for i in vcloudtxns:
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin3*i.quantity)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"sub_reseller/vcloud/vcloudreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filtersubresellervcloud_report(request):
if request.session.has_key("user"):
if request.method=="POST":
form = vcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
fusername=form.cleaned_data.get("username")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
#print(brand,fusername)
fuser=''
if(fusername!='All'):
filterdata=UserData.objects.get(username=fusername)
fuser=filterdata.name
else:
fuser=fusername
filter={'ffdate':fromdate,'ttdate':todate,'fuser':fuser}
userdetails = UserData.objects.get(username=request.session["user"])
reseller=UserData.objects.filter(sponserId=username,postId="User")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords = 0
productsum = 0
quantitysum = 0
profitsum = 0
vcloudtxns=vcloudtransactions()
try:
print(usertype)
print(fusername)
print(type)
print(brand)
if(fusername=="All" and type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username).order_by('-date')
print("One")
elif(fusername=="All" and type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, brand=brand).order_by('-date')
elif(fusername=="All" and type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, type=type).order_by('-date')
elif(fusername=="All" and type !="All" and brand !="All"):
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, brand=brand).order_by('-date')
elif(fusername!="All" and type !="All" and brand !="All"):
print('five')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, type=type, sponser3__username=username, sponser4__username=fusername, brand=brand).order_by('-date')
elif(fusername =="All" and type =="All" and brand !="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username).order_by('-date')
elif(fusername =="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__postId=usertype).order_by('-date')
elif(fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__username=fusername).order_by('-date')
elif(fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__username=fusername).order_by('-date')
else:
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__username=fusername,brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin3*i.quantity)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"sub_reseller/vcloud/vcloudreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(subresellervcloudreport)
else:
return redirect(subresellervcloudreport)
else:
return redirect(LoginPage)
def subresellervcloudStore(request):
if request.session.has_key("user"):
username=request.session["user"]
ads = adverisements.objects.filter(adtype="Image",usertype="Sub_Reseller",ctype="Vcloud").order_by('-id')[:10]
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card with cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
data=dict()
content = []
for i in pdcts:
try:
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
print(i['brand__brand'])
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
print(username)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
print(margindet)
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand_id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'productcount':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'brand__denomination':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
print(content)
except Exception as e:
print(e)
pass
buttonlist=["Cutting","Non Cutting"]
buttonclass=["btn-warning","btn-success"]
btnlist = zip(buttonlist, buttonclass)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/vcloud/vcloudStore.html",{'pdcts':content,'btnlist':btnlist,'user':userdetails,'ads':ads})
else:
return redirect(LoginPage)
def subresellerfilteredvcloudstore(request,brandtype):
if request.session.has_key("user"):
username=request.session["user"]
buttonclass=[]
ads = adverisements.objects.filter(adtype="Image",usertype="Sub_Reseller",ctype="Vcloud").order_by('-id')[:10]
if(brandtype=="Cutting"):
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card with cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
data=dict()
content = []
for i in pdcts:
try:
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
#print(lpd)
#print(productcost)
count=0
if not lpd:
pass;
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand_id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'productcount':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'brand__denomination':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
print(content)
except Exception as e:
print(e)
pass
buttonclass=["btn-warning","btn-success"]
else:
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card without cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
data=dict()
content = []
for i in pdcts:
try:
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
#print(lpd)
#print(productcost)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand_id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'productcount':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'brand__denomination':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
print(content)
except Exception as e:
print(e)
pass
buttonclass=["btn-success","btn-warning"]
buttonlist=["Cutting","Non Cutting"]
btnlist = zip(buttonlist, buttonclass)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/vcloud/vcloudStore.html",{'pdcts':content,'btnlist':btnlist,'user':userdetails,'ads':ads})
else:
return redirect(LoginPage)
def subresellersaveassignVcloudBrands(request):
if request.session.has_key("user"):
if request.method == "POST":
try:
reseller = request.POST.get('username', None)
values = request.POST.get('values', None)
states = request.POST.get('states', None)
brands = request.POST.get('brands', None)
margins = request.POST.get('margins', None)
v = values.split(',')
s = states.split(',')
b = brands.split(',')
m = margins.split(',')
username = request.session["user"]
assignedby = UserData.objects.get(username=username)
assignedto = UserData.objects.get(username=reseller)
for i in range(0,len(s)):
if(int(s[i])==0):
print(True)
brandid=b[int(i)]
brdet=vcloudBrands.objects.get(id=brandid)
print(brdet)
try:
vdt = vcloudAssignments.objects.get(brand=brdet,assignedby=assignedby,assignedto=assignedto)
vdt.delete()
vadt = vcloudAssignments.objects.get(brand=brdet,assignedby=assignedto)
print(vadt)
for i in vadt:
try:
ud = vcloudAssignments.objects.filter(brand=brdet,assignedby=i.assignedto)
ud.delete()
except Exception as e:
print("inner "+str(e))
vadt.delete()
except vcloudAssignments.DoesNotExist:
print("Error")
else:
print(False)
brandid=b[int(i)]
brdet=vcloudBrands.objects.get(id=brandid)
try:
assdet = vcloudAssignments.objects.get(brand=brdet,assignedby=assignedby,assignedto=assignedto)
assdet.margin = Decimal(v[int(i)])
assdet.save()
except vcloudAssignments.DoesNotExist:
vass = vcloudAssignments()
vass.brand=brdet
vass.assignedto=assignedto
vass.assignedby=assignedby
vass.margin = Decimal(v[int(i)])
vass.save()
data={"status":"Success"}
return JsonResponse(data)
except:
return JsonResponse({"status":"Error"})
else:
pass
else:
return redirect(LoginPage)
def subgetvcloudproductcost(brand,username):
print(brand)
prdcts=vcloudBrands.objects.get(brand=brand)
print(prdcts)
prdctcost = Decimal(prdcts.denomination)
margins=0
while(True):
userdet = UserData.objects.filter(username=username).values('sponserId','postId')
pdct = vcloudAssignments.objects.filter(assignedto=username, brand__brand=brand).values('margin')
if(pdct):
if(userdet[0]['postId']=="Admin"):
break;
else:
prdctcost = prdctcost+Decimal(pdct[0]['margin'])
username=userdet[0]['sponserId']
else:
break;
print(prdctcost)
return prdctcost
def subresellerassignVcloudBrands(request):
if request.session.has_key("user"):
brands = vcloudAssignments.objects.filter(assignedto=request.session["user"]).values('brand','brand__brand')
username=request.session["user"]
costlist=list()
brandlist=list()
for j in brands:
try:
prdcts=vcloudBrands.objects.get(brand=j['brand__brand'])
#prdcts=vcloudProducts.objects.filter(brand__brand=j['brand__brand'],status=True).order_by('brand').annotate(productcount=Count('brand')).values('brand','brand__brand','brand__id','brand__denomination','brand__logo','brand__description','brand__currency','brand__category')
if(prdcts):
cost=subgetvcloudproductcost(j['brand__brand'],username)
#costlist.append(cost)
data={'cost':cost,'brand':prdcts.id,'brand__brand':prdcts.brand,'brand__id':prdcts.id,'brand__denomination':prdcts.denomination,'brand__logo':prdcts.logo.url,'brand__description':prdcts.description,'brand__currency':prdcts.currency,'brand__category':prdcts.category}
brandlist.append(data)
else:
pass
except vcloudProducts.DoesNotExist:
pass;
resellers = UserData.objects.filter(postId="User",sponserId=request.session["user"])
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/vcloud/assignVcloudBrands.html",{'brands':brands,'products':brandlist,'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def subresellerviewbrands(request):
if request.session.has_key("user"):
username = request.session["user"]
vcdprod=vcloudBrands.objects.all()
resultlist=list()
statuslist=list()
for i in vcdprod:
vca=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i.brand)
if not vca:
statuslist.append(False)
else:
statuslist.append(True)
vcd=list(vcdprod)
print(vcd)
print(statuslist)
#print(data)
ldb=zip(vcd,statuslist)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/vcloud/viewBrands.html",{'pdcts':list(ldb),'user':userdetails})
else:
return redirect(LoginPage)
def check_balance(username,brand):
userbal=UserData.objects.filter(username=username).only('balance')
usermargin=vcloudAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
def sub_buy_vcloud_brands(request):
if request.session.has_key("user"):
if request.method == "POST":
username=request.session["user"]
brand = request.POST.get('brandid', None)
quantity = request.POST.get('quantity', None)
amt = request.POST.get('amt', None)
branddet=vcloudBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=request.session["user"])
#checkqty = vcloudProducts.objects.filter(brand__brand=brand, status=True).exclude(productstatus=1).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('productcount')
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=vcloudProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
content=dict()
licheckqty=list(checkqty)
brand_id=0
deno=0
if(licheckqty[0]['productcount'] >= int(quantity)):
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = vcloudProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
#print(prdctcost)
#print(cost)
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
print(flag)
break;
username=userdet2[0]['sponserId']
if(flag):
try:
prdctcddet=vcloudProducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
#print(h.username)
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'brand':h.brand.brand,'brand_logo':h.brand.logo.url,'password':h.password,'status':h.status,'suser':username,'sdate':h.sdate}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Vcloud"
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.quantity = quantity
vcrep.amount = amt
vcrep.rtype = "Web"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
print(ms)
print(admin)
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
obj = vcloudtransactions.objects.latest('id')
print(obj.id)
content["data"] = result
content["res_status"]="success"
content["trid"]=obj.id
except:
content["res_status"]="Failed"
else:
for i in prdctdet:
i.suser=None
i.save()
content["res_status"]="Failed"
return JsonResponse(content,safe=False)
else:
return redirect(subresellervcloudStore)
else:
return redirect(LoginPage)
def subprintLayout(request):
return render(request,"sub_reseller/printLayout.html")
def subeditresellerProfilevcloud(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(resellerprofiledcard)
else:
messages.warning(request,'Internal Error Occured')
return redirect(resellerprofiledcard)
else:
return redirect(LoginPage)
#________________DCARD_______________
def subresellerDcardDashboard(request):
if request.session.has_key("user"):
username = request.session["user"]
#print(last_month)
reseller = UserData.objects.filter(sponserId=username,postId="User")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
username = request.session["user"]
type = request.session["usertype"]
try:
user = UserData.objects.get(username = username, postId = type)
except UserData.DoesNotExist:
return redirect(LoginPage)
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser3__username=username,type="Dcard").order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin3*i.quantity
data3={'user':i.sponser4.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = datacardAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
for i in brand:
pd=datacardproducts.objects.filter(brand=i['brand__id'], status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass;
#break;
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=datacardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"sub_reseller/dcard/dashboard-dcard.html",{'filterform':dcardDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':user,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filtersubresellerDcardDashboard(request):
if request.session.has_key("user"):
if request.method == "POST":
form = dcardDashboardfilter(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
uuusername=form.cleaned_data.get("username")
#mffromdate=datetime.strptime(fromdate, '%b %d %Y %I:%M%p')
print(type(fromdate))
print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
reseller = UserData.objects.filter(sponserId=currentuser,postId="Sub_Reseller")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(username)
userdetails = UserData.objects.get(username=request.session["user"])
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,sponser3__username=currentuser,type="Dcard",sponser4__username=uuusername).order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin3*i.quantity
data3={'user':i.sponser4.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = datacardAssignments.objects.filter(assignedto=currentuser).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=datacardproducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=datacardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"subreseller/dcard/dashboard-dcard.html",{'filterform':vcloudDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':userdetails,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(subresellerDcardDashboard)
else:
return(subresellerDcardDashboard)
else:
return redirect(LoginPage)
def subresellerprofiledcard(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"sub_reseller/dcard/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def subreselleraddResellerDcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/dcard/addReseller.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def subreselleraddUserDcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/dcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def subresellerviewResellerDcard(request):
if request.session.has_key("user"):
resellers = UserData.objects.filter(sponserId=request.session["user"],postId="Sub_Reseller")
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/dcard/viewResellers.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def subresellerviewUserDcard(request):
if request.session.has_key("user"):
user = request.session["user"]
resellers = UserData.objects.filter(postId="User",sponserId=user)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/dcard/viewUser.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def subresellerbalanceTransferDcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
bthist=balanceTransactionReport.objects.filter(source=userdetails,category="BT").order_by('-date')
#print(bthist)
return render(request,"sub_reseller/dcard/balanceTransfer.html",{'bthist':bthist,'user':userdetails})
else:
return redirect(LoginPage)
def subreselleraddPaymentDcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
phist=fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"sub_reseller/dcard/addPayment.html",{'phist':phist})
else:
return redirect(LoginPage)
def subresellerdatacardreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser3__username=username).order_by('-date')
#vcloudtxns = vcloudtransactions.objects.all().order_by('-date')
reseller=UserData.objects.filter(sponserId=username,postId="User")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
cost=0
for i in vcloudtxns:
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin3*i.quantity)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"sub_reseller/dcard/dcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filtersubresellerdcard_report(request):
if request.session.has_key("user"):
if request.method=="POST":
form = vcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
fusername=form.cleaned_data.get("username")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
#print(brand,fusername)
fuser=''
if(fusername!='All'):
filterdata=UserData.objects.get(username=fusername)
fuser=filterdata.name
else:
fuser=fusername
filter={'ffdate':fromdate,'ttdate':todate,'fuser':fuser}
userdetails = UserData.objects.get(username=request.session["user"])
reseller=UserData.objects.filter(sponserId=username,postId="User")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords = 0
productsum = 0
quantitysum = 0
profitsum = 0
vcloudtxns=vcloudtransactions()
try:
print(usertype)
print(fusername)
print(type)
print(brand)
if(fusername=="All" and type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username).order_by('-date')
print("One")
elif(fusername=="All" and type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, brand=brand).order_by('-date')
elif(fusername=="All" and type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, type=type).order_by('-date')
elif(fusername=="All" and type !="All" and brand !="All"):
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, brand=brand).order_by('-date')
elif(fusername!="All" and type !="All" and brand !="All"):
print('five')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, type=type, sponser3__username=username, sponser4__username=fusername, brand=brand).order_by('-date')
elif(fusername =="All" and type =="All" and brand !="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username).order_by('-date')
elif(fusername =="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__postId=usertype).order_by('-date')
elif(fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__username=fusername).order_by('-date')
elif(fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__username=fusername).order_by('-date')
else:
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__username=fusername,brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin3*i.quantity)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"sub_reseller/dcard/dcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(subresellerdatacardreport)
else:
return redirect(subresellerdatacardreport)
else:
return redirect(LoginPage)
def subresellerbTReportDcard(request):
if request.session.has_key("user"):
username = request.session["user"]
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="User")
fromsum = balanceTransactionReport.objects.filter(source=userdetails,category='BT').aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(destination=userdetails,category='BT').aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(source=userdetails).order_by('-date') | balanceTransactionReport.objects.filter(destination=userdetails).order_by('-date')
return render(request,"sub_reseller/dcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filtersubresellerdcardbtreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="User")
fromsum=None
tosum=None
bthist=None
try:
if(susername == "Self"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
elif(susername == "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(susername != "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"sub_reseller/dcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(subresellerbTReportDcard)
else:
return redirect(subresellerbTReportDcard)
else:
return redirect(LoginPage)
def subresellerpaymentReportDcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=request.session["user"],postId="User")
phist = fundTransactionReport.objects.filter(source=userdetails).order_by('-date')|fundTransactionReport.objects.filter(destination=userdetails).order_by('-date')
bsum = fundTransactionReport.objects.filter(source=userdetails).aggregate(Sum('amount'))
return render(request,"sub_reseller/dcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filtersubresellerdcardpaymentreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="User")
bsum=None
phist=None
try:
if(susername=="Self"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
#print(phist)
elif(susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
print(phist)
elif(susername != "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except Exception as e:
print(e)
pass
return render(request,"sub_reseller/dcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(subresellerpaymentReportDcard)
else:
return redirect(subresellerpaymentReportDcard)
else:
return redirect(LoginPage)
def subresellerassignDCardBrands(request):
if request.session.has_key("user"):
brands = datacardAssignments.objects.filter(assignedto=request.session["user"]).values('brand','brand__brand','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
username=request.session["user"]
bd=list(brands)
prdcts=list()
costs=list()
for i in brands:
prd=dcardBrands.objects.get(brand=i['brand__brand'])
#prd=datacardproducts.objects.filter(brand__brand=i['brand__brand'], status=True).order_by('brand').values('brand').annotate(productcount=Count('brand')).values('brand','brand__brand','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
#print(len(prd))
if(prd):
cost=getDatacardProductCost(username,i["brand__brand"])
data={'cost':cost,'brand':prd.id,'brand__brand':prd.brand,'brand__id':prd.id,'brand__denomination':prd.denomination,'brand__logo':prd.logo.url,'barnd__description':prd.description,'brand__currency':prd.currency}
prdcts.append(data)
resellers = UserData.objects.filter(postId="User",sponserId=request.session["user"])
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/dcard/assignDcardbrand.html",{'brands':bd,'products':prdcts,'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def subresellerdcardstore(request):
if request.session.has_key("user"):
username=request.session["user"]
user = UserData.objects.get(username=username)
btnlist=list()
content=list()
ads = adverisements.objects.filter(adtype="Image",usertype="Sub_Reseller",ctype="Dcard").order_by('-id')[:10]
dproducts = datacardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
if(len(btnlist)==0):
pass
else:
dcardproducts = datacardAssignments.objects.filter(assignedto=username,brand__brand__contains=btnlist[0]).order_by('brand').values('brand__brand','margin')
print(dcardproducts)
#print(buttons)
for i in dcardproducts:
dcp=datacardproducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getDatacardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
else:
pass
#print(content)
return render(request,"sub_reseller/dcard/datastore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def subgetDatacardProductCost(username,brand):
prdcts=datacardproducts.objects.filter(brand__brand=brand,status=True).order_by('brand').values('brand__denomination')
prdctcost=0
margins=0
while(True):
userdet = UserData.objects.filter(username=username).values('sponserId','postId')
pdct = datacardAssignments.objects.filter(assignedto=username, brand__brand=brand).values('margin')
if(userdet[0]['postId']=="Admin"):
break;
else:
prdctcost = Decimal(prdcts[0]["brand__denomination"])
prdctcost = prdctcost+Decimal(pdct[0]['margin'])
username=userdet[0]['sponserId']
print(prdctcost)
return prdctcost
def subviewfiltereddatastore(brand):
brands=datacardproducts.objects.filter(brand__brand__contains=brand,status=True).order_by('brand').values('brand').annotate(productcount=Count('brand')).values('productcount','brand__brand','brand__id','brand__description','brand__denomination','brand__logo','brand__currency')
return brands
def subresellerfilterdcardstore(request,brand):
if request.session.has_key("user"):
#print(brand)
username = request.session['user']
user=UserData.objects.get(username=username)
btnlist=list()
dproducts = datacardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
ads = adverisements.objects.filter(adtype="Image",usertype="Sub_Reseller",ctype="Dcard").order_by('-id')[:10]
for j in dproducts:
buttons=(j["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
dcardproducts = datacardAssignments.objects.filter(assignedto=username,brand__brand__contains=brand).order_by('brand').values('brand__brand','margin')
print(dcardproducts)
content=list()
for i in dcardproducts:
dcp=datacardproducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getDatacardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
else:
pass
print(content)
return render(request,"sub_reseller/dcard/datastore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def subeditresellerProfileDcard(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(subresellerprofiledcard)
else:
messages.warning(request,'Internal Error Occured')
return redirect(subresellerprofiledcard)
else:
return redirect(LoginPage)
def subresellersubmitUser(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="User"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(subreselleraddUserDcard)
else:
messages.warning(request, form.errors)
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"sub_reseller/dcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"sub_reseller/dcard/addUser.html",{'form':AddUserDataForm,'user':username})
else:
return redirect(LoginPage)
def subresellersubBalTransDcard(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
userdet = UserData.objects.get(username=user)
bal = userdet.balance
newbal=bal+Decimal(amount)
cdbal = userdet.targetAmt
newcdbal = cdbal-Decimal(amount)
userdet.targetAmt = newcdbal
userdet.balance = newbal
userdet.save()
userdetails = UserData.objects.get(username=request.session["user"])
btreport = balanceTransactionReport()
btreport.source = userdetails
btreport.destination = userdet
btreport.category = "BT"
btreport.pbalance = bal
btreport.nbalance = newbal
btreport.cramount = newcdbal
btreport.amount = amount
btreport.remarks = 'Added To Balance'
btreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(subresellerbalanceTransferDcard)
#userdata=UserData.objects.get(username=)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(subresellerbalanceTransferDcard)
else:
return redirect(LoginPage)
def subresellersubPayTrans(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
remarks = request.POST.get('remarks', None)
userdet = UserData.objects.get(username=user)
obalance = userdet.targetAmt
cdbal = userdet.targetAmt
newcdbal = cdbal+Decimal(amount)
userdet.targetAmt = newcdbal
userdet.save()
closeuser = UserData.objects.get(username=user)
userdetails = UserData.objects.get(username=request.session["user"])
ftreport=fundTransactionReport()
ftreport.source = userdetails
ftreport.destination = userdet
ftreport.obalance = obalance
ftreport.cbalance = closeuser.targetAmt
ftreport.role = userType
ftreport.amount = amount
ftreport.balance = newcdbal
ftreport.remarks = remarks
ftreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(subreselleraddPaymentDcard)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(subreselleraddPaymentDcard)
else:
return redirect(LoginPage)
def sub_buy_datacard_brands(request):
if request.session.has_key("user"):
if request.method == "POST":
username=request.session["user"]
brand = request.POST.get('brandid', None)
quantity = request.POST.get('quantity', None)
amt = request.POST.get('amt', None)
branddet=dcardBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=request.session["user"])
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=datacardproducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
content=dict()
licheckqty=list(checkqty)
brand_id=0
deno=0
if(licheckqty[0]['productcount'] >= int(quantity)):
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = datacardproducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=datacardAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
#print(prdctcost)
#print(cost)
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
print(flag)
break;
username=userdet2[0]['sponserId']
if(flag):
try:
prdctcddet=datacardproducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'brand':h.brand.brand,'brand_logo':h.brand.logo.url, 'status':h.status,'suser':username,'sdate':h.sdate}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Dcard"
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.quantity = quantity
vcrep.amount = amt
vcrep.rtype = "Web"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
obj = vcloudtransactions.objects.latest('id')
print(obj.id)
content["data"] = result
content["res_status"]="success"
content["trid"]=obj.id
except:
content["res_status"]="Failed"
else:
for i in prdctdet:
i.suser=None
i.save()
content["res_status"]="Failed"
return JsonResponse(content,safe=False)
else:
return redirect(subresellerdcardstore)
else:
return redirect(LoginPage)
def subresellerdcardviewbrands(request):
if request.session.has_key("user"):
if request.session.has_key("user"):
username = request.session["user"]
vcdprod=dcardBrands.objects.all()
resultlist=list()
statuslist=list()
for i in vcdprod:
vca=datacardAssignments.objects.filter(assignedto=username,brand__brand=i.brand)
if not vca:
statuslist.append(False)
else:
statuslist.append(True)
vcd=list(vcdprod)
print(vcd)
print(statuslist)
#print(data)
ldb=zip(vcd,statuslist)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/dcard/viewBrands.html",{'pdcts':list(ldb),'user':userdetails})
else:
return redirect(LoginPage)
#________________RCARD_______________
def subresellerRcardDashboard(request):
if request.session.has_key("user"):
last_month = datetime.today() - timedelta(days=1)
username = request.session["user"]
#print(last_month)
reseller = UserData.objects.filter(sponserId=username,postId="User")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
username = request.session["user"]
type = request.session["usertype"]
try:
user = UserData.objects.get(username = username, postId = type)
except UserData.DoesNotExist:
return redirect(LoginPage)
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser3__username=username,type="Rcard").order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin3*i.quantity
data3={'user':i.sponser4.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = rcardAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=rcardProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=rcardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"sub_reseller/rcard/dashboard-rcard.html",{'filterform':rcardDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':user,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filtersubresellerrcardDashboard(request):
if request.session.has_key("user"):
if request.method == "POST":
form = rcardDashboardfilter(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
uuusername=form.cleaned_data.get("username")
#mffromdate=datetime.strptime(fromdate, '%b %d %Y %I:%M%p')
print(type(fromdate))
print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
reseller = UserData.objects.filter(sponserId=currentuser,postId="User")
#print(reseller)
resellerlist=list()
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
#print(username)
userdetails = UserData.objects.get(username=request.session["user"])
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,sponser3__username=currentuser,type="Rcard",sponser4__username=uuusername).order_by('-date')
content=list()
topuser=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
#data3={'user':i.sponser2.name,'amount':(i.denominations*i.quantity)}
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin3*i.quantity
data3={'user':i.sponser4.name,'amount':(cost*i.quantity)}
topuser.append(data3)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = rcardAssignments.objects.filter(assignedto=currentuser).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=rcardProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=rcardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
list3=list()
sorted_users = sorted(topuser, key=itemgetter('user'))
for key, group in itertools.groupby(sorted_users, key=lambda x:x['user']):
amountsum=0
for g in group:
amountsum=amountsum+g["amount"]
#print(amountsum)
data5={'user':key,'amount':amountsum}
list3.append(data5)
return render(request,"sub_reseller/rcard/dashboard-rcard.html",{'filterform':rcardDashboardfilter,'reseller':resellerlist,'recenttransactions':content,'products':product,'user':userdetails,'topuser':list3,'last_month':last_month,'boxval':box_data})
else:
return redirect(subresellerRcardDashboard)
else:
return(subresellerRcardDashboard)
else:
return redirect(LoginPage)
def subresellerprofilercard(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"sub_reseller/rcard/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def subreselleraddUserRcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/rcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
return redirect(LoginPage)
def subresellerviewUserRcard(request):
if request.session.has_key("user"):
user = request.session["user"]
resellers = UserData.objects.filter(postId="User",sponserId=user)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/rcard/viewUser.html",{'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def subresellerbalanceTransferRcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
bthist=balanceTransactionReport.objects.filter(source=userdetails,category="BT").order_by('-date')
#print(bthist)
return render(request,"sub_reseller/rcard/balanceTransfer.html",{'bthist':bthist,'user':userdetails})
else:
return redirect(LoginPage)
def subreselleraddPaymentRcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
phist=fundTransactionReport.objects.filter(source=userdetails).order_by('-date')
return render(request,"sub_reseller/rcard/addPayment.html",{'phist':phist})
else:
return redirect(LoginPage)
def subresellerrcardreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,sponser3__username=username).order_by('-date')
#vcloudtxns = vcloudtransactions.objects.all().order_by('-date')
reseller=UserData.objects.filter(sponserId=username,postId="User")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
cost=0
for i in vcloudtxns:
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin3*i.quantity)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"sub_reseller/rcard/rcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filtersubresellerrcard_report(request):
if request.session.has_key("user"):
if request.method=="POST":
form = vcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
fusername=form.cleaned_data.get("username")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
#print(brand,fusername)
fuser=''
if(fusername!='All'):
filterdata=UserData.objects.get(username=fusername)
fuser=filterdata.name
else:
fuser=fusername
filter={'ffdate':fromdate,'ttdate':todate,'fuser':fuser}
userdetails = UserData.objects.get(username=request.session["user"])
reseller=UserData.objects.filter(sponserId=username,postId="User")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
for i in reseller:
resellerdata={'username':i.username,'name':i.name}
resellerlist.append(resellerdata)
content=list()
noofrecords = 0
productsum = 0
quantitysum = 0
profitsum = 0
try:
print(usertype)
print(fusername)
print(type)
print(brand)
if(fusername=="All" and type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username).order_by('-date')
print("One")
elif(fusername=="All" and type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, brand=brand).order_by('-date')
elif(fusername=="All" and type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, type=type).order_by('-date')
elif(fusername=="All" and type !="All" and brand !="All"):
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, brand=brand).order_by('-date')
elif(fusername!="All" and type !="All" and brand !="All"):
print('five')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, type=type, sponser3__username=username, sponser4__username=fusername, brand=brand).order_by('-date')
elif(fusername =="All" and type =="All" and brand !="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username).order_by('-date')
elif(fusername =="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__postId=usertype).order_by('-date')
elif(fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__username=fusername).order_by('-date')
elif(fusername !="All" and type =="All" and brand =="All"):
print('Six')
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__username=fusername).order_by('-date')
else:
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, sponser3__username=username, sponser4__username=fusername,brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
else:
profit=(i.margin3*i.quantity)
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit,"rtype":i.rtype}
content.append(data)
profitsum = profitsum+profit
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"sub_reseller/rcard/rcardreport.html",{'filterform':vcloudreportfilterform,'products':content,'user':userdetails,'reseller':resellerlist, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(subresellerrcardreport)
else:
return redirect(subresellerrcardreport)
else:
return redirect(LoginPage)
def subresellerbTReportRcard(request):
if request.session.has_key("user"):
if request.session.has_key("user"):
username = request.session["user"]
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="User")
fromsum = balanceTransactionReport.objects.filter(source=userdetails,category='BT').aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(destination=userdetails,category='BT').aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(source=userdetails).order_by('-date') | balanceTransactionReport.objects.filter(destination=userdetails).order_by('-date')
return render(request,"sub_reseller/rcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filtersubresellerrcardbtreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="User")
fromsum=None
tosum=None
bthist=None
try:
if(susername == "Self"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
elif(susername == "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
elif(susername != "All"):
fromsum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
tosum = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails).aggregate(Sum('amount'))
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except:
pass
return render(request,"sub_reseller/rcard/balanceTransferReport.html",{'form':balancetransferfilterform,'reseller':reseller,'bthist':bthist,'fromsum':fromsum['amount__sum'],'tosum':tosum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(subresellerbTReportRcard)
else:
return redirect(subresellerbTReportRcard)
else:
return redirect(LoginPage)
def subresellerpaymentReportRcard(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=request.session["user"],postId="User")
phist = fundTransactionReport.objects.filter(source=userdetails).order_by('-date')|fundTransactionReport.objects.filter(destination=userdetails).order_by('-date')
bsum = fundTransactionReport.objects.filter(source=userdetails).aggregate(Sum('amount'))
return render(request,"sub_reseller/rcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails})
else:
return redirect(LoginPage)
def filtersubresellerrcardpaymentreport(request):
if request.session.has_key("user"):
if request.method=="POST":
form = balancetransferfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
usertype=form.cleaned_data.get("usertype")
susername=form.cleaned_data.get("username")
username = request.session["user"]
filter={'ffdate':fromdate,'ttdate':todate,'fuser':susername}
userdetails = UserData.objects.get(username=request.session["user"])
reseller = UserData.objects.filter(sponserId=username,postId="User")
bsum=None
phist=None
try:
if(susername=="Self"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
#print(phist)
elif(susername == "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
print(phist)
elif(susername != "All"):
bsum = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername).aggregate(Sum('amount'))
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails,destination__username=susername)
except Exception as e:
print(e)
pass
return render(request,"sub_reseller/rcard/paymentReport.html",{'form':paymentfilterform,'reseller':reseller,'phist':phist,'sum':bsum['amount__sum'],'user':userdetails,'filter':filter})
else:
return redirect(subresellerpaymentReportRcard)
else:
return redirect(subresellerpaymentReportRcard)
else:
return redirect(LoginPage)
def subresellerassignRCardBrands(request):
if request.session.has_key("user"):
brands = rcardAssignments.objects.filter(assignedto=request.session["user"]).values('brand','brand__brand','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
username=request.session["user"]
bd=list(brands)
prdcts=list()
costs=list()
for i in brands:
prd=rcardBrands.objects.get(brand=i['brand__brand'])
#prd=rcardProducts.objects.filter(brand__brand=i['brand__brand'], status=True).order_by('brand').values('brand').annotate(productcount=Count('brand')).values('brand','brand__brand','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
if(prd):
cost=getReachargeProductCost(username,i["brand__brand"])
data={'cost':cost,'brand':prd.id,'brand__brand':prd.brand,'brand__id':prd.id,'brand__denomination':prd.denomination,'brand__logo':prd.logo.url,'barnd__description':prd.description,'brand__currency':prd.currency}
prdcts.append(data)
#print(pddata[0])
resellers = UserData.objects.filter(postId="User",sponserId=request.session["user"])
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/rcard/assignRcardbrand.html",{'brands':bd,'products':prdcts,'resellers':resellers,'user':userdetails})
else:
return redirect(LoginPage)
def subresellerrcardstore(request):
if request.session.has_key("user"):
username=request.session["user"]
user = UserData.objects.get(username=username)
ads = adverisements.objects.filter(adtype="Image",usertype="Sub_Reseller",ctype="Rcard").order_by('-id')[:10]
btnlist=list()
dproducts = rcardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
content=list()
if(len(btnlist)!=0):
dcardproducts = rcardAssignments.objects.filter(assignedto=username,brand__brand__contains=btnlist[0]).order_by('brand').values('brand__brand','margin')
#print(buttons)
for i in dcardproducts:
dcp=rcardProducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getRcardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
print(content)
else:
pass;
return render(request,"sub_reseller/rcard/rcardstore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def subgetRcardProductCost(username,brand):
prdcts=rcardProducts.objects.filter(brand__brand=brand,status=True).order_by('brand').values('brand__denomination')
prdctcost=0
margins=0
while(True):
userdet = UserData.objects.filter(username=username).values('sponserId','postId')
pdct = rcardAssignments.objects.filter(assignedto=username, brand__brand=brand).values('margin')
if(userdet[0]['postId']=="Admin"):
break;
else:
prdctcost = Decimal(prdcts[0]["brand__denomination"])
prdctcost = prdctcost+Decimal(pdct[0]['margin'])
username=userdet[0]['sponserId']
print(prdctcost)
return prdctcost
def subviewfilteredreachargestore(brand):
brands=rcardProducts.objects.filter(brand__brand__contains=brand,status=True).order_by('brand').values('brand').annotate(productcount=Count('brand')).values('productcount','brand__brand','brand__id','brand__description','brand__denomination','brand__logo','brand__currency')
return brands
def subresellerfilterrcardstore(request,brand):
if request.session.has_key("user"):
#print(brand)
username=request.session["user"]
user = UserData.objects.get(username=username)
ads = adverisements.objects.filter(adtype="Image",usertype="Sub_Reseller",ctype="Rcard").order_by('-id')[:10]
btnlist=list()
dproducts = rcardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
dcardproducts = rcardAssignments.objects.filter(assignedto=username,brand__brand__contains=brand).order_by('brand').values('brand__brand','margin')
content=list()
#print(buttons)
for i in dcardproducts:
dcp=rcardProducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
buttons=(dcp[0]["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
cost=getRcardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
print(content)
else:
pass;
return render(request,"sub_reseller/rcard/rcardstore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def subeditresellerProfileRcard(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(subresellerprofilercard)
else:
messages.warning(request,'Internal Error Occured')
return redirect(subresellerprofilercard)
else:
return redirect(LoginPage)
def subresellersubmitUser(request):
if request.session.has_key("user"):
if request.method == "POST":
form = AddUserDataForm(request.POST or None)
print(form.errors)
if form.is_valid():
username=form.cleaned_data.get("username")
password=form.cleaned_data.get("password")
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
sponser = request.session["user"]
sponseruser=UserData.objects.get(username=sponser)
Userdata=form.save(commit=False)
Userdata.postId="User"
Userdata.sponserId = sponseruser
Userdata.status = True
Userdata.balance = 0
Userdata.targetAmt = 0
Userdata.rentalAmt = 0
Userdata.dcard_status = True
Userdata.rcard_status = True
Userdata.password = hash
Userdata.save()
messages.success(request, 'Successfully Added')
return redirect(subreselleraddUserRcard)
else:
messages.warning(request, form.errors)
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"sub_reseller/rcard/addUser.html",{'form':AddUserDataForm,'user':userdetails})
else:
userdetails = UserData.objects.get(username=request.session["user"])
form = AddUserDataForm()
return render(request,"sub_reseller/rcard/addUser.html",{'form':AddUserDataForm,'user':username})
else:
return redirect(LoginPage)
def subresellersubBalTransRcard(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
userdet = UserData.objects.get(username=user)
bal = userdet.balance
newbal=bal+Decimal(amount)
cdbal = userdet.targetAmt
newcdbal = cdbal-Decimal(amount)
userdet.targetAmt = newcdbal
userdet.balance = newbal
userdet.save()
userdetails = UserData.objects.get(username=request.session["user"])
btreport = balanceTransactionReport()
btreport.source = userdetails
btreport.destination = userdet
btreport.category = "BT"
btreport.pbalance = bal
btreport.nbalance = newbal
btreport.cramount = newcdbal
btreport.amount = amount
btreport.remarks = 'Added To Balance'
btreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(subresellerbalanceTransferRcard)
#userdata=UserData.objects.get(username=)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(subresellerbalanceTransferRcard)
else:
return redirect(LoginPage)
def subresellerrcardsubPayTrans(request):
if request.session.has_key("user"):
if request.method == "POST":
userType = request.POST.get('userType', None)
user = request.POST.get('users', None)
amount = request.POST.get('amount', None)
remarks = request.POST.get('remarks', None)
userdet = UserData.objects.get(username=user)
obalance = userdet.targetAmt
cdbal = userdet.targetAmt
newcdbal = cdbal+Decimal(amount)
userdet.targetAmt = newcdbal
userdet.save()
closeuser = UserData.objects.get(username=user)
userdetails = UserData.objects.get(username=request.session["user"])
ftreport=fundTransactionReport()
ftreport.source = userdetails
ftreport.destination = userdet
ftreport.obalance = obalance
ftreport.cbalance = closeuser.targetAmt
ftreport.role = userType
ftreport.amount = amount
ftreport.balance = newcdbal
ftreport.remarks = remarks
ftreport.save()
messages.success(request, 'Successfully Updated The balance')
return redirect(subreselleraddPaymentRcard)
else:
messages.warning(request, 'Internal Error Occured')
return redirect(subreselleraddPaymentRcard)
else:
return redirect(LoginPage)
def subresellefilteredrrcardstore(request,brandtype):
if request.session.has_key("user"):
username=request.session["user"]
user = UserData.objects.get(username=username)
ads = adverisements.objects.filter(adtype="Image",usertype="Sub_Reseller",ctype="Rcard").order_by('-id')[:10]
btnlist=list()
dproducts = rcardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
dcardproducts = rcardAssignments.objects.filter(assignedto=username,brand__brand__contains=brandtype).order_by('brand').values('brand__brand','margin')
content=list()
#print(buttons)
for i in dcardproducts:
dcp=rcardProducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
buttons=(dcp[0]["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
cost=getRcardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
print(content)
return render(request,"sub_reseller/rcard/rcardstore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def sub_buy_rcard_brands(request):
if request.session.has_key("user"):
if request.method == "POST":
username=request.session["user"]
brand = request.POST.get('brandid', None)
quantity = request.POST.get('quantity', None)
amt = request.POST.get('amt', None)
branddet=rcardBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=request.session["user"])
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=rcardProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
content=dict()
licheckqty=list(checkqty)
brand_id=0
deno=0
if(licheckqty[0]['productcount'] >= int(quantity)):
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = rcardProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=rcardAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
#print(prdctcost)
#print(cost)
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
print(flag)
break;
username=userdet2[0]['sponserId']
if(flag):
try:
prdctcddet=rcardProducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'brand':h.brand.brand,'brand_logo':h.brand.logo.url, 'status':h.status,'suser':username,'sdate':h.sdate}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Rcard"
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.quantity = quantity
vcrep.amount = amt
vcrep.rtype = "Web"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
obj = vcloudtransactions.objects.latest('id')
print(obj.id)
content["data"] = result
content["res_status"]="success"
content["trid"]=obj.id
except:
content["res_status"]="Failed"
else:
for i in prdctdet:
i.suser=None
i.save()
content["res_status"]="Failed"
return JsonResponse(content,safe=False)
else:
return redirect(subresellerrcardstore)
else:
return redirect(LoginPage)
def subresellerrcardviewbrands(request):
if request.session.has_key("user"):
if request.session.has_key("user"):
username = request.session["user"]
vcdprod=rcardBrands.objects.all()
resultlist=list()
statuslist=list()
for i in vcdprod:
vca=rcardAssignments.objects.filter(assignedto=username,brand__brand=i.brand)
if not vca:
statuslist.append(False)
else:
statuslist.append(True)
vcd=list(vcdprod)
print(vcd)
print(statuslist)
#print(data)
ldb=zip(vcd,statuslist)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/rcard/viewBrands.html",{'pdcts':list(ldb),'user':userdetails})
else:
return redirect(LoginPage)
#________________________________________________________________USER_______________________________________________________________
#________________VCLOUD_______________
def uservcloudhomePage(request):
if request.session.has_key("user"):
last_month = datetime.today() - timedelta(days=1)
username = request.session["user"]
type = request.session["usertype"]
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,type="Vcloud",saleduser__username=username).order_by('-date')
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"obalance":i.obalance,"cbalance":i.cbalance,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = vcloudAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
#print(i['brand__id'])
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
return render(request,"user/vcloud/dashboard-vcloud.html",{'filterform':uservclouddashboardfilter,'recenttransactions':content,'products':product,'user':userdetails,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filteruservcloudhomepage(request):
if request.session.has_key("user"):
if request.method == "POST":
form = uservclouddashboardfilter(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
username=request.session["user"]
#mffromdate=datetime.strptime(fromdate, '%b %d %Y %I:%M%p')
#print(type(fromdate))
#print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
userdetails = UserData.objects.get(username=request.session["user"])
#vcloudtxns = vcloudtransactions.objects.filter(type="Vcloud").order_by('-date')
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,type="Vcloud",saleduser__username=username).order_by('-date')
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"obalance":i.obalance,"cbalance":i.cbalance,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand=vcloudBrands.objects.all()
product=list()
for j in brand:
prdcts=vcloudProducts.objects.filter(brand__id=j.id,status=True).order_by("brand__brand").values("brand").annotate(productcount=Count('brand')).values('brand__brand', 'productcount','brand__denomination')
#print(prdcts)
for k in prdcts:
data2={"brand":k['brand__brand'],"count":k['productcount'],"denomination":k['brand__denomination']}
product.append(data2)
#print(topuser)
return render(request,"user/vcloud/dashboard-vcloud.html",{'filterform':vcloudDashboardfilter,'recenttransactions':content,'products':product,'user':userdetails,'last_month':last_month,'boxval':box_data})
else:
return redirect(uservcloudhomePage)
else:
return(uservcloudhomePage)
else:
return redirect(LoginPage)
def uservcloudprofile(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"user/vcloud/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def userrvcloudreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,saleduser__username=username).order_by('-date')
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"obalance":i.obalance,"cbalance":i.cbalance,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"user/vcloud/vcloudreport.html",{'filterform':uservcloudreportfilterform,'products':content,'user':userdetails,'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filteruservcloud_report(request):
if request.session.has_key("user"):
if request.method=="POST":
form = uservcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
#print(brand,fusername)
filter={'ffdate':fromdate,'ttdate':todate}
reseller=UserData.objects.filter(sponserId=username,postId="User")
resellerlist=list()
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
userdetails = UserData.objects.get(username=username)
content=list()
noofrecords = 0
productsum = 0
quantitysum = 0
profitsum = 0
vcloudtxns=vcloudtransactions()
try:
print(type)
print(brand)
if(type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username).order_by('-date')
print("One")
elif(type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username, brand=brand).order_by('-date')
elif(type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username, type=type).order_by('-date')
else:
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username, brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"obalance":i.obalance,"cbalance":i.cbalance,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+0
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"user/vcloud/vcloudreport.html",{'filterform':uservcloudreportfilterform,'products':content,'user':userdetails, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(userrvcloudreport)
else:
return redirect(userrvcloudreport)
else:
return redirect(LoginPage)
def uservcloudStore(request):
if request.session.has_key("user"):
username=request.session["user"]
ads = adverisements.objects.filter(adtype="Image",usertype="User",ctype="Vcloud").order_by('-id')[:10]
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card with cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
print(len(list(pdcts)))
data=dict()
content = []
for i in pdcts:
try:
print(i['brand__brand'])
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
#print(len(pd))
count=0
if not lpd:
pass;
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
#print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
#print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
print(margindet)
if(userdet2[0]['postId']=="Admin"):
break;
else:
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
#print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand_id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'productcount':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'brand__denomination':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
except Exception as e:
pass;
print(content)
print(len(content))
buttonlist=["Cutting","Non Cutting"]
buttonclass=["btn-warning","btn-success"]
btnlist = zip(buttonlist, buttonclass)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"user/vcloud/vcloudStore.html",{'pdcts':content,'btnlist':btnlist,'user':userdetails,'ads':ads})
else:
return redirect(LoginPage)
def userviewbrands(request):
if request.session.has_key("user"):
username = request.session["user"]
vcdprod=vcloudBrands.objects.all()
resultlist=list()
statuslist=list()
for i in vcdprod:
vca=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i.brand)
if not vca:
statuslist.append(False)
else:
statuslist.append(True)
vcd=list(vcdprod)
print(vcd)
print(statuslist)
#print(data)
ldb=zip(vcd,statuslist)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"user/vcloud/viewBrands.html",{'pdcts':list(ldb),'user':userdetails})
else:
return redirect(LoginPage)
def uservcloudeditProfile(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(uservcloudprofile)
else:
messages.warning(request,'Internal Error Occured')
return redirect(uservcloudprofile)
else:
return redirect(LoginPage)
def user_buy_vcloud_brands(request):
if request.session.has_key("user"):
if request.method == "POST":
username=request.session["user"]
brand = request.POST.get('brandid', None)
quantity = request.POST.get('quantity', None)
amt = request.POST.get('amt', None)
branddet=vcloudBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=request.session["user"])
#checkqty = vcloudProducts.objects.filter(brand__brand=brand, status=True).exclude(productstatus=1).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('productcount')
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=vcloudProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
content=dict()
licheckqty=list(checkqty)
brand_id=0
deno=0
if(licheckqty[0]['productcount'] >= int(quantity)):
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = vcloudProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
#print(prdctcost)
#print(cost)
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
print(flag)
break;
username=userdet2[0]['sponserId']
if(flag):
try:
prdctcddet=vcloudProducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
#print(h.username)
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'brand':h.brand.brand,'brand_logo':h.brand.logo.url,'password':h.password,'status':h.status,'suser':username,'sdate':h.sdate}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
closeuser=UserData.objects.get(username=request.session["user"])
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Vcloud"
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.quantity = quantity
vcrep.obalance = userdet.balance
vcrep.cbalance = closeuser.balance
vcrep.amount = amt
vcrep.rtype = "Web"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
print(ms)
print(admin)
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
obj = vcloudtransactions.objects.latest('id')
print(obj.id)
content["data"] = result
content["res_status"]="success"
content["trid"]=obj.id
except:
content["res_status"]="Failed"
else:
for i in prdctdet:
i.suser=None
i.save()
content["res_status"]="Failed"
return JsonResponse(content,safe=False)
else:
return redirect(uservcloudStore)
else:
return redirect(LoginPage)
def userfilteredvcloudstore(request,brandtype):
if request.session.has_key("user"):
username=request.session["user"]
buttonclass=[]
ads = adverisements.objects.filter(adtype="Image",usertype="User",ctype="Vcloud").order_by('-id')[:10]
print(brandtype)
if(brandtype=="Cutting"):
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card with cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
data=dict()
content = []
for i in pdcts:
try:
print(i['brand__brand'])
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
#print(lpd)
#print(productcost)
count=0
if not lpd:
pass;
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand_id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'productcount':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'brand__denomination':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
print(content)
except Exception as e:
print(e)
pass;
buttonclass=["btn-warning","btn-success"]
else:
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card without cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
print(pdcts)
data=dict()
content = []
for i in pdcts:
try:
print(i['brand__brand'])
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
#print(lpd)
#print(productcost)
#print(lpd)
count=0
if not lpd:
pass;
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
#print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
#print(margindet)
if(userdet2[0]['postId']=="Admin"):
break;
else:
#print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
#print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand_id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'productcount':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'brand__denomination':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
#print(content)
except Exception as e:
print(e)
pass;
buttonclass=["btn-success","btn-warning"]
buttonlist=["Cutting","Non Cutting"]
btnlist = zip(buttonlist, buttonclass)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"user/vcloud/vcloudStore.html",{'pdcts':content,'btnlist':btnlist,'user':userdetails,'ads':ads})
else:
return redirect(LoginPage)
#________________DCARD_______________
def userDcardDashboard(request):
if request.session.has_key("user"):
last_month = datetime.today() - timedelta(days=1)
#print(last_month)
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,type="Dcard",saleduser__username=username).order_by('-date')
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"obalance":i.obalance,"cbalance":i.cbalance,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = datacardAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
for i in brand:
pd=datacardproducts.objects.filter(brand=i['brand__id'], status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass;
#break;
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=datacardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
return render(request,"user/dcard/dashboard-dcard.html",{'filterform':userdcardDashboardfilter,'recenttransactions':content,'products':product,'user':userdetails,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filteruserDcardDashboard(request):
if request.session.has_key("user"):
if request.method == "POST":
form = userdcardDashboardfilter(request.POST or None)
print("Haiii")
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
#mffromdate=datetime.strptime(fromdate, '%b %d %Y %I:%M%p')
#print(type(fromdate))
print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
userdetails = UserData.objects.get(username=request.session["user"])
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,type="Dcard",saleduser__username=currentuser).order_by('-date')
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"obalance":i.obalance,"cbalance":i.cbalance,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = datacardAssignments.objects.filter(assignedto=currentuser).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=datacardproducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=datacardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
#print(product)
return render(request,"user/dcard/dashboard-dcard.html",{'filterform':userdcardDashboardfilter,'recenttransactions':content,'products':product,'user':userdetails,'last_month':last_month,'boxval':box_data})
else:
return redirect(userDcardDashboard)
else:
return redirect(userDcardDashboard)
else:
return redirect(LoginPage)
def userprofiledcard(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"user/dcard/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def userdatacardreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,saleduser__username=username).order_by('-date')
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"obalance":i.obalance,"cbalance":i.cbalance,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"user/dcard/dcardreport.html",{'filterform':uservcloudreportfilterform,'products':content,'user':userdetails,'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filteruserdcard_report(request):
if request.session.has_key("user"):
if request.method=="POST":
form = uservcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
#print(brand,fusername)
filter={'ffdate':fromdate,'ttdate':todate}
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
userdetails = UserData.objects.get(username=username)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
vcloudtxns=vcloudtransactions()
try:
print(type)
print(brand)
if(type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username).order_by('-date')
print("One")
elif(type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username, brand=brand).order_by('-date')
elif(type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username, type=type).order_by('-date')
else:
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username, brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"obalance":i.obalance,"cbalance":i.cbalance,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+0
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"user/dcard/dcardreport.html",{'filterform':uservcloudreportfilterform,'products':content,'user':userdetails, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(userdatacardreport)
else:
return redirect(userdatacardreport)
else:
return redirect(LoginPage)
def userdcardstore(request):
if request.session.has_key("user"):
username=request.session["user"]
user = UserData.objects.get(username=username)
btnlist=list()
content=list()
ads = adverisements.objects.filter(adtype="Image",usertype="User",ctype="Dcard").order_by('-id')[:10]
dproducts = datacardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
if(len(btnlist)==0):
pass
else:
dcardproducts = datacardAssignments.objects.filter(assignedto=username,brand__brand__contains=btnlist[0]).order_by('brand').values('brand__brand','margin')
print(dcardproducts)
#print(buttons)
for i in dcardproducts:
dcp=datacardproducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getDatacardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
else:
pass
return render(request,"user/dcard/datastore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def userfilterdcardstore(request,brandtype):
if request.session.has_key("user"):
#print(brand)
username = request.session['user']
user=UserData.objects.get(username=username)
btnlist=list()
ads = adverisements.objects.filter(adtype="Image",usertype="User",ctype="Dcard").order_by('-id')[:10]
dproducts = datacardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for j in dproducts:
buttons=(j["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
dcardproducts = datacardAssignments.objects.filter(assignedto=username,brand__brand__contains=brandtype).order_by('brand').values('brand__brand','margin')
print(dcardproducts)
content=list()
for i in dcardproducts:
dcp=datacardproducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getDatacardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
else:
pass;
print(content)
return render(request,"user/dcard/datastore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def usereditProfileDcard(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(userprofiledcard)
else:
messages.warning(request,'Internal Error Occured')
return redirect(userprofiledcard)
else:
return redirect(LoginPage)
def user_buy_datacard_brands(request):
if request.session.has_key("user"):
if request.method == "POST":
username=request.session["user"]
brand = request.POST.get('brandid', None)
quantity = request.POST.get('quantity', None)
amt = request.POST.get('amt', None)
branddet=dcardBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=request.session["user"])
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=datacardproducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
content=dict()
licheckqty=list(checkqty)
brand_id=0
deno=0
if(licheckqty[0]['productcount'] >= int(quantity)):
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = datacardproducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=datacardAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
#print(prdctcost)
#print(cost)
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
print(flag)
break;
username=userdet2[0]['sponserId']
if(flag):
try:
prdctcddet=datacardproducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'brand':h.brand.brand,'brand_logo':h.brand.logo.url, 'status':h.status,'suser':username,'sdate':h.sdate}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
closeuser=UserData.objects.get(username=request.session["user"])
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Dcard"
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.quantity = quantity
vcrep.obalance = userdet.balance
vcrep.cbalance = closeuser.balance
vcrep.amount = amt
vcrep.rtype = "Web"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
obj = vcloudtransactions.objects.latest('id')
print(obj.id)
content["data"] = result
content["res_status"]="success"
content["trid"]=obj.id
except:
content["res_status"]="Failed"
else:
for i in prdctdet:
i.suser=None
i.save()
content["res_status"]="Failed"
return JsonResponse(content,safe=False)
else:
return redirect(userdcardstore)
else:
return redirect(LoginPage)
def userdcardviewbrands(request):
if request.session.has_key("user"):
username = request.session["user"]
vcdprod=dcardBrands.objects.all()
resultlist=list()
statuslist=list()
for i in vcdprod:
vca=datacardAssignments.objects.filter(assignedto=username,brand__brand=i.brand)
if not vca:
statuslist.append(False)
else:
statuslist.append(True)
vcd=list(vcdprod)
print(vcd)
print(statuslist)
#print(data)
ldb=zip(vcd,statuslist)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"user/dcard/viewBrands.html",{'pdcts':list(ldb),'user':userdetails})
else:
return redirect(LoginPage)
#________________RCARD_______________
def userRcardDashboard(request):
if request.session.has_key("user"):
last_month = datetime.today() - timedelta(days=1)
username = request.session["user"]
type = request.session["usertype"]
try:
user = UserData.objects.get(username = username, postId = type)
except UserData.DoesNotExist:
return redirect(LoginPage)
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,type="Rcard",saleduser__username=username).order_by('-date')
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"obalance":i.obalance,"cbalance":i.cbalance,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = rcardAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=rcardProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=rcardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
print(product)
return render(request,"user/rcard/dashboard-rcard.html",{'filterform':userrcardDashboardfilter,'recenttransactions':content,'products':product,'user':user,'last_month':last_month,'boxval':box_data})
else:
return redirect(LoginPage)
def filteruserrcardDashboard(request):
if request.session.has_key("user"):
if request.method == "POST":
form = userrcardDashboardfilter(request.POST or None)
print("Haiii")
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
#mffromdate=datetime.strptime(fromdate, '%b %d %Y %I:%M%p')
#print(type(fromdate))
print(fromdate.strftime("%B %d, %Y"))
last_month=fromdate.strftime("%B %d, %I:%M %p")+" To "+todate.strftime("%B %d, %I:%M %p")
userdetails = UserData.objects.get(username=request.session["user"])
vcloudtxns = vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,type="Rcard",saleduser__username=currentuser).order_by('-date')
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
for i in vcloudtxns:
count=count+1
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"obalance":i.obalance,"cbalance":i.cbalance,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum,'noofrecords':count}
brand = rcardAssignments.objects.filter(assignedto=currentuser).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
product=list()
print(brand)
for i in brand:
print(i['brand__id'])
pd=rcardProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
#print("Haiii")
else:
username=request.session["user"]
productcost=Decimal(lpd[0]['brand__denomination'])
print(productcost)
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
print(userdet2)
margindet=rcardAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
print(margindet[0]['margin'])
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
print(productcost)
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand":lpd[0]['brand__brand'],'rate':productcost}
product.append(data)
#print(content)
#print(product)
return render(request,"user/rcard/dashboard-rcard.html",{'filterform':userrcardDashboardfilter,'recenttransactions':content,'products':product,'user':userdetails,'last_month':last_month,'boxval':box_data})
else:
return redirect(userRcardDashboard)
else:
return redirect(userRcardDashboard)
else:
return redirect(LoginPage)
def userprofileRcard(request):
if request.session.has_key("user"):
user = request.session["user"]
userDet = UserData.objects.get(username=user)
return render(request,"user/rcard/editProfile.html",{'user':userDet})
else:
return redirect(LoginPage)
def userrcardreport(request):
if request.session.has_key("user"):
userdetails = UserData.objects.get(username=request.session["user"])
username=request.session["user"]
last_month = datetime.today() - timedelta(days=1)
vcloudtxns = vcloudtransactions.objects.filter(date__gte=last_month,saleduser__username=username).order_by('-date')
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"obalance":i.obalance,"cbalance":i.cbalance,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"user/rcard/rcardreport.html",{'filterform':uservcloudreportfilterform,'products':content,'user':userdetails,'brand':vcbrandlist,'box':box_data,'date':last_month})
else:
return redirect(LoginPage)
def filteruserrcard_report(request):
if request.session.has_key("user"):
if request.method=="POST":
form = uservcloudreportfilterform(request.POST or None)
print(form.errors)
if form.is_valid():
username=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
type=form.cleaned_data.get("type")
brand=form.cleaned_data.get("brand")
#print(brand,fusername)
filter={'ffdate':fromdate,'ttdate':todate}
vcbrand=vcloudBrands.objects.all()
vcbrandlist=list()
for b in vcbrand:
branddata={'brand':b.brand}
vcbrandlist.append(branddata)
userdetails = UserData.objects.get(username=username)
content=list()
noofrecords = 0
productsum = 0
quantitysum = 0
profitsum = 0
vcloudtxns=vcloudtransactions()
try:
print(type)
print(brand)
if(type=="All" and brand=="All"):
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username).order_by('-date')
print("One")
elif(type=="All" and brand !="All"):
print("TWo")
vcloudtxns==vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username, brand=brand).order_by('-date')
elif(type !="All" and brand =="All"):
print("Three")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username, type=type).order_by('-date')
else:
print("four")
vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate, saleduser__username=username, brand=brand).order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0,"rtype":i.rtype}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = profitsum+0
except:
pass
box_data={'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return render(request,"user/rcard/rcardreport.html",{'filterform':uservcloudreportfilterform,'products':content,'user':userdetails, 'brand':vcbrandlist,'box':box_data,'filter':filter})
else:
return redirect(userdatacardreport)
else:
return redirect(userdatacardreport)
else:
return redirect(LoginPage)
def userrcardstore(request):
if request.session.has_key("user"):
username=request.session["user"]
user = UserData.objects.get(username=username)
ads = adverisements.objects.filter(adtype="Image",usertype="User",ctype="Rcard").order_by('-id')[:10]
btnlist=list()
dproducts = rcardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
content=list()
if(len(btnlist)==0):
pass
else:
dcardproducts = rcardAssignments.objects.filter(assignedto=username,brand__brand__contains=btnlist[0]).order_by('brand').values('brand__brand','margin')
for i in dcardproducts:
dcp=rcardProducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getRcardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
else:
pass
return render(request,"user/rcard/rcardstore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def userfilterrcardstore(request,brand):
if request.session.has_key("user"):
#print(brand)
username=request.session["user"]
ads = adverisements.objects.filter(adtype="Image",usertype="User",ctype="Rcard").order_by('-id')[:10]
user = UserData.objects.get(username=username)
btnlist=list()
dproducts = rcardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
dcardproducts = rcardAssignments.objects.filter(assignedto=username,brand__brand__contains=brand).order_by('brand').values('brand__brand','margin')
content=list()
#print(buttons)
for i in dcardproducts:
dcp=rcardProducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getRcardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
else:
pass
return render(request,"user/rcard/rcardstore.html",{'dcardproducts':content,'btnlist':btnlist,'user':user,'ads':ads})
else:
return redirect(LoginPage)
def user_buy_rcard_brands(request):
if request.session.has_key("user"):
if request.method == "POST":
username=request.session["user"]
brand = request.POST.get('brandid', None)
quantity = request.POST.get('quantity', None)
amt = request.POST.get('amt', None)
branddet=rcardBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=request.session["user"])
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=rcardProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
content=dict()
licheckqty=list(checkqty)
brand_id=0
deno=0
if(licheckqty[0]['productcount'] >= int(quantity)):
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = rcardProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=rcardAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
#print(prdctcost)
#print(cost)
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
print(flag)
break;
username=userdet2[0]['sponserId']
if(flag):
try:
prdctcddet=rcardProducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'brand':h.brand.brand,'brand_logo':h.brand.logo.url, 'status':h.status,'suser':username,'sdate':h.sdate}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
closeuser=UserData.objects.get(username=request.session["user"])
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Rcard"
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.quantity = quantity
vcrep.obalance = userdet.balance
vcrep.cbalance = closeuser.balance
vcrep.amount = amt
vcrep.rtype = "Web"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
obj = vcloudtransactions.objects.latest('id')
print(obj.id)
content["data"] = result
content["res_status"]="success"
content["trid"]=obj.id
except:
content["res_status"]="Failed"
else:
for i in prdctdet:
i.suser=None
i.save()
content["res_status"]="Failed"
return JsonResponse(content,safe=False)
else:
return redirect(userrcardstore)
else:
return redirect(LoginPage)
def userrcardviewbrands(request):
if request.session.has_key("user"):
if request.session.has_key("user"):
username = request.session["user"]
vcdprod=rcardBrands.objects.all()
resultlist=list()
statuslist=list()
for i in vcdprod:
vca=rcardAssignments.objects.filter(assignedto=username,brand__brand=i.brand)
if not vca:
statuslist.append(False)
else:
statuslist.append(True)
vcd=list(vcdprod)
print(vcd)
print(statuslist)
#print(data)
ldb=zip(vcd,statuslist)
userdetails = UserData.objects.get(username=request.session["user"])
return render(request,"user/rcard/viewBrands.html",{'pdcts':list(ldb),'user':userdetails})
else:
return redirect(LoginPage)
def usereditProfilercard(request):
if request.session.has_key("user"):
if request.method == "POST":
user = request.session["user"]
name = request.POST.get('name', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
mobileno = request.POST.get('mobileno', None)
userDet = UserData.objects.get(username=user)
userDet.name = name
userDet.address = address
userDet.email = email
userDet.mobileno = mobileno
userDet.save()
messages.success(request, 'Successfully Updated')
return redirect(subresellerprofilercard)
else:
messages.warning(request,'Internal Error Occured')
return redirect(subresellerprofilercard)
else:
return redirect(LoginPage)
#________________Need To Host_______________
def addcsvProduct(request):
if request.session.has_key("user"):
user=request.session["user"]
userdet=UserData.objects.get(username=user)
brands=vcloudBrands.objects.values('id','brand')
vlogs=vclouduplogs.objects.all().order_by('-cdate');
return render(request,"admin/vcloud/addcsvproduct.html",{'form':addvcloudproductascsv,'brands':brands,'user':userdet,'vlogs':vlogs})
else:
return redirect(LoginPage)
def vcloudcsvupload(request):
if request.session.has_key("user"):
if request.method == "POST":
try:
form = addvcloudproductascsv(request.POST, request.FILES)
if form.is_valid():
brand = form.cleaned_data.get("brand")
csvfile = request.FILES['filename']
print(csvfile.name)
filedata = csvfile.read().decode("utf-8")
lines = filedata.split("\r\n")
scount=0
pcount=0
content=list()
count=0
for line in lines:
print(line)
if(line!=''):
count=count+1
print(count)
flag=True
fields = line.split(",")
data_dict = {}
print(fields[0])
print(fields[1])
data_dict["username"] = fields[0]
data_dict["password"] = fields[1]
res=vcloudProducts.objects.filter(username = data_dict["username"]).exists()
print(res)
res1=vcloudupproducts.objects.filter(username = data_dict["username"]).exists()
#print(res2)
if(res==True or res1==True):
print(res)
print(res1)
pcount=pcount+1
print("Exist");
print("------------")
print(data_dict["username"])
else:
pcount=pcount+1
scount=scount+1
content.append(data_dict)
print(res)
print(res1)
print("Not Exist")
else:
pass
#print(data_dict["username"])
#print(flag)
print(content)
print(scount)
print(pcount)
user = UserData.objects.get(username=request.session["user"])
bd = vcloudBrands.objects.get(id=brand)
#print(bd.id)
vclog=vclouduplogs()
vclog.brand = bd
vclog.user = user
vclog.file = csvfile
vclog.scount = scount
vclog.pcount = pcount
vclog.save()
lid=vclouduplogs.objects.latest('id')
#print(lid.id)
vcpbj=vclouduplogs.objects.get(id=lid.id)
#print(vcpbj)
for item in content:
print(item["username"]);
vcpd=vcloudupproducts()
vcpd.fileid=vcpbj
vcpd.brand=bd
vcpd.denomination=bd.denomination
vcpd.username=item["username"]
vcpd.password=item["password"]
vcpd.save()
messages.success(request,"SuccessFully Added The Csv")
else:
messages.warning(request,form.errors)
return redirect(addcsvProduct)
except Exception as e:
print(e)
messages.warning(request,form.errors)
return redirect(addcsvProduct)
return redirect(addcsvProduct)
else:
return redirect(LoginPage)
def vcloudlogtoproduct(request,id):
if request.session.has_key("user"):
print(id)
vlog = vclouduplogs.objects.get(id=id)
vcprod = vcloudupproducts.objects.filter(fileid=vlog.id)
for item in vcprod:
vcprd=vcloudProducts()
vcprd.brand=vlog.brand
vcprd.username=item.username
vcprd.password=item.password
vcprd.denomination=item.denomination
vcprd.fileid=vlog
vcprd.save()
vlog.status=False
vlog.sdate=datetime.now()
vlog.save()
return redirect(addcsvProduct)
else:
return redirect(addcsvProduct)
def adddcardcsvProduct(request):
if request.session.has_key("user"):
user=request.session["user"]
userdet=UserData.objects.get(username=user)
brands=dcardBrands.objects.values('id','brand')
vlogs=dcarduplogs.objects.all().order_by('-cdate');
return render(request,"admin/dcard/addcsvproduct.html",{'form':adddcardproductascsv,'brands':brands,'user':userdet,'vlogs':vlogs})
else:
return redirect(LoginPage)
def dcardcsvupload(request):
if request.session.has_key("user"):
if request.method == "POST":
form = adddcardproductascsv(request.POST, request.FILES)
if form.is_valid():
brand = form.cleaned_data.get("brand")
csvfile = request.FILES['filename']
print(csvfile.name)
filedata = csvfile.read().decode("utf-8")
lines = filedata.split("\r\n")
scount=0
pcount=0
content=list()
for line in lines:
if(line != ''):
fields = line.split(",")
data_dict = {}
data_dict["username"] = fields[0]
res=datacardproducts.objects.filter(username = data_dict["username"]).exists()
print(res)
res2=dcardupproducts.objects.filter(username = data_dict["username"]).exists()
print(res2)
if(res==True or res2==True):
pcount=pcount+1
else:
pcount=pcount+1
scount=scount+1
content.append(data_dict)
else:
pass
#print(brand)
print(content)
user = UserData.objects.get(username=request.session["user"])
bd = dcardBrands.objects.get(id=int(brand))
print(bd.id)
vclog=dcarduplogs()
vclog.brand = bd
vclog.user = user
vclog.file = csvfile
vclog.scount = scount
vclog.pcount = pcount
vclog.save()
lid=dcarduplogs.objects.latest('id')
print(lid.id)
vcpbj=dcarduplogs.objects.get(id=lid.id)
print(vcpbj)
for item in content:
vcpd=dcardupproducts()
vcpd.fileid=vcpbj
vcpd.brand=bd
vcpd.denomination=bd.denomination
vcpd.username = item["username"]
vcpd.save()
messages.success(request,"SuccessFully Added The Csv")
else:
messages.warning(request,form.errors)
return redirect(adddcardcsvProduct)
return redirect(adddcardcsvProduct)
else:
return redirect(LoginPage)
def dcardlogtoproduct(request,id):
if request.session.has_key("user"):
print(id)
vlog = dcarduplogs.objects.get(id=id)
vcprod = dcardupproducts.objects.filter(fileid=vlog.id)
for item in vcprod:
vcprd=datacardproducts()
vcprd.brand=vlog.brand
vcprd.username=item.username
vcprd.denomination=item.denomination
vcprd.fileid=vlog
vcprd.save()
vlog.status=False
vlog.sdate=datetime.now()
vlog.save()
return redirect(adddcardcsvProduct)
else:
return redirect(adddcardcsvProduct)
def addrcardcsvProduct(request):
if request.session.has_key("user"):
user=request.session["user"]
userdet=UserData.objects.get(username=user)
brands=rcardBrands.objects.values('id','brand')
vlogs=rcarduplogs.objects.all().order_by('-cdate');
return render(request,"admin/rcard/addcsvproduct.html",{'form':addrcardproductascsv,'brands':brands,'user':userdet,'vlogs':vlogs})
else:
return redirect(LoginPage)
def rcardcsvupload(request):
if request.session.has_key("user"):
if request.method == "POST":
form = addrcardproductascsv(request.POST, request.FILES)
if form.is_valid():
brand = form.cleaned_data.get("brand")
csvfile = request.FILES['filename']
print(csvfile.name)
filedata = csvfile.read().decode("utf-8")
lines = filedata.split("\r\n")
scount=0
pcount=0
content=list()
for line in lines:
if(line!=''):
fields = line.split(",")
data_dict = {}
data_dict["username"] = fields[0]
res=rcardProducts.objects.filter(username = data_dict["username"]).exists()
print(res)
res2=rcardupproducts.objects.filter(username = data_dict["username"]).exists()
print(res2)
if(res==True or res2==True):
print(fields[0])
pcount=pcount+1
else:
pcount=pcount+1
scount=scount+1
content.append(data_dict)
else:
pass
print(content)
user = UserData.objects.get(username=request.session["user"])
bd = rcardBrands.objects.get(id=int(brand))
print(bd.id)
vclog=rcarduplogs()
vclog.brand = bd
vclog.user = user
vclog.file = csvfile
vclog.scount = scount
vclog.pcount = pcount
vclog.save()
lid=rcarduplogs.objects.latest('id')
print(lid.id)
vcpbj=rcarduplogs.objects.get(id=lid.id)
print(vcpbj)
for item in content:
vcpd=rcardupproducts()
vcpd.fileid=vcpbj
vcpd.brand=bd
vcpd.denomination=bd.denomination
vcpd.username=item["username"]
vcpd.save()
messages.success(request,"SuccessFully Added The Csv")
else:
messages.warning(request,form.errors)
return redirect(addrcardcsvProduct)
return redirect(addrcardcsvProduct)
else:
return redirect(LoginPage)
def rcardlogtoproduct(request,id):
if request.session.has_key("user"):
#print(id)
vlog = rcarduplogs.objects.get(id=id)
vcprod = rcardupproducts.objects.filter(fileid=vlog.id)
for item in vcprod:
vcprd=rcardProducts()
vcprd.brand=vlog.brand
vcprd.username=item.username
vcprd.denomination=item.denomination
vcprd.fileid=vlog
vcprd.save()
vlog.status=False
vlog.sdate=datetime.now()
vlog.save()
return redirect(addrcardcsvProduct)
else:
return redirect(addrcardcsvProduct)
def vcloudchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"admin/vcloud/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def submitvcloudchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(vcloudchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(vcloudchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(vcloudchangepassword)
else:
messages.warning(request,form.errors)
return redirect(vcloudchangepassword)
else:
return redirect(vcloudchangepassword)
else:
return(LoginPage)
def dcardchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"admin/dcard/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def submitdcardchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(dcardchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(dcardchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(dcardchangepassword)
else:
messages.warning(request,form.errors)
return redirect(dcardchangepassword)
else:
return redirect(dcardchangepassword)
else:
return(LoginPage)
def rcardchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"admin/rcard/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def submitrcardchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(rcardchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(rcardchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(rcardchangepassword)
else:
messages.warning(request,form.errors)
return redirect(rcardchangepassword)
else:
return redirect(rcardchangepassword)
else:
return(LoginPage)
def resellervcloudchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"reseller/vcloud/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def resellersubmitvcloudchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(resellervcloudchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(resellervcloudchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(resellervcloudchangepassword)
else:
messages.warning(request,form.errors)
return redirect(resellervcloudchangepassword)
else:
return redirect(resellervcloudchangepassword)
else:
return(LoginPage)
def resellerdcardchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"reseller/dcard/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def resellersubmitdcardchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(resellerdcardchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(resellerdcardchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(resellerdcardchangepassword)
else:
messages.warning(request,form.errors)
return redirect(resellerdcardchangepassword)
else:
return redirect(resellerdcardchangepassword)
else:
return(LoginPage)
def resellerrcardchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"reseller/rcard/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def resellersubmitrcardchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(resellerrcardchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(resellerrcardchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(resellerrcardchangepassword)
else:
messages.warning(request,form.errors)
return redirect(resellerrcardchangepassword)
else:
return redirect(resellerrcardchangepassword)
else:
return(LoginPage)
def subresellervcloudchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/vcloud/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def subresellersubmitvcloudchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(subresellervcloudchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(subresellervcloudchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(subresellervcloudchangepassword)
else:
messages.warning(request,form.errors)
return redirect(subresellervcloudchangepassword)
else:
return redirect(subresellervcloudchangepassword)
else:
return(LoginPage)
def subresellerdcardchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/dcard/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def subresellersubmitdcardchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(subresellerdcardchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(subresellerdcardchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(subresellerdcardchangepassword)
else:
messages.warning(request,form.errors)
return redirect(subresellerdcardchangepassword)
else:
return redirect(subresellerdcardchangepassword)
else:
return(LoginPage)
def subresellerrcardchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"sub_reseller/rcard/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def subresellersubmitrcardchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(subresellerrcardchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(subresellerrcardchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(subresellerrcardchangepassword)
else:
messages.warning(request,form.errors)
return redirect(subresellerrcardchangepassword)
else:
return redirect(subresellerrcardchangepassword)
else:
return(LoginPage)
def uservcloudchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"user/vcloud/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def usersubmitvcloudchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(uservcloudchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(uservcloudchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(uservcloudchangepassword)
else:
messages.warning(request,form.errors)
return redirect(uservcloudchangepassword)
else:
return redirect(uservcloudchangepassword)
else:
return(LoginPage)
def userdcardchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"user/dcard/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def usersubmitdcardchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(userdcardchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(userdcardchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(userdcardchangepassword)
else:
messages.warning(request,form.errors)
return redirect(userdcardchangepassword)
else:
return redirect(userdcardchangepassword)
else:
return(LoginPage)
def userrcardchangepassword(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
return render(request,"user/rcard/changepassword.html",{'form':changepassword,'user':userdet})
else:
return redirect(LoginPage)
def usersubmitrcardchangepassword(request):
if request.session.has_key("user"):
if request.method=="POST":
form = changepassword(request.POST or None)
if form.is_valid():
username = request.session["user"]
cpassword = form.cleaned_data.get("cpassword")
npassword = form.cleaned_data.get("npassword")
cnpassword = form.cleaned_data.get("cnpassword")
if(npassword==cnpassword):
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
messages.success(request,"Password Changed Successfully.!")
return redirect(userrcardchangepassword)
else:
messages.warning(request,"Incorrect Password, Try Again.!")
return redirect(userrcardchangepassword)
else:
messages.warning(request,"Passwords Are Not Matching.!")
return redirect(userrcardchangepassword)
else:
messages.warning(request,form.errors)
return redirect(userrcardchangepassword)
else:
return redirect(userrcardchangepassword)
else:
return(LoginPage)
def resetpasswordvcloudreseller(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(vcloudviewReseller)
def resetpasswordvclouduser(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(vcloudviewUser)
def resetpassworddcardreseller(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(dcardviewReseller)
def resetpassworddcarduser(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(dcardviewUser)
def resetpasswordrcardreseller(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(rcardviewReseller)
def resetpasswordrcarduser(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(rcardviewUser)
def resetpasswordresellervcloudreseller(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(resellervcloudviewReseller)
def resetpasswordresellervclouduser(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(resellervcloudviewUser)
def resetpasswordresellerdcardreseller(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(resellerviewResellerDcard)
def resetpasswordresellerdcarduser(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(resellerviewUserDcard)
def resetpasswordresellerrcardreseller(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(resellerviewResellerRcard)
def resetpasswordresellerrcarduser(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(resellerviewUserRcard)
def resetpasswordsubresellervclouduser(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(subresellervcloudviewUser)
def resetpasswordsubresellerdcarduser(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(subresellerviewUserDcard)
def vcloudchangeResellerStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(vcloudviewReseller)
def dcardchangeResellerStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(dcardviewReseller)
def rcardchangeResellerStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(rcardviewReseller)
def vcloudchangeUserStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(vcloudviewUser)
def dcardchangeUserStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(dcardviewUser)
def rcardchangeUserStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(rcardviewUser)
def resellervcloudchangeResellerStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(resellervcloudviewReseller)
def resellerdcardchangeResellerStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(resellerviewResellerDcard)
def resellerrcardchangeResellerStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(resellerviewResellerRcard)
def resellervcloudchangeUserStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(resellervcloudviewUser)
def resellerdcardchangeUserStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(resellerviewUserDcard)
def resellerrcardchangeUserStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(resellerviewUserRcard)
def subresellervcloudchangeUserStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(subresellervcloudviewUser)
def subresellerdcardchangeUserStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(subresellerviewUserDcard)
def subresellerrcardchangeUserStatus(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
if(userdet.status):
userdet.status=False
userdet.save()
else:
userdet.status=True
userdet.save()
return redirect(subresellerviewUserRcard)
def resetpasswordsubresellerrcarduser(request,username):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=username)
password=username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
print(username)
return redirect(subresellerviewUserRcard)
def vcloudcardsdownloads(request,id):
print(id)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
pddet=vcloudProducts.objects.get(id=id)
imagelogo=pddet.brand.logo.url
str=imagelogo.replace("%20", " ")
print(str)
logo = str.lstrip('/')
print(image)
print(logo)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
draw.text((100, 290),"Password : "+pddet.password,(0,0,0),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
def dcardcardsdownloads(request,id):
print(id)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
pddet=datacardproducts.objects.get(id=id)
imagelogo=pddet.brand.logo.url
str=imagelogo.replace("%20", " ")
print(str)
logo = str.lstrip('/')
print(image)
print(logo)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
#draw.text((100, 290),"Password : "+pddet.password,(255,255,255),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
def rcardcardsdownloads(request,id):
print(id)
image="media/img/card.png"
img = Image.open(image)
draw = ImageDraw.Draw(img)
fontpath = os.path.join(settings.BASE_DIR, "static/pfont/sans_serif.ttf")
print(fontpath)
font = ImageFont.truetype(fontpath, 16)
pddet=rcardProducts.objects.get(id=id)
imagelogo=pddet.brand.logo.url
str=imagelogo.replace("%20", " ")
print(str)
logo = str.lstrip('/')
print(image)
print(logo)
draw.text((100, 200),"Owner : "+pddet.suser.name,(0,0,0),font=font)
draw.text((100, 230),"Brand : "+pddet.brand.brand,(0,0,0),font=font)
draw.text((100, 260),"Username : "+pddet.username,(0,0,0),font=font)
#draw.text((100, 290),"Password : "+pddet.password,(255,255,255),font=font)
img.save('media/img/sample-out.png')
dimage = Image.open(os.path.join(settings.MEDIA_ROOT, "img/sample-out.png"))
print(dimage)
filename = dimage.filename
print(filename)
wrapper = FileWrapper(open(filename,'rb'))
content_type = mimetypes.guess_type(filename)[0]
print(content_type)
response = HttpResponse(wrapper, content_type='content_type')
response['Content-Disposition'] = "attachment; filename=card.png"
return response
#return redirect(vcloudreport)
def uservcloudpaymentreport(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
phist = fundTransactionReport.objects.filter(destination=userdet).order_by('-date')[:40]
return render(request,"user/vcloud/paymentReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(LoginPage)
def filteruservcloudpaymentreport(request):
if request.session.has_key("user"):
if request.method == "POST":
form = datefilterform(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
userdet=UserData.objects.get(username=currentuser)
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdet).order_by('-date')
return render(request,"user/vcloud/paymentReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(uservcloudpaymentreport)
else:
return redirect(uservcloudpaymentreport)
else:
return redirect(LoginPage)
def userdcardpaymentreport(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
phist = fundTransactionReport.objects.filter(destination=userdet).order_by('-date')
return render(request,"user/dcard/paymentReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(LoginPage)
def filteruserdcardpaymentreport(request):
if request.session.has_key("user"):
if request.method == "POST":
form = datefilterform(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
userdet=UserData.objects.get(username=currentuser)
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdet).order_by('-date')
return render(request,"user/dcard/paymentReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(userdcardpaymentreport)
else:
return redirect(userdcardpaymentreport)
else:
return redirect(LoginPage)
def userrcardpaymentreport(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
phist = fundTransactionReport.objects.filter(destination=userdet).order_by('-date')
return render(request,"user/rcard/paymentReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(LoginPage)
def filteruserrcardpaymentreport(request):
if request.session.has_key("user"):
if request.method == "POST":
form = datefilterform(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
userdet=UserData.objects.get(username=currentuser)
phist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdet).order_by('-date')
return render(request,"user/rcard/paymentReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(userrcardpaymentreport)
else:
return redirect(userrcardpaymentreport)
else:
return redirect(LoginPage)
#_________________________________________________________________________________API__________________________________________________________________________
#def voiplogin(request):
class UserLogin(APIView):
def get(self, request):
username = request.GET['username']
password = request.GET['password']
print(username)
print(password)
return Response(status=status.HTTP_302_FOUND)
#pass;
def post(self,request):
"""
User Authentication Api.\n
Arguments :\n
username - String
password - String
"""
username = request.POST['username']
password = request.POST['password']
print(username)
print(password)
hashkey = username+password
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
userdata=UserDataSerializer(user,many=True)
return Response(userdata.data,status=status.HTTP_302_FOUND)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
login_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(login_schema)
def apiLogin(request):
username = request.data.get("username")
try:
user = UserData.objects.get(username=username)
print(user.status)
if(user):
if(user.status):
userdata=UserDataSerializer(user)
return Response({'success':True,'data':userdata.data}, status=HTTP_200_OK)
else:
return Response({'success': False,'message':'Login Restricted By Parent'}, status=HTTP_200_OK)
else:
return Response({'success': False, 'message':'Invalid Credentials'},status=HTTP_200_OK)
except:
return Response({'success': False, 'message':'Invalid Credentials'},status=HTTP_200_OK)
resellerlist_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(resellerlist_schema)
def apiGetAllResellerList(request):
"""
<h3 style="color:green;">Get All Reseller List Under A User.</h3>
"""
username = request.data.get("username")
user = UserData.objects.get(username=username)
if(user.postId=="Admin"):
resellers = UserData.objects.filter(sponserId=user,postId="Reseller")
if(resellers):
users = ResellerOrUserListSerializer(resellers,many=True)
return Response({'success':True, 'data':users.data},status=HTTP_200_OK)
else:
return Response({'success':True, 'data':[]},status=HTTP_200_OK)
elif(user.postId=="Reseller"):
resellers = UserData.objects.filter(sponserId=username,postId="Sub_Reseller")
if(resellers):
users = ResellerOrUserListSerializer(resellers,many=True)
return Response({'success':True,'data':users.data},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
else:
return Response({'success':'False','message':'Error Occured'},status=HTTP_200_OK)
userlist_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(userlist_schema)
def apiGetAllUserList(request):
try:
username = request.data.get("username")
user = UserData.objects.get(username=username)
users = UserData.objects.filter(sponserId=user)
if(users):
userdata = ResellerOrUserListSerializer(users,many=True)
return Response({'success':True,'data':userdata.data},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
getsingleuser_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("user", required=True, location="form", type="string", description="user"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(getsingleuser_schema)
def apiGetSingleUserDetails(request):
try:
username = request.data.get("user")
user = UserData.objects.get(username=username)
userdata = SingleUserDetailsSerializer(user)
return Response({'success':True,'data':userdata.data},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Invalid User'},status=HTTP_200_OK)
balancetransfer_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("user", required=True, location="form", type="string", description="username"),
coreapi.Field("amount", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(balancetransfer_schema)
def apiBalanceTransfer(request):
username = request.data.get("username")
sponser = request.data.get("user")
amount = request.data.get("amount")
try:
sponserdet = UserData.objects.get(username=sponser)
bal = sponserdet.balance
newbal=bal+Decimal(amount)
cdbal = sponserdet.targetAmt
newcdbal = cdbal-Decimal(amount)
sponserdet.targetAmt = newcdbal
sponserdet.balance = newbal
sponserdet.save()
userdetails = UserData.objects.get(username=username)
btreport = balanceTransactionReport()
btreport.source = userdetails
btreport.destination = sponserdet
btreport.category = "BT"
btreport.amount = amount
btreport.pbalance = bal
btreport.nbalance = newbal
btreport.cramount = newcdbal
btreport.remarks = 'Added To Balance'
btreport.save()
data={'balance':newbal,'credit':newcdbal}
return Response({'success':True,'data':data},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
fundtransfer_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("user", required=True, location="form", type="string", description="sponser"),
coreapi.Field("amount", required=True, location="form", type="string", description="amount"),
coreapi.Field("remarks", required=True, location="form", type="string", description="remarks"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(fundtransfer_schema)
def apiFundTransfer(request):
username = request.data.get("username")
sponser = request.data.get("user")
amount = request.data.get("amount")
remarks = request.data.get("remarks")
try:
sponserdet = UserData.objects.get(username=sponser)
print(sponserdet.username)
obalance = sponserdet.targetAmt
print(obalance)
cdbal = sponserdet.targetAmt
newcdbal = cdbal+Decimal(amount)
sponserdet.targetAmt = newcdbal
sponserdet.save()
closeuser = UserData.objects.get(username=sponser)
print(closeuser)
userdetails = UserData.objects.get(username=username)
print(userdetails)
ftreport=fundTransactionReport()
ftreport.source = userdetails
ftreport.destination = sponserdet
ftreport.obalance = obalance
ftreport.cbalance = closeuser.targetAmt
ftreport.role = sponserdet.postId
ftreport.amount = amount
ftreport.balance = newcdbal
ftreport.remarks = remarks
ftreport.save()
data={'credit':newcdbal}
return Response({'success':True,'data':data},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
changepassword_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("cpassword", required=True, location="form", type="string", description="cpassword"),
coreapi.Field("npassword", required=True, location="form", type="string", description="npassword"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(changepassword_schema)
def apiChangePassword(request):
username = request.data.get("username")
cpassword = request.data.get("cpassword")
npassword = request.data.get("npassword")
hashkey = username+cpassword
hash = hashlib.sha256(hashkey.encode()).hexdigest()
if (UserData.objects.filter(username = username, password = hash)).exists():
user = UserData.objects.get(username = username, password = hash)
newhashkey = username+npassword
newhash = hashlib.sha256(newhashkey.encode()).hexdigest()
user.password=newhash
user.save()
return Response({'success':True,'data':'Password Changed Successfully'}, status=HTTP_200_OK)
else:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
resetpassword_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("user", required=True, location="form", type="string", description="user"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(resetpassword_schema)
def apiResetPassword(request):
username = request.data.get("user")
try:
userdet= UserData.objects.get(username=username)
if(userdet):
password = username
hashkey = username+password
newhash = hashlib.sha256(hashkey.encode()).hexdigest()
userdet.password=newhash
userdet.save()
return Response({'success':True,'data':'Successfully Reseted'},status=HTTP_200_OK)
else:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
balancetransactionreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(balancetransactionreport_schema)
def apiGetBalanceTransactionHistory(request):
username = request.data.get("username")
userdetails = UserData.objects.get(username=username)
try:
bthist = balanceTransactionReport.objects.filter(source=userdetails,category="BT").order_by('-date')[:40]
if(bthist):
data = BalanceTransferHistorySerializer(bthist,many=True)
return Response({'success':True,'data':data.data},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
fundtransactionreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(fundtransactionreport_schema)
def apiGetFundTransactionHistory(request):
username = request.data.get("username")
userdetails = UserData.objects.get(username=username)
try:
bthist = fundTransactionReport.objects.filter(source=userdetails).order_by('-date')[:40]
#print(balhist)
if(bthist):
data = FundTransferHistorySerializer(bthist,many=True)
return Response({'success':True,'data':data.data},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
creditbalance_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("user", required=True, location="form", type="string", description="user"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(creditbalance_schema)
def apiGetCreditBalance(request):
username = request.data.get("user")
try:
userdetails = UserData.objects.get(username=username)
if(userdetails):
data={'credit':userdetails.targetAmt}
return Response({'success':True,'data':data},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
voipstore_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(voipstore_schema)
def apiGetVoipStore(request):
username = request.data.get("username")
userdet = UserData.objects.get(username=username)
if(userdet.postId != "Admin"):
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card with cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description','margin')
if(len(pdcts)==0):
return Response(status=HTTP_204_NO_CONTENT)
else:
data=dict()
content = []
for i in pdcts:
try:
pd=vcloudProducts.objects.filter(brand__id=i['brand__id'], status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
else:
username = request.data.get("username")
productcost=Decimal(lpd[0]['brand__denomination'])
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand__id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'count':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'cost':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
except Exception as e:
print(e)
pass
return Response(content,status=HTTP_200_OK)
else:
return Response(status=HTTP_406_NOT_ACCEPTABLE)
filteredvoipstore_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("category", required=True, location="form", type="string", description="category"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(filteredvoipstore_schema)
def apiGetFilteredVoipStore(request):
username = request.data.get("username")
category = request.data.get("category")
userdet = UserData.objects.get(username=username)
try:
if(userdet.postId!="Admin"):
if(category=="Cutting"):
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card with cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
print(pdcts)
if(len(pdcts)==0):
return Response({'success':True,'data':[]},status=HTTP_200_OK)
else:
data=dict()
content = []
for i in pdcts:
try:
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass;
else:
username = request.data.get("username")
productcost=Decimal(lpd[0]['brand__denomination'])
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand__id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'count':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'cost':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
except Exception as e:
print(e)
pass
return Response({'success':True,'data':content},status=HTTP_200_OK)
else:
print(username)
pdcts = vcloudAssignments.objects.filter(assignedto=username,brand__category="card without cutting").order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
print(pdcts)
if(len(pdcts)==0):
return Response({'success':True,'data':[]},status=HTTP_200_OK)
else:
data=dict()
content = []
for i in pdcts:
try:
pd=vcloudProducts.objects.filter(brand=i['brand__id'],status=True).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand', 'productcount','brand__id','brand__logo','brand__denomination','brand__currency','brand__description')
lpd=list(pd)
count=0
if not lpd:
pass
else:
username = request.data.get("username")
productcost=Decimal(lpd[0]['brand__denomination'])
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId')
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=i['brand__brand']).values('margin')
if(userdet2[0]['postId']=="Admin"):
break;
else:
productcost = Decimal(productcost)+Decimal(margindet[0]['margin'])
username=userdet2[0]['sponserId']
count=int(count)+1
data={"brand__id":lpd[0]['brand__id'],"brand__brand":lpd[0]['brand__brand'],'count':lpd[0]['productcount'],'brand__logo':lpd[0]['brand__logo'],'cost':productcost,'brand__currency':lpd[0]['brand__currency'],'brand__description':lpd[0]['brand__description']}
content.append(data)
except Exception as e:
pass;
return Response({'success':True, 'data':content},status=HTTP_200_OK)
else:
return Response({'success':False,'message':'Restricted UserType'},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
getownbrand_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(getownbrand_schema)
def apiGetOwnBrandList(request):
username = request.data.get("username")
userdet = UserData.objects.get(username=username)
if(userdet.postId!="Admin"):
pdcts = vcloudAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand','brand__id','brand__logo','brand__currency','brand__description')
return Response({'success':True,'data':pdcts},status=HTTP_200_OK)
else:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
getpurchase_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("brand", required=True, location="form", type="string", description="brand"),
coreapi.Field("quantity", required=True, location="form", type="string", description="quantity"),
coreapi.Field("amount", required=True, location="form", type="string", description="amount"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(getpurchase_schema)
def apiGetPurchase(request):
try:
username = request.data.get("username")
brand = request.data.get("brand")
quantity = request.data.get("quantity")
amt = request.data.get("amount")
branddet=vcloudBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=username)
strlog = username+' buyed '+quantity+' '+brand
#str = username+' Buyed '+str(quantity)+' '+brand+' by '+amount
print(strlog)
plog=PurchaseLog()
plog.logdesc=strlog
plog.save()
print("Hello")
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=vcloudProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
licheckqty=list(checkqty)
brand_id=0
deno=0
print(licheckqty[0]['productcount'])
if(licheckqty[0]['productcount'] >= int(quantity)):
print("Haiii")
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = vcloudProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=vcloudAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
break;
username=userdet2[0]['sponserId']
print(flag)
if(flag):
try:
prdctcddet=vcloudProducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
#print(h.username)
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'password':h.password,'brand':h.brand.brand,'brand_logo':h.brand.logo.url,'status':h.status,'suser':username,'sdate':convert_datetime_timezone(h.sdate),'description':branddet.description,'denomination':amt}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
username = request.data.get("username")
closeuser = UserData.objects.get(username=username)
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Vcloud"
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.obalance = userdet.balance
vcrep.quantity = quantity
vcrep.cbalance = closeuser.balance
vcrep.amount = amt
vcrep.rtype = "App"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
return Response({'success':True,'data':result},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Sorry You Requested Product is buyed by Someone'},status=HTTP_200_OK)
else:
return Response({'success':False,'message':'Something Wrong May Happend, Try Again.! Else Contact Your Administrator'},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
getpurchasereport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(getpurchasereport_schema)
def apiGetPurchaseReport(request):
try:
username = request.data.get("username")
print(username)
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
userdet = UserData.objects.get(username=username)
print(userdet)
if(userdet.postId=='Reseller'):
#print("Haiii")
vcloudtxns=vcloudtransactions.objects.filter(sponser2__username=username,type="Vcloud",rtype="App").order_by('-date')[:20]
print(vcloudtxns)
for i in vcloudtxns:
print(i)
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
print(i)
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
count=count+1
print(data)
else:
profit=i.margin2
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":i.margin2,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
count=count+1
#print(content)
elif(userdet.postId=='Sub_Reseller'):
vcloudtxns=vcloudtransactions.objects.filter(sponser3__username=username,type="Vcloud",rtype="App").order_by('-date')[:20]
for i in vcloudtxns:
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin3
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":i.margin3,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
else:
vcloudtxns=vcloudtransactions.objects.filter(saleduser__username=username,type="Vcloud",rtype="App").order_by('-date')[:20]
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
print(content)
if(len(content)==0):
return Response({'success':True,'data':[]},status=HTTP_200_OK)
else:
data={"transaction":content,'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return Response({'success':True,'data':data},status=HTTP_200_OK)
except Exception as e:
print(e)
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
getpurchaseproductreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="Username"),
coreapi.Field("password", required=True, location="form", type="string", description="Password"),
coreapi.Field("id", required=True, location="form", type="string", description="Transaction Id"),
coreapi.Field("type", required=True, location="form", type="string", description="Transaction Type")
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(getpurchaseproductreport_schema)
def apiGetPurchasedProductReport(request):
try:
id = request.data.get("id")
type = request.data.get("type")
pdlist=list()
vcloudtxns=vcloudtransactions.objects.get(id=id)
productid=vcloudtxns.product_id
result = productid.rstrip(',')
pdid = result.split(',')
if(type=="Vcloud"):
for i in pdid:
pddet=vcloudProducts.objects.get(id=i)
data={"id":pddet.id,"brand":pddet.brand.brand,"carduname":pddet.username,"password":pddet.password,"denomination":vcloudtxns.denominations,"brand_logo":pddet.brand.logo.url,"sdate":pddet.sdate,"description":pddet.brand.description}
pdlist.append(data)
elif(type=="Dcard"):
for i in pdid:
pddet=datacardproducts.objects.get(id=i)
data={"id":pddet.id,"brand":pddet.brand.brand,"carduname":pddet.username,"denomination":vcloudtxns.denominations,"brand_logo":pddet.brand.logo.url,"sdate":pddet.sdate,"description":pddet.brand.description}
pdlist.append(data)
else:
for i in pdid:
pddet=rcardProducts.objects.get(id=i)
data={"id":pddet.id,"brand":pddet.brand.brand,"carduname":pddet.username,"denomination":vcloudtxns.denominations,"brand_logo":pddet.brand.logo.url,"sdate":pddet.sdate,"description":pddet.brand.description}
pdlist.append(data)
return Response({'success':True,'data':pdlist},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occurred'},status=HTTP_200_OK)
filteredtransactionreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("fromdate", required=True, location="form", type="date", description="transaction id"),
coreapi.Field("todate", required=True, location="form", type="date", description="transaction id"),
coreapi.Field("user", required=True, location="form", type="date", description="transaction id"),
coreapi.Field("type", required=True, location="form", type="date", description="transaction id"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(filteredtransactionreport_schema)
def apiGetFilteredTransactionReport(request):
username=request.data.get("username")
fromdate=request.data.get("fromdate")
todate=request.data.get("todate")
fusername=request.data.get("user")
type=request.data.get("type")
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
userdet = UserData.objects.get(username=fusername)
#vcloudtxns=vcloudtransactions.objects.filter(date__lte=todate,date__gte=fromdate).order_by('-date')
#print(vcloudtxns)
try:
userdet = UserData.objects.get(username=username)
print(userdet.postId)
if(userdet.postId=='Reseller'):
vcloudtxns=vcloudtransactions.objects.filter(sponser2__username=username,date__gte=fromdate,date__lte=todate,type=type,rtype="App").order_by('-date')
print(vcloudtxns)
for i in vcloudtxns:
print(i)
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
print(i)
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
print(data)
else:
profit=i.margin2
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":i.margin2,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
#print(content)
elif(userdet.postId=='Sub_Reseller'):
vcloudtxns=vcloudtransactions.objects.filter(sponser3__username=username,date__lte=todate,date__gte=fromdate,type=type,rtype="App").order_by('-date')
for i in vcloudtxns:
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin3
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":i.margin3,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
else:
vcloudtxns=vcloudtransactions.objects.filter(saleduser__username=username,date__lte=todate,date__gte=fromdate,type=type,rtype="App").order_by('-date')
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
print(content)
if(len(content)==0):
return Response({'success':True,'data':[]},status=HTTP_200_OK)
else:
data={"transaction":content,'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return Response({'success':True,'data':data},status=HTTP_200_OK)
except Exception as e:
print(e)
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
filteredbalancetransactionreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("fromdate", required=True, location="form", type="date", description="fromdate"),
coreapi.Field("todate", required=True, location="form", type="date", description="todate"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(filteredbalancetransactionreport_schema)
def apiGetFilteredBalanceTransactionHistory(request):
username = request.data.get("username")
userdetails = UserData.objects.get(username=username)
fromdate=request.data.get("fromdate")
todate=request.data.get("todate")
try:
bthist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
if(bthist):
data = BalanceTransferHistorySerializer(bthist,many=True)
return Response({'success':True,'data':data.data},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
filteredtobalancetransactionreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("fromdate", required=True, location="form", type="date", description="fromdate"),
coreapi.Field("todate", required=True, location="form", type="date", description="todate"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(filteredtobalancetransactionreport_schema)
def apiGetFilteredToBalanceTransactionHistory(request):
username = request.data.get("username")
userdetails = UserData.objects.get(username=username)
fromdate=request.data.get("fromdate")
todate=request.data.get("todate")
try:
bthist = balanceTransactionReport.objects.filter(date__gte =fromdate,date__lte=todate, destination=userdetails)
if(bthist):
data = BalanceTransferHistorySerializer(bthist,many=True)
return Response({'success':True,'data':data.data},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
filteredfundtransactionreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("fromdate", required=True, location="form", type="date", description="fromdate"),
coreapi.Field("todate", required=True, location="form", type="date", description="todate"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(filteredfundtransactionreport_schema)
def apiGetFilteredFundTransactionHistory(request):
username = request.data.get("username")
userdetails = UserData.objects.get(username=username)
fromdate=request.data.get("fromdate")
todate=request.data.get("todate")
try:
bthist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,source=userdetails)
if(bthist):
data = FundTransferHistorySerializer(bthist,many=True)
return Response({'success':True,'data':data.data},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
filteredtofundtransactionreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("fromdate", required=True, location="form", type="date", description="fromdate"),
coreapi.Field("todate", required=True, location="form", type="date", description="todate"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(filteredtofundtransactionreport_schema)
def apiGetFilteredToFundTransactionHistory(request):
username = request.data.get("username")
userdetails = UserData.objects.get(username=username)
fromdate=request.data.get("fromdate")
todate=request.data.get("todate")
try:
bthist = fundTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdetails)
if(bthist):
data = FundTransferHistorySerializer(bthist,many=True)
return Response({'success':True,'data':data.data},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
tobalncetransactionreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(tobalncetransactionreport_schema)
def apiGetToBalanceTransactionHistory(request):
username = request.data.get("username")
userdetails = UserData.objects.get(username=username)
try:
bthist = balanceTransactionReport.objects.filter(destination=userdetails,category="BT").order_by('-date')
if(bthist):
data = BalanceTransferHistorySerializer(bthist,many=True)
return Response({'success':True,'data':data.data},status=HTTP_200_OK)
else:
return Response({'success':False,'data':[]},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
tofundtransactionreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(tofundtransactionreport_schema)
def apiGetToFundTransactionHistory(request):
username = request.data.get("username")
userdetails = UserData.objects.get(username=username)
try:
bthist = fundTransactionReport.objects.filter(destination=userdetails).order_by('-date')
if(bthist):
data = FundTransferHistorySerializer(bthist,many=True)
return Response({'success':True,'data':data.data},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
dcardstore_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(dcardstore_schema)
def apiGetDcardStore(request):
username = request.data.get("username")
user = UserData.objects.get(username=username)
btnlist=list()
dproducts = datacardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
content=list()
if(len(btnlist)!=0):
dcardproducts = datacardAssignments.objects.filter(assignedto=username,brand__brand__contains=btnlist[0]).order_by('brand').values('brand__brand','margin')
for i in dcardproducts:
dcp=datacardproducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getDatacardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
#data={'data':content,'fbuttons':btnlist}
return Response({'success':True,'data':content,'fbuttons':btnlist},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
filtereddcardstore_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("category", required=True, location="form", type="string", description="category"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(filtereddcardstore_schema)
def apiGetFilteredDcardStore(request):
username = request.data.get("username")
brand = request.data.get("category")
user = UserData.objects.get(username=username)
btnlist=list()
dproducts = datacardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
content=list()
if(len(btnlist)!=0):
dcardproducts = datacardAssignments.objects.filter(assignedto=username,brand__brand__contains=brand).order_by('brand').values('brand__brand','margin')
for i in dcardproducts:
dcp=datacardproducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getDatacardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
#data={'data':content,'buttons':btnlist}
return Response({'success':True,'data':content,'fbuttons':btnlist},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
dcardownbrand_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(dcardownbrand_schema)
def apiGetDcardOwnBrandList(request):
username = request.data.get("username")
userdet = UserData.objects.get(username=username)
if(userdet.postId!="Admin"):
pdcts = datacardAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand','brand__id','brand__logo','brand__currency','brand__description')
return Response({'success':True,'data':pdcts},status=HTTP_200_OK)
else:
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
dcardpurchase_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("brand", required=True, location="form", type="string", description="brand"),
coreapi.Field("quantity", required=True, location="form", type="string", description="quantity"),
coreapi.Field("amount", required=True, location="form", type="string", description="amount"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(dcardpurchase_schema)
def apiGetDcardPurchase(request):
try:
username = request.data.get("username")
brand = request.data.get("brand")
quantity = request.data.get("quantity")
amt = request.data.get("amount")
branddet=dcardBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=username)
strlog = username+' buyed '+quantity+' '+brand
#str = username+' Buyed '+str(quantity)+' '+brand+' by '+amount
print(strlog)
plog=PurchaseLog()
plog.logdesc=strlog
plog.save()
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=datacardproducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
licheckqty=list(checkqty)
brand_id=0
deno=0
if(licheckqty[0]['productcount'] >= int(quantity)):
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = datacardproducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=datacardAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
break;
username=userdet2[0]['sponserId']
print(flag)
if(flag):
try:
prdctcddet=datacardproducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'brand':h.brand.brand,'brand_logo':h.brand.logo.url,'status':h.status,'suser':username,'sdate':convert_datetime_timezone(h.sdate),'description':branddet.description,'denomination':amt}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
username = request.data.get("username")
closeuser = UserData.objects.get(username=username)
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Dcard"
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.quantity = quantity
vcrep.obalance = userdet.balance
vcrep.cbalance = closeuser.balance
vcrep.amount = amt
vcrep.rtype = "App"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
return Response({'success':True,'data':result},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Sorry. You are requested product is buyed by Someone'},status=HTTP_200_OK)
else:
return Response({'success':False,'message':'Something Wrong May Happend, Try Again.! Else Contact Your Administrator'},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
dcardpurchaseProductReport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("id", required=True, location="form", type="string", description="transaction id"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(dcardpurchaseProductReport_schema)
def apiGetPurchasedDcardProductReport(request):
try:
id = request.data.get("id")
vcloudtxns=vcloudtransactions.objects.get(id=id)
#print(vcloudtxns)
productid=vcloudtxns.product_id
result = productid.rstrip(',')
pdid = result.split(',')
pdlist=list()
for i in pdid:
pddet=datacardproducts.objects.get(id=i)
data={"id":pddet.id,"brand":pddet.brand.brand,"username":pddet.username,"denomination":pddet.denomination,"logo":pddet.brand.logo.url,"date":pddet.sdate,"description":pddet.d}
pdlist.append(data)
return Response({'success':True,'data':pdlist},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Happend'},status=HTTP_200_OK)
dcardpurchaseReport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(dcardpurchaseReport_schema)
def apiGetDcardPurchaseReport(request):
try:
username = request.data.get("username")
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
userdet = UserData.objects.get(username=username)
print(userdet)
if(userdet.postId=='Reseller'):
#print("Haiii")
vcloudtxns=vcloudtransactions.objects.filter(sponser2__username=username,type="Dcard",rtype="App").order_by('-date')[:20]
print(vcloudtxns)
for i in vcloudtxns:
print(i)
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
print(i)
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
count=count+1
print(data)
else:
profit=i.margin2
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":i.margin2,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
count=count+1
#print(content)
elif(userdet.postId=='Sub_Reseller'):
vcloudtxns=vcloudtransactions.objects.filter(sponser3__username=username,type="Dcard",rtype="App").order_by('-date')[:20]
for i in vcloudtxns:
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin3
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":i.margin3,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
else:
vcloudtxns=vcloudtransactions.objects.filter(saleduser__username=username,type="Dcard",rtype="App").order_by('-date')[:20]
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
print(content)
if(len(content)==0):
return Response({'success':True,'data':[]},status=HTTP_200_OK)
else:
data={"transaction":content,'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return Response({'success':True,'data':data},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Happend'},status=HTTP_200_OK)
def vcloudlogtoproductdelete(request,id):
try:
print(id)
det = vclouduplogs.objects.filter(id=id)
det.delete()
return redirect(addcsvProduct)
except:
return redirect(addcsvProduct)
def dcardlogtoproductdelete(request,id):
try:
print(id)
det = dcarduplogs.objects.filter(id=id)
det.delete()
return redirect(adddcardcsvProduct)
except:
return redirect(adddcardcsvProduct)
def rcardlogtoproductdelete(request,id):
try:
print(id)
det = rcarduplogs.objects.filter(id=id)
det.delete()
return redirect(addrcardcsvProduct)
except:
return redirect(addrcardcsvProduct)
# dcardpurchaseReport_schema = AutoSchema(manual_fields=[
# coreapi.Field("username", required=True, location="form", type="string", description="username"),
# coreapi.Field("password", required=True, location="form", type="string", description="password"),
# coreapi.Field("fromdate", required=True, location="form", type="string", description="fromdate"),
# coreapi.Field("todate", required=True, location="form", type="string", description="todate"),
# coreapi.Field("user", required=True, location="form", type="string", description="user"),
# coreapi.Field("brand", required=True, location="form", type="string", description="brand"),
# ])
# @csrf_exempt
# @api_view(["POST"])
# @permission_classes((AllowAny,))
# @schema(dcardpurchaseReport_schema)
# def apiGetDcardFilteredTransactionReport(request):
# username=request.data.get("username")
# fromdate=request.data.get("fromdate")
# todate=request.data.get("todate")
# fusername=request.data.get("user")
# brand=request.data.get("brand")
# content=list()
# noofrecords=0
# productsum =0
# quantitysum =0
# profitsum =0
# try:
# vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,type="Dcard",brand=brand).order_by('-date')
# for i in vcloudtxns:
# saleduser=i.saleduser.username
# saledusername=None
# usertype=i.saleduser.postId
# while(True):
# if(username==saleduser):
# margin=0
# profit=0
# name=UserData.objects.get(username=saleduser)
# if(name.username==fusername):
# data={"id":i.id,"saleduser":name.name,"role":usertype,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":margin,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":profit}
# noofrecords=noofrecords+1
# productsum=productsum+(i.amount*i.quantity)
# quantitysum=quantitysum+i.quantity
# content.append(data)
# break
# else:
# break
# elif(username==saledusername):
# if(usertype1=="Admin"):
# margin=i.margin1
# profit=margin*i.quantity
# name=UserData.objects.get(username=saleduser)
# if(name.username==fusername):
# data={"id":i.id,"saleduser":name.name,"role":usertype,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":margin,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":profit}
# content.append(data)
# noofrecords=noofrecords+1
# productsum=productsum+(i.amount*i.quantity)
# quantitysum=quantitysum+i.quantity
# profitsum=profitsum+profit
# break
# else:
# break
# else:
# margin=0
# if(usertype1=="Reseller"):
# margin=i.margin2
# elif(usertype1=="Sub_Reseller"):
# margin=i.margin3
# else:
# margin=i.margin4
# profit=margin*i.quantity
# name=UserData.objects.get(username=saleduser)
# if(name.username==fusername):
# data={"id":i.id,"saleduser":name.name,"role":usertype,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":margin,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":profit}
# content.append(data)
# noofrecords=noofrecords+1
# productsum=productsum+(i.amount*i.quantity)
# quantitysum=quantitysum+i.quantity
# profitsum=profitsum+profit
# break
# else:
# break
# else:
# if(saledusername==None):
# saledusername=saleduser
# usdet=UserData.objects.get(username=saledusername)
# if(usdet.sponserId != None):
# saleduser=usdet.username
# usertype=usdet.postId
# saledusername=usdet.sponserId.username
# usertype1=usdet.sponserId.postId
# else:
# break
# if(len(content)==0):
# return Response({'success':True,'data':[]},status=HTTP_200_OK)
# else:
# data={"transaction":content,'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
# return Response({'success':True,'data':data},status=HTTP_200_OK)
# except:
# return Response({'success':False,'mesage':'Something Unexpected Occured'},status=HTTP_200_OK)
rcardstore_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(rcardstore_schema)
def apiGetRcardStore(request):
username = request.data.get("username")
user = UserData.objects.get(username=username)
btnlist=list()
content=list()
dproducts = rcardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
if(len(btnlist)!=0):
dcardproducts = rcardAssignments.objects.filter(assignedto=username,brand__brand__contains=btnlist[0]).order_by('brand').values('brand__brand','margin')
print(dcardproducts)
for i in dcardproducts:
dcp=rcardProducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','brand__currency')
if(len(dcp)>0):
cost=getRcardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
#data={'data':content,'fbuttons':btnlist}
return Response({'success':True,'data':content,'fbuttons':btnlist},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
filteredrcardstore_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("category", required=True, location="form", type="string", description="category"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(filteredrcardstore_schema)
def apiGetFilteredRcardStore(request):
username = request.data.get("username")
brand = request.data.get("category")
user = UserData.objects.get(username=username)
btnlist=list()
content=list()
dproducts = rcardAssignments.objects.filter(assignedto=username).order_by('brand').values('brand__brand','margin')
for i in dproducts:
buttons=(i["brand__brand"]).split(" ")
if buttons[0] not in btnlist:
btnlist.append(buttons[0])
if(len(btnlist)!=0):
dcardproducts = rcardAssignments.objects.filter(assignedto=username,brand__brand__contains=brand).order_by('brand').values('brand__brand','margin')
for i in dcardproducts:
dcp=rcardProducts.objects.filter(brand__brand=i["brand__brand"],status=True).order_by('brand').values('brand').annotate(count=Count('brand')).values('count','brand__id','brand__brand','brand__description','brand__denomination','brand__logo','count','brand__currency')
if(len(dcp)>0):
cost=getRcardProductCost(username,dcp[0]["brand__brand"])
data={'brand__id':dcp[0]['brand__id'],'brand__brand':dcp[0]['brand__brand'],'brand__logo':dcp[0]['brand__logo'],'brand__description':dcp[0]['brand__description'],'brand__currency':dcp[0]['brand__currency'],'count':dcp[0]['count'],'cost':cost}
content.append(data)
#data={'data':content,'fbuttons':btnlist}
return Response({'success':True,'data':content,'fbuttons':btnlist},status=HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=HTTP_200_OK)
rcardbrandlist_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(rcardbrandlist_schema)
def apiGetRcardOwnBrandList(request):
username = request.data.get("username")
userdet = UserData.objects.get(username=username)
if(userdet.postId!="Admin"):
pdcts = rcardAssignments.objects.filter(assignedto=username).order_by('brand__brand').values('brand__brand').annotate(productcount=Count('brand')).values('brand','brand__brand','brand__id','brand__logo','brand__currency','brand__description')
return Response({'success':True,'data':pdcts},status=HTTP_200_OK)
else:
return Response({'success':False,'message':'Something Unexpected Occur'},status=HTTP_200_OK)
rcardpurchasedproductreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("id", required=True, location="form", type="string", description="transactionid"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(rcardpurchasedproductreport_schema)
def apiGetPurchasedRcardProductReport(request):
try:
id = request.data.get("id")
vcloudtxns=vcloudtransactions.objects.get(id=id)
#print(vcloudtxns)
productid=vcloudtxns.product_id
result = productid.rstrip(',')
pdid = result.split(',')
pdlist=list()
for i in pdid:
pddet=rcardProducts.objects.get(id=i)
data={"id":pddet.id,"brand":pddet.brand.brand,"username":pddet.username,"denomination":pddet.denomination,"logo":pddet.brand.logo.url}
pdlist.append(data)
return Response({'success':True,'data':pdlist},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
rcardpurchasedreport_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(rcardpurchasedreport_schema)
def apiGetRcardPurchaseReport(request):
try:
username = request.data.get("username")
content=list()
noofrecords=0
productsum =0
quantitysum =0
profitsum =0
count=0
userdet = UserData.objects.get(username=username)
print(userdet)
if(userdet.postId=='Reseller'):
#print("Haiii")
vcloudtxns=vcloudtransactions.objects.filter(sponser2__username=username,type="Rcard",rtype="App").order_by('-date')[:20]
print(vcloudtxns)
for i in vcloudtxns:
print(i)
cost=i.denominations+i.margin1
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
print(i)
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser2.name,"role":i.sponser2.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
count=count+1
print(data)
else:
profit=i.margin2
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":i.margin2,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
count=count+1
#print(content)
elif(userdet.postId=='Sub_Reseller'):
vcloudtxns=vcloudtransactions.objects.filter(sponser3__username=username,type="Rcard",rtype="App").order_by('-date')[:20]
for i in vcloudtxns:
cost=i.denominations+i.margin1+i.margin2
productsum=productsum+(cost*i.quantity)
quantitysum=quantitysum+i.quantity
if(i.saleduser.username==username):
profit=0
data={"id":i.id,"saleduser":i.sponser3.name,"role":i.sponser3.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
else:
profit=i.margin3
data={"id":i.id,"saleduser":i.sponser4.name,"role":i.sponser4.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":i.margin3,"quantity":i.quantity,"amount":(cost*i.quantity),"profit":profit}
content.append(data)
profitsum = profitsum+profit
else:
vcloudtxns=vcloudtransactions.objects.filter(saleduser__username=username,type="Rcard",rtype="App").order_by('-date')[:20]
for i in vcloudtxns:
data={"id":i.id,"saleduser":i.saleduser.name,"role":i.saleduser.postId,"date":convert_datetime_timezone(i.date),"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":0,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":0}
content.append(data)
productsum=productsum+(i.amount*i.quantity)
quantitysum=quantitysum+i.quantity
profitsum = 0
print(content)
if(len(content)==0):
return Response({'success':True,'data':[]},status=HTTP_200_OK)
else:
data={"transaction":content,'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
return Response({'success':True,'data':data},status=HTTP_200_OK)
except Exception as e:
print(e)
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
# rcardfilteredtransactionreport_schema = AutoSchema(manual_fields=[
# coreapi.Field("username", required=True, location="form", type="string", description="username"),
# coreapi.Field("password", required=True, location="form", type="string", description="password"),
# coreapi.Field("fromdate", required=True, location="form", type="string", description="fromdate"),
# coreapi.Field("todate", required=True, location="form", type="string", description="todate"),
# coreapi.Field("user", required=True, location="form", type="string", description="user"),
# coreapi.Field("brand", required=True, location="form", type="string", description="user"),
# ])
# @csrf_exempt
# @api_view(["POST"])
# @permission_classes((AllowAny,))
# @schema(rcardfilteredtransactionreport_schema)
# def apiGetRcardFilteredTransactionReport(request):
# username=request.data.get("username")
# fromdate=request.data.get("fromdate")
# todate=request.data.get("todate")
# fusername=request.data.get("user")
# brand=request.data.get("brand")
# content=list()
# noofrecords=0
# productsum =0
# quantitysum =0
# profitsum =0
# try:
# vcloudtxns=vcloudtransactions.objects.filter(date__gte=fromdate,date__lte=todate,type="Rcard",brand=brand).order_by('-date')
# for i in vcloudtxns:
# saleduser=i.saleduser.username
# saledusername=None
# usertype=i.saleduser.postId
# while(True):
# if(username==saleduser):
# margin=0
# profit=0
# name=UserData.objects.get(username=saleduser)
# data={"id":i.id,"saleduser":name.name,"role":usertype,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":margin,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":profit}
# noofrecords=noofrecords+1
# productsum=productsum+(i.amount*i.quantity)
# quantitysum=quantitysum+i.quantity
# content.append(data)
# break
# elif(username==saledusername):
# if(usertype1=="Admin"):
# margin=i.margin1
# profit=margin*i.quantity
# name=UserData.objects.get(username=saleduser)
# data={"id":i.id,"saleduser":name.name,"role":usertype,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":margin,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":profit}
# content.append(data)
# noofrecords=noofrecords+1
# productsum=productsum+(i.amount*i.quantity)
# quantitysum=quantitysum+i.quantity
# profitsum=profitsum+profit
# break
# else:
# margin=0
# if(usertype1=="Reseller"):
# margin=i.margin2
# elif(usertype1=="Sub_Reseller"):
# margin=i.margin3
# else:
# margin=i.margin4
# profit=margin*i.quantity
# name=UserData.objects.get(username=saleduser)
# data={"id":i.id,"saleduser":name.name,"role":usertype,"date":i.date,"brand":i.brand,"type":i.type,"brand_id":i.brand_id,"product_id":i.product_id,"denomination":i.denominations,"margin":margin,"quantity":i.quantity,"amount":(i.amount*i.quantity),"profit":profit}
# content.append(data)
# noofrecords=noofrecords+1
# productsum=productsum+(i.amount*i.quantity)
# quantitysum=quantitysum+i.quantity
# profitsum=profitsum+profit
# break
# else:
# if(saledusername==None):
# saledusername=saleduser
# usdet=UserData.objects.get(username=saledusername)
# if(usdet.sponserId != None):
# saleduser=usdet.username
# usertype=usdet.postId
# saledusername=usdet.sponserId.username
# usertype1=usdet.sponserId.postId
# else:
# break
# if(len(content)==0):
# return Response({'success':True,'data':[]},status=HTTP_200_OK)
# else:
# data={"transaction":content,'productsum':productsum,'quantitysum':quantitysum,'profitsum':profitsum}
# return Response({'success':True,'data':data},status=HTTP_200_OK)
# except:
# return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
rcardpurchase_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
coreapi.Field("brand", required=True, location="form", type="string", description="brand"),
coreapi.Field("quantity", required=True, location="form", type="string", description="quantity"),
coreapi.Field("amount", required=True, location="form", type="string", description="amount"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(rcardpurchase_schema)
def apiGetRcardPurchase(request):
try:
username = request.data.get("username")
brand = request.data.get("brand")
quantity = request.data.get("quantity")
amt = request.data.get("amount")
branddet=rcardBrands.objects.get(brand=brand)
userdet=UserData.objects.get(username=username)
strlog = username+' buyed '+quantity+' '+brand
#str = username+' Buyed '+str(quantity)+' '+brand+' by '+amount
print(strlog)
plog=PurchaseLog()
plog.logdesc=strlog
plog.save()
ctime=datetime.now()
time = timedelta(minutes = 5)
now_minus_5 = ctime - time
checkqty=rcardProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5))).values('brand').annotate(productcount=Count('brand')).values('productcount')
print(checkqty)
needamt=0;
result=list()
licheckqty=list(checkqty)
brand_id=0
deno=0
if(licheckqty[0]['productcount'] >= int(quantity)):
usertype=''
marginlist=list()
margins=0
count=0;
flag=True
prdct_id=''
mllist=list()
sponserlist=list()
prdctdet = rcardProducts.objects.filter(Q(brand__brand=brand) & Q(status=True) & (Q(sdate__isnull=True) | Q(sdate__lte=now_minus_5)))[:int(quantity)]
ctime = datetime.now()
for i in prdctdet:
i.productstatus=1
i.suser = userdet
i.sdate = ctime
i.save()
count=0
admin=''
while(True):
userdet2=UserData.objects.filter(username=username).values('sponserId','postId','balance')
margindet=rcardAssignments.objects.filter(assignedto=username,brand__brand=brand).values('margin')
if(userdet2[0]['postId']=="Admin"):
admin=username
break;
else:
cost=Decimal(amt)
prdctcost = (cost*Decimal(quantity))-(Decimal(margins)*Decimal(quantity))
margins=margins+Decimal(margindet[0]['margin'])
if(userdet2[0]['balance']>=prdctcost):
data={'margin':margindet[0]['margin'],'balance':userdet2[0]['balance'],'username':username,'prdctcost':prdctcost}
marginlist.append(data)
mllist.append(margindet[0]['margin'])
sponserlist.append(username)
else:
flag=False
break;
username=userdet2[0]['sponserId']
print(flag)
if(flag):
try:
prdctcddet=rcardProducts.objects.filter(brand__brand=brand,status=True,productstatus=1,suser=userdet,sdate=ctime)[:int(quantity)]
for h in prdctcddet:
h.status=False
h.save()
brand_id=h.brand.id
deno=h.brand.denomination
prdct_id=prdct_id+""+str(h.id)+","
res={"productid":h.id,"carduname":h.username,'brand':h.brand.brand,'brand_logo':h.brand.logo.url,'status':h.status,'suser':username,'sdate':convert_datetime_timezone(h.sdate),'description':branddet.description,'denomination':amt}
result.append(res)
ml=marginlist[::-1]
for k in ml:
uname = k['username']
margin = k['margin']
balance = k['balance']
pcost = k['prdctcost']
cb=Decimal(balance)-Decimal(pcost)
userd=UserData.objects.get(username=uname)
userd.balance=cb
userd.save()
mllen = len(mllist)
username = request.data.get("username")
closeuser = UserData.objects.get(username=username)
vcrep=vcloudtransactions()
vcrep.saleduser = userdet
vcrep.brand = brand
vcrep.type = "Rcard"
vcrep.obalance = userdet.balance
vcrep.cbalance = closeuser.balance
vcrep.brand_id = brand_id
vcrep.product_id = prdct_id
vcrep.quantity = quantity
vcrep.amount = amt
vcrep.rtype = "App"
vcrep.denominations = deno
ms = mllist[::-1]
mu = sponserlist[::-1]
print(ms)
print(admin)
ad=UserData.objects.get(username=admin)
if(mllen==1):
vcrep.margin1=ms[0]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[0])
elif(mllen==2):
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[1])
vcrep.sponser3=UserData.objects.get(username=sponserlist[0])
else:
vcrep.margin1=ms[0]
vcrep.margin2=ms[1]
vcrep.margin3=ms[2]
vcrep.sponser1=ad
vcrep.sponser2=UserData.objects.get(username=sponserlist[2])
vcrep.sponser3=UserData.objects.get(username=sponserlist[1])
vcrep.sponser4=UserData.objects.get(username=sponserlist[0])
vcrep.save()
return Response({'success':True,'data':result},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Wrong May Happend, Try Again.! Else Contact Your Administrator'},status=HTTP_200_OK)
else:
return Response({'success':False,'message':'Something Wrong May Happend, Try Again.! Else Contact Your Administrator'},status=HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occured'},status=HTTP_200_OK)
def getAllMargin(request):
if request.session.has_key("user"):
if request.method == 'POST':
username = request.session["user"]
content = list()
try:
userdetails = UserData.objects.get(username=username)
user = request.POST.get('username')
type = request.POST.get('type', None)
print(user)
print(userdetails.username)
print(type)
muserdet = UserData.objects.get(username=user)
if(type=="Vcloud"):
mdet = vcloudAssignments.objects.filter(assignedby=userdetails,assignedto=muserdet)
for i in mdet:
data={'brandid':i.brand.id,'margin':i.margin}
content.append(data)
elif(type=="Dcard"):
mdet = datacardAssignments.objects.filter(assignedby=userdetails,assignedto=muserdet)
print(mdet)
for i in mdet:
data={'brandid':i.brand.id,'margin':i.margin}
content.append(data)
else:
mdet = rcardAssignments.objects.filter(assignedby=userdetails,assignedto=muserdet)
for i in mdet:
data={'brandid':i.brand.id,'margin':i.margin}
content.append(data)
except:
pass;
return JsonResponse(content,safe=False)
else:
return JsonResponse({"status":"Error"})
else:
return redirect(LoginPage)
def addAdvertisements(request):
user = UserData.objects.get(username = request.session["user"])
return render(request,"admin/vcloud/addads.html",{'form':AddPromotionForm,'user':user})
def submitadvertisements(request):
if request.session.has_key("user"):
if request.method == 'POST':
print("Haiii")
form = AddPromotionForm(request.POST, request.FILES)
print("Haiii")
print(form.errors)
if form.is_valid():
bd = form.save()
messages.success(request, 'Added Successfully')
return redirect(addAdvertisements)
else:
messages.warning(request, form.errors)
return redirect(addAdvertisements)
else:
return redirect(addAdvertisements)
else:
return redirect(LoginPage)
getAdsImage_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(getAdsImage_schema)
def apiGetImageAdvertisements(request):
try:
username = request.data.get("username")
user = UserData.objects.get(username=username)
ads = adverisements.objects.filter(usertype=user.postId, adtype="Image")
if(len(ads)>0):
adsdata=ImageAdsSerializer(ads,many=True)
return Response({'success':True,'data':adsdata.data},status=status.HTTP_200_OK)
else:
return Response({'success':True,'data':[]},status=status.HTTP_200_OK)
except:
return Response({'success':False,'message':'Something Unexpected Occured'},status=status.HTTP_200_OK)
getAdsText_schema = AutoSchema(manual_fields=[
coreapi.Field("username", required=True, location="form", type="string", description="username"),
coreapi.Field("password", required=True, location="form", type="string", description="password"),
])
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
@schema(getAdsText_schema)
def apiGetTextAdvertisements(request):
try:
content=[]
username = request.data.get("username")
user = UserData.objects.get(username=username)
ads = adverisements.objects.filter(usertype=user.postId)
if(len(ads)>0):
for i in ads:
if(i.adtype=="Image"):
data={"type":i.adtype,"content":i.adimage.url}
content.append(data)
else:
data={"type":i.adtype,"content":i.adtext}
content.append(data)
return Response(content,status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_204_NO_CONTENT)
except:
return Response(status=HTTP_403_FORBIDDEN)
def viewAds(request):
if request.session.has_key("user"):
user = UserData.objects.get(username=request.session["user"])
ads = adverisements.objects.all()
return render(request,"admin/vcloud/promo.html",{'ads':ads,'user':user})
else:
return redirect(LoginPage)
def deleteAds(request,id):
ads=adverisements.objects.get(id=id)
ads.delete()
return redirect(viewAds)
def deleteVcloudBrands(request,id):
dt = vcloudBrands.objects.get(id=id)
dt.delete()
return redirect(manageVcloudBrands)
def deleteDcardBrands(request,id):
dt = dcardBrands.objects.get(id=id)
dt.delete()
return redirect(manageDCardBrands)
def deleteRcardBrands(request,id):
dt = rcardBrands.objects.get(id=id)
dt.delete()
return redirect(manageRCardBrands)
def dcardaddAdvertisements(request):
user = UserData.objects.get(username = request.session["user"])
return render(request,"admin/dcard/addads.html",{'form':AddPromotionForm,'user':user})
def dcardsubmitadvertisements(request):
if request.session.has_key("user"):
if request.method == 'POST':
print("Haiii")
form = AddPromotionForm(request.POST, request.FILES)
print("Haiii")
print(form.errors)
if form.is_valid():
bd = form.save()
messages.success(request, 'Added Successfully')
return redirect(dcardaddAdvertisements)
else:
messages.warning(request, form.errors)
return redirect(dcardaddAdvertisements)
else:
return redirect(dcardaddAdvertisements)
else:
return redirect(LoginPage)
def dcardviewAds(request):
if request.session.has_key("user"):
user = UserData.objects.get(username=request.session["user"])
ads = adverisements.objects.all()
return render(request,"admin/dcard/promo.html",{'ads':ads,'user':user})
else:
return redirect(LoginPage)
def dcarddeleteAds(request,id):
ads=adverisements.objects.get(id=id)
ads.delete()
return redirect(dcardviewAds)
def rcardaddAdvertisements(request):
user = UserData.objects.get(username = request.session["user"])
return render(request,"admin/rcard/addads.html",{'form':AddPromotionForm,'user':user})
def rcardsubmitadvertisements(request):
if request.session.has_key("user"):
if request.method == 'POST':
print("Haiii")
form = AddPromotionForm(request.POST, request.FILES)
print("Haiii")
print(form.errors)
if form.is_valid():
bd = form.save()
messages.success(request, 'Added Successfully')
return redirect(rcardaddAdvertisements)
else:
messages.warning(request, form.errors)
return redirect(rcardaddAdvertisements)
else:
return redirect(rcardaddAdvertisements)
else:
return redirect(LoginPage)
def rcardviewAds(request):
if request.session.has_key("user"):
user = UserData.objects.get(username=request.session["user"])
ads = adverisements.objects.all()
return render(request,"admin/rcard/promo.html",{'ads':ads,'user':user})
else:
return redirect(LoginPage)
def rcarddeleteAds(request,id):
ads=adverisements.objects.get(id=id)
ads.delete()
return redirect(rcardviewAds)
def deleteVcloudProduct(request,id):
if request.session.has_key("user"):
product=vcloudProducts.objects.get(id=id)
product.delete()
return redirect(vcloudmanageProduct)
else:
return redirect(LoginPage)
def deleteDcardProduct(request,id):
if request.session.has_key("user"):
product=datacardproducts.objects.get(id=id)
product.delete()
return redirect(dcardmanageProduct)
else:
return redirect(LoginPage)
def deleteRcardProduct(request,id):
if request.session.has_key("user"):
product=rcardProducts.objects.get(id=id)
product.delete()
return redirect(rcardmanageProduct)
else:
return redirect(LoginPage)
def uservcloudbtreport(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
phist = balanceTransactionReport.objects.filter(destination=userdet).order_by('-date')
return render(request,"user/vcloud/btReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(LoginPage)
def filteruservcloudbtreport(request):
if request.session.has_key("user"):
if request.method == "POST":
form = datefilterform(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
userdet=UserData.objects.get(username=currentuser)
phist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdet).order_by('-date')
return render(request,"user/vcloud/btReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(uservcloudbtreport)
else:
return redirect(uservcloudbtreport)
else:
return redirect(LoginPage)
def userdcardbtreport(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
phist = balanceTransactionReport.objects.filter(destination=userdet).order_by('-date')
return render(request,"user/dcard/btReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(LoginPage)
def filteruserdcardbtreport(request):
if request.session.has_key("user"):
if request.method == "POST":
form = datefilterform(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
userdet=UserData.objects.get(username=currentuser)
phist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdet).order_by('-date')
return render(request,"user/vcloud/btReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(userdcardbtreport)
else:
return redirect(userdcardbtreport)
else:
return redirect(LoginPage)
def userrcardbtreport(request):
if request.session.has_key("user"):
userdet=UserData.objects.get(username=request.session["user"])
phist = balanceTransactionReport.objects.filter(destination=userdet).order_by('-date')
return render(request,"user/dcard/btReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(LoginPage)
def filteruserrcardbtreport(request):
if request.session.has_key("user"):
if request.method == "POST":
form = datefilterform(request.POST or None)
print(form.errors)
if form.is_valid():
currentuser=request.session["user"]
fromdate=form.cleaned_data.get("fromdate")
todate=form.cleaned_data.get("todate")
userdet=UserData.objects.get(username=currentuser)
phist = balanceTransactionReport.objects.filter(date__gte=fromdate,date__lte=todate,destination=userdet).order_by('-date')
return render(request,"user/vcloud/btReport.html",{'form':datefilterform,'user':userdet,'phist':phist})
else:
return redirect(userrcardbtreport)
else:
return redirect(userrcardbtreport)
else:
return redirect(LoginPage)
def databasefix(request):
vcloudtxns=vcloudtransactions.objects.filter(sponser1__isnull=True)
print(vcloudtxns)
count=0
for i in vcloudtxns:
username=i.saleduser.username
data=list()
while(True):
user=UserData.objects.get(username=username)
if(user.postId=="Admin"):
#print(username)
data.append(username)
#print(count)
break;
else:
#print(username)
data.append(username)
username=user.sponserId.username
#print(data)
print(len(data))
if(len(data)==2):
sponser1=UserData.objects.get(username=data[1])
sponser2=UserData.objects.get(username=data[0])
vd=vcloudtransactions.objects.get(id=i.id)
vd.sponser1=sponser1
vd.sponser2=sponser2
vd.save()
count=count+1
print("success :"+str(count))
elif(len(data)==3):
print("Haiii")
sponser1=UserData.objects.get(username=data[2])
sponser2=UserData.objects.get(username=data[1])
sponser3=UserData.objects.get(username=data[0])
vd=vcloudtransactions.objects.get(id=i.id)
vd.sponser1=sponser1
vd.sponser2=sponser2
vd.sponser3=sponser3
vd.save()
count=count+1
print("success :"+str(count))
elif(len(data)==4):
sponser1=UserData.objects.get(username=data[3])
sponser2=UserData.objects.get(username=data[2])
sponser3=UserData.objects.get(username=data[1])
sponser4=UserData.objects.get(username=data[0])
vd=vcloudtransactions.objects.get(id=i.id)
vd.sponser1=sponser1
vd.sponser2=sponser2
vd.sponser3=sponser3
vd.sponser4=sponser4
vd.save()
count=count+1
print("success :"+str(count))
return redirect(vcloudhomepage)
def convert_datetime_timezone(dt):
tz1 ="UTC"
tz2 ="Asia/Riyadh"
tz1 = pytz.timezone(tz1)
tz2 = pytz.timezone(tz2)
new_dt = str(dt)
new_dt = new_dt[:19]
dt = datetime.strptime(new_dt,"%Y-%m-%d %H:%M:%S")
dt = tz1.localize(dt)
dt = dt.astimezone(tz2)
dt = dt.strftime("%b %d, %Y - %I:%M %p")
return dt
|
[
"jishnuchandralayam@gmail.com"
] |
jishnuchandralayam@gmail.com
|
a31b32768b8e24ce287fb8161192f16f6ddc2a5b
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_088/ch12_2020_09_03_17_14_08_176382.py
|
0fcbc84b977d85e7534cfd47f90398c5fe211e9c
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 112
|
py
|
a=10
b=5
def resolve_equacao_1o_grau(x):
resolve_equacao_1o_grau = a*x +b
return resolve_equacao_1o_grau
|
[
"you@example.com"
] |
you@example.com
|
5d24ee6b54d47695bc100f83f84d1f87af4bb5bd
|
e037114adce145d846c6ce64aab1798dfd689ffc
|
/testcode/test_vpn.py
|
b21c23246f15edc7418e7934418382b1251fda8f
|
[] |
no_license
|
Jingfei-Han/citation_prediction
|
11562ef51db24861001aae8aaf2f1b31cec3f304
|
cfd1c255a894e61b179d5004febbd67b32894ad7
|
refs/heads/master
| 2021-01-19T09:58:16.406627
| 2017-07-17T02:22:49
| 2017-07-17T02:22:49
| 87,803,920
| 0
| 2
| null | 2017-05-04T06:11:11
| 2017-04-10T11:39:08
|
Python
|
UTF-8
|
Python
| false
| false
| 985
|
py
|
#encoding:utf-8
import requests
#scholar.google.com.hk
headers = {
'Accept':'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
'Accept-Encoding':'gzip, deflate, sdch',
'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4',
'Connection':'keep-alive',
'Host':'ga.shhr.online',
'Referer':'https://ga.shhr.online/extdomains/scholar.google.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
'Cookie' : 'NID=103=gbCPErM0LV-e_Fmt62GDBERDlJe3qkXfNfthwvXX1lNAtGYq5hxvNWQr2RPKfIKTsbmAHESUGVhbqfv1JK44y8xwxHN52-5t6YZmsf7aqd8t-pd_DQkvy2i7tqNkzsIY; GSP=LM=1494311848:S=SYYUsD7oVa3HJKbG'
}
url = "https://ga.shhr.online/extdomains/scholar.google.com/scholar?q=Load-Balancing+Multipath+Switching+System+with+Flow+Slice+&btnG=&hl=en&as_sdt=0%2C5&as_ylo=2012&as_yhi=2012"
res = requests.get(url, headers=headers)
print res.status_code
print res.cookies
|
[
"jfhan007@gmail.com"
] |
jfhan007@gmail.com
|
466900412ac96d39fae512e6fb256007a4496259
|
074e444f175d6b944abaac3648ec34a8acab24e0
|
/KDPutils/kdputils/replies.py
|
8fea2f34ad4f0466f8aa9be910b1a72143d5ffde
|
[
"Apache-2.0"
] |
permissive
|
killvxk/LLDBagility
|
8f4e1091a00d95c486f5a618672416ca6fc31f35
|
6cc0df91bd49e43997b77048611d1b73f43f7b29
|
refs/heads/master
| 2020-06-06T23:29:14.052238
| 2019-06-28T07:38:40
| 2019-06-28T07:38:40
| 192,875,551
| 0
| 0
|
Apache-2.0
| 2019-06-28T07:38:41
| 2019-06-20T07:55:14
|
Python
|
UTF-8
|
Python
| false
| false
| 2,734
|
py
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from . import protocol
# https://github.com/apple/darwin-xnu/blob/xnu-4903.221.2/osfmk/kdp/kdp.c
def kdp_connect(error):
return dict(
is_reply=0x1,
request=protocol.KDPRequest.KDP_CONNECT,
seq=-1,
len=-1,
key=-1,
error=error,
)
def kdp_disconnect():
return dict(
is_reply=0x1, request=protocol.KDPRequest.KDP_DISCONNECT, seq=-1, len=-1, key=-1
)
def kdp_hostinfo(cpus_mask, cpu_type, cpu_subtype):
return dict(
is_reply=0x1,
request=protocol.KDPRequest.KDP_HOSTINFO,
seq=-1,
len=-1,
key=-1,
cpus_mask=cpus_mask,
cpu_type=cpu_type,
cpu_subtype=cpu_subtype,
)
def kdp_version(version, feature):
return dict(
is_reply=0x1,
request=protocol.KDPRequest.KDP_VERSION,
seq=-1,
len=-1,
key=-1,
version=version,
feature=feature,
pad0=0x0,
pad1=0x0,
)
def kdp_readregs(error, regs):
return dict(
is_reply=0x1,
request=protocol.KDPRequest.KDP_READREGS,
seq=-1,
len=-1,
key=-1,
error=error,
**regs
)
def kdp_writeregs(error):
return dict(
is_reply=0x1,
request=protocol.KDPRequest.KDP_WRITEREGS,
seq=-1,
len=-1,
key=-1,
error=error,
)
def kdp_resumecpus():
return dict(
is_reply=0x1, request=protocol.KDPRequest.KDP_RESUMECPUS, seq=-1, len=-1, key=-1
)
def kdp_reattach():
return dict(
is_reply=0x1, request=protocol.KDPRequest.KDP_REATTACH, seq=-1, len=-1, key=-1
)
def kdp_readmem64(error, data):
return dict(
is_reply=0x1,
request=protocol.KDPRequest.KDP_READMEM64,
seq=-1,
len=-1,
key=-1,
error=error,
data=data,
)
def kdp_writemem64(error):
return dict(
is_reply=0x1,
request=protocol.KDPRequest.KDP_WRITEMEM64,
seq=-1,
len=-1,
key=-1,
error=error,
)
def kdp_breakpoint64_set(error):
return dict(
is_reply=0x1,
request=protocol.KDPRequest.KDP_BREAKPOINT64_SET,
seq=-1,
len=-1,
key=-1,
error=error,
)
def kdp_breakpoint64_remove(error):
return dict(
is_reply=0x1,
request=protocol.KDPRequest.KDP_BREAKPOINT64_REMOVE,
seq=-1,
len=-1,
key=-1,
error=error,
)
def kdp_kernelversion(version):
return dict(
is_reply=0x1,
request=protocol.KDPRequest.KDP_KERNELVERSION,
seq=-1,
len=-1,
key=-1,
version=version,
)
|
[
"fcagnin@quarkslab.com"
] |
fcagnin@quarkslab.com
|
52d27b0ab61e4b43276b9753f55a4cf60273abe6
|
e5caf8b108da88553f6db9b11f2a4911c578cb6a
|
/快速排序及其优化/QuickSort_NotRecursion.py
|
f75c05c8aa07f03b923c1e3569ec460ff0fa1f15
|
[] |
no_license
|
zg-diligence/blog_contents
|
663e33cbeddb3457a8badac870a03f8250c711ee
|
8252a2ff800271566aec56aeef4334efe75864b3
|
refs/heads/master
| 2021-01-23T17:39:35.036750
| 2017-05-14T03:23:36
| 2017-05-14T03:23:36
| 82,987,688
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 8,567
|
py
|
"""
Copyright(c) 2017 Gang Zhang
All rights reserved.
Author:Gang Zhang
Date:2017.5.11
Abstract:
This program mainly implements quick_sort and its improvement.
There are 5 methods for choose of the pivot element in total, and
in QuickSort_6 we implements the three-way quick_sorting.
All the implementations are not recursive.
"""
import time
import random
import matplotlib.pyplot as plt
def InsertionSort(arr, low, high):
"""Insertion sorting"""
size = high - low + 1
if size <= 1: return
for i in range(low, high + 1):
tmp, j = arr[i], i - 1
while j >= low:
if arr[j] > tmp:
arr[j + 1], j = arr[j], j - 1
else:break
arr[j + 1] = tmp
def median_of_three(arr, low, high, mid = -1):
"""return pos of the median of three"""
if mid == -1: mid = (low + high) // 2
if arr[mid] <= arr[low] <= arr[high] or arr[high] <= arr[low] <= arr[mid]:
return low
if arr[low] <= arr[mid] <= arr[high] or arr[high] <= arr[mid] <= arr[low]:
return mid
if arr[low] <= arr[high] <= arr[mid] or arr[mid] <= arr[high] <= arr[low]:
return high
def median_of_nine(arr, low, high):
"""return pos of the median of nine"""
size = high - low + 1
median_1 = median_of_three(arr, low, low + size // 3)
median_2 = median_of_three(arr, low + size // 3 + 1, high - size // 3)
median_3 = median_of_three(arr, high - size // 3 + 1, high)
return median_of_three(arr, median_1, median_2, median_3)
def qsort(arr, stack):
"""called by main sorting function"""
high, low = stack.pop(-1), stack.pop(-1)
pivot, less_equal, greater = arr[high], [], []
for x in arr[low:high]:
if x <= pivot:less_equal.append(x)
else:greater.append(x)
arr[low: high + 1] = less_equal + [pivot] + greater
if len(less_equal) > 1:
stack.append(low);stack.append(low + len(less_equal) - 1)
if len(greater) > 1:
stack.append(high - len(greater) + 1);stack.append(high)
def QuickSort_1(arr):
"""choose arr[n] as the pivot"""
if len(arr) <= 1: return arr
stack = [0, len(arr)-1]
while stack:
qsort(arr, stack)
return arr
def QuickSort_2(arr):
"""choose an element randomly as the pivot"""
if len(arr) <= 1: return arr
stack = [0, len(arr)-1]
while stack:
low, high = stack[-2], stack[-1]
pos = random.randint(low, high)
arr[pos], arr[high] = arr[high], arr[pos]
qsort(arr, stack)
return arr
def QuickSort_3(arr):
"""choose the bigger one between the first two diffrent elements as the pivot"""
if len(arr) <= 1:return arr
stack = [0, len(arr)-1]
while stack:
low, high = stack[-2], stack[-1]
pos, k = low, low + 1
while k <= high:
if arr[k] > arr[pos]:
pos = k;break
elif arr[k] < arr[pos]:
break
k += 1
if k == high + 1:
stack.pop(-1); stack.pop(-1); continue
arr[pos], arr[high] = arr[high], arr[pos]
qsort(arr, stack)
return arr
def QuickSort_4(arr):
"""choose median of three as the pivot"""
if len(arr) <= 1: return arr
stack = [0, len(arr) - 1]
while stack:
low, high = stack[-2], stack[-1]
pos = median_of_three(arr, low, high)
arr[pos], arr[high] = arr[high], arr[pos]
qsort(arr, stack)
return arr
def QuickSort_5(arr):
"""sort in different ways at lenth of the arr"""
"""
when n < 7, insertion_sort
when n = 7, choose the median one as the pivot
when 7 < n < 40, choose the median of three as the pivot
when n >= 40, choose the median of ni
ne as the pivot
"""
if len(arr) <= 1: return arr
stack = [0, len(arr) - 1]
while stack:
size, low, high = stack[-1] - stack[-2] + 1, stack[-2], stack[-1]
if size < 7:
InsertionSort(arr, low, high)
stack.pop(-1); stack.pop(-1); continue
elif size == 7:
arr[low + 3], arr[high] = arr[high], arr[low + 3]
elif 7 < size < 40:
pos = median_of_three(arr, low, high)
arr[pos], arr[high] = arr[high], arr[pos]
else:
pos = median_of_nine(arr, low, high)
arr[pos], arr[high] = arr[high], arr[pos]
qsort(arr, stack)
return arr
def QuickSort_6(arr):
"""quick_sort in three ways"""
if len(arr) <= 1: return arr
stack = [0, len(arr)-1]
while stack:
high, low = stack.pop(-1), stack.pop(-1)
pivot, less, equal, greater =arr[random.randint(low, high)], [], [], []
for x in arr[low: high + 1]:
if x < pivot: less.append(x)
elif x == pivot: equal.append(x)
else:greater.append(x)
arr[low: high + 1] = less + equal + greater
if len(less) > 1:
stack.append(low); stack.append(low + len(less) - 1)
if len(greater) > 1:
stack.append(high - len(greater) + 1);stack.append(high)
return arr
def test_func(SortWays, standard = 1000):
"""test for each function with different scale data"""
arrays = [[random.randint(1, 10000000) for k in range(standard * m)] for m in range(1, 91, 3)]
times, names = [], [str(len(arr)) for arr in arrays]
for sort in SortWays: # test for the custom sorting function.
func_time = []
for arr in arrays:
t1 = time.time()
sort(arr[:])
t2 = time.time()
func_time.append(round(t2 - t1, 6))
times.append(func_time)
func_time = []
for arr in arrays: # test for the library sorting function.
t1 = time.time()
sorted(arr[:])
t2 = time.time()
func_time.append(round(t2 - t1, 6))
times.append(func_time)
return times, names
def test_arr(SortWays, RecordsNum = 10000):
"""test different function with the same data."""
arrays = [[25] * RecordsNum,
list(range(RecordsNum)),
list(range(RecordsNum, 0, -1)),
[random.randint(1, 10000000) for k in range(RecordsNum)],
[random.randint(1, 100) for k in range(RecordsNum)]]
names = ['same records',
'positive sequence',
'negative sequence',
'random sequence',
'repetited records']
times = []
for arr in arrays:
arr_time = []
for sort in SortWays: # test for the custom sorting function.
t1 = time.time()
sort(arr[:])
t2 = time.time()
arr_time.append(round(t2 - t1, 6))
t1 = time.time()
sorted(arr[:]) # test for library function.
t2 = time.time()
arr_time.append(round(t2 - t1, 6))
times.append(arr_time)
return times, names
if __name__ == '__main__':
SortWays = [QuickSort_1, QuickSort_2, QuickSort_3, QuickSort_4, QuickSort_5, QuickSort_6]
func_names = ['right_most', 'random', 'bigger_one', 'mid_three', 'mid_nine', '3ways', 'sorted']
# test for data users input.
while True:
arr = [int(elem) for elem in input('请输入数据:\n').split(' ')]
for k in range(len(SortWays)):
print(func_names[k], ":\n", SortWays[k](arr[:]), sep='', end='\n\n')
if input('Do you want to continue(Y/N):') != 'Y':break
# test for single data.
times, names = test_arr(SortWays)
for k in range(len(times)):
plt.subplot(3, 2, k+1)
plt.bar([x for x in range(1, 8)], times[k], color='y', width=0.5)
plt.xticks(list(range(1, 8)), func_names)
plt.title(names[k])
plt.tight_layout(w_pad=0.5, h_pad=0.5)
plt.show()
# test for single function, show together.
times, names = test_func(SortWays)
color = list('bgrcmyk')
for k in range(len(times)):
plt.plot(names, times[k], color[k] + 'o-', linewidth=1, label=func_names[k])
plt.legend(loc='upper left')
plt.title('comparision')
plt.show()
# test for single function, show separately.
for k in range(len(times)):
plt.subplot(3, 3, k+1)
plt.plot(names, times[k], color[k] + 'o-', linewidth=1)
plt.title(func_names[k])
plt.tight_layout(w_pad=0.5, h_pad=0.5)
plt.show()
"""
4 8 45 12 47 12 45 48 123 45 78 455 2 1 2 3 5 45 78 4 54 1 24 5 42 456 2 456 7 51 564 5 15 1 2 45 42 4 5 1 5421 565 2 1 54 12 45 1 2 4 51 5 4 15 54 878 4 54 78 45 12 154 612 45 4 5 2124 215 4 2 45 12 45 1 24 51 54 2 45 6122 45 4 1 2 5 2 8 4 4 5 4 4 1 2 8 4
"""
|
[
"zg_diligence@126.com"
] |
zg_diligence@126.com
|
a4a49c81eeac6f694c2f8096b47fd36dc5b78d06
|
402d54f2da4f572e617c18de3c64a8df24a9228f
|
/myvoice.py
|
d154e5aa13aabdeb7912bd51aa2be5b2a43b04c7
|
[] |
no_license
|
johnbangla/voice
|
773242cc8f29eb1b61b2108377cdca75f14bda2f
|
fcb9d4e6daaa74d8f15e187e2ec37181d088a1a1
|
refs/heads/master
| 2023-06-22T11:46:10.865314
| 2021-07-22T18:42:43
| 2021-07-22T18:42:43
| 388,563,388
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,237
|
py
|
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import time
import requests
import subprocess #process various system commands like to log off or to restart your system
# from ecapture import ecapture as ec #for capturing photos
import playsound # to play saved mp3 file
from gtts import gTTS # google text to speech
import os # to save/open files
import wolframalpha # to calculate strings into formula
from selenium import webdriver # to control browser operations
def talk():
input=sr.Recognizer()
with sr.Microphone() as source:
audio=input.listen(source)
data=""
try:
data=input.recognize_google(audio)
print("Your question is, " + data)
except sr.UnknownValueError:
print("Sorry I did not hear your question, Please repeat again.")
return data
def respond(output):
num=0
print(output)
num += 1
response=gTTS(text=output, lang='en')
file = str(num)+".mp3"
response.save(file)
playsound.playsound(file, True)
os.remove(file)
if __name__=='__main__':
respond("Hi, I am your personal assistant")
while(1):
respond("How can I help you?")
text=talk().lower()
if text==0:
continue
if "stop" in str(text) or "exit" in str(text) or "bye" in str(text):
respond("Ok bye and take care")
break
if 'wikipedia' in text:
respond('Searching Wikipedia')
text =text.replace("wikipedia", "")
results = wikipedia.summary(text, sentences=3)
respond("According to Wikipedia")
print(results)
respond(results)
elif 'time' in text:
strTime=datetime.datetime.now().strftime("%H:%M:%S")
respond(f"the time is {strTime}")
elif 'search' in text:
text = text.replace("search", "")
webbrowser.open_new_tab(text)
time.sleep(5)
# elif "camera" in statement or "take a photo" in statement:
# print("camera")
# ec.capture(0,"robo camera","img.jpg")
# elif "calculate" or "what is" in text:
# question=talk()
# app_id="API key"
# client = wolframalpha.Client(app_id)
# res = client.query(question)
# answer = next(res.results).text
# respond("The answer is " + answer)
elif 'who are you' in text or 'what can you do' in text:
respond(' I can fetch information for you, perform mathematical calculations, take photo, open applications, get weather details.')
elif 'open gmail' in text:
webbrowser.open_new_tab("https://www.gmail.com")
respond("Gmail is open")
time.sleep(5)
elif "who made you" or "who created you" or "who discovered you" :
respond("I was built by Mirthula")
print("I was built by Mirthula")
elif 'open google' in text:
webbrowser.open_new_tab("https://www.google.com")
respond("Google is open")
time.sleep(5)
elif 'youtube' in text:
driver = webdriver.Chrome(r"C:\Users\DhanushDhyan\Downloads\chromedriver_win32\chromedriver.exe")
driver.implicitly_wait(1)
driver.maximize_window()
respond("Opening in youtube")
indx = text.split().index('youtube')
query = text.split()[indx + 1:]
driver.get("http://www.youtube.com/results?search_query =" + '+'.join(query))
elif "weather" in text:
respond("what is the city name")
city_name=talk()
api_key="API key"
base_url="https://api.openweathermap.org/data/2.5/weather?"
complete_url=base_url+"appid="+api_key+"&q="+city_name
response = requests.get(complete_url)
x=response.json()
if x["cod"]!="404":
y=x["main"]
current_temperature = y["temp"]
current_humidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
respond(" Temperature is " +
str(current_temperature) +
"\n humidity in percentage is " +
str(current_humidiy) +
"\n description " +
str(weather_description))
elif "shut down" in text:
respond("Ok , your system will shut down in 10 secs")
subprocess.call(["shutdown", "/l"])
elif "open word" in text:
respond("Opening Microsoft Word")
os.startfile('file location')
else:
respond("Application not available")
#To install pyAudio
#https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio
|
[
"johnbangla@gmail.com"
] |
johnbangla@gmail.com
|
76d919db27aec2ea25b8174be788faff4a56d33b
|
cf45f3d1f10bf85337602cbd2feb8558a12a5144
|
/ch10/factorialLog.py
|
6552b792b006c37b7802110995971516aba2be75
|
[] |
no_license
|
takumi3682/automatestuff-ja
|
58cc1209ff11d5cd6c94bcf8aada457c2be7fda0
|
b72c3421976ddb404f4bc93bd379474e78112b4b
|
refs/heads/master
| 2023-08-28T04:40:32.669185
| 2023-08-05T00:06:12
| 2023-08-05T00:06:12
| 260,598,802
| 0
| 0
| null | 2020-05-02T02:26:24
| 2020-05-02T02:26:23
| null |
UTF-8
|
Python
| false
| false
| 467
|
py
|
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('プログラム開始')
def factorial(n):
logging.debug('factorial({})開始'.format(n))
total = 1
for i in range(n + 1):
total *= i
logging.debug('i = {}, total = {}'.format(i, total))
logging.debug('factorial({})終了'.format(n))
return total
print(factorial(5))
logging.debug('プログラム終了')
|
[
"aizoaikawa@gmail.com"
] |
aizoaikawa@gmail.com
|
27a8e3f0c62cdbdd303f4f78d4ba566e4c9f0a4a
|
ab2d968bf2bb7f04f5ebb83c71b8bef37c28d7e4
|
/insert_data_mysql.py
|
2f462bf04404c8690ee83f0d8259a3e3f6757a57
|
[] |
no_license
|
lushilong/python-do-somework
|
d6e35cfb8967b1335783f5f7d3c2a2e2ccadb156
|
eb1ea0b1191270fedaca3aa20b3ca370c3447028
|
refs/heads/master
| 2020-06-01T18:59:31.475074
| 2014-07-02T07:55:03
| 2014-07-02T07:55:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,735
|
py
|
#!/usr/bin/python
#-*-coding=utf-8
#
import sys
import MySQLdb
import time
import random
import string
def CreateTableSql(table_name):
create_table_sql = "create table " + table_name + \
"(time_" + RandomChar(20) + " varchar(25), "\
"a_" + RandomChar(20) + " char(120), "\
"b_" + RandomChar(20) + " char(120), "\
"c_" + RandomChar(20) + " char(120), "\
"d_" + RandomChar(20) + " char(120), "\
"e_" + RandomChar(20) + " char(120), "\
"f_" + RandomChar(20) + " char(120), "\
"g_" + RandomChar(20) + " char(120), "\
"h_" + RandomChar(20) + " char(120), "\
"i_" + RandomChar(20) + " char(120), "\
"j_" + RandomChar(20) + " char(120), "\
"k_" + RandomChar(20) + " char(120), "\
"l_" + RandomChar(20) + " char(120), "\
"m_" + RandomChar(20) + " char(120), "\
"n_" + RandomChar(20) + " char(120))"
return create_table_sql
def InsertDataSql(table_name):
insert_data_sql = "insert into " + table_name + \
" values('" + str(time.strftime('%a %b %d %H:%M:%S %Y',time.localtime(time.time()))) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "', " +\
"'" + RandomChar(80) + "')"
return insert_data_sql
def RandomChar(n):
random_char = ''.join([random.choice(string.letters+string.digits) for e in range(n)])
return random_char
if __name__ == '__main__':
start_time = str(time.strftime('%a %b %d %H:%M:%S %Y',time.localtime(time.time())))
logfile = open("/home/shilong/Temp/insert_mysql_data_log.txt", "a")
print >> logfile, "==================== %s ====================" % start_time
try:
conn = MySQLdb.connect(host="192.168.88.124",user="root",passwd="dingjia",db="scutech")
cur = conn.cursor()
except MySQLdb.DatabaseError as e:
error, = e.args
print >> logfile, error.message
sys.exit(0)
tables = ['scutech_one', 'scutech_two', 'scutech_three', 'scutech_four', 'scutech_five', 'scutech_six']
i = 0
for t in tables:
j = 1
# create_table_sql = CreateTableSql(t)
# try:
# cur.execute(create_table_sql)
# print >> logfile, "Table %s Created!" % t.upper()
# except MySQLdb.DatabaseError as e:
# error = e.args
# print >> logfile, "Create table %s raising some Errors:" % t.upper(), error
# sys.exit(0)
while j <= 100:
i += 1
insert_data_sql = InsertDataSql(t)
try:
cur.execute(insert_data_sql)
except MySQLdb.DatabaseError as e:
error, = e.args
print >> logfile, "Insert into table %s raising some Errors: " % t.upper(), error.message
break
if i%1000 == 0:
conn.commit()
time.sleep(5)
j += 1
print >> logfile, "Table %s has inserted %d records" % (t.upper(), j-1)
conn.commit()
cur.close()
conn.close()
print >> logfile, "All Table Insert Completed!"
end_time = str(time.strftime('%a %b %d %H:%M:%S %Y',time.localtime(time.time())))
print >> logfile, "==================== %s ====================\n" % end_time
logfile.close()
|
[
"lushilonger@foxmail.com"
] |
lushilonger@foxmail.com
|
84def82cf32dd4ac95c3ac7ee84e10f20137b73a
|
2bb90b620f86d0d49f19f01593e1a4cc3c2e7ba8
|
/pardus/playground/igungor/2011/devel/kernel/default/drivers/module-compat-wireless/actions.py
|
5e096ade79e4f81b2a2c1fe9d1d52e72b8d1ac92
|
[] |
no_license
|
aligulle1/kuller
|
bda0d59ce8400aa3c7ba9c7e19589f27313492f7
|
7f98de19be27d7a517fe19a37c814748f7e18ba6
|
refs/heads/master
| 2021-01-20T02:22:09.451356
| 2013-07-23T17:57:58
| 2013-07-23T17:57:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 935
|
py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2010-2011 TUBITAK/UEKAE
# Licensed under the GNU General Public License, version 2.
# See the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
from pisi.actionsapi import kerneltools
from pisi.actionsapi import shelltools
from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
from pisi.actionsapi import get
KDIR = kerneltools.getKernelVersion()
def setup():
pisitools.dosed("config.mk", "\$\(MAKE\) -C \$\(KLIB_BUILD\) kernelversion", "echo \"%s\"" % KDIR)
pisitools.dosed("scripts/gen-compat-autoconf.sh", "make -C \$KLIB_BUILD kernelversion", "echo \"%s\"" % KDIR)
def build():
autotools.make("MODPROBE=/bin/true KLIB=/lib/modules/%s" % KDIR)
def install():
autotools.install("KLIB=/lib/modules/%s KMODPATH_ARG='INSTALL_MOD_PATH=%s' DEPMOD=/bin/true" % (KDIR, get.installDIR()))
pisitools.dodoc("COPYRIGHT", "README")
|
[
"yusuf.aydemir@istanbul.com"
] |
yusuf.aydemir@istanbul.com
|
1cf2a2249ceed83cd8519c2383fa0d484f10644e
|
bdf86d69efc1c5b21950c316ddd078ad8a2f2ec0
|
/venv/Lib/site-packages/twisted/words/tap.py
|
8ce22c892173a3627b4cef4830ba485de67dd8c1
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
DuaNoDo/PythonProject
|
543e153553c58e7174031b910fd6451399afcc81
|
2c5c8aa89dda4dec2ff4ca7171189788bf8b5f2c
|
refs/heads/master
| 2020-05-07T22:22:29.878944
| 2019-06-14T07:44:35
| 2019-06-14T07:44:35
| 180,941,166
| 1
| 1
| null | 2019-06-04T06:27:29
| 2019-04-12T06:05:42
|
Python
|
UTF-8
|
Python
| false
| false
| 2,428
|
py
|
# -*- test-case-name: twisted.words.test.test_tap -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Shiny new words service maker
"""
import socket
import sys
from twisted import plugin
from twisted.application import strports
from twisted.application.service import MultiService
from twisted.cred import checkers, credentials, portal, strcred
from twisted.python import usage
from twisted.words import iwords, service
class Options(usage.Options, strcred.AuthOptionMixin):
supportedInterfaces = [credentials.IUsernamePassword]
optParameters = [
('hostname', None, socket.gethostname(),
'Name of this server; purely an informative')]
compData = usage.Completions(multiUse=["group"])
interfacePlugins = {}
plg = None
for plg in plugin.getPlugins(iwords.IProtocolPlugin):
assert plg.name not in interfacePlugins
interfacePlugins[plg.name] = plg
optParameters.append((
plg.name + '-port',
None, None,
'strports description of the port to bind for the ' + plg.name + ' server'))
del plg
def __init__(self, *a, **kw):
usage.Options.__init__(self, *a, **kw)
self['groups'] = []
def opt_group(self, name):
"""Specify a group which should exist
"""
self['groups'].append(name.decode(sys.stdin.encoding))
def opt_passwd(self, filename):
"""
Name of a passwd-style file. (This is for
backwards-compatibility only; you should use the --auth
command instead.)
"""
self.addChecker(checkers.FilePasswordDB(filename))
def makeService(config):
credCheckers = config.get('credCheckers', [])
wordsRealm = service.InMemoryWordsRealm(config['hostname'])
wordsPortal = portal.Portal(wordsRealm, credCheckers)
msvc = MultiService()
# XXX Attribute lookup on config is kind of bad - hrm.
for plgName in config.interfacePlugins:
port = config.get(plgName + '-port')
if port is not None:
factory = config.interfacePlugins[plgName].getFactory(wordsRealm, wordsPortal)
svc = strports.service(port, factory)
svc.setServiceParent(msvc)
# This is bogus. createGroup is async. makeService must be
# allowed to return a Deferred or some crap.
for g in config['groups']:
wordsRealm.createGroup(g)
return msvc
|
[
"teadone@naver.com"
] |
teadone@naver.com
|
58e738192e740fb80d200280f2d75140c2d06c0d
|
d7d97550d7d1bd68203b395b5ab867981e905942
|
/flaskface/migrations/versions/3e8ba40e9535_add_salman.py
|
2c3142d0c61d49200f8b03a2614517219e7aa6ba
|
[] |
no_license
|
salman036/NewFlaskBlog
|
e7f2162d86a91ad3497b3b801c516b89819bc241
|
5d26995bf2b028575e2ddb5e91e73a3db2f21dd3
|
refs/heads/master
| 2020-09-25T00:38:55.163104
| 2019-12-04T14:04:26
| 2019-12-04T14:04:26
| 225,881,007
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 653
|
py
|
"""Add salman
Revision ID: 3e8ba40e9535
Revises: 2d1175e7060a
Create Date: 2019-05-21 12:41:50.546530
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '3e8ba40e9535'
down_revision = '2d1175e7060a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('post', sa.Column('salman', sa.String(length=50), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('post', 'salman')
# ### end Alembic commands ###
|
[
"salman.saleem@southvillesol.com"
] |
salman.saleem@southvillesol.com
|
a716d66822de62f506ba8f9c4053623b117cc539
|
d0c42d27f986b2636bfcadedea221a055e549234
|
/LogApp/apps.py
|
d7cd0d34b77c7fd5c2f036161906f2d41a645e78
|
[] |
no_license
|
CristianAThompson/DjangoTimeLog
|
62a8362995d49157017da94331fa7cec3778c2b5
|
c4ff9f39654c5cc3a049fd4a6a4d73d7e5d6cfe2
|
refs/heads/master
| 2021-01-22T22:03:52.526159
| 2017-07-09T16:23:10
| 2017-07-09T16:23:10
| 92,755,756
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 92
|
py
|
from django.apps import AppConfig
class LogappConfig(AppConfig):
name = 'LogApp'
|
[
"Thompsonacristian@gmail.com"
] |
Thompsonacristian@gmail.com
|
39bbd25fb8ff6bca91c0a134551e64b75016cc66
|
91a879fc92dc2117bdeab2d606a85988827d2895
|
/rango/urls.py
|
9845ccaa080f76e8138a2c4f573282947de8317d
|
[] |
no_license
|
irfan5d7/tango_django
|
1958e4c8dcdc71654ff42bc089fd034d33b29a02
|
ee43b6bb8915ed828c1339506b48bac83a283c1a
|
refs/heads/master
| 2020-03-22T07:38:00.772357
| 2018-07-04T11:35:53
| 2018-07-04T11:35:53
| 139,713,618
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,191
|
py
|
from django .urls import path
from django.conf import settings
from rango import views
from rango.Views import *
from rango.views import *
from django.conf.urls import include, url
app_name = 'rango'
from rango.Views import *
urlpatterns = [
url('index/',index,name= 'index'),
url(r'rango/',index,name='index'),
url(r'about/$', about, name='about'),
url('add_category/',add_category,name='add_category'),
url(r'^suggest/$',suggest_category, name='suggest_category'),
url(r'category/(?P<category_name_slug>[\w\-]+)/add_page/$', add_page, name='add_page'),
url(r'category/(?P<category_name_slug>[\w\-]+)/$',show_category, name='show_category'),
url(r'^register/$',register,name = 'register'),
url(r'^login/$',user_login, name='login'),
url(r'^restricted/',restricted,name='restricted'),
url(r'^logout/$',user_logout,name ='logout'),
url(r'^search_bing/', search_bing, name='search_bing'),
url(r'goto/$',track_url,name = 'goto'),
url(r'^register_profile/$',register_profile, name='register_profile'),
url(r'^profile/(?P<username>[\w\-]+)/$',profile, name='profile'),
url(r'^like_category/$',like_category,name='like_category'),
]
|
[
"irfanahmed.511.ia@gmail.com"
] |
irfanahmed.511.ia@gmail.com
|
79234b8ad6914fbf14491bfbc20543ada6bdf54f
|
9091fa04f4e57460b34b852d968da43b0a3de59c
|
/CSCI 1100/LAB/LAB1/lab1_part2.py
|
4df29b7554eae894d830d3dc57eab1c0ef610fe9
|
[] |
no_license
|
YunheWang0813/RPI-Repository
|
b09af436e295c41b423106447ce268b0fb79721b
|
c0f279474ea5db91eab0c438c57ae0dc198c5609
|
refs/heads/master
| 2020-03-31T23:03:14.761451
| 2019-02-08T00:15:47
| 2019-02-08T00:15:47
| 152,641,110
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 183
|
py
|
base10=128
A=base10*10**9
base2=A/2**30
difference=base10-base2
print base2, difference
print base10 , "In base10 is actually", base2 , "in base2", difference, "less than advertised."
|
[
"41502154+YunheWang0813@users.noreply.github.com"
] |
41502154+YunheWang0813@users.noreply.github.com
|
0e07d1d7b746b504b65fee1d7e6d8c5723e0ee18
|
4d203bb9e01c27c5202cda384c5c68c10c55acaf
|
/auth/routes.py
|
4ef091685c2478bf4b42e30659728d6ea460cfd2
|
[] |
no_license
|
otolifi/projeto_brasileirao
|
6157ed419c7780f042c7e12f4a0fc86ae5136fd0
|
3ad8511899f4dbcb715fa07514fa1d0305fbcb42
|
refs/heads/main
| 2023-03-23T05:57:28.902860
| 2021-03-19T07:00:16
| 2021-03-19T07:00:16
| 349,330,054
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,706
|
py
|
from flask import render_template, flash, redirect, url_for, request
from flask_login import current_user, login_user, logout_user
from werkzeug.urls import url_parse
from brasileirao import db
from auth import bp
from auth.forms import LoginForm, RegistrationForm
from models import User
@bp.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('main.index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash('Usuário ou senha incorreto')
return redirect(url_for('auth.login'))
login_user(user, remember=form.remember_me.data)
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
next_page = url_for('main.index')
return redirect(next_page)
return render_template('login.html', title='Entrar', form=form)
@bp.route('/logout')
def logout():
logout_user()
return redirect(url_for('main.index'))
@bp.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('main.index'))
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, email=form.email.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Parabéns, você se registrou!')
return redirect(url_for('auth.login'))
return render_template('register.html', title='Registro', form=form)
|
[
"otolifi@gmail.com"
] |
otolifi@gmail.com
|
fcfb8ef20727545c9b23c07d5af434c785d5b1c7
|
76bf6bdc6c3b3c0a758529fecb9931f83cb5eff9
|
/data/raw/LREC/converter.py
|
4abbb16931f6293095ef14cc1635cb07af5e44b1
|
[
"MIT"
] |
permissive
|
heathher/neural_sequence_labeling
|
6376089cde24dbae093494ecc0f9951ddc7582a3
|
81c83443982f5b1723fde3d446eb94e8cb7a4c44
|
refs/heads/master
| 2020-03-30T17:55:22.783711
| 2018-10-05T20:05:18
| 2018-10-05T20:05:18
| 151,475,385
| 0
| 0
|
MIT
| 2018-10-03T20:21:45
| 2018-10-03T20:21:45
| null |
UTF-8
|
Python
| false
| false
| 746
|
py
|
import sys
import codecs
mapping = {"COMMA": ",COMMA", "PERIOD": ".PERIOD", "QUESTION": "?QUESTIONMARK", "O": ""}
counts = dict((p, 0) for p in mapping)
with codecs.open(sys.argv[1], 'r', 'utf-8', 'ignore') as f_in, \
codecs.open(sys.argv[2], 'w', 'utf-8') as f_out:
for i, line in enumerate(f_in):
line = line.replace('?', '')
parts = line.split()
if len(parts) == 0:
continue
if len(parts) == 1:
word = ""
punct = parts[0]
else:
word, punct = parts
counts[punct] += 1
f_out.write("%s %s " % (word, mapping[punct]))
print("Counts:")
for p, c in counts.items():
print("%s: %d" % (p, c))
|
[
"isaac.changhau@gmail.com"
] |
isaac.changhau@gmail.com
|
a63804b47305dbd9f10f230e3541635bf03deec9
|
d8e5d0edf38dc91974d84bc3c2b13a354ddfe8e9
|
/tables.py
|
6023c741661fa25f45edb5740904160ca6b5ea4f
|
[] |
no_license
|
ByronPiedrahita/cursoSelenium
|
f2cef8b7d65f0b3afa784e9c9c38871a296bfd77
|
d9929faf92729b030e9e3cebdcdc2b5d2f4317a0
|
refs/heads/master
| 2023-01-27T21:16:28.602670
| 2020-11-26T16:31:38
| 2020-11-26T16:31:38
| 315,665,318
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,655
|
py
|
"""
Este scrip obtiene el header de una tabla y su contenido
"""
import unittest
from selenium import webdriver
class Tables(unittest.TestCase):
def setUp(self):
self.driver= webdriver.Chrome(executable_path = r'./chromedriver.exe')
driver = self.driver
driver.get("http://the-internet.herokuapp.com/")
driver.maximize_window()
driver.implicitly_wait(1)
driver.find_element_by_link_text('Sortable Data Tables').click()
def test_sort_tables(self):
driver = self.driver
table_data = list()
# Obtengo una lista de los tr en el body de la tabla
# a dicha lista le aplico un len() y obtenermos cuantos datos hay en el body
data_size = driver.find_elements_by_xpath('//*[@id="table1"]/tbody/tr')
# Obtener una lista de los th contenido en el thead de la tabla
# Con la lista de los th, le aplico un len a la lista y veos cuantos header hay
header_size = driver.find_elements_by_xpath('//*[@id="table1"]/thead/tr/th')
for i in range(1,len(data_size)+1):
for j in range(1,len(header_size)): # Omitimos el header action
header = driver.find_element_by_xpath(f'//*[@id="table1"]/thead/tr/th[{j}]/span').text
content = driver.find_element_by_xpath(f'//*[@id="table1"]/tbody/tr[{i}]/td[{j}]').text
table_data.append({header:content})
print(table_data)
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main(verbosity=2)
|
[
"byronpiedrahita.programmer@gmail.com"
] |
byronpiedrahita.programmer@gmail.com
|
921820e9f1397a494d67886c8060fe4e1a81a750
|
3844ce3c9fcf735f0c46f0f66ec14a734ca7205c
|
/without_dbsnp_c/access_single.py
|
aa7fd7cd62bb7dbac456dbcececa09b54b1b3d52
|
[] |
no_license
|
MingruBai/PrincetonCOS598F-DNADeduplication
|
9165cf872254663e2feb355fd9018da55b7cc349
|
f46c688c93d6c007a0dff8bfe22d671baff6b05c
|
refs/heads/master
| 2020-12-24T21:22:06.189886
| 2016-05-16T20:24:18
| 2016-05-16T20:24:18
| 56,558,472
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,188
|
py
|
import sys
import os
def access_single(chr, target):
if target <= 0:
print "Invalid target coordinate.";
sys.exit();
#Decompress:
os.system("bzip2 -d -k ./var/chr"+chr+"_formatted.txt.bz2");
#Read variations:
cfile = open("./var/chr"+chr+"_formatted.txt",'r');
tList = cfile.readline().strip();
pList = cfile.readline().strip().split();
sList = cfile.readline().strip().split();
cfile.close();
#Pointer at reference genome:
refLoc = target;
#Difference used to adjust relative distance:
prevDiff = 0;
found = False;
for i in range(len(tList)):
t = tList[i];
p = int(pList[i]);
s = sList[i];
#Update the relative position
p = p + prevDiff;
#If access point is before next variation:
if target < p:
get_ref(chr, refLoc - 1);
found = True;
break;
#If SNP:
if t == '0':
target = target - p;
prevDiff = 0;
if target == 0:
found = True;
sys.stdout.write(s);
break;
#If deletion:
if t == '1':
numDel = int(s);
refLoc = refLoc + numDel;
target = target - p + 1;
prevDiff = 1 - numDel;
#If insertion:
if t == '2':
numIns = len(s);
if target <= p + numIns - 1:
sys.stdout.write(s[target - p]);
found = True;
break;
refLoc = refLoc - numIns;
target = target - p - numIns + 1;
prevDiff = 1;
#If no more variation:
if not found:
get_ref(chr, refLoc - 1);
sys.stdout.write('\n');
os.system("rm ./var/chr"+chr+"_formatted.txt");
# def get_ref(chr, loc):
# rfile = open("./chr/chr"+chr+".fa",'r')
# rfile.readline();
# n = loc / 50;
# p = loc % 50;
# for i in range(n):
# rfile.readline();
# sys.stdout.write(rfile.readline().strip()[p]);
# rfile.close()
def get_ref(chr, loc):
rfile = open("../chr/chr"+chr+".fa",'r')
#filename = "./chr/chr"+chr+".fa";
#lineNum = loc / 50 + 2;
#linePos = loc % 50;
rfile.readline();
n = loc / 50;
p = loc % 50;
#WHY IT IS SLOW!!!!!
# for i in range(n):
# rfile.readline();
rfile.seek(n*51,1);
#print lineNum,linePos
#print linecache.getline(filename, lineNum)
sys.stdout.write(rfile.readline().strip()[p]);
#sys.stdout.write(linecache.getline(filename, lineNum).strip()[linePos]);
rfile.close()
|
[
"mingru.bai@princeton.edu"
] |
mingru.bai@princeton.edu
|
699bf5b0c29e30e6ff4bcd121ae06c61f101c9b8
|
675818b17d8d54c5ffac3b7d01af280031758364
|
/controller/sens_reader.py
|
e55ea60cc88505e504898d130352fe581bcc2b91
|
[
"MIT"
] |
permissive
|
manuelzanaboni/RPi-oven-controller
|
f6713e0be3005f46b36fa5fb7f937aad06c5c9f4
|
1d1eaf5f895ac26685e551554f51a12955c484da
|
refs/heads/master
| 2021-07-07T20:49:03.195813
| 2021-05-28T10:45:51
| 2021-05-28T10:45:51
| 243,621,388
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,640
|
py
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sqlite3
import time
from threading import Thread
from math import isnan
import MAX6675.MAX6675 as MAX6675
import Adafruit_BMP.BMP085 as BMP085
import utils.default_gpio as PIN
from utils.messages import SENS_READER_MSGS as MSG
SLEEP_TIME = 3
class SensReader(Thread):
def __init__(self, controller):
super(SensReader, self).__init__()
self.controller = controller
""" Sensors initialization """
self.ovenThermocouple = MAX6675.MAX6675(PIN.CLK, PIN.CS1, PIN.SO1)
self.floorThermocouple = MAX6675.MAX6675(PIN.CLK, PIN.CS2, PIN.SO2)
self.pufferThermocouple = MAX6675.MAX6675(PIN.CLK, PIN.CS3, PIN.SO3)
self.fumesThermocouple = MAX6675.MAX6675(PIN.CLK, PIN.CS4, PIN.SO4)
self.pressionSensor = BMP085.BMP085(busnum=1, mode=BMP085.BMP085_ULTRAHIGHRES)
self.gasSensor = BMP085.BMP085(busnum=4, mode=BMP085.BMP085_ULTRAHIGHRES)
self.__avgPression = 0
self.__avgGas = 0
self.__reCalibrate = False
self.stop = False
def kill(self):
self.stop = True
def setReCalibrate(self, state):
if state is not None:
self.__reCalibrate = state
def calibratePressionSensors(self):
self.controller.notify(MSG["calibration"])
sum = self.aggregateReads(self.pressionSensor, 3)
self.__avgPression = sum // 3
sum = self.aggregateReads(self.gasSensor, 3)
self.__avgGas = sum // 3
def aggregateReads(self, sensor, num):
sum = 0
for i in range(num):
sum += sensor.read_pressure()
time.sleep(0.03)
return sum
def run(self):
""" calibrate sensors"""
self.calibratePressionSensors()
self.controller.notify(MSG["startup"])
while not self.stop:
if self.__reCalibrate:
self.calibratePressionSensors()
self.__reCalibrate = False
""" get data """
ovenTemp = self.ovenThermocouple.readTempC()
floorTemp = self.floorThermocouple.readTempC()
pufferTemp = self.pufferThermocouple.readTempC()
fumesTemp = self.fumesThermocouple.readTempC()
"""
pression1 = self.pressionSensor.read_pressure()
delta1 = pression1 - mean1
pression2 = self.gasSensor.read_pressure()
delta2 = pression2 - mean2
"""
# pression1 = self.aggregateReads(self.pressionSensor, 10) // 10
pression1 = self.pressionSensor.read_pressure()
delta1 = pression1 - self.__avgPression
# pression2 = self.aggregateReads(self.gasSensor, 10) // 10
pression2 = self.gasSensor.read_pressure()
delta2 = pression2 - self.__avgGas
""" display data """
self.controller.setData(ovenTemp, floorTemp, pufferTemp, fumesTemp, delta1, delta2)
""" persist data """
if self.controller.config["persistData"]:
""" Build query string """
insert_string = "INSERT INTO Temperatures VALUES(datetime('now', 'localtime')"
if not isnan(ovenTemp):
insert_string += ", " + str(ovenTemp)
else:
insert_string += ", NULL"
if not isnan(floorTemp):
insert_string += ", " + str(floorTemp)
else:
insert_string += ", NULL"
if not isnan(pufferTemp):
insert_string += ", " + str(pufferTemp)
else:
insert_string += ", NULL"
if not isnan(fumesTemp):
insert_string += ", " + str(fumesTemp)
else:
insert_string += ", NULL"
insert_string += ")"
try:
con = sqlite3.connect('oven.db')
with con:
cur = con.cursor()
cur.execute(insert_string)
con.commit()
except:
print("Couldn't write on DB")
self.controller.notifyCritical(MSG["DB_error"])
time.sleep(SLEEP_TIME)
|
[
"mzana97@gmail.com"
] |
mzana97@gmail.com
|
742fd5ae5f818bd6835d081b2691c4c91f7d18de
|
28ef4d7c6a431a1c80a76a1dab5b00e06087c390
|
/a6-13d100026/assign6.py
|
8439102d4d307dce8225077d440704fcb710fcf5
|
[] |
no_license
|
adititan/Particle-Fluid-flow-SImulation
|
a2a395c3164dd8b1d03d17553b5e214e66f708a4
|
ae8c42ec141b098c708e5c29ac0154388d03c25a
|
refs/heads/master
| 2020-06-15T14:24:23.278606
| 2016-12-01T13:58:10
| 2016-12-01T13:58:10
| 75,285,859
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,257
|
py
|
import random
import matplotlib.pyplot as plt
import numpy as np
from copy import deepcopy
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
num_of_vort =10000
def axis_function():
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
def exact_sol(z,t,h):
return 1/(4*np.pi*mu*t)*np.exp(-abs(z)**2/(4*mu*t)) * h**2
def remesh(x,y,gamma_list,x_lim,y_lim,h):
nx, ny = 2*x_lim/h +1, 2*y_lim/h +1
xa = np.linspace(-x_lim, x_lim, nx)
ya = np.linspace(-y_lim, y_lim, ny)
xv, yv = np.meshgrid(xa, ya)
x_new,y_new,gamma_new = [],[], []
for m in range(len(x)):
pos_x,pos_y,gamma0 = x[m],y[m],gamma_list[m]
x0 = pos_x - int(round(pos_x/h - 0.5))*h
y0 = pos_y - int(round(pos_y/h - 0.5))*h
if (h - pos_y % h < 1e-5) and (h - pos_x % h < 1e-5):
x_new += [pos_x-x0]
y_new += [pos_y-y0]
gamma_new += [gamma0]
elif (h - pos_x % h < 1e-5):
x_new += [pos_x-x0, pos_x-x0]
y_new += [pos_y-y0, pos_y-y0+h]
gamma_new += [gamma0*(1-y0) , gamma0*y0]
elif (h - pos_y % h < 1e-5):
x_new += [pos_x-x0, pos_x-x0+h]
y_new += [pos_y-y0, pos_y-y0]
gamma_new += [gamma0*(1-x0) , gamma0*x0]
else:
x_new += [pos_x-x0, pos_x-x0+h, pos_x-x0, pos_x-x0+h]
y_new += [pos_y-y0, pos_y-y0, pos_y-y0+h, pos_y-y0+h]
gamma_new += [gamma0*(1-y0)*(1-x0) , gamma0*x0*(1-y0) , gamma0*(1-x0)*y0,gamma0*x0*y0]
plt.scatter(xv,yv,color='r')
return x_new,y_new,gamma_new
def error(x_lim,y_lim,x_remesh,y_remesh,gamma_remesh):
nx, ny = 2*x_lim/h +1, 2*y_lim/h +1
xa = np.linspace(-x_lim, x_lim, nx)
ya = np.linspace(-y_lim, y_lim, ny)
xv, yv = np.meshgrid(xa, ya)
error = [[0.0 for i in range(len(xa))] for j in range(len(ya))]
approx_gamma = [[0.0 for i in range(len(xa))] for j in range(len(ya))]
for k in range(len(x_remesh)):
i = int((x_remesh[k] + x_lim)*(nx-1)/2.0/x_lim)
j = int((y_remesh[k] + y_lim)*(ny-1)/2.0/y_lim)
approx_gamma[j][i] += gamma_remesh[k]
for i,xv_pos in enumerate(xa):
for j,yv_pos in enumerate(ya):
z_pos = xv_pos +1j*yv_pos
exact_gamma = exact_sol(z_pos,t,h)
error[j][i] = (approx_gamma[j][i] - exact_gamma )/exact_gamma
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(xv, yv, error , rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
plt.title("Relative Error Profile with grid size = 8x8")
plt.savefig('error_10000.png')
rms_error =sum((error[j][i])**2 for i in range(len(xa)) for j in range(len(xa)))
return (np.sqrt((rms_error)/nx/ny))
def point_vortex_diffusion(gamma):
x0,y0 = [0.0],[0.0]
gamma_list = [1.0/num_of_vort]*num_of_vort
x_next,y_next = x0*num_of_vort,y0*num_of_vort
for j in range(0,num_of_vort):
x_next[j] += np.random.normal(mean, sigma, 1)[0]
y_next[j] += np.random.normal(mean, sigma, 1)[0]
plt.figure()
plt.scatter(x_next,y_next)
axis_function()
plt.title("Vorticity distribution after 1 sec with num of vortices = 100000.(Using delta_t = 0.1 sec)")
plt.savefig('vort_10000.png')
plt.figure()
x,y,gamma_list = remesh(x_next,y_next,gamma_list,x_lim,y_lim,h)
plt.scatter(x,y)
axis_function()
plt.title(" Vorticity Distribution just after remeshing ( num of vortices = 100000)")
plt.savefig('remesh_10000.png')
return x,y,gamma_list
if __name__ == '__main__':
gamma = 1.0
mu = 0.1 #viscosity
t =1.0
mean = 0.0
delta_t = 0.1
h = 0.05
sigma = np.sqrt(2*mu*delta_t)
x_lim,y_lim = int(round(3*sigma))+1 , int(round(3*sigma))+1
x_remesh,y_remesh,gamma_remesh = point_vortex_diffusion(gamma)
error(x_lim,y_lim,x_remesh,y_remesh,gamma_remesh)
num_vort = [100,500,1000,3000,10000,100000]
errorr = [0.0]*len(num_vort)
for a in range(len(num_vort)):
num_of_vort = num_vort[a]
x_remesh,y_remesh,gamma_remesh = point_vortex_diffusion(gamma)
errorr[a] = error(x_lim,y_lim,x_remesh,y_remesh,gamma_remesh)
plt.figure()
plt.plot(np.log(num_vort),errorr)
plt.title("Variation of Error with Number of Vortices")
plt.xlabel('log(#Vortices)')
plt.ylabel('RMS Error')
plt.savefig('error_plot.png')
|
[
"tanejaaditi1@gmail.com"
] |
tanejaaditi1@gmail.com
|
0979443d74af43683177b884ac41e14055e18679
|
f0d713996eb095bcdc701f3fab0a8110b8541cbb
|
/KT8ApJ2EJcLz4K3t2_4.py
|
d326e5b8c8f8e2569101be27e750656ece4cf909
|
[] |
no_license
|
daniel-reich/turbo-robot
|
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
|
a7a25c63097674c0a81675eed7e6b763785f1c41
|
refs/heads/main
| 2023-03-26T01:55:14.210264
| 2021-03-23T16:08:01
| 2021-03-23T16:08:01
| 350,773,815
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 622
|
py
|
"""
For this challenge, you are supposed to find the sum of the digits of a two-
digit number. Sounds easy, right? But for this challenge, I expect you to find
the sum of the digits mathematically.
Sure, you can convert the number into a string and then manipulate it so it
returns the sum of the digits, but the point of this challenge is to see if
you know how to return the sum of the digits of a two-digit number
**mathematically**.
### Examples
two_digit_sum(45) ➞ 9
two_digit_sum(38) ➞ 11
two_digit_sum(67) ➞ 13
### Notes
`%` `//`
"""
def two_digit_sum(n):return n%10 + n//10
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
42722c5f846ebc3fc0d99f76f160c15656ea0aa0
|
fac77900129f3e11b2b72cd65a4f9e088aaa8bbc
|
/PythonExercicios/ex078.py
|
49c2e68f9a9520a2d0f8678d6851b6e2c4f07480
|
[
"MIT"
] |
permissive
|
Lucas-ns/Python-3-Curso-Em-Video
|
ff01cc35b383b7c548e4aa1e92e6ed60bad25079
|
f6d338fffd7a4606d34fab09634eea0fe4b3dfb3
|
refs/heads/main
| 2023-03-18T09:02:49.685841
| 2021-03-16T20:45:14
| 2021-03-16T20:45:14
| 348,480,428
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 494
|
py
|
value = []
for cont in range(0, 5):
value.append(int(input(f'Digite um valor para a posição {cont}: ')))
print(f'Você digitou os valores {value}')
print(f'O maior valor digitado foi {max(value)} nas posições ', end='')
for i, v in enumerate(value):
if v == max(value):
print(f'{i}...', end=' ')
print()
print(f'O menor valor digitado foi {min(value)} nas posições ', end='')
for i, v in enumerate(value):
if v == min(value):
print(f'{i}...', end=' ')
print()
|
[
"nascimentolucas786@gmail.com"
] |
nascimentolucas786@gmail.com
|
2d0c3272106195dfcc1a50e0cb7603119a4b1663
|
949d782a80d82af30d87c93c1b605b265736f4ec
|
/demos/httpauth/httpauthdemo.py
|
149af223d630c6da3895947046a62dd5ad0dbc34
|
[
"Apache-2.0"
] |
permissive
|
nkvoll/cyclone
|
96f524f311b6c11ce839e35664c0bf8334ef9cd4
|
35023be3dc3b433f978baf78e2394012528e12d2
|
refs/heads/master
| 2021-01-18T07:38:59.877590
| 2012-02-22T13:05:54
| 2012-02-22T13:05:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,133
|
py
|
#!/usr/bin/env python
# coding: utf-8
#
# Copyright 2010 Alexandre Fiori
# based on the original Tornado by Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import base64
import functools
import sys
import cyclone.web
from twisted.python import log
from twisted.internet import reactor
class Application(cyclone.web.Application):
def __init__(self):
handlers = [
(r"/", IndexHandler),
]
cyclone.web.Application.__init__(self, handlers, debug=True)
def HTTPBasic(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
try:
auth_type, auth_data = self.request.headers["Authorization"].split()
assert auth_type == "Basic"
usr, pwd = base64.b64decode(auth_data).split(":", 1)
assert usr == "root@localhost"
assert pwd == "123"
except:
# All arguments are optional. Defaults are:
# log_message=None, auth_type="Basic", realm="Restricted Access"
raise cyclone.web.HTTPAuthenticationRequired(
log_message="Authentication failed!",
auth_type="Basic", realm="DEMO")
else:
self._current_user = usr
return method(self, *args, **kwargs)
return wrapper
class IndexHandler(cyclone.web.RequestHandler):
@HTTPBasic
def get(self):
self.write("Hi, %s." % self._current_user)
def main():
log.startLogging(sys.stdout)
reactor.listenTCP(8888, Application(), interface="127.0.0.1")
reactor.run()
if __name__ == "__main__":
main()
|
[
"fiorix@gmail.com"
] |
fiorix@gmail.com
|
e8fee1b202a3827a703ffc1adbf51291c7ee2d7d
|
e516656a3ae3bc09c72334056be1f42c88282d32
|
/core/views.py
|
f2711471d73baece13342491e7ca7f4591758efc
|
[] |
no_license
|
matheus-henrique/placar
|
752de95ae3f3f26352700b51c5c4c44a5d1517a1
|
b2c602870d307569988cd5524f422ba2f30062f0
|
refs/heads/master
| 2021-01-12T10:44:51.776428
| 2016-11-02T17:03:49
| 2016-11-02T17:03:49
| 72,662,091
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 695
|
py
|
from django.shortcuts import render
import json
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request,"index.html",{})
def receberDados(request):
dados = request.body
dados = dados.decode("utf-8")
dados = json.loads(dados)
print(dados)
arq = open('core/static/placar.txt',"w")
for i in dados['dados']:
if('descricao' in i):
arq.write(i['hora_inicio']+';'+i['datainicio']+';'+i['cronometro']+';'+i['hora']+';'+i['time']+';'+i['descricao']+';')
arq.write("\n")
else:
arq.write(i['hora_inicio']+';'+i['datainicio']+';'+i['cronometro']+';'+i['hora']+';'+i['time']+';'+''+';')
arq.write("\n")
return HttpResponse("Done")
|
[
"Matheus Henrique"
] |
Matheus Henrique
|
613adb12b44a0e73bb2d5accbeca87fab0746afb
|
2b15b7f7a6872391ed67489bb5ea06f3672e2672
|
/run.py
|
5dd6beb69d72ad8bead18efdbc70b1efa69a42f9
|
[] |
no_license
|
rbowlus/fakebook_project
|
001f48ad864a6d3b967f24f048cb7a7a0cfec881
|
447f23c59f81848ef4b8d445aa94dca78e2c143b
|
refs/heads/main
| 2023-06-24T10:03:23.322630
| 2021-07-27T14:34:38
| 2021-07-27T14:34:38
| 383,186,075
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 469
|
py
|
from app import create_app, db
from app.blueprints.authentication.models import User
from app.blueprints.blog.models import Post
from app.blueprints.shop.models import Cart, Order, Product, StripeProduct
app = create_app()
@app.shell_context_processor
def make_context():
return {
'db': db,
'User': User,
'Post': Post,
'Cart': Cart,
'Order': Order,
'Product': Product,
'StripeProduct': StripeProduct
}
|
[
"rachel.bowlus@gmail.com"
] |
rachel.bowlus@gmail.com
|
c35613b4b84a754b9853b3e38c44fd9387a11436
|
0426bf7ca6e161cca6a293436d2995f0c818652f
|
/apps/lead/tortoise_models/lead.py
|
8d5c6f0773b8b76750df283eff997e978b6def41
|
[] |
no_license
|
olegshek/anor_home_bot
|
414a67c4f1eceb6cf9546df410aa8207de63b9ef
|
0f0fd220604cd3a4ae8dd8588ec9194cd7492b26
|
refs/heads/master
| 2023-06-23T02:30:35.741276
| 2021-07-20T10:56:35
| 2021-07-20T10:56:35
| 359,393,299
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,468
|
py
|
from django.utils import timezone
from tortoise import models, fields
from apps.lead import app_name
from core.utils import generate_number
class Lead(models.Model):
number = fields.IntField(default=generate_number)
customer = fields.ForeignKeyField(f'{app_name}.Customer', on_delete=fields.CASCADE, related_name='leads')
created_at = fields.DatetimeField(default=timezone.now, blank=True, editable=False)
class Meta:
table = f'{app_name}_lead'
class ApartmentTransaction(models.Model):
customer = fields.ForeignKeyField(f'{app_name}.Customer', on_delete=fields.CASCADE,
related_name='apartment_transactions')
lead = fields.ForeignKeyField(f'{app_name}.Lead', on_delete=fields.CASCADE, null=True,
related_name='apartment_transactions')
apartment = fields.ForeignKeyField(f'{app_name}.Apartment', on_delete=fields.CASCADE,
related_name='apartment_transactions')
created_at = fields.DatetimeField(default=timezone.now, blank=True, editable=False)
class Meta:
table = f'{app_name}_apartmenttransaction'
class StoreTransaction(models.Model):
customer = fields.ForeignKeyField(f'{app_name}.Customer', on_delete=fields.CASCADE,
related_name='store_transactions')
lead = fields.ForeignKeyField(f'{app_name}.Lead', on_delete=fields.CASCADE, null=True,
related_name='store_transactions')
store = fields.ForeignKeyField(f'{app_name}.Store', on_delete=fields.CASCADE,
related_name='store_transactions')
created_at = fields.DatetimeField(default=timezone.now, blank=True, editable=False)
class Meta:
table = f'{app_name}_storetransaction'
class DuplexTransaction(models.Model):
customer = fields.ForeignKeyField(f'{app_name}.Customer', on_delete=fields.CASCADE,
related_name='duplex_transactions')
lead = fields.ForeignKeyField(f'{app_name}.Lead', on_delete=fields.CASCADE, null=True,
related_name='duplex_transactions')
duplex = fields.ForeignKeyField(f'{app_name}.Duplex', on_delete=fields.CASCADE, related_name='transactions')
created_at = fields.DatetimeField(default=timezone.now, blank=True, editable=False)
class Meta:
table = f'{app_name}_duplextransaction'
|
[
"olegshek2398@gmail.com"
] |
olegshek2398@gmail.com
|
ba321ad0c6f4371f9a6a723d17d510f324b9e827
|
f60617e714fc01a5960fb69163c4df3200704426
|
/mini_gplus/resources/link_preview.py
|
0f71ec11248ba7a2582f9d1d4807856e4118b54a
|
[
"MIT"
] |
permissive
|
baronrustamov/pill-city
|
97d1063f60766623ddfe95c8486bdd3de0ccdb1e
|
196635e7d0019def1d5ee3b38f82e270085201a0
|
refs/heads/master
| 2023-08-18T21:11:11.978403
| 2021-10-13T17:55:50
| 2021-10-13T17:55:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 769
|
py
|
from flask_restful import Resource, fields, marshal_with, reqparse
from flask_jwt_extended import jwt_required
from mini_gplus.daos.link_preview import get_link_preview
link_preview_parser = reqparse.RequestParser()
link_preview_parser.add_argument('url', type=str, required=True)
class LinkPreviewState(fields.Raw):
def format(self, state):
return state.value
link_preview_fields = {
'url': fields.String,
'title': fields.String,
'subtitle': fields.String,
'image_urls': fields.List(fields.String),
'state': LinkPreviewState
}
class LinkPreview(Resource):
@jwt_required()
@marshal_with(link_preview_fields)
def post(self):
args = link_preview_parser.parse_args()
return get_link_preview(args['url'])
|
[
"whj19931115@gmail.com"
] |
whj19931115@gmail.com
|
fc590619e970d6a75ddefa62a3d11211e4d65c82
|
d0253c2b9fe72f00e1763c34527f52cdd8da3213
|
/data_precessing.py
|
897ea58cfad5c1350006052025cc8a1cb80b7aab
|
[] |
no_license
|
humapleleaf/EVRP-based-on-RL
|
561980cfcb9886e6e0825ec0594c0f7ff1f34c05
|
354e6e022a2316da78f708efa8a51bc5d3fa1ae0
|
refs/heads/master
| 2022-02-17T15:56:40.949152
| 2019-07-23T03:27:06
| 2019-07-23T03:27:06
| 198,333,176
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,401
|
py
|
import matplotlib.pyplot as plt
import os
from math import radians, cos, sin, asin, sqrt
path = 'GVRP_Instances/Table 2'
x = []
y = []
depot = set()
afs = set()
for filename in os.listdir(path):
with open(os.path.join(path, filename), 'r') as f:
lines = f.readlines()[2:26]
depot.add((float(lines[0].split()[2]), float(lines[0].split()[3])))
for i in range(1, 4):
afs.add((float(lines[i].split()[2]), float(lines[i].split()[3])))
for line in lines[6:]:
line = line.strip()
if not line.startswith('C'):
print(f'the format of {filename} is not consistent with the others')
print(line)
break
line = line.split()
x.append(float(line[2]))
y.append(float(line[3]))
assert len(depot) == 1 and len(afs) == 3
# min(x): -79.44, max(x): -75.51; min(y): 36.03, max(y): 39.49
print('min(x): %.2f, max(x): %.2f; min(y): %.2f, max(y): %.2f' % (min(x), max(x), min(y), max(y)))
depot = list(depot)
plt.scatter(depot[0][0], depot[0][1], s=200, c='black', marker='*')
afs = list(afs)
afs_x = [cor[0] for cor in afs]
afs_y = [cor[1] for cor in afs]
plt.scatter(afs_x, afs_y)
plt.scatter(x, y)
def cal_dis(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
c = 2 * asin(sqrt(a))*4182.44949 # miles
# c = 2 * atan2(sqrt(a), sqrt(1 - a)) * 4182.44949
return c
dis = []
afs2depot = [cal_dis(depot[0][0], depot[0][1], afs1, afs2) for afs1, afs2 in zip(afs_x, afs_y)]
for lon, lat in zip(x, y):
d = cal_dis(depot[0][0], depot[0][1], lon, lat)
if d > 150: # at most 150 miles for one way
afs2cus = [cal_dis(lon, lat, afs1, afs2) for afs1, afs2 in zip(afs_x, afs_y)]
dis_by_afs = min([d1+d2 for d1, d2 in zip(afs2cus, afs2depot)])
if dis_by_afs > 300:
print(f'point ({lon}, {lat}) cannot be satisfied')
dis.append(d*2)
else:
plt.scatter(lon, lat, marker='x', c='r', s=100)
dis.append(d + dis_by_afs)
else:
dis.append(d*2)
plt.show()
|
[
"humaple@sjtu.edu.cn"
] |
humaple@sjtu.edu.cn
|
91639fc4fdeab850e09373a69e084fbbe1365a05
|
481a3c657e2886970cb3c62133ea2c780c85799e
|
/2nd/src/models/product.py
|
4665335d0303c333259d0a9c673851ac5587322e
|
[] |
no_license
|
KunjManiar/DBMS
|
6ebb881b811c574c5bb6f689ef2e0b98b1750c1c
|
1c7668cba02f8c2dcc3222d7259e726ba2a6423c
|
refs/heads/master
| 2020-04-02T14:48:56.460826
| 2018-10-25T12:27:24
| 2018-10-25T12:27:24
| 154,540,101
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,474
|
py
|
from src.common.database import Database
import uuid
class Product():
def __init__(self,name,category,supplier,quantity,unit_price,unit_selling_price,unit_in_order,reorder_level,available_stock=None,_id=None):
self._id = uuid.uuid4().hex if _id is None else _id
self.name = name
self.category = category
self.supplier = supplier
self.quantity = quantity
self.unit_price = unit_price
self.unit_selling_price = unit_selling_price
self.available_stock = 0 if available_stock is None else available_stock
self.unit_in_order = unit_in_order
self.reorder_level = reorder_level
def save_to_mongo(self):
Database.insert(collection='product',
data=self.json())
def json(self):
return {
'_id' : self._id,
'name' : self.name,
'category' : self.category,
'supplier' : self.supplier,
'quantity' : self.quantity,
'unit_price' : self.unit_price,
'unit_selling_price' :self.unit_selling_price,
'available_stock' : self.available_stock,
'unit_in_order' : self.unit_in_order,
'reorder_level' : self.reorder_level
}
@classmethod
def from_id(cls, _id):
staff = Database.find(collection='staff',
query={'_id': _id})
return cls(**staff)
|
[
"noreply@github.com"
] |
KunjManiar.noreply@github.com
|
d8615202d1cfda0fd3377384e36df70087fdde9f
|
feb08c753869b7715f88f5d051184e3c677c2d78
|
/tests/flat_test.py
|
6982663709120873aa79619931939c9ce6eed7b2
|
[] |
no_license
|
hbcbh1999/pydp
|
8cb5386ae6ceb7f87b50dd06b726e8464f5381d5
|
0119bc961db5052d67588a4dd40cbe659cfa3445
|
refs/heads/master
| 2021-01-01T09:19:56.140177
| 2016-09-30T06:22:29
| 2016-09-30T06:22:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,421
|
py
|
import src.flat_concave
import src.examples
import numpy as np
import src.bounds
import src.qualities
range_end = 2**40
alpha = 0.1
eps = 0.1
delta = 1e-6
beta = 0.01
samples_size = 1000 # int(bounds.step6_n2_bound(range_end, eps, alpha, beta))
print "range size: %d" % range_end
print "sample size: %d" % samples_size
data_center = np.random.uniform(range_end/3, range_end/3*2)
data = src.examples.get_random_data(samples_size, pivot=data_center)
data = sorted(filter(lambda x: 0 <= x <= range_end, data))
maximum_quality = src.qualities.min_max_maximum_quality(data, 0, range_end)
print "the exact median is: %d" % np.median(data)
print "the best quality of a domain element: %d" % maximum_quality
quality_result_lower_bound = maximum_quality*(1-alpha)
print 'minimum "allowed" quality: %d' % quality_result_lower_bound
print "testing flat_concave to find median"
try:
result = src.flat_concave.evaluate(data, range_end, src.qualities.quality_minmax, maximum_quality,
alpha, eps, delta, src.qualities.min_max_intervals_bounding,
src.qualities.min_max_maximum_quality, True)
result_quality = src.qualities.quality_minmax(data, result)
except ValueError:
print "Adist returned 'Bottom'"
result = -1
result_quality = -1
print "result from flat_concave: %d" % result
print "and its quality: %d \n" % result_quality
|
[
"menitm@gmail.com"
] |
menitm@gmail.com
|
7bd0f8da2049db75527f1ecc0fd9c1c7ad284967
|
7f5da04042cfdf99c51b5995ca6b92dfe13d9544
|
/Preprocessing/00_dicom_to_nrrd.py
|
d9e7c46fe75ecfa8781914cc7da39744b37551f2
|
[] |
no_license
|
sdmishra123/Capstone---Determining-the-aggressiveness-of-Prostate-Cancer
|
8ae4f4d673e9d64bac738d62852c2d385f93e8f3
|
d7253bda3c3465bb727163a2a8731bab07ab262e
|
refs/heads/main
| 2023-02-28T20:05:21.436722
| 2021-02-12T02:42:39
| 2021-02-12T02:42:39
| 305,130,423
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,057
|
py
|
import os
''' NOTE: This file will run in Slicer python interactor.
NOTE: Make sure that the following directories are consistent with settings
file.
'''
dicom_root = "/project2/rcc/tszasz/MRIRC/Prostate_DeepLearning_Projects/ProstateX/Data_Prep/raw/DOI"
#dicom_root = "/project2/rcc/tszasz/MRIRC/Prostate_DeepLearning_Projects/ProstateX/Data_Prep/TEST/raw/DOI"
ktrans_root = "/project2/rcc/tszasz/MRIRC/Prostate_DeepLearning_Projects/ProstateX/Data_Prep/raw/ProstateXKtrains-train-fixed/"
#ktrans_root = "/project2/rcc/tszasz/MRIRC/Prostate_DeepLearning_Projects/ProstateX/Data_Prep/TEST/raw/ProstateXKtrans-test-fixedv2/"
intermediate_folder = "/project2/rcc/tszasz/MRIRC/Prostate_DeepLearning_Projects/ProstateX/Data_Prep/intermediate/"
outputdirectory = os.path.join(intermediate_folder, 'nrrd-test')
#outputdirectory = os.path.join(intermediate_folder, 'nrrd-test')
excluded_patients = []
# excluded_patients = ["ProstateX-0191","ProstateX-0190","ProstateX-0025","ProstateX-0031"]
patient_folders = [patient_folder for patient_folder in sorted(os.listdir(dicom_root))
if patient_folder not in excluded_patients]
if not os.path.exists(outputdirectory):
os.makedirs(outputdirectory)
start_patient = 0
for patient_folder in patient_folders:
print patient_folder
patient_number = int(patient_folder.split('-')[1])
if patient_number > start_patient:
patient_folder_path = os.path.join(dicom_root, patient_folder)
study_folders = sorted(os.listdir(patient_folder_path))
if len(study_folders) == 1:
study_folder = study_folders[0]
study_folder_path = os.path.join(patient_folder_path, study_folder)
series_folders = sorted(os.listdir(study_folder_path))
print patient_folder, len(series_folders)
elif len(study_folders) > 1:
print "patient has more than one studies: {}".format(patient_folder)
print "It was not added to the studies collection."
else:
print "no study foler for patient:{}".format(patient_folder)
for series_folder in series_folders:
series_folder_path = os.path.join(study_folder_path, series_folder)
file_names = [os.path.join(series_folder_path, file_name) for file_name in os.listdir(series_folder_path)]
plugin = slicer.modules.dicomPlugins['DICOMScalarVolumePlugin']()
if plugin:
loadables = plugin.examine([file_names])
if len(loadables) == 0:
print('plugin failed to interpret this series')
else:
series_description = slicer.dicomDatabase.fileValue(file_names[0], "0008,103E")
series_number = slicer.dicomDatabase.fileValue(file_names[0], "0020,0011")
# print series_description
required_serires_descriptions = ["t2_tse_tra", "t2_tse_sag", "t2_tse_cor", "ADC", "BVAL"]
#
# Load the dicom data
#
if any(description in series_description for description in required_serires_descriptions):
print 'loading:', series_description
volume = plugin.load(loadables[0])
volume_name = series_description + '_' + series_number
volume.SetName(volume_name)
####
output_file_name = patient_folder + '_' + volume_name + '.nrrd'
slicer.util.saveNode(volume, os.path.join(outputdirectory, output_file_name))
slicer.mrmlScene.RemoveNode(volume)
slicer.app.processEvents()
ktrans_path = ktrans_root + patient_folder + '/' + patient_folder + '-Ktrans.mhd'
loadVolume(ktrans_path)
node = getNode(patient_folder + '-Ktrans')
output_file_name = patient_folder + '_Ktrans' + '.nrrd'
slicer.util.saveNode(node, os.path.join(outputdirectory, output_file_name))
slicer.mrmlScene.RemoveNode(node)
slicer.app.processEvents()
|
[
"noreply@github.com"
] |
sdmishra123.noreply@github.com
|
5e877588098192b60485f9d7dd9186bdad24c160
|
fb3ac3f35977aa8943610323ca9954c33ca73a29
|
/notasi.py
|
c2e875bc5702945b571086d7b56ae91344525efa
|
[] |
no_license
|
khonsanur/matkom
|
372b2350cd089ff712f076eecafeb48b80c966ea
|
401fab413431e3fce196e7281df2c46b185f1e84
|
refs/heads/main
| 2023-01-07T03:41:46.424378
| 2020-11-10T16:59:21
| 2020-11-10T16:59:21
| 311,726,332
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 521
|
py
|
print("No.1")
#Notasi Sigma kuadrat dari 13 s.d. 17
hasil = 0
n = 17
for i in range (13, n+1):
hasil= hasil + i*5 + 2
print("hasilnya adalah:", hasil)
end=()
print("\n")
print("No.2")
# Notasi Sigma kuadrat dari 5 s.d. 10
hasil = 0
n = 10
for i in range (5, n+1):
hasil= hasil + i*i + 2*i - 1
print("hasilnya adalah:", hasil)
end=()
print("\n")
print("No.3")
# Notasi PI kuadrat dari 4 s.d. 8
hasil = 1
n = 8
for i in range (4, n+1):
hasil = hasil * (i - 3)
print("hasilnya adalah:", hasil)
|
[
"noreply@github.com"
] |
khonsanur.noreply@github.com
|
8f3a746658bbd823e376e62689603d6d2df063a9
|
04c2de497ed169b31b09c99f0473bf5ce9146e8f
|
/vvv.py
|
149f72b29dd297bc4aa37dca3ad1afbe04c41691
|
[] |
no_license
|
kruthikaneelam/programs
|
2e3377df7a7e259d4add642b5b38d5c991433b09
|
b3cd944e143dfbb1a35ef087b10cf3752e0314d4
|
refs/heads/master
| 2020-04-25T02:19:57.960460
| 2019-03-29T05:27:00
| 2019-03-29T05:27:00
| 172,435,542
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 272
|
py
|
import smtplib
s=smtplib.SMTP("smtp.gmail.com","587")
s.starttls()
sender="kruthikan6666@gmail.com"
receiver="cocoousha@gmail.com"
msg="heyy baby"
s.login(sender,"9449831120")
s.sendmail(sender,receiver,msg)
print("erroe occured")
print("msg sent successfully")
s.quit()
|
[
"noreply@github.com"
] |
kruthikaneelam.noreply@github.com
|
1b5956358f78d6d291448ab208fb8f49a4f914e6
|
6395929fd1aede043f9c060a8f2fb992a5052da2
|
/TD_light/td_light.py
|
7cbaa9ffe675fdfb0310821e341b8c7e6142eca0
|
[] |
no_license
|
openalea-training/agreenium_training_2018
|
3acfb220dd7def1cd08e0ac0461ba6644e9191a1
|
ff84736d07ac8e0ceb740dca6c0f88984951c3cf
|
refs/heads/master
| 2021-09-09T12:59:21.168326
| 2018-03-16T11:01:18
| 2018-03-16T11:01:18
| 124,087,745
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,275
|
py
|
import pandas
import numpy
import matplotlib.pyplot as plt
import openalea.plantgl.all as pgl
from alinea.astk.sun_and_sky import sun_sky_sources, sky_sources, \
cie_relative_luminance
from alinea.caribu.CaribuScene import CaribuScene
from alinea.caribu.light import light_sources
from objects import mtg_tree, mtg_nenuphar, add_sun, add_sky, simple_tree, display_leaves
def read_meteo_mpt(when='winter'):
if when == 'winter':
path = 'incoming_radiation_ZA13.csv'
else:
path = 'incoming_radiation_ZB13.csv'
df = pandas.read_csv(path, index_col=0, parse_dates=True)
df.index = df.index.tz_localize('UTC').tz_convert('Europe/Paris')
return df
def montpellier_spring_2013():
return read_meteo_mpt('spring')
def montpellier_winter_2013():
return read_meteo_mpt('winter')
def actual_irradiance(daydate, db):
when = pandas.date_range(start=daydate, freq='H', periods=25,
tz='Europe/Paris')
return db.loc[when,'ghi']
def apple_tree():
return pgl.Scene('appletree-result.geom')
def apple_tree_leaves():
return [24, 30, 36, 42, 60, 66, 72, 78, 84, 128, 140, 152, 158, 170, 230,
236, 242, 248, 254, 308, 314, 320, 326, 354, 360, 366, 372, 378,
414, 420, 426, 432, 438, 452, 458, 464, 472, 478, 484, 490, 538,
550, 556, 562, 574, 580, 586, 592, 598, 604, 610, 616, 622, 628,
634, 640, 646, 658, 664, 670, 682, 694, 700, 712, 718, 730, 742,
748, 754, 760, 778, 784, 790, 796, 802, 816, 822, 828, 834, 876,
882, 888, 894, 900, 948, 954, 962, 968, 974, 980, 986, 1046, 1058,
1064, 1076, 1082, 1094, 1106, 1112, 1118, 1124, 1136, 1142, 1148,
1160, 1166, 1172, 1178, 1184, 1196, 1208, 1214, 1220, 1226, 1232,
1238, 1244, 1250, 1262, 1268, 1274, 1280, 1286, 1298, 1304, 1310,
1316, 1328, 1340, 1352, 1364, 1376, 1382, 1430, 1436, 1442, 1450,
1456, 1462, 1468, 1494, 1500, 1506, 1512, 1518, 1524, 1530, 1536,
1550, 1556, 1562, 1568, 1574, 1616, 1622, 1628, 1634, 1640, 1734,
1740, 1746, 1752, 1758, 1848, 1854, 1860, 1866, 1872, 1928, 1934,
1942, 1948, 1954, 1960, 1966, 2008, 2014, 2020, 2026, 2044, 2050,
2056, 2062, 2068, 2076, 2082, 2088, 2094, 2100, 2204, 2210, 2216,
2222, 2228, 2236, 2242, 2248, 2254, 2260, 2320, 2326, 2332, 2338,
2396, 2402, 2408, 2414, 2464, 2470, 2476, 2482, 2514, 2520, 2526,
2534, 2540, 2546, 2552, 2624, 2630, 2636, 2642, 2712, 2718, 2724,
2732, 2738, 2744, 2750, 2808, 2814, 2820, 2828, 2834, 2840, 2846,
2852, 2934, 2940, 2946, 2954, 2960, 2966, 2972, 3010, 3016, 3022,
3028, 3034, 3052, 3058, 3064, 3070, 3076, 3118, 3124, 3130, 3138,
3144, 3150, 3156, 3176, 3182, 3190, 3196, 3202, 3208, 3214, 3234,
3246, 3252, 3258, 3264, 3270, 3276, 3282, 3302, 3308, 3314, 3320,
3326, 3368, 3374, 3380, 3386, 3452, 3458, 3464, 3472, 3478, 3484,
3490, 3538, 3544, 3550, 3556, 3562, 3622, 3628, 3634, 3640, 3646,
3666, 3672, 3680, 3686, 3692, 3698, 3704, 3714, 3720, 3726, 3732,
3738, 3750, 3756, 3762, 3768, 3780, 3786]
def test_scene(s):
tesselator = pgl.Tesselator()
d = s.todict()
for pid, pgl_objects in d.iteritems():
for shape in pgl_objects:
if not shape.apply(tesselator):
print(pid)
def illuminate(scene, sky=None, sun=None, pattern=None):
if sky is None and sun is None:
sky = sky_sources()
light = []
if sky is not None:
light += light_sources(*sky)
if sun is not None:
light += light_sources(*sun)
infinite=False
if pattern is not None:
infinite = True
cs = CaribuScene(scene, light=light,scene_unit='cm', pattern=pattern)
raw, agg = cs.run(direct=True, simplify=True, infinite=infinite)
return cs, raw, agg
def display_light(cs, raw):
cs.plot(raw['Ei'])
def leaf_irradiance(agg, leaves=None, aggregate=False):
df = pandas.DataFrame(agg)
if leaves is not None:
df = df.loc[df.index.isin(leaves),:]
if aggregate:
df = df.apply(numpy.mean)
return df
def light_response(irradiance, alpha=0.01, Pm=1, R=0):
return alpha * irradiance * Pm / (alpha * irradiance + Pm) -R
def irrad_opt(alpha=0.01, Pm=1):
return Pm * 0.7 / alpha / (1 - 0.7)
def pm_acclimated(irrad, alpha=0.01):
return irrad / (0.7 * alpha / (1 - 0.7))
def plant_biomass(g, duration = 12, sky=None, df=None, ghi=1, Pm=1):
if df is None:
cs, raw, agg = illuminate(g, sky=sky)
df = pandas.Dataframe(agg)
ei = ghi * df.Ei
p = light_response(ei, Pm=Pm)
return (df.area * p * duration).sum()
def polar_grid(zenith=20, azimuth=80):
""" generate elevation, azimuth and zenith matrix for polar plot"""
zen, az = numpy.meshgrid(numpy.radians(numpy.linspace(0,90,zenith)),
numpy.radians(numpy.linspace(0,360,azimuth)))
return numpy.radians(90) - zen, az, zen
def polar_plot(zen, az, values):
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
m=ax.contourf(az, zen, values)
plt.colorbar(m)
plt.show()
|
[
"Christian.Fournier@supagro.inra.fr"
] |
Christian.Fournier@supagro.inra.fr
|
bba8c5c1db4074c72979c7188ab3d0415844151e
|
b9e45c40fb07aafe7dd987b9cbd81da0634d9f4b
|
/Transcrypt/modules/org/transcrypt/compiler.py
|
658f0933657083f91cb55d4844a8d1411fdad017
|
[
"Apache-2.0"
] |
permissive
|
techdragon/Transcrypt
|
11cee1c1f7f8abd3e7d4fa24c0712e9359b6f7e6
|
0752ada0b2bc4c38dfa29f911139921e52b03e62
|
refs/heads/master
| 2020-04-07T13:15:57.339431
| 2016-02-17T14:38:55
| 2016-02-17T14:38:55
| 51,932,000
| 0
| 0
| null | 2016-02-17T15:20:37
| 2016-02-17T15:20:37
| null |
UTF-8
|
Python
| false
| false
| 50,054
|
py
|
# ====== Legal notices
#
# Copyright (C) 2015 GEATEC engineering
#
# This program is free software.
# You can use, redistribute and/or modify it, but only under the terms stated in the QQuickLicence.
#
# 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 QQuickLicense for details.
#
# The QQuickLicense can be accessed at: http://www.qquick.org/licence.html
import os
import sys
import ast
import re
import copy
import datetime
import shutil
import traceback
from org.transcrypt import __base__, utils, minify, static_check
class ModuleMetadata:
def __init__ (self, program, name):
self.name = name
searchedModulePaths = []
for searchDir in program.moduleSearchDirs:
relPrepath = self.name.replace ('.', '/')
prepath = '{}/{}'.format (searchDir, relPrepath)
self.isDir = os.path.isdir (prepath)
if self.isDir:
self.sourceDir = prepath
self.filePrename = '__init__'
else:
self.sourceDir, self.filePrename = prepath.rsplit ('/', 1)
# Target dir should be the JavaScript subdir of the sourceDir
self.targetDir = '{}/{}'.format (self.sourceDir, __base__.__envir__.targetSubDir)
self.sourcePath = '{}/{}.py' .format (self.sourceDir, self.filePrename)
self.targetPath = '{}/{}.mod.js'.format (self.targetDir, self.filePrename)
searchedModulePaths += [self.sourcePath, self.targetPath]
if (os.path.isfile (self.sourcePath) or os.path.isfile (self.targetPath)):
break;
else:
# If even the target can't be loaded then there's a problem with this module, root or not
raise utils.Error (
moduleName = self.name,
message = '\n\tAttempt to load module: {}\n\tCan\'t find any of:\n\t\t{}\n'.format (
self.name, '\n\t\t'. join (searchedModulePaths)
)
)
def sourceExists (self):
return os.path.isfile (self.sourcePath)
def targetExists (self):
return os.path.isfile (self.targetPath)
def exists (self):
return self.sourceExists () or self.targetExists ()
def dirty (self):
# Find youngest of .py and .js files and use that as "original"
youngestTime = 0
youngestPath = None
for path in self.targetPath, self.sourcePath: # Order matters
if os.path.isfile (path):
pathTime = os.path.getmtime (path)
if utils.commandArgs.build or pathTime > youngestTime: # Builds correctly also if some source files are missing
youngestTime = pathTime
youngestPath = path
return youngestPath == self.sourcePath
class Program:
def __init__ (self, moduleSearchDirs):
self.header = '"use strict";\n// {}\'ed from Python, {}\n'.format (
__base__.__envir__.transpilerName.capitalize (), datetime.datetime.now ().strftime ('%Y-%m-%d %H:%M:%S'),
)
self.moduleSearchDirs = moduleSearchDirs
self.sourcePath = os.path.abspath (utils.commandArgs.source) .replace ('\\', '/')
self.sourceDir = '/'.join (self.sourcePath.split ('/') [ : -1])
self.sourceFileName = self.sourcePath.split ('/') [-1]
self.moduleDict = {}
self.fragments = {}
self.compile ()
def compile (self):
# Define names early, since they are cross-used in module compilation
prefix = 'org.{}'.format (__base__.__envir__.transpilerName)
self.coreModuleName = '{}.{}'.format (prefix, '__core__')
self.baseModuleName = '{}.{}'.format (prefix, '__base__')
self.standardModuleName = '{}.{}'.format (prefix, '__standard__')
self.builtinModuleName = '{}.{}'.format (prefix, '__builtin__')
self.mainModuleName = self.sourceFileName [ : -3]
# Module compilation
Module (self, ModuleMetadata (self, self.coreModuleName))
Module (self, ModuleMetadata (self, self.baseModuleName))
Module (self, ModuleMetadata (self, self.standardModuleName))
Module (self, ModuleMetadata (self, self.builtinModuleName))
try:
moduleMetadata = ModuleMetadata (self, self.mainModuleName)
Module (self, moduleMetadata) # Will trigger recursive compilation
except Exception as exception:
utils.enhanceException (
exception,
message = str (exception)
)
# Join all non-inline modules
normallyImportedTargetCode = ''.join ([
self.moduleDict [moduleName] .targetCode
for moduleName in sorted (self.moduleDict)
if not moduleName in (self.coreModuleName, self.baseModuleName, self.standardModuleName, self.builtinModuleName, self.mainModuleName)
])
# And sandwich them between the in-line modules
targetCode = (
self.header +
'function {} () {{\n'.format (self.mainModuleName) +
self.moduleDict [self.coreModuleName].targetCode +
self.moduleDict [self.baseModuleName] .targetCode +
self.moduleDict [self.standardModuleName] .targetCode +
self.moduleDict [self.builtinModuleName].targetCode +
normallyImportedTargetCode +
self.moduleDict [self.mainModuleName].targetCode +
' return __all__;\n' +
'}\n' +
'window [\'{0}\'] = {0} ();\n'.format (self.mainModuleName)
)
targetFileName = '{}/{}.js'.format ('{}/{}'.format (self.sourceDir, __base__.__envir__.targetSubDir), self.mainModuleName)
utils.log (False, 'Saving result in: {}\n', targetFileName)
with utils.create (targetFileName) as aFile:
aFile.write (targetCode)
miniFileName = '{}/{}/{}.min.js'.format (self.sourceDir, __base__.__envir__.targetSubDir, self.mainModuleName)
utils.log (False, 'Saving minified result in: {}\n', miniFileName)
if not utils.commandArgs.nomin:
minify.run (targetFileName, miniFileName)
def provide (self, moduleName):
if moduleName == '__main__':
moduleName = self.mainModuleName
moduleMetadata = ModuleMetadata (self, moduleName)
if moduleMetadata.name in self.moduleDict: # Find out if module is already provided
return self.moduleDict [moduleMetadata.name]
else: # If not, provide by loading or compiling
return Module (self, moduleMetadata)
class Module:
def __init__ (self, program, moduleMetadata, strip = False):
self.program = program
self.metadata = moduleMetadata # May contain dots if it's imported
self.program.moduleDict [self.metadata.name] = self
if self.metadata.dirty ():
self.parse ()
if utils.commandArgs.check:
static_check.run (self.metadata.sourcePath, self.parseTree)
self.dump ()
self.generate ()
self.extract ()
self.saveJavascript ()
else:
self.loadJavascript ()
self.extract ()
def loadJavascript (self):
utils.log (False, 'Loading precompiled module: {}\n', self.metadata.targetPath)
with open (self.metadata.targetPath) as aFile:
self.targetCode = aFile.read ()
if self.metadata.name in (self.program.coreModuleName, self.program.builtinModuleName):
# Remove comment-like line tails and empty lines (so no // inside a string allowed)
self.targetCode = '{}\n'.format (
'\n'.join ([line for line in [line.split ('//') [0] .rstrip () for line in self.targetCode.split ('\n')] if line])
)
def saveJavascript (self,):
utils.log (False, 'Saving precompiled module: {}\n', self.metadata.targetPath)
with utils.create (self.metadata.targetPath) as aFile:
aFile.write (self.targetCode)
def extract (self):
utils.log (False, 'Extracting metadata from: {}\n', self.metadata.targetPath)
useFragment = self.targetCode [self.targetCode.rfind ('<use>') : self.targetCode.rfind ('</use>')]
self.use = sorted (set ([
word
for word in useFragment.replace ('__pragma__', ' ') .replace ('(', ' ') .replace (')', ' ') .replace ('\'', ' ') .replace ('+', ' ') .split ()
if not word.startswith ('<')
]))
for moduleName in self.use:
self.program.provide (moduleName)
allFragment = self.targetCode [self.targetCode.rfind ('<all>') : self.targetCode.rfind ('</all>')]
self.all = sorted (set ([
word [1 : ]
for word in allFragment.replace ('__all__', ' ') .replace ('=', ' ') .split ()
if word.startswith ('.')
]))
extraLines = [
'__pragma__ = 0', # No code will be emitted for pragma's anyhow
'__pragma__ (\'skip\')', # Here __pragma__ must already be a known name for the static_check
'__new__ = __include__ = 0',
'__pragma__ (\'noskip\')'
''
] if utils.commandArgs else []
nrOfExtraLines = max (len (extraLines) - 1, 0) # Last line only to force linefeed
extraLines = '\n'.join (extraLines)
def parse (self):
try:
utils.log (False, 'Parsing module: {}\n', self.metadata.sourcePath)
with open (self.metadata.sourcePath) as sourceFile:
self.sourceCode = utils.extraLines + sourceFile.read ()
self.parseTree = ast.parse (self.sourceCode)
except SyntaxError as syntaxError:
utils.enhanceException (
syntaxError,
moduleName = self.metadata.name,
lineNr = syntaxError.lineno,
message = (
'{} <SYNTAX FAULT] {}'.format (
syntaxError.text [:syntaxError.offset].lstrip (),
syntaxError.text [syntaxError.offset:].rstrip ()
)
if syntaxError.text else
syntaxError.args [0]
)
)
def dump (self):
utils.log (False, 'Dumping syntax tree of module: {}\n', self.metadata.sourcePath)
def walk (name, value, tabLevel):
self.treeFragments .append ('\n{0}{1}: {2} '.format (tabLevel * '\t', name, type (value).__name__ ))
if isinstance (value, ast.AST):
for field in ast.iter_fields (value):
walk (field [0], field [1], tabLevel + 1)
elif isinstance (value, list):
for element in value:
walk ('element', element, tabLevel + 1)
else:
self.treeFragments.append ('= {0}'.format (value))
self.treeFragments = []
walk ('file', self.parseTree, 0)
self.textTree = ''.join (self.treeFragments) [1:]
with utils.create ('{}/{}.tree'.format (self.metadata.targetDir, self.metadata.filePrename)) as treeFile:
treeFile.write (self.textTree)
def generate (self):
utils.log (False, 'Generating code for module: {}\n', self.metadata.targetPath)
self.targetCode = ''.join (Generator (self) .targetFragments)
with utils.create (self.metadata.targetPath) as targetFile:
targetFile.write (self.targetCode)
class Generator (ast.NodeVisitor):
# Terms like parent, child, ancestor and descendant refer to the parse tree here, not to inheritance
def __init__ (self, module):
self.module = module
self.targetFragments = []
self.skipSemiNew = False
self.indentLevel = 0
self.scopes = []
self.use = set ()
self.all = set ()
self.importHeads = set ()
self.aliasers = [self.getAliaser (*alias) for alias in (
# START predef_aliases
('js_sort', 'sort'),
('sort', 'py_sort'),
('js_split', 'split'),
('split', 'py_split'),
('keys', 'py_keys'),
('js_arguments', 'arguments'),
('arguments', 'py_arguments')
# END predef_aliases
)]
self.tempIndices = {}
self.stubsName = 'org.{}.stubs.'.format (__base__.__envir__.transpilerName)
self.nameConsts = {
None: 'null',
True: 'true',
False: 'false'
}
self.operators = {
ast.Invert: ('~', 100),
ast.UAdd: ('+', 100),
ast.USub: ('-', 100),
ast.Pow: (None, 110), # Dealt with separately
ast.Mult: ('*', 90),
ast.MatMult: (None, 90), # Dealt with separately
ast.Div: ('/', 90),
ast.FloorDiv: (None, 90), # Dealt with separately
ast.Mod: ('%', 90),
ast.Add: ('+', 80),
ast.Sub: ('-', 80),
ast.LShift: ('<<', 70),
ast.RShift: ('>>', 70),
ast.BitAnd: ('&', 60),
ast.BitXor: ('^', 50),
ast.BitOr: ('|', 40),
ast.Eq: ('==', 30),
ast.NotEq: ('!=', 30),
ast.Lt: ('<', 30),
ast.LtE: ('<=', 30),
ast.Gt: ('>', 30),
ast.GtE: ('>=', 30),
ast.Is: ('===', 30), # Not really, but closest for now
ast.IsNot: ('!==', 30), # Not really, but closest for now
ast.In: (None, 30), # Dealt with separately
ast.NotIn: (None, 30), # Dealt with separately
ast.Not: ('!', 20),
ast.And: ('&&', 10),
ast.Or: ('||', 0)
}
self.allowKeywordArgs = utils.commandArgs.kwargs
self.allowOperatorOverloading = utils.commandArgs.opov
self.memoizeCalls = utils.commandArgs.fcall
self.codeGeneration = True
try:
self.visit (module.parseTree)
except Exception as exception:
utils.enhanceException (exception, moduleName = self.module.metadata.name, lineNr = self.lineNr)
if self.tempIndices:
raise utils.Error (
message = '\n\tTemporary variables leak in code generator: {}'.format (self.tempIndices)
)
def visitSubExpr (self, node, child):
def getPriority (exprNode):
if type (exprNode) in (ast.BinOp, ast.BoolOp):
return self.operators [type (exprNode.op)][1]
elif type (exprNode) == ast.Compare:
return self.operators [type (exprNode.ops [0])][1] # All ops have same priority
else:
return 1000000 # No need for parenthesis
if getPriority (child) < getPriority (node):
self.emit ('(')
self.visit (child)
self.emit (')')
else:
self.visit (child)
def getAliaser (self, pyFragment, jsFragment):
return (pyFragment, re.compile ('''
(^{0}$)| # Whole word
(__{0}__)| # Contains __<pyFragment>__
(^{0}__)| # Starts with <pyFragment>__
(__{0}$)| # Ends with __<pyFragment>
((?<=\.){0}__)| # Starts with '.<pyFragment>__'
(__{0}(?=\.)) # Ends with '__<pyFragment>.'
'''.format (pyFragment), re.VERBOSE), jsFragment)
def filterId (self, qualifiedId):
for aliaser in self.aliasers:
qualifiedId = re.sub (aliaser [1], aliaser [2], qualifiedId)
return qualifiedId
def tabs (self, indentLevel = None):
if indentLevel == None:
indentLevel = self.indentLevel
return indentLevel * '\t'
def emit (self, fragment, *formatter):
if (
not self.targetFragments or
(self.targetFragments and self.targetFragments [-1] .endswith ('\n'))
):
self.targetFragments.append (self.tabs ())
fragment = fragment [:-1] .replace ('\n', '\n' + self.tabs ()) + fragment [-1]
self.targetFragments.append (fragment.format (*formatter))
def indent (self):
self.indentLevel += 1
def dedent (self):
self.indentLevel -= 1
def inscope (self, scope):
self.scopes.append (scope)
def descope (self):
self.scopes.pop ()
def getscope (self, scopeType = None):
if scopeType:
for scope in reversed (self.scopes):
if type (scope) == scopeType:
return scope
else:
return self.scopes [-1]
def emitComma (self, index, blank = True):
if index:
self.emit (', ' if blank else ',')
def emitBody (self, body):
for stmt in body:
self.visit (stmt)
if self.skipSemiNew: # No imports here, but just to be sure for the future
self.skipSemiNew = False
else:
self.emit (';\n')
def nextTemp (self, name):
if name in self.tempIndices:
self.tempIndices [name] += 1
else:
self.tempIndices [name] = 0
return self.getTemp (name)
def getTemp (self, name):
if name in self.tempIndices:
return '__{}{}__'.format (name, self.tempIndices [name])
else:
return None
def prevTemp (self, name):
self.tempIndices [name] -= 1
if self.tempIndices [name] < 0:
del self.tempIndices [name]
def useModule (self, name):
result = self.module.program.provide (name) # Must be done first because it can generate a healthy exception
self.use.add (name) # Must not be done if the healthy exception occurs
return result
def getPragmaKindFromExpr (self, node):
return (
node.value.args [0] .s
if (
type (node) == ast.Expr and type (node.value) == ast.Call and
type (node.value.func) == ast.Name and node.value.func.id == '__pragma__'
) else
None
)
def visit (self, node):
try:
self.lineNr = node.lineno
except:
pass
pragmaKind = self.getPragmaKindFromExpr (node)
if pragmaKind == 'skip':
self.codeGeneration = False
elif pragmaKind == 'noskip':
self.codeGeneration = True
if self.codeGeneration:
ast.NodeVisitor.visit (self, node)
def visit_arg (self, node):
self.emit (node.arg)
def visit_arguments (self, node): # Visited for def's, not for calls
self.emit ('(')
for index, arg in enumerate (node.args):
self.emitComma (index)
self.visit (arg)
# If there's a vararg or a kwarg, no formal parameter is emitted for it, it's just retrieved in the body
# so def f (a, b=3, *x, c, d=4, **y, e, f = 5) generates function f (a, b, c, d, e, f), since x and y are never passed in positionally
self.emit (') {{\n')
self.indent () # Start of function body, the end is not in visit_arguments
# Defaults for positional args (before *), only if not passed normally before this point
# They can also be passed in as keyword args
# If so, the keywords are filled in starting with the last positional arg
# So after a keyword positional arg cannot follow a non-keyword positional arg
# The kwargdict may be the last of the actual params
# It should not initialize a formal param, so it's overwritten by the default as well.
for arg, expr in reversed (list (zip (reversed (node.args), reversed (node.defaults)))):
if expr:
self.emit ('if (typeof {0} == \'undefined\' || ({0} != null && {0} .__class__ == __kwargdict__)) {{;\n', arg.arg)
self.indent ()
self.emit ('var {} = ', arg.arg)
self.visit (expr)
self.emit (';\n')
self.dedent ()
self.emit ('}};\n')
# Defaults for kwonly args (after *), unconditionally, since they will be passed only after this point
for arg, expr in zip (node.kwonlyargs, node.kw_defaults):
if expr:
self.emit ('var {} = ', arg.arg)
self.visit (expr)
self.emit (';\n')
if self.allowKeywordArgs:
self.emit ('if (arguments.length) {{\n')
self.indent ()
# Store index of last actual param
self.emit ('var {} = arguments.length - 1;\n', self.nextTemp ('ilastarg'))
# Any calltime keyword args are passed in a JavaScript-only object of type __kwargdict__
# If it's there, copy the __kwargdict__ into local var __allkwargs__
# And lower __ilastarg__ by 1, since the last calltime arg wasn't a normal (Python) one
# It's only known at call time if there are keyword arguments, unless there are no arguments at all, so allways have to generate this code
self.emit ('if (arguments [{0}] && arguments [{0}].__class__ == __kwargdict__) {{\n', self.getTemp ('ilastarg'))
self.indent ()
self.emit ('var {} = arguments [{}--];\n', self.nextTemp ('allkwargs'), self.getTemp ('ilastarg'))
# If there is a **kwargs arg, make a local to hold its calltime contents
if node.kwarg:
self.emit ('var {} = {{}};\n', node.kwarg.arg)
# __kwargdict__ may contain deftime defined keyword args, but also keyword args that are absorbed by **kwargs
self.emit ('for (var {} in {}) {{\n', self.nextTemp ('attrib'), self.getTemp ('allkwargs'))
self.indent ()
# We'll make the distinction between normal keyword args and **kwargs keyword args in a switch
if node.args + node.kwonlyargs or node.kwarg:
self.emit ('switch ({}) {{\n', self.getTemp ('attrib'))
self.indent ()
# First generate a case for each normal keyword arg, generating a local for it
for arg in node.args + node.kwonlyargs:
self.emit ('case \'{0}\': var {0} = {1} [{2}]; break;\n', arg.arg, self.getTemp ('allkwargs'), self.getTemp ('attrib'))
# Then put the rest into the **kwargs local
if node.kwarg:
self.emit ('default: {0} [{1}] = {2} [{1}];\n', node.kwarg.arg, self.getTemp ('attrib'), self.getTemp ('allkwargs'))
self.dedent ()
self.emit ('}}\n') # switch..
self.prevTemp ('allkwargs')
self.prevTemp ('attrib')
self.dedent ()
self.emit ('}}\n') # for (__attrib__..
# Take out the kwargdict marker, to prevent it from being passed in to another call, leading to confusion there
if node.kwarg:
self.emit ('{}.__class__ = null;\n', node.kwarg.arg)
self.dedent ()
self.emit ('}}\n') # if (arguments [{0}]..
# If there's a vararg, assign an array containing the remainder of the actual non keyword only params, except for the __kwargdict__
if node.vararg:
# Slice starts at end of formal positional params, ends with last actual param, all actual keyword args are taken out into the __kwargdict__
self.emit (
'var {} = tuple ([].slice.apply (arguments).slice ({}, {} + 1));\n',
node.vararg.arg,
len (node.args),
self.getTemp ('ilastarg')
)
self.prevTemp ('ilastarg')
self.dedent ()
self.emit ('}}\n') # if (arguments.length..
else:
if node.vararg: # See above
self.emit (
'var {} = tuple ([].slice.apply (arguments).slice ({}));\n',
node.vararg.arg,
len (node.args),
)
def visit_Assign (self, node):
targetLeafs = (ast.Attribute, ast.Subscript, ast.Name)
def assignTarget (target, value, pathIndices = []):
def emitPathIndices ():
if pathIndices:
self.emit (' ')
for pathIndex in pathIndices:
self.emit ('[{}]'.format (pathIndex))
else: # Most frequent and simple case, only one atomary LHS
pass
# Special case for target slice (as opposed to target index)
if type (target) == ast.Subscript and type (target.slice) == ast.Slice:
self.visit (target.value)
try:
self.emit ('.__setslice__ (')
if target.slice.lower == None:
self.emit ('0')
else:
self.visit (target.slice.lower)
self.emit (', ')
if target.slice.upper == None:
self.emit ('null')
else:
self.visit (target.slice.upper)
self.emit (', ')
if target.slice.step:
self.visit (target.slice.step)
else:
self.emit ('null')
self.emit (', ')
self.visit (value)
self.emit (')')
except Exception as exception:
utils.enhanceException (exception, lineNr = self.lineNr, message = 'Invalid LHS slice')
else:
if isPropertyAssign and not target.id == self.getTemp ('left'):
self.emit ('Object.defineProperty ({}, \'{}\', '.format (self.getscope () .name, target.id))
self.visit (value)
emitPathIndices ()
self.emit (');')
else:
if type (target) == ast.Name:
if type (self.getscope ()) == ast.ClassDef and target.id != self.getTemp ('left'):
self.emit ('{}.'.format (self.getscope () .name))
else:
self.emit ('var ')
self.visit (target)
self.emit (' = ')
self.visit (value)
emitPathIndices ()
# Tuple assignment LHS tree walker
# The target (LHS) guides the walk, so it determines the source indices
# However if a target leaf is an LHS slice,
# the actual assignment will involve iterating through an extra index level,
# as [1, 2][1:1] = [2, 3] should give [1, 2, 3, 4] rather than [1, [2, 3], 4]
# This extra target level is walked in the splice and
def walkTarget (expr, pathIndices):
if type (expr) in targetLeafs: # It's an LValue, matching an RHS leaf source
self.emit (';\n')
# Create and visit RHS node on the fly, to benefit from assignTarget
assignTarget (expr, ast.Name (id = self.getTemp ('left'), ctx = ast.Load), pathIndices)
else: # It's a sequence
pathIndices.append (None) # Add indexing level for that sequence
for index, elt in enumerate (expr.elts):
pathIndices [-1] = index
walkTarget (elt, pathIndices) # Walk deeper until finally pathIndices is used in emitting an RHS leaf
pathIndices.pop () # Remove the indexing level since we're done with that sequence
def getIsPropertyAssign (value):
if type (value) == ast.Call and type (value.func) == ast.Name and value.func.id == 'property':
return True
else:
try: # Assume it's a tuple or a list of properties (and so recursively)
return getIsPropertyAssign (value.elts [0])
except: # At this point it wasn't a property and also not a tuple or a list of properties
return False
isPropertyAssign = type (self.getscope ()) == ast.ClassDef and getIsPropertyAssign (node.value)
# In transpiling to efficient JavaScript, we need a special, simplified case for properties
# In JavaScript generating '=' for properties won't do, it has to be 'Object.defineProperty'
# We can't look out for property installation at runtime, that would make all assignments slow
# So we introduce the restriction that an assignment involves no properties at all or only properties
# Also these properties have to use the 'property' function 'literally'
# With these restrictions we can recognize property installation at compile time
if len (node.targets) == 1 and type (node.targets [0]) in targetLeafs:
# Fast shortcut for the most frequent and simple case
assignTarget (node.targets [0], node.value)
else:
# Multiple RHS or tuple assignment, we need __tmp__, create assignment node on the fly and visit it
self.visit (ast.Assign ([ast.Name (self.nextTemp ('left'), ast.Store)], node.value))
for expr in node.targets:
walkTarget (expr, [])
self.prevTemp ('left')
def visit_Attribute (self, node):
self.visit (node.value)
self.emit ('.{}', self.filterId (node.attr))
def visit_AugAssign (self, node):
self.visit (node.target) # No need to emit var first, it has to exist already
# Optimize for ++ and --
if type (node.value) == ast.Num and node.value.n == 1:
if type (node.op) == ast.Add:
self.emit ('++')
return
elif type (node.op) == ast.Sub:
self.emit ('--')
return
elif type (node.value) == ast.UnaryOp and type (node.value.operand) == ast.Num and node.value.operand.n == 1:
if type (node.op) == ast.Add:
if type (node.value.op) == ast.UAdd:
self.emit ('++')
return
elif type (node.value.op) == ast.USub:
self.emit ('--')
return
elif type (node.op) == ast.Sub:
if type (node.value.op) == ast.UAdd:
self.emit ('--')
return
elif type (node.value.op) == ast.USub:
self.emit ('++')
return
self.emit (' {}= ', self.operators [type (node.op)][0])
self.visit (node.value)
def visit_BinOp (self, node):
if type (node.op) == ast.FloorDiv:
self.emit ('Math.floor (')
self.visit (node.left)
self.emit (') / ')
self.emit ('Math.floor (')
self.visit (node.right)
self.emit (')')
elif type (node.op) in (ast.MatMult, ast.Pow) or (self.allowOperatorOverloading and type (node.op) in (ast.Mult, ast.Div, ast.Add, ast.Sub)):
self.emit ('{} ('.format (self.filterId (
'Math.pow' if type (node.op) == ast.Pow else
'matmul' if type (node.op) == ast.MatMult else
'mul' if type (node.op) == ast.Mult else
'div' if type (node.op) == ast.Div else
'add' if type (node.op) == ast.Add else
'sub' # if type (node.op) == ast.Sub else
)))
self.visit (node.left)
self.emit (', ')
self.visit (node.right)
self.emit (')')
else:
self.visitSubExpr (node, node.left)
self.emit (' {} '.format (self.operators [type (node.op)][0]))
self.visitSubExpr (node, node.right)
def visit_BoolOp (self, node):
for index, value in enumerate (node.values):
if index:
self.emit (' {} '.format (self.operators [type (node.op)][0]))
self.visitSubExpr (node, value)
def visit_Break (self, node):
self.emit ('{} = true;\n', self.getTemp ('break'))
self.emit ('break')
def visit_Call (self, node):
def emitKwargDict ():
self.emit ('__kwargdict__ (')
hasSeparateKeyArgs = False
hasKwargs = False
for keyword in node.keywords:
if keyword.arg:
hasSeparateKeyArgs = True
else:
hasKwargs = True
break # **kwargs is always the last arg
if hasSeparateKeyArgs:
if hasKwargs:
self.emit ('__merge__ (')
self.emit ('{{') # Allways if hasSeparateKeyArgs
for keywordIndex, keyword in enumerate (node.keywords):
if keyword.arg:
self.emitComma (keywordIndex)
self.emit ('{}: ', keyword.arg)
self.visit (keyword.value)
else:
# It's the **kwargs arg, so the last arg
# In JavaScript this must be an expression denoting an Object (sometimes specialized as kwargdict)
# The keyword args in there have to be added to the __kwargdict__ as well
if hasSeparateKeyArgs:
self.emit ('}}, ')
self.visit (keyword.value)
if hasSeparateKeyArgs:
if hasKwargs:
self.emit (')') # Terminate merge
else:
self.emit ('}}') # Only if not terminated already because hasKwargs
self.emit (')')
def include (fileName):
searchedIncludePaths = []
for searchDir in self.module.program.moduleSearchDirs:
filePath = '{}/{}'.format (searchDir, fileName)
if os.path.isfile (filePath):
return open (filePath) .read ()
else:
searchedIncludePaths.append (filePath)
else:
raise utils.Error (
moduleName = self.module.metadata.name,
lineNr = self.lineNr,
message = '\n\tAttempt to include file: {}\n\tCan\'t find any of:\n\t\t{}\n'.format (
node.args [0], '\n\t\t'. join (searchedIncludePaths)
)
)
if type (node.func) == ast.Name:
if node.func.id == 'property':
self.emit ('{0}.call ({1}, {1}.{2}'.format (node.func.id, self.getscope (ast.ClassDef) .name, node.args [0].id))
if len (node.args) > 1:
self.emit (', {}.{}'.format (self.getscope (ast.ClassDef) .name, node.args [1].id))
self.emit (')')
return
elif node.func.id == '__pragma__':
if node.args [0] .s == 'kwargs': # Start emitting kwargs code for FunctionDef's
self.allowKeywordArgs = True
elif node.args [0] .s == 'nokwargs': # Stop emitting kwargs code for FunctionDef's
self.allowKeywordArgs = False
elif node.args [0] .s == 'opov': # Overloading of a small sane subset of operators allowed
self.allowOperatorOverloading = True
elif node.args [0] .s == 'noopov': # Operloading of a small sane subset of operators disallowed
self.allowOperatorOverloading = False
elif node.args [0] .s == 'js': # Include JavaScript code literally in the output
self.emit ('\n{}\n', node.args [1] .s.format (* [
eval (
compile (
ast.Expression (arg),
'<string>',
'eval'
),
{},
{'__include__': include}
)
for arg in node.args [2:]
]))
elif node.args [0] .s == 'alias':
self.aliasers.insert (0, self.getAliaser (node.args [1] .s, node.args [2].s))
elif node.args [0] .s == 'noalias':
if len (node.args) == 1:
self.aliasers = []
else:
for index in range (len (self.aliasers)) .reverse ():
if self.aliasers [index][0] == node.args [1]:
self.aliasers.pop (index)
elif node.args [0] .s == 'fcall':
self.memoizeCalls = True
elif node.args [0] .s == 'nofcall':
self.memoizeCalls = False
elif node.args [0] .s in ('skip', 'noskip'):
pass # Easier dealth with on statement / expression level in self.visit
else:
raise utils.Error (
moduleName = self.module.metadata.name,
lineNr = self.lineNr,
message = 'Unknown pragma: {}'.format (
node.args [0] .s if type (node.args [0]) == ast.Str else node.args [0]
)
)
return
elif node.func.id == '__new__':
self.emit ('new ')
self.visit (node.args [0])
return
self.visit (node.func)
for index, expr in enumerate (node.args):
if type (expr) == ast.Starred:
self.emit ('.apply (null, ') # Note that in generated a.b.f (), a.b.f is a bound function already
for index, expr in enumerate (node.args):
if index:
self.emit ('.concat (')
if type (expr) == ast.Starred:
self.visit (expr)
else:
self.emit ('[')
self.visit (expr)
self.emit (']')
if index:
self.emit (')')
if node.keywords:
self.emit ('.concat ([') # At least *args was present before this point
emitKwargDict ()
self.emit ('])')
self.emit (')')
break;
else:
self.emit (' (')
for index, expr in enumerate (node.args):
self.emitComma (index)
self.visit (expr)
if node.keywords:
self.emitComma (len (node.args))
emitKwargDict ()
self.emit (')')
def visit_ClassDef (self, node):
if type (self.getscope ()) == ast.Module:
self.all.add (node.name)
self.emit ('var {0} = __class__ (\'{0}\', [', self.filterId (node.name))
if node.bases:
for index, expr in enumerate (node.bases):
try:
self.emitComma (index)
self.visit_Name (expr)
except Exception as exception:
utils.enhanceException (moduleName = self.module.metadata.name, lineNr = self.lineNr, message = 'Invalid base class')
else:
self.emit ('object')
self.emit ('], {{')
self.inscope (node)
self.indent ()
classVarAssigns = []
index = 0
for stmt in node.body:
if type (stmt) == ast.FunctionDef:
self.emitComma (index, False)
self.visit (stmt)
index += 1
elif type (stmt) == ast.Assign:
classVarAssigns.append (stmt) # Has to be done after the class because tuple assignment requires the use of an algorithm
elif self.getPragmaKindFromExpr (stmt):
self.visit (stmt)
self.dedent ()
self.emit ('\n}})')
for index, classVarAssign in enumerate (classVarAssigns):
self.emit (';\n')
self.visit (classVarAssign)
self.descope () # No earlier, class vars need it
def visit_Compare (self, node):
if len (node.comparators) > 1:
self.emit ('(')
left = node.left
for index, (operand, right) in enumerate (zip (node.ops, node.comparators)):
if index:
self.emit (' && ')
if type (operand) in (ast.In, ast.NotIn):
self.emit ('{}__in__ (', '!' if type (operand) == ast.NotIn else '')
self.visitSubExpr (node, left)
self.emit (', ')
self.visitSubExpr (node, right)
self.emit (')')
else:
self.visitSubExpr (node, left)
self.emit (' {0} '.format (self.operators [type (operand)][0]))
self.visitSubExpr (node, right)
left = right
if len (node.comparators) > 1:
self.emit(')')
def visit_Continue (self, node):
self.emit ('continue')
def visit_Dict (self, node):
if not utils.commandArgs.jskeys:
for key in node.keys:
if not type (key) in (ast.Str, ast.Num):
self.emit ('dict ([')
for index, (key, value) in enumerate (zip (node.keys, node.values)):
self.emitComma (index)
self.emit ('[')
self.visit (key) # In a JavaScrip list, name is evaluated as variable or function call to produce a key
self.emit (', ')
self.visit (value)
self.emit (']')
self.emit ('])')
return
self.emit ('{{')
for index, (key, value) in enumerate (zip (node.keys, node.values)):
self.emitComma (index)
self.visit (key) # In a JavaScript object literal name isn't evaluated but literally taken to be a key ('virtual' quotes added)
self.emit (': ')
self.visit (value)
self.emit ('}}')
def visit_Expr (self, node):
self.visit (node.value)
def visit_For (self, node):
self.emit ('var {} = ', self.nextTemp ('iter'))
self.visit (node.iter)
self.emit (';\n')
if node.orelse:
self.emit ('var {} = false;\n', self.nextTemp ('break'))
self.emit ('for (var {0} = 0; {0} < {1}.length; {0}++) {{\n', self.nextTemp ('index'), self.getTemp ('iter'))
self.indent ()
# Create and visit Assign node on the fly to benefit from tupple assignment
self.visit (ast.Assign (
[node.target],
ast.Subscript (
value = ast.Name (id = self.getTemp ('iter'), ctx = ast.Load),
slice = ast.Index (ast.Num (n = self.getTemp ('index'))),
ctx = ast.Load
)
))
self.emit (';\n')
self.emitBody (node.body)
self.dedent ()
self.emit ('}}\n')
if node.orelse:
self.emit ('if (!{}) {{\n', self.getTemp ('break'))
self.prevTemp ('break')
self.indent ()
self.emitBody (node.orelse)
self.dedent ()
self.emit ('}}\n')
self.skipSemiNew = True
self.prevTemp ('index')
self.prevTemp ('iter')
def visit_FunctionDef (self, node):
def emitScopedBody ():
self.inscope (node)
self.emitBody (node.body)
self.dedent ()
self.descope ()
if not node.name == '__pragma__': # Don't generate code for the dummy pragma definition starting the extraLines in utils
# Pragma should never be defined, except once directly in JavaScript to support __pragma__ ('<all>')
# The rest of its use is only at compile time at compile time
if type (self.getscope ()) in (ast.Module, ast.FunctionDef): # Global or function scope, so it's no method
if type (self.getscope ()) == ast.Module:
self.all.add (node.name)
self.emit ('var {} = function ', self.filterId (node.name))
self.visit (node.args)
emitScopedBody ()
self.emit ('}}')
else: # Class scope, so it's a method and needs the currying mechanism
self.emit ('\nget {} () {{return __get__ (this, function ', self.filterId (node.name))
self.visit (node.args)
emitScopedBody ()
self.emit ('}}')
if self.memoizeCalls:
self.emit (', \'{}\'', node.name) # Name will be used as attribute name to add bound function to instance
self.emit (');}}')
def visit_If (self, node):
self.emit ('if (')
self.visit (node.test)
self.emit (') {{\n')
self.indent ()
self.emitBody (node.body)
self.dedent ()
self.emit ('}}\n')
if node.orelse:
self.emit ('else {{\n')
self.indent ()
self.emitBody (node.orelse)
self.dedent ()
self.emit ('}}\n')
self.skipSemiNew = True
def visit_IfExp (self, node):
self.emit ('(')
self.visit (node.test)
self.emit (' ? ')
self.visit (node.body)
self.emit (' : ')
self.visit (node.orelse)
self.emit (')')
def visit_Import (self, node): # Import .. can only import modules
names = [alias for alias in node.names if not alias.name.startswith (self.stubsName)]
if not names:
self.skipSemiNew = True
return
for index, alias in enumerate (names):
try:
self.useModule (alias.name)
except Exception as exception:
utils.enhanceException (exception, moduleName = self.module.metadata.name, lineNr = self.lineNr, message = 'Can\'t import module \'{}\''.format (alias.name))
if alias.asname:
self.emit ('var {} = __init__ (__world__.{})', self.filterId (alias.asname), self.filterId (alias.name))
else:
aliasSplit = alias.name.split ('.', 1)
head = aliasSplit [0]
tail = aliasSplit [1] if len (aliasSplit) > 1 else ''
self.importHeads.add (head)
self.emit ('__nest__ ({}, \'{}\', __init__ (__world__.{}))', self.filterId (head), self.filterId (tail), self.filterId (alias.name))
if index < len (names) - 1:
self.emit (';\n')
def visit_ImportFrom (self, node): # From .. import can import modules or entities in modules
if node.module.startswith (self.stubsName):
self.skipSemiNew = True
return
try:
# N.B. It's ok to call a modules __init__ multiple times, see __core__.mod.js
for index, alias in enumerate (node.names):
if alias.name == '*': # * Never refers to modules, only to entities in modules
if len (node.names) > 1:
raise Error (moduleName = module.metadata.name, lineNr = node.lineno, message = 'Can\'t import module \'{}\''.format (alias.name))
module = self.useModule (node.module)
for index, name in enumerate (module.all):
self.emit ('var {0} = __init__ (__world__.{1}).{0}', self.filterId (name), self.filterId (node.module))
if index < len (module.all) - 1:
self.emit (';\n')
else:
try: # Try if alias.name denotes a module
self.useModule ('{}.{}'.format (node.module, alias.name))
if alias.asname:
self.emit ('var {} = __init__ (__world__.{}.{})', self.filterId (alias.asname), self.filterId (node.module), self.filterId (alias.name))
else:
self.emit ('var {0} = __init__ (__world__.{1}.{0})', self.filterId (alias.name), self.filterId (node.module))
except: # If it doesn't it denotes an entity inside a module
self.useModule (node.module)
if alias.asname:
self.emit ('var {} = __init__ (__world__.{}).{}', self.filterId (alias.asname), self.filterId (node.module), self.filterId (alias.name))
else:
self.emit ('var {0} = __init__ (__world__.{1}).{0}', self.filterId (alias.name), self.filterId (node.module))
if index < len (node.names) - 1:
self.emit (';\n')
except Exception as exception:
utils.enhanceException (exception, lineNr = self.lineNr, message = 'Can\'t import from module \'{}\''.format (node.module))
def visit_Index (self, node):
self.emit (' [')
self.visit (node.value)
self.emit (']')
def visit_Lambda (self, node):
self.emit ('(function __lambda__ ',) # Extra () needed to make it callable at definition time
self.visit (node.args)
self.emit ('return ')
self.visit (node.body)
self.dedent ()
self.emit (';}})')
def visit_List (self, node):
self.emit ('list ([')
for index, elt in enumerate (node.elts):
self.emitComma (index)
self.visit (elt)
self.emit ('])')
def visit_ListComp (self, node):
elts = []
bodies = [[]]
# Create and visit For node on the fly to benefit from tupple assignment
# The For node creates an Assign node on the fly, to get this done
def nestLoops (generators):
for comprehension in generators:
target = comprehension.target
iter = comprehension.iter
# Make room for body of this for
bodies.append ([])
# Append this for to previous body
bodies [-2].append (ast.For (target, iter, bodies [-1], []))
for expr in comprehension.ifs:
test = expr
# Make room for body of this if
bodies.append ([])
# Append this if to previous body
bodies [-2].append (ast.If (test, bodies [-1], []))
bodies [-1].append (
# Nodes to generate __accu<i>__.append (<elt>)
ast.Call (
ast.Attribute (
ast.Name (
self.getTemp ('accu'),
ast.Load),
'append',
ast.Load
),
[node.elt],
[]
)
)
self.visit (
bodies [0][0]
)
self.emit ('function () {{\n')
self.inscope (ast.FunctionDef ())
self.indent ()
self.emit ('var {} = [];\n', self.nextTemp ('accu'))
nestLoops (node.generators [:]) # Leave original in intact, just for neatness
self.emit ('return {};\n'.format (self.getTemp ('accu')))
self.prevTemp ('accu')
self.dedent ()
self.skipSemiNew = False # Was still True since the outer for wasn't visited as part of a Body
self.descope ()
self.emit ('}} ()')
def visit_Module (self, node):
self.inscope (node)
self.indent ()
if self.module.metadata.name == self.module.program.mainModuleName:
self.emit ('(function () {{\n')
else:
self.emit ('__nest__ (\n')
self.indent ()
self.emit ('__all__,\n')
self.emit ('\'{}\', {{\n', self.filterId (self.module.metadata.name))
self.indent ()
self.emit ('__all__: {{\n')
self.indent ()
self.emit ('__inited__: false,\n')
self.emit ('__init__: function (__all__) {{\n')
self.indent ()
importHeadsIndex = len (self.targetFragments)
importHeadsLevel = self.indentLevel
self.emitBody (node.body)
if self.use:
self.use = sorted (self.use)
self.emit ('__pragma__ (\'<use>\' +\n') # Only the last occurence of <use> and </use> are special.
self.indent ()
for name in self.use:
self.emit ('\'{}\' +\n', name)
self.dedent ()
self.emit ('\'</use>\')\n')
if self.all:
self.all = sorted (self.all)
self.emit ('__pragma__ (\'<all>\')\n') # Only the last occurence of <all> and </all> are special.
self.indent ()
for name in self.all:
self.emit ('__all__.{0} = {0};\n', self.filterId (name))
self.dedent ()
self.emit ('__pragma__ (\'</all>\')\n')
self.dedent ()
if self.module.metadata.name == self.module.program.mainModuleName:
self.emit ('}}) ();\n')
else:
self.emit ('}}\n')
self.dedent ()
self.emit ('}}\n')
self.dedent ()
self.emit ('}}\n')
self.dedent ()
self.emit (');\n')
self.dedent ()
self.targetFragments.insert (importHeadsIndex, ''.join ([
'{}var {} = {{}};\n'.format (self.tabs (importHeadsLevel), self.filterId (head))
for head in sorted (self.importHeads)
]))
self.descope ()
def visit_Name (self, node):
if type (node.ctx) == ast.Store:
if type (self.getscope ()) == ast.Module:
self.all.add (node.id)
self.emit (self.filterId (node.id))
def visit_NameConstant (self, node):
self.emit (self.nameConsts [node.value])
def visit_Num (self, node):
self.emit ('{}', node.n)
def visit_Pass (self, node):
self.skipSemiNew = True
def visit_Raise (self, node):
self.emit ('__except__ = ')
self.visit (node.exc)
self.emit (';\n')
self.emit ('__except__.__cause__ = ')
if node.cause:
self.visit (node.cause)
else:
self.emit ('null')
self.emit (';\n')
self.emit ('throw __except__')
def visit_Return (self, node):
self.emit ('return ')
if node.value:
self.visit (node.value)
def visit_Set (self, node):
self.emit ('new set ([')
for index, elt in enumerate (node.elts):
self.emitComma (index)
self.visit (elt)
self.emit ('])')
def visit_Str (self, node):
self.emit ('{}', repr (node.s))
# Visited for RHS index, RHS slice and LHS index but not for LHS slice
# LHS slices are dealth with directy in visit_Assign, since the RHS is needed for it also
def visit_Subscript (self, node):
self.visit (node.value)
if type (node.slice) == ast.Slice: # Then we're sure node.ctx == ast.Load
try:
if node.slice.step == None:
self.emit ('.slice (')
if node.slice.lower == None:
self.emit ('0')
else:
self.visit (node.slice.lower)
if node.slice.upper != None:
self.emit (', ')
self.visit (node.slice.upper)
else:
self.emit ('.__getslice__ (')
if node.slice.lower == None:
self.emit ('0')
else:
self.visit (node.slice.lower)
self.emit (', ')
if node.slice.upper == None:
self.emit ('null')
else:
self.visit (node.slice.upper)
self.emit (', ')
self.visit (node.slice.step)
self.emit (')')
except Exception as exception:
utils.enhanceException (exception, lineNr = self.lineNr, message = 'Invalid RHS slice')
else: # Here target.slice is an ast.Index, target.ctx may vary (ast.ExtSlice not dealth with yet)
self.visit (node.slice)
def visit_Try (self, node):
self.emit ('try {{\n')
self.indent ()
self.emitBody (node.body)
self.dedent ()
self.emit ('}}\n')
self.emit ('catch (__except__) {{\n')
self.indent ()
for index, excepthandler in enumerate (node.handlers):
if excepthandler.type:
if index:
self.emit ('else ')
self.emit ('if (isinstance (__except__, ')
self.visit (excepthandler.type)
self.emit (')) {{\n')
else:
self.emit ('else {{\n')
self.indent ()
if excepthandler.name:
self.emit ('var {} = __except__;\n', excepthandler.name)
self.emitBody (excepthandler.body)
self.dedent ()
self.emit ('}}\n')
self.dedent ()
self.emit ('}}\n')
if node.finalbody:
self.emit ('finally {{')
self.emitBody (node.finalbody)
self.emit ('}}\n')
self.skipSemiNew = True
def visit_Tuple (self, node):
self.emit ('tuple (')
self.visit_List (node)
self.emit (')')
def visit_UnaryOp (self, node):
self.emit (self.operators [type (node.op)][0])
self.visitSubExpr (node, node.operand)
def visit_While (self, node):
if node.orelse:
self.emit ('var {} = false;\n', self.nextTemp ('break'))
self.emit ('while (')
self.visit (node.test)
self.emit (') {{\n')
self.indent ()
self.emitBody (node.body)
self.dedent ()
self.emit ('}}\n')
if node.orelse:
self.emit ('if (!{}) {{\n', self.getTemp ('break'))
self.prevTemp ('break')
self.indent ()
self.emitBody (node.orelse)
self.dedent ()
self.emit ('}}\n')
self.skipSemiNew = True
def visit_With (self, node):
for withitem in node.items:
self.visit (withitem.optional_vars)
self.emit (' = ')
self.visit (withitem.context_expr)
self.emit (';\n')
self.emitBody (node.body)
for withitem in node.items:
self.visit (withitem.optional_vars)
self.emit ('.close ()')
|
[
"info@qquick.org"
] |
info@qquick.org
|
2251d36de384f06402ed70c0aaa4d5c9af52190e
|
7916316f52c3fcad0f32856d24398cf7bdaab691
|
/mdensenet/densenet_denoise.py
|
6bab22510bd9a734d0865e19b93988eb0f457b2f
|
[] |
no_license
|
citymap/Denoise_ML
|
ccd6e118d2c374af4b9d2984cfeeafc41584e7c7
|
d8edb283b99c41cbdd7909a52ea2ca06eae81269
|
refs/heads/master
| 2020-08-11T18:53:17.967862
| 2019-03-26T09:50:21
| 2019-03-26T09:50:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 8,231
|
py
|
from keras.layers import Input, Conv2D, BatchNormalization, UpSampling2D, Concatenate, MaxPooling2D
from keras.models import Model
import numpy as np
import os
import console
import conversion
from data import Data
import argparse
import random
import string
# Network parameters
class Densenet_denoise:
def __init__(self):
# Input
noisy = Input(shape=(None, None, 1), name='input')
# dense block 1
convA = Conv2D(32, 3, activation='relu', padding='same')(noisy) # 128*128*64
convA = Concatenate()([noisy, convA]) # 128*128*65
convA = Conv2D(32, 3, activation='relu', padding='same')(convA) # 128*128*64
convA = BatchNormalization()(convA)
# down sample 1
ds1 = Conv2D(32, 4, strides=2, activation='relu', padding='same', use_bias=False)(convA) # 64*64*64
# dense block 2
convB = Conv2D(64, 3, activation='relu', padding='same')(ds1) # 64*64*64
convB = Concatenate()([ds1, convB]) # 128*128*128
convB = Conv2D(64, 3, activation='relu', padding='same', use_bias=False)(convB) # 64*64*64
convB = BatchNormalization()(convB)
# down sample 2
ds2 = Conv2D(64, 4, strides=2, activation='relu', padding='same', use_bias=False)(convB) # 32*32*64
# dense block 3
convC = Conv2D(128, 3, activation='relu', padding='same')(ds2) # 32*32*128
convC = Concatenate()([ds2, convC]) # 32*32*192
convC = Conv2D(128, 3, activation='relu', padding='same')(convC) # 32*32*128
convC = BatchNormalization()(convC)
# up sample 1
up1 = UpSampling2D((2, 2))(convC) # 64*64*128
# dense block 4
conv = Concatenate()([up1, convB]) # 64*64*192
convD = Conv2D(64, 3, activation='relu', padding='same')(conv) # 64*64*64
convD = Concatenate()([conv, convD]) # 64*64*256
convD = Conv2D(64, 3, activation='relu', padding='same')(convD) # 64*64*64
convD = BatchNormalization()(convD)
# up sample 2
up2 = UpSampling2D((2, 2))(convD) # 128*128*64
# dense block 5
conv = Concatenate()([up2, convA]) # 128*128*128
convE = Conv2D(32, 3, activation='relu', padding='same')(conv) # 128*128*64
convE = Concatenate()([conv, convE]) # 128*128*192
convE = Conv2D(32, 3, activation='relu', padding='same')(convE) # 128*128*64
convE = BatchNormalization()(convE)
# fully connection
clean = Conv2D(32, 3, activation='relu', padding='same')(convE)
clean = Conv2D(32, 3, activation='relu', padding='same')(clean) # 128*128*32
clean = Conv2D(1, 3, activation='relu', padding='same')(clean) # 128*128*1
dense_net = Model(inputs=noisy, outputs=clean)
# dense_net.summary()
print("Model has", dense_net.count_params(), "params")
dense_net.compile(loss='mean_squared_error', optimizer='rmsprop')
self.model = dense_net
# need to know so that we can avoid rounding errors with spectrogram
# this should represent how much the input gets downscaled
# in the middle of the network
self.peakDownscaleFactor = 4
def train(self, data, epochs, batch=8):
xTrain, yTrain = data.train()
xValid, yValid = data.valid()
while epochs > 0:
console.log("Training for", epochs, "epochs on", len(xTrain), "examples")
self.model.fit(xTrain, yTrain, batch_size=batch, epochs=epochs, validation_data=(xValid, yValid))
console.notify(str(epochs) + " Epochs Complete!", "Training on", data.inPath, "with size", batch)
while True:
try:
epochs = int(input("How many more epochs should we train for? "))
break
except ValueError:
console.warn("Oops, number parse failed. Try again, I guess?")
if epochs > 0:
save = input("Should we save intermediate weights [y/n]? ")
if not save.lower().startswith("n"):
weightPath = ''.join(random.choice(string.digits) for _ in range(16)) + ".h5"
console.log("Saving intermediate weights to", weightPath)
self.saveWeights(weightPath)
def saveWeights(self, path):
self.model.save_weights(path, overwrite=True)
def loadWeights(self, path):
self.model.load_weights(path)
def isolateVocals(self, path, fftWindowSize, phaseIterations=10):
console.log("Attempting to isolate vocals from", path)
audio, sampleRate = conversion.loadAudioFile(path, sr=22100)
spectrogram, phase = conversion.audioFileToSpectrogram(audio, fftWindowSize=fftWindowSize)
console.log("Retrieved spectrogram; processing...")
expandedSpectrogram = conversion.expandToGrid(spectrogram, self.peakDownscaleFactor)
expandedSpectrogramWithBatchAndChannels = expandedSpectrogram[np.newaxis, :, :, np.newaxis]
print(expandedSpectrogramWithBatchAndChannels.shape)
# 预测
predictedSpectrogramWithBatchAndChannels = self.model.predict(expandedSpectrogramWithBatchAndChannels)
predictedSpectrogram = predictedSpectrogramWithBatchAndChannels[0, :, :, 0] # o /// o
newSpectrogram = predictedSpectrogram[:spectrogram.shape[0], :spectrogram.shape[1]]
console.log("Processed spectrogram; reconverting to audio")
newAudio = conversion.spectrogramToAudioFile(newSpectrogram, sampleRate, fftWindowSize=fftWindowSize, phaseIterations=phaseIterations)
# file information
pathParts = os.path.split(path)
fileNameParts = os.path.splitext(pathParts[1])
outputFileNameBase = os.path.join(pathParts[0], fileNameParts[0] + "_densenet")
console.log("Converted to audio; writing to", outputFileNameBase)
conversion.saveAudioFile(newAudio, outputFileNameBase + ".wav", sampleRate)
# conversion.saveSpectrogram(newSpectrogram, outputFileNameBase + ".png")
# conversion.saveSpectrogram(spectrogram, os.path.join(pathParts[0], fileNameParts[0]) + ".png")
console.log("Vocal isolation complete")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Acapella extraction with a convolutional neural network")
parser.add_argument("--fft", default=1536, type=int, help="Size of FFT windows")
parser.add_argument("--data_path", default='train_data', type=str, help="Path containing training data")
parser.add_argument("--split", default=0.9, type=float, help="Proportion of the data to train on")
parser.add_argument("--epochs", default=1, type=int, help="Number of epochs to train.")
parser.add_argument("--weights", default='denoise_v1_3.h5', type=str, help="h5 file to read/write weights to")
parser.add_argument("--batch", default=50, type=int, help="Batch size for training")
parser.add_argument("--phase", default=10, type=int, help="Phase iterations for reconstruction")
parser.add_argument("--load", default=False, action='store_true', help="Load previous weights file before starting")
parser.add_argument("files", nargs="*", default=[])
args = parser.parse_args()
densenet_denoise = Densenet_denoise()
print(len(args.files))
if len(args.files) == 0 and args.data_path:
console.log("No files provided; attempting to train on " + args.data_path + "...")
if args.load:
console.h1("Loading Weights")
densenet_denoise.loadWeights(args.weights)
console.h1("Loading Data")
data = Data(args.data_path, args.fft, args.split)
console.h1("Training Model")
densenet_denoise.train(data, args.epochs, args.batch)
densenet_denoise.saveWeights(args.weights)
elif len(args.files) > 0:
console.log("Weights provided; performing inference on " + str(args.files) + "...")
console.h1("Loading weights")
densenet_denoise.loadWeights(args.weights)
for f in args.files:
densenet_denoise.isolateVocals(f, args.fft, args.phase)
else:
console.error("Please provide data to train on (--data) or files to infer on")
|
[
"chenxiaoyan@188w.com"
] |
chenxiaoyan@188w.com
|
5f60e7a213b77548b6a3686ce9e9fb1dedd4b481
|
a1e71d563dfeec4c8460386e8cb1badf00208bf1
|
/mysite/blog/migrations/0006_contact.py
|
556677975e1f45e902ddd90c8f49b1c22f82c2f1
|
[] |
no_license
|
alazarale/site
|
dcd65ae30d5a5bf4d6a45651f590c46ca467d387
|
fce619507bacdaee11480c346cee1e18b851036f
|
refs/heads/master
| 2020-04-02T07:53:48.989113
| 2016-06-30T12:12:55
| 2016-06-30T12:12:55
| 62,307,694
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 846
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0005_comment'),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
('name', models.CharField(max_length=120)),
('email', models.EmailField(blank=True, max_length=254)),
('subject', models.CharField(max_length=200)),
('message', models.TextField()),
('sent', models.DateTimeField(auto_now_add=True)),
],
options={
'ordering': ['-sent'],
},
),
]
|
[
"noreply@github.com"
] |
alazarale.noreply@github.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.