blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2
values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220
values | src_encoding stringclasses 30
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 2 10.3M | extension stringclasses 257
values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
00c0d530a5b0f65588d44f4fdf36cb651f4784c0 | c6a777a66d2959dfb51744e43727c07f5e256145 | /src/Crawler/Cookie/CrawlerCookie.py | 2cfd5ad2da6cec2d3d57f4e2a28c047351436fdf | [] | no_license | imarklei90/MyPythonProject | 46ef01ff0b05cf92085580ea551d95e8a6e53b0b | 0854f6b20f3432b780ef58906f6f89e499d48f50 | refs/heads/master | 2021-06-25T22:54:26.188844 | 2020-09-08T01:37:01 | 2020-09-08T01:37:01 | 90,716,687 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 426 | py | # -*- encoding:utf-8 -*-
import urllib2
import cookielib
'''
保存Cookie到变量
'''
#声明一个CookieJar对象实例来保存Cookie
cookie = cookielib.CookieJar()
#创建Cookie处理器
handler = urllib2.HTTPCookieProcessor(cookie)
#构建Opener
opener = urllib2.build_opener(handler)
response = opener.open("http://www.baidu.com")
for item in cookie:
print "Name= " + item.name
print "Value= " + item.value | [
"imarklei90@126.com"
] | imarklei90@126.com |
b6ed62cc68aadcab0458c7b448ea6bc26e94984c | a420a6c6af1afa44bf988ebaebc5b3aafa6cee9d | /items/admin.py | 97341721b4584aa2c74a4d06e294e24ff9e54eb8 | [] | no_license | fon-harry/crafter_django | c4365f1975d9aed6fd0d7f618e000cba399a0354 | f4ee046f99031221ceb958313ee80b4b48049d86 | refs/heads/master | 2021-06-25T09:11:29.177645 | 2017-09-12T04:50:38 | 2017-09-12T04:50:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 241 | py | from django.contrib import admin
from items.models import Item, ItemParam
class ParamInline(admin.TabularInline):
model = ItemParam
class ItemAdmin(admin.ModelAdmin):
inlines = [ParamInline]
admin.site.register(Item, ItemAdmin)
| [
"fon.harry@gmail.com"
] | fon.harry@gmail.com |
1118b60ecc4364aa073ecbde1360f49df0809525 | fef8fb0ee587e682b6ede434e6744526ce1e9c87 | /deepqlearning/plottrainresults.py | 2f8a31617f1483e39d405c8b70a6652c364aec3a | [] | no_license | MioNok/q-stock-exploring | a4cbe46cc5e45090fee3c482260bb3698813f4ea | 0de37623f093d95ba586f21f2753f8b73a6c9ef6 | refs/heads/master | 2022-12-11T00:39:31.453693 | 2020-03-23T12:10:59 | 2020-03-23T12:10:59 | 220,065,743 | 0 | 0 | null | 2022-12-08T03:23:38 | 2019-11-06T18:41:53 | Python | UTF-8 | Python | false | false | 1,588 | py | import matplotlib.pyplot as plt
import glob
import os
import pandas as pd
import numpy as np
#Latest log file
list_of_files = glob.glob('logdata/*')
latest_file = str(max(list_of_files, key=os.path.getctime))
#latest_file = "logdata/LogdataTest_256x256.20c_RewSha-0.5_test_serie.csv"
#Plots a bar graph showing the distribution of percantage gains per stock during the training
dataraw = pd.read_csv(latest_file)
tickers = pd.read_csv("data/SP500-100tickers.txt", header = None).transpose()[0].tolist()[:dataraw.shape[0]-1]
#Taking the last 10% of data, dont want to include training data where epsilon has been high.
trainlen = len(dataraw) - (len(dataraw) * 0.1)
#If the data you want to plot happens to be less than 1000 rows, ignore this an use all the data
if len(dataraw) < 2500:
trainlen = 0
datasub = dataraw.iloc[int(trainlen):,]
datasubgroup = datasub.groupby("Stocknr").mean()
#Debug
print("Latest file:",latest_file)
print(datasubgroup.shape)
print(len(tickers))
datasubgroup["tickers"] = tickers#.map(str)
datasubgroup = datasubgroup.sort_values("reward_pcr")
symbols = datasubgroup.tickers
print("Sum current port",sum(datasubgroup.current_port_sum))
print("Sum benchmark port", sum(datasubgroup.benchmark_port_sum))
print("Result", sum(datasubgroup.current_port_sum) - sum(datasubgroup.benchmark_port_sum))
#Y axis the mean percentage gain per stock, X axis the tickers
plt.figure(figsize=(20,5))
#plt.bar(symbols,datasubgroup.reward_pcr)
plt.bar(symbols,datasubgroup.current_port_sum - datasubgroup.benchmark_port_sum)
plt.xticks(rotation=90)
plt.show()
| [
"nokelainen.m@gmail.com"
] | nokelainen.m@gmail.com |
ea2f5c0278cf81ce6a961011b597677d80605caa | c6588d0e7d361dba019743cacfde83f65fbf26b8 | /x12/5030/240005030.py | e169346e38e95704c267b8fa6401b8abee37c150 | [] | no_license | djfurman/bots-grammars | 64d3b3a3cd3bd95d625a82204c3d89db6934947c | a88a02355aa4ca900a7b527b16a1b0f78fbc220c | refs/heads/master | 2021-01-12T06:59:53.488468 | 2016-12-19T18:37:57 | 2016-12-19T18:37:57 | 76,887,027 | 0 | 0 | null | 2016-12-19T18:30:43 | 2016-12-19T18:30:43 | null | UTF-8 | Python | false | false | 1,585 | py | from bots.botsconfig import *
from records005030 import recorddefs
syntax = {
'version' : '00403', #version of ISA to send
'functionalgroup' : 'MZ',
}
structure = [
{ID: 'ST', MIN: 1, MAX: 1, LEVEL: [
{ID: 'BGN', MIN: 1, MAX: 1},
{ID: 'N1', MIN: 0, MAX: 99999, LEVEL: [
{ID: 'N2', MIN: 0, MAX: 2},
{ID: 'N3', MIN: 0, MAX: 2},
{ID: 'N4', MIN: 0, MAX: 1},
]},
{ID: 'LX', MIN: 1, MAX: 99999, LEVEL: [
{ID: 'N1', MIN: 0, MAX: 1, LEVEL: [
{ID: 'N2', MIN: 0, MAX: 2},
{ID: 'N3', MIN: 0, MAX: 2},
{ID: 'N4', MIN: 0, MAX: 1},
{ID: 'NM1', MIN: 0, MAX: 1},
{ID: 'NTE', MIN: 0, MAX: 1},
]},
{ID: 'EFI', MIN: 0, MAX: 1, LEVEL: [
{ID: 'BIN', MIN: 1, MAX: 1},
]},
{ID: 'L11', MIN: 1, MAX: 99999, LEVEL: [
{ID: 'MS2', MIN: 0, MAX: 99999},
{ID: 'LS', MIN: 0, MAX: 1, LEVEL: [
{ID: 'MAN', MIN: 1, MAX: 99999, LEVEL: [
{ID: 'L11', MIN: 0, MAX: 99999},
{ID: 'AT7', MIN: 0, MAX: 99999},
{ID: 'CD3', MIN: 0, MAX: 99999},
{ID: 'NM1', MIN: 0, MAX: 1},
{ID: 'Q7', MIN: 0, MAX: 99999},
]},
{ID: 'LE', MIN: 1, MAX: 1},
]},
{ID: 'EFI', MIN: 0, MAX: 1, LEVEL: [
{ID: 'BIN', MIN: 1, MAX: 1},
]},
]},
]},
{ID: 'SE', MIN: 1, MAX: 1},
]}
]
| [
"jason.capriotti@gmail.com"
] | jason.capriotti@gmail.com |
52481a8e4926b59a22f1e76782153122afa24d64 | fcdc5d3df5e947fc89ddb6ecb4c0cf73677a5213 | /blatt_2/MadGraph5_v1_3_20/tests/test_manager.py | eff53914e2bf5cdbfbc2233a9e2f1604ab320cc8 | [] | no_license | harrypuuter/tp1 | 382fb9efe503c69f0249c46a7870ede088d8291d | e576e483dc77f6dcd477c73018ca2ea3955cd0c7 | refs/heads/master | 2021-01-10T11:38:16.467278 | 2016-01-27T16:28:46 | 2016-01-27T16:28:46 | 45,135,053 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,530 | py | #!/usr/bin/env python
################################################################################
#
# Copyright (c) 2009 The MadGraph Development team and Contributors
#
# This file is a part of the MadGraph 5 project, an application which
# automatically generates Feynman diagrams and matrix elements for arbitrary
# high-energy processes in the Standard Model and beyond.
#
# It is subject to the MadGraph license which should accompany this
# distribution.
#
# For more information, please visit: http://madgraph.phys.ucl.ac.be
#
################################################################################
""" Manager for running the test library
This library offer a simple way to launch test.
To run a test/class of test/test file/module of test/...
you just have to launch
test_manager.run(NAME)
or
test_manager.run(LIST_OF_NAME)
the NAME can contain regular expression (in python re standard format)
"""
import sys
if not sys.version_info[0] == 2 or sys.version_info[1] < 6:
sys.exit('MadGraph 5 works only with python 2.6 or later (but not python 3.X).\n\
Please upgrate your version of python.')
import inspect
import logging
import logging.config
import optparse
import os
import re
import unittest
#Add the ROOT dir to the current PYTHONPATH
root_path = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]
sys.path.insert(0, root_path)
# Only for profiling with -m cProfile!
#root_path = os.path.split(os.path.dirname(os.path.realpath(sys.argv[0])))[0]
#sys.path.append(root_path)
from madgraph import MG4DIR
#position of MG_ME
MGME_dir = MG4DIR
#===============================================================================
# run
#===============================================================================
def run(expression='', re_opt=0, package='./tests/unit_tests', verbosity=1):
""" running the test associated to expression. By default, this launch all
test inherited from TestCase. Expression can be the name of directory,
module, class, function or event standard regular expression (in re format)
"""
#init a test suite
testsuite = unittest.TestSuite()
collect = unittest.TestLoader()
for test_fct in TestFinder(package=package, expression=expression, \
re_opt=re_opt):
data = collect.loadTestsFromName(test_fct)
testsuite.addTest(data)
return unittest.TextTestRunner(verbosity=verbosity).run(testsuite)
#===============================================================================
# TestFinder
#===============================================================================
class TestFinder(list):
""" Class introspecting the test module to find the available test.
The routine collect_dir looks in all module/file to find the different
functions in different test class. This produce a list, on which external
routines can loop on.
In order to authorize definition and loop on this object on the same time,
i.e: for test in TestFinder([opt])-. At each time a loop is started,
we check if a collect_dir ran before, and run it if necessary.
"""
search_class = unittest.TestCase
class TestFinderError(Exception):
"""Error associated to the TestFinder class."""
pass
def __init__(self, package='tests/', expression='', re_opt=0):
""" initialize global variable for the test """
list.__init__(self)
self.package = package
self.rule = []
if self.package[-1] != '/':
self.package += '/'
self.restrict_to(expression, re_opt)
self.launch_pos = ''
def _check_if_obj_build(self):
""" Check if a collect is already done
Uses to have smart __iter__ and __contain__ functions
"""
if len(self) == 0:
self.collect_dir(self.package, checking=True)
def __iter__(self):
""" Check that a collect was performed (do it if needed) """
self._check_if_obj_build()
return list.__iter__(self)
def __contains__(self, value):
""" Check that a collect was performed (do it if needed) """
self._check_if_obj_build()
return list.__contains__(self, value)
def collect_dir(self, directory, checking=True):
""" Find the file and the subpackage in this package """
#ensures that we are at root position
move = False
if self.launch_pos == '':
move = True
self.go_to_root()
for name in os.listdir(os.path.join(root_path,directory)):
local_check = checking
status = self.status_file(os.path.join(root_path, directory,name))
#directory + '/' + name)
if status is None:
continue
if checking:
if self.check_valid(directory + '/' + name):
local_check = False #since now perform all the test
if status == 'file':
self.collect_file(directory + '/' + name, local_check)
elif status == "module":
self.collect_dir(directory + '/' + name, local_check)
if move:
self.go_to_initpos()
def collect_file(self, filename, checking=True):
""" Find the different class instance derivated of TestCase """
pyname = self.passin_pyformat(filename)
__import__(pyname)
obj = sys.modules[pyname]
#look at class
for name in dir(obj):
class_ = getattr(obj, name)
if inspect.isclass(class_) and \
issubclass(class_, unittest.TestCase):
if checking:
if self.check_valid(name):
check_inside = False
else:
check_inside = True
else:
check_inside = False
self.collect_function(class_, checking=check_inside, \
base=pyname)
def collect_function(self, class_, checking=True, base=''):
"""
Find the different test function in this class
test functions should start with test
"""
if not inspect.isclass(class_):
raise self.TestFinderError, 'wrong input class_'
if not issubclass(class_, unittest.TestCase):
raise self.TestFinderError, 'wrong input class_'
#devellop the name
if base:
base += '.' + class_.__name__
else:
base = class_.__name__
candidate = [base + '.' + name for name in dir(class_) if \
name.startswith('test')\
and inspect.ismethod(eval('class_.' + name))]
if not checking:
self += candidate
else:
self += [name for name in candidate if self.check_valid(name)]
def restrict_to(self, expression, re_opt=0):
"""
store in global the expression to fill in order to be a valid test
"""
if isinstance(expression, list):
pass
elif isinstance(expression, basestring):
if expression in '':
expression = ['.*'] #made an re authorizing all regular name
else:
expression = [expression]
else:
raise self.TestFinderError, 'obj should be list or string'
self.rule = []
for expr in expression:
#fix the beginning/end of the regular expression
if not expr.startswith('^'):
expr = '^' + expr
if not expr.endswith('$'):
expr = expr + '$'
self.rule.append(re.compile(expr, re_opt))
def check_valid(self, name):
""" check if the name correspond to the rule """
if not isinstance(name, basestring):
raise self.TestFinderError, 'check valid take a string argument'
for specific_format in self.format_possibility(name):
for expr in self.rule:
if expr.search(specific_format):
return True
return False
@staticmethod
def status_file(name):
""" check if a name is a module/a python file and return the status """
if os.path.isfile(os.path.join(root_path, name)):
if name.endswith('.py') and '__init__' not in name:
return 'file'
elif os.path.isdir(os.path.join(root_path, name)):
if os.path.isfile(os.path.join(root_path, name , '__init__.py')):
return 'module'
@classmethod
def passin_pyformat(cls, name):
""" transform a relative position in a python import format """
if not isinstance(name, basestring):
raise cls.TestFinderError, 'collect_file takes a file position'
name = name.replace('//', '/') #sanity
#deal with begin/end
if name.startswith('./'):
name = name[2:]
if not name.endswith('.py'):
raise cls.TestFinderError, 'Python files should have .py extension'
else:
name = name[:-3]
if name.startswith('/'):
raise cls.TestFinderError, 'path must be relative'
if '..' in name:
raise cls.TestFinderError, 'relative position with \'..\' is' + \
' not supported for the moment'
#replace '/' by points -> Python format
name = name.replace('/', '.')
#position
return name
def format_possibility(self, name):
""" return the different string derivates from name in order to
scan all the different format authorizes for a restrict_to
format authorizes:
1) full file position
2) name of the file (with extension)
3) full file position whithour extension
4) name of the file (whithout extension)
5) name of the file (but suppose name in python format)
6) if name is a python file, try with a './' and with package pos
"""
def add_to_possibility(possibility, val):
""" add if not exist """
if val not in possibility:
possibility.append(val)
#end local def
#sanity
if name.startswith('./'):
name = name[2:]
name = name.replace('//', '/')
# init with solution #
out = [name]
# add solution 2
new_pos = name.split('/')[-1]
add_to_possibility(out, new_pos)
#remove extension and add solution3 and 6
if name.endswith('.py'):
add_to_possibility(out, './' + name)
add_to_possibility(out, self.package + name)
name = name[:-3]
add_to_possibility(out, name)
#add solution 4
new_pos = name.split('/')[-1]
add_to_possibility(out, new_pos)
#add solution 5
new_pos = name.split('.')[-1]
add_to_possibility(out, new_pos)
return out
def go_to_root(self):
"""
go to the root directory of the module.
This ensures that the script works correctly whatever the position
where is launched
"""
#self.launch_pos = os.path.realpath(os.getcwd())
#self.root_path = root_path
#os.chdir(root_path)
def go_to_initpos(self):
"""
go to the root directory of the module.
This ensures that the script works correctly whatever the position
where is launched
"""
#os.chdir(self.launch_pos)
#self.launch_pos = ''
if __name__ == "__main__":
usage = "usage: %prog [expression1]... [expressionN] [options] "
parser = optparse.OptionParser(usage=usage)
parser.add_option("-v", "--verbose", default=1,
help="defined the verbosity level [%default]")
parser.add_option("-r", "--reopt", type="int", default=0,
help="regular expression tag [%default]")
parser.add_option("-p", "--path", default='tests/unit_tests',
help="position to start the search (from root) [%default]")
parser.add_option("-l", "--logging", default='CRITICAL',
help="logging level (DEBUG|INFO|WARNING|ERROR|CRITICAL) [%default]")
(options, args) = parser.parse_args()
if len(args) == 0:
args = ''
if options.path == 'U':
options.path = 'tests/unit_tests'
elif options.path == 'P':
options.path = 'tests/parallel_tests'
elif options.path == 'A':
options.path = 'tests/acceptance_tests'
try:
logging.config.fileConfig(os.path.join(root_path,'tests','.mg5_logging.conf'))
logging.root.setLevel(eval('logging.' + options.logging))
logging.getLogger('madgraph').setLevel(eval('logging.' + options.logging))
logging.getLogger('cmdprint').setLevel(eval('logging.' + options.logging))
logging.getLogger('tutorial').setLevel('ERROR')
except:
pass
#logging.basicConfig(level=vars(logging)[options.logging])
run(args, re_opt=options.reopt, verbosity=options.verbose, \
package=options.path)
#some example
# run('iolibs')
# run('test_test_manager.py')
# run('./tests/unit_tests/bin/test_test_manager.py')
# run('IOLibsMiscTest')
# run('TestTestFinder')
# run('test_check_valid_on_file')
# run('test_collect_dir.*') # '.*' stands for all possible char (re format)
| [
"brommer.sebastian@gmail.com"
] | brommer.sebastian@gmail.com |
ea04b23575df228493aa423e8c7d0d0551fbf78f | c56782d17af21274a4b7a8a44f4e5382abbd2e2d | /homeassistant/components/nest/climate_sdm.py | 6ee988b714f7ef5a6e6d28a552c6aee8b2c67010 | [
"Apache-2.0"
] | permissive | atetevoortwis/home-assistant | bc6ecc778862739dea0d34465c23b49b48741239 | 046d7d2a239e0eab370ff9d11b1885ee9c69dffe | refs/heads/dev | 2023-02-22T17:58:43.345572 | 2022-06-18T17:58:10 | 2022-06-18T17:58:10 | 160,043,546 | 0 | 0 | Apache-2.0 | 2023-02-22T06:22:31 | 2018-12-02T12:10:43 | Python | UTF-8 | Python | false | false | 12,822 | py | """Support for Google Nest SDM climate devices."""
from __future__ import annotations
from typing import Any, cast
from google_nest_sdm.device import Device
from google_nest_sdm.device_manager import DeviceManager
from google_nest_sdm.device_traits import FanTrait, TemperatureTrait
from google_nest_sdm.exceptions import ApiException
from google_nest_sdm.thermostat_traits import (
ThermostatEcoTrait,
ThermostatHeatCoolTrait,
ThermostatHvacTrait,
ThermostatModeTrait,
ThermostatTemperatureSetpointTrait,
)
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
ATTR_HVAC_MODE,
ATTR_TARGET_TEMP_HIGH,
ATTR_TARGET_TEMP_LOW,
FAN_OFF,
FAN_ON,
PRESET_ECO,
PRESET_NONE,
ClimateEntityFeature,
HVACAction,
HVACMode,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import DATA_DEVICE_MANAGER, DOMAIN
from .device_info import NestDeviceInfo
# Mapping for sdm.devices.traits.ThermostatMode mode field
THERMOSTAT_MODE_MAP: dict[str, HVACMode] = {
"OFF": HVACMode.OFF,
"HEAT": HVACMode.HEAT,
"COOL": HVACMode.COOL,
"HEATCOOL": HVACMode.HEAT_COOL,
}
THERMOSTAT_INV_MODE_MAP = {v: k for k, v in THERMOSTAT_MODE_MAP.items()}
# Mode for sdm.devices.traits.ThermostatEco
THERMOSTAT_ECO_MODE = "MANUAL_ECO"
# Mapping for sdm.devices.traits.ThermostatHvac status field
THERMOSTAT_HVAC_STATUS_MAP = {
"OFF": HVACAction.OFF,
"HEATING": HVACAction.HEATING,
"COOLING": HVACAction.COOLING,
}
THERMOSTAT_RANGE_MODES = [HVACMode.HEAT_COOL, HVACMode.AUTO]
PRESET_MODE_MAP = {
"MANUAL_ECO": PRESET_ECO,
"OFF": PRESET_NONE,
}
PRESET_INV_MODE_MAP = {v: k for k, v in PRESET_MODE_MAP.items()}
FAN_MODE_MAP = {
"ON": FAN_ON,
"OFF": FAN_OFF,
}
FAN_INV_MODE_MAP = {v: k for k, v in FAN_MODE_MAP.items()}
FAN_INV_MODES = list(FAN_INV_MODE_MAP)
MAX_FAN_DURATION = 43200 # 15 hours is the max in the SDM API
MIN_TEMP = 10
MAX_TEMP = 32
async def async_setup_sdm_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the client entities."""
device_manager: DeviceManager = hass.data[DOMAIN][DATA_DEVICE_MANAGER]
entities = []
for device in device_manager.devices.values():
if ThermostatHvacTrait.NAME in device.traits:
entities.append(ThermostatEntity(device))
async_add_entities(entities)
class ThermostatEntity(ClimateEntity):
"""A nest thermostat climate entity."""
_attr_min_temp = MIN_TEMP
_attr_max_temp = MAX_TEMP
def __init__(self, device: Device) -> None:
"""Initialize ThermostatEntity."""
self._device = device
self._device_info = NestDeviceInfo(device)
self._attr_supported_features = 0
@property
def should_poll(self) -> bool:
"""Disable polling since entities have state pushed via pubsub."""
return False
@property
def unique_id(self) -> str | None:
"""Return a unique ID."""
# The API "name" field is a unique device identifier.
return self._device.name
@property
def name(self) -> str | None:
"""Return the name of the entity."""
return self._device_info.device_name
@property
def device_info(self) -> DeviceInfo:
"""Return device specific attributes."""
return self._device_info.device_info
async def async_added_to_hass(self) -> None:
"""Run when entity is added to register update signal handler."""
self._attr_supported_features = self._get_supported_features()
self.async_on_remove(
self._device.add_update_listener(self.async_write_ha_state)
)
@property
def temperature_unit(self) -> str:
"""Return the unit of temperature measurement for the system."""
return TEMP_CELSIUS
@property
def current_temperature(self) -> float | None:
"""Return the current temperature."""
if TemperatureTrait.NAME not in self._device.traits:
return None
trait: TemperatureTrait = self._device.traits[TemperatureTrait.NAME]
return trait.ambient_temperature_celsius
@property
def target_temperature(self) -> float | None:
"""Return the temperature currently set to be reached."""
if not (trait := self._target_temperature_trait):
return None
if self.hvac_mode == HVACMode.HEAT:
return trait.heat_celsius
if self.hvac_mode == HVACMode.COOL:
return trait.cool_celsius
return None
@property
def target_temperature_high(self) -> float | None:
"""Return the upper bound target temperature."""
if self.hvac_mode != HVACMode.HEAT_COOL:
return None
if not (trait := self._target_temperature_trait):
return None
return trait.cool_celsius
@property
def target_temperature_low(self) -> float | None:
"""Return the lower bound target temperature."""
if self.hvac_mode != HVACMode.HEAT_COOL:
return None
if not (trait := self._target_temperature_trait):
return None
return trait.heat_celsius
@property
def _target_temperature_trait(
self,
) -> ThermostatHeatCoolTrait | None:
"""Return the correct trait with a target temp depending on mode."""
if (
self.preset_mode == PRESET_ECO
and ThermostatEcoTrait.NAME in self._device.traits
):
return cast(
ThermostatEcoTrait, self._device.traits[ThermostatEcoTrait.NAME]
)
if ThermostatTemperatureSetpointTrait.NAME in self._device.traits:
return cast(
ThermostatTemperatureSetpointTrait,
self._device.traits[ThermostatTemperatureSetpointTrait.NAME],
)
return None
@property
def hvac_mode(self) -> HVACMode:
"""Return the current operation (e.g. heat, cool, idle)."""
hvac_mode = HVACMode.OFF
if ThermostatModeTrait.NAME in self._device.traits:
trait = self._device.traits[ThermostatModeTrait.NAME]
if trait.mode in THERMOSTAT_MODE_MAP:
hvac_mode = THERMOSTAT_MODE_MAP[trait.mode]
return hvac_mode
@property
def hvac_modes(self) -> list[HVACMode]:
"""List of available operation modes."""
supported_modes = []
for mode in self._get_device_hvac_modes:
if mode in THERMOSTAT_MODE_MAP:
supported_modes.append(THERMOSTAT_MODE_MAP[mode])
return supported_modes
@property
def _get_device_hvac_modes(self) -> set[str]:
"""Return the set of SDM API hvac modes supported by the device."""
modes = []
if ThermostatModeTrait.NAME in self._device.traits:
trait = self._device.traits[ThermostatModeTrait.NAME]
modes.extend(trait.available_modes)
return set(modes)
@property
def hvac_action(self) -> HVACAction | None:
"""Return the current HVAC action (heating, cooling)."""
trait = self._device.traits[ThermostatHvacTrait.NAME]
if trait.status == "OFF" and self.hvac_mode != HVACMode.OFF:
return HVACAction.IDLE
return THERMOSTAT_HVAC_STATUS_MAP.get(trait.status)
@property
def preset_mode(self) -> str:
"""Return the current active preset."""
if ThermostatEcoTrait.NAME in self._device.traits:
trait = self._device.traits[ThermostatEcoTrait.NAME]
return PRESET_MODE_MAP.get(trait.mode, PRESET_NONE)
return PRESET_NONE
@property
def preset_modes(self) -> list[str]:
"""Return the available presets."""
modes = []
if ThermostatEcoTrait.NAME in self._device.traits:
trait = self._device.traits[ThermostatEcoTrait.NAME]
for mode in trait.available_modes:
if mode in PRESET_MODE_MAP:
modes.append(PRESET_MODE_MAP[mode])
return modes
@property
def fan_mode(self) -> str:
"""Return the current fan mode."""
if (
self.supported_features & ClimateEntityFeature.FAN_MODE
and FanTrait.NAME in self._device.traits
):
trait = self._device.traits[FanTrait.NAME]
return FAN_MODE_MAP.get(trait.timer_mode, FAN_OFF)
return FAN_OFF
@property
def fan_modes(self) -> list[str]:
"""Return the list of available fan modes."""
if (
self.supported_features & ClimateEntityFeature.FAN_MODE
and FanTrait.NAME in self._device.traits
):
return FAN_INV_MODES
return []
def _get_supported_features(self) -> int:
"""Compute the bitmap of supported features from the current state."""
features = 0
if HVACMode.HEAT_COOL in self.hvac_modes:
features |= ClimateEntityFeature.TARGET_TEMPERATURE_RANGE
if HVACMode.HEAT in self.hvac_modes or HVACMode.COOL in self.hvac_modes:
features |= ClimateEntityFeature.TARGET_TEMPERATURE
if ThermostatEcoTrait.NAME in self._device.traits:
features |= ClimateEntityFeature.PRESET_MODE
if FanTrait.NAME in self._device.traits:
# Fan trait may be present without actually support fan mode
fan_trait = self._device.traits[FanTrait.NAME]
if fan_trait.timer_mode is not None:
features |= ClimateEntityFeature.FAN_MODE
return features
async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
"""Set new target hvac mode."""
if hvac_mode not in self.hvac_modes:
raise ValueError(f"Unsupported hvac_mode '{hvac_mode}'")
api_mode = THERMOSTAT_INV_MODE_MAP[hvac_mode]
trait = self._device.traits[ThermostatModeTrait.NAME]
try:
await trait.set_mode(api_mode)
except ApiException as err:
raise HomeAssistantError(f"Error setting HVAC mode: {err}") from err
async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set new target temperature."""
hvac_mode = self.hvac_mode
if kwargs.get(ATTR_HVAC_MODE) is not None:
hvac_mode = kwargs[ATTR_HVAC_MODE]
await self.async_set_hvac_mode(hvac_mode)
low_temp = kwargs.get(ATTR_TARGET_TEMP_LOW)
high_temp = kwargs.get(ATTR_TARGET_TEMP_HIGH)
temp = kwargs.get(ATTR_TEMPERATURE)
if ThermostatTemperatureSetpointTrait.NAME not in self._device.traits:
return
trait = self._device.traits[ThermostatTemperatureSetpointTrait.NAME]
try:
if self.preset_mode == PRESET_ECO or hvac_mode == HVACMode.HEAT_COOL:
if low_temp and high_temp:
await trait.set_range(low_temp, high_temp)
elif hvac_mode == HVACMode.COOL and temp:
await trait.set_cool(temp)
elif hvac_mode == HVACMode.HEAT and temp:
await trait.set_heat(temp)
except ApiException as err:
raise HomeAssistantError(f"Error setting HVAC mode: {err}") from err
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set new target preset mode."""
if preset_mode not in self.preset_modes:
raise ValueError(f"Unsupported preset_mode '{preset_mode}'")
trait = self._device.traits[ThermostatEcoTrait.NAME]
try:
await trait.set_mode(PRESET_INV_MODE_MAP[preset_mode])
except ApiException as err:
raise HomeAssistantError(f"Error setting HVAC mode: {err}") from err
async def async_set_fan_mode(self, fan_mode: str) -> None:
"""Set new target fan mode."""
if fan_mode not in self.fan_modes:
raise ValueError(f"Unsupported fan_mode '{fan_mode}'")
if fan_mode == FAN_ON and self.hvac_mode == HVACMode.OFF:
raise ValueError(
"Cannot turn on fan, please set an HVAC mode (e.g. heat/cool) first"
)
trait = self._device.traits[FanTrait.NAME]
duration = None
if fan_mode != FAN_OFF:
duration = MAX_FAN_DURATION
try:
await trait.set_timer(FAN_INV_MODE_MAP[fan_mode], duration=duration)
except ApiException as err:
raise HomeAssistantError(f"Error setting HVAC mode: {err}") from err
| [
"noreply@github.com"
] | atetevoortwis.noreply@github.com |
fa12e96df5c231714ad31f68a8c115b1b98665ec | a2a49fe339b22feeda85000bed3313788ef4279f | /interface_project/interface/webtours.py | 19ee7f8c515ca6c9eb2c1a69abc230c0c62516dd | [] | no_license | guor911/interface_autotest_project | 980ef434b52b83597843312435870e7d2abdfe96 | eb1d6e23924c7eb9f97a0988551e2afcaffcd516 | refs/heads/master | 2021-01-22T21:21:55.726794 | 2017-08-18T03:51:35 | 2017-08-18T03:51:35 | 100,670,730 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,891 | py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
import urllib.parse
import json
from globalpkg.log import logger
from htmlparser import MyHTMLParser
from unittesttestcase import MyUnittestTestCase
step_output = None
class WebTours(MyUnittestTestCase):
def setUp(self):
pass
# 测试访问WebTours首页
def test_visit_webtours(self):
# 根据被测接口的实际情况,合理的添加HTTP头
# header = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0'
# }
logger.info('正在发起GET请求...')
response = self.http.get(self.url, (self.params))
logger.info('正在解析返回结果')
# 解析HTML文档
parser = MyHTMLParser(strict = False)
parser.feed(response)
# 比较结果
starttag_data = parser.get_starttag_data()
i = 0
for data_list in starttag_data:
if data_list[0] == 'title' and data_list[1] == 'Web Tours':
i = i + 1
self.assertNotEqual(str(i), self.expected_result['result'], msg='访问WebTours失败')
# 如果有需要,连接数据库,读取数据库相关值,用于和接口请求返回结果做比较
# 测试接口2
def test_xxxxxx(self):
'''提交body数据为json格式的POST请求'''
header = {'Content-Type':'application/json','charset':'utf-8'}
self.http.set_header(header)
self.params = json.dumps(eval(self.params)) # 将参数转为url编码字符串# 注意,此处params为字典类型的数据
self.params = self.params.encode('utf-8')
response = self.http.post(self.url, self.params)
self.assertEqual(response['code'], 0, msg='返回code不等于0')
def tearDown(self):
pass | [
"guor911@users.noreply.github.com"
] | guor911@users.noreply.github.com |
2174eb348a13e069f56247f14210d3a3ae056b7a | 2d30c45f9da0f1016491208e7d0f9f0edc27b160 | /TensorFlow/variable.py | e6becc64f8154d708c8a90435fb198f674fc59c1 | [] | no_license | IFICL/Python | ab1b2f95233a23bbd942e3c3be30155f9c34a905 | 818effdeae38cb2d9407b5d2e61db49b1884bdbb | refs/heads/master | 2021-07-02T20:43:25.580733 | 2020-07-27T15:46:13 | 2020-07-27T15:46:13 | 101,303,287 | 0 | 0 | null | 2017-08-24T14:32:04 | 2017-08-24T14:21:33 | null | UTF-8 | Python | false | false | 384 | py | #!/usr/bin/python2.7
#Filename:variable.py
import tensorflow as tf
state = tf.Variable(0, name="counter")
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)
init_op = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init_op)
print sess.run(state)
for _ in range(3):
sess.run(update)
print sess.run(state)
| [
"291474043@qq.com"
] | 291474043@qq.com |
c70a779cc10fd3ba3fe7aca2d9736f9bcb91c53f | d594f3926f6379ef7c382c608cb211f507240420 | /csunplugged/tests/utils/errors/test_ThumbnailPageNotFoundError.py | b73009b6a4421c213fecea7a8dec041baac543c4 | [
"LicenseRef-scancode-secret-labs-2011",
"MIT",
"OFL-1.1",
"LGPL-2.0-or-later",
"AGPL-3.0-only",
"CC-BY-4.0",
"Apache-2.0",
"BSD-3-Clause",
"CC-BY-SA-4.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | uccser/cs-unplugged | 0b9151f84dd490d5b90771a3706327a623d39edc | 363e281ff17cefdef0ec61078b1718eef2eaf71a | refs/heads/develop | 2023-08-25T08:45:29.833025 | 2023-08-22T02:58:35 | 2023-08-22T02:58:35 | 66,315,075 | 200 | 41 | MIT | 2023-09-14T02:15:40 | 2016-08-22T23:16:40 | Python | UTF-8 | Python | false | false | 958 | py | """Test class for ThumbnailPageNotFoundError error."""
from django.test import SimpleTestCase
from utils.errors.ThumbnailPageNotFoundError import ThumbnailPageNotFoundError
from unittest.mock import Mock
class ThumbnailPageNotFoundErrorTest(SimpleTestCase):
"""Test class for ThumbnailPageNotFoundError error.
Note: Tests to check if these were raised appropriately
are located where this exception is used.
"""
def test_attributes(self):
generator = Mock()
generator.__class__.__name__ = "Name"
exception = ThumbnailPageNotFoundError(generator)
self.assertEqual(exception.generator_name, "Name")
def test_string(self):
generator = Mock()
generator.__class__.__name__ = "Name"
exception = ThumbnailPageNotFoundError(generator)
self.assertEqual(
exception.__str__(),
"Name did not return a page with a designated thumbnail."
)
| [
"jackmorgannz@gmail.com"
] | jackmorgannz@gmail.com |
034e52336eae5d2e099249d72684781794fd0f7e | 2a76fb251735143db07d408ea7cf030fa0a63afd | /emimi by Mija/Auxiliares/plebicito.py | 6c59f8bec94e9f512eafd49c1b87214767e02468 | [] | no_license | MijaToka/Random3_1415 | 96c5b0f5fd19c01c12487cf6b41add0372ea3cc4 | 1b7780422529418a74a3885f64c1ff74aa147e61 | refs/heads/master | 2023-04-20T11:42:23.960514 | 2021-05-08T21:57:44 | 2021-05-08T21:57:44 | 329,778,241 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,018 | py | import porcentaje as per
def plebicito(apruebo,rechazo,blanco,nulo):
total = apruebo + rechazo + blanco + nulo
totPar = apruebo + rechazo
# % c/u vs total
aTot = per.porcentaje(apruebo,total)
rTot = per.porcentaje(rechazo,total)
bTot = per.porcentaje(blanco,total)
nTot = per.porcentaje(nulo,total)
# % relativos de apruebo y rechazo
aPar = per.porcentaje(apruebo,totPar)
rPar = per.porcentaje(rechazo,totPar)
print('')
print('El porcentaje absoluto fue:')
print(' ')
print('-Apruebo: '+ str(aTot))
print('-Rechazo: ' + str(rTot))
print('-Blanco: ' + str(bTot))
print('-Nulo: ' + str(nTot))
print('')
print('El porcentaje relativo fue:')
print(' ')
print('-Apruebo:' + str(aPar))
print('-Rechazo:' + str(rPar))
return
print('Ingrese cantidad total de votos para cada opción')
a = int(input('Apruebo '))
r = int(input('Rechazo '))
b = int(input('Blanco '))
n = int(input('Nulo '))
plebicito(a,r,b,n) | [
"mijail.tokarev@ug.uchile.cl"
] | mijail.tokarev@ug.uchile.cl |
9aedd1dcef9bba603276f63a2461f08343919225 | 588e4587cac37b78ee4f00bb8d6f22f08445500e | /classify.py | 741ec6115bbc3e37c092639b29f9925f8db0b1ad | [
"MIT"
] | permissive | Bachir-Bouhafs/Integration-IA-In-App | 805794cf41a3120e9f1ec5a2848d25d6387cbf02 | 6d1888f1a207eb9e418607c30f10df4dcc39a303 | refs/heads/master | 2023-01-13T16:41:40.563166 | 2020-11-19T02:58:04 | 2020-11-19T02:58:04 | 279,342,113 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,400 | py | import tensorflow as tf
import sys
import os
# Disable tensorflow compilation warnings
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
def analyse(imageObj):
# Read the image_data
image_data = tf.io.gfile.GFile("/content/Plastic-Detection-Model/static/images/"+imageObj, 'rb').read()
# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
in tf.io.gfile.GFile("tf_files/retrained_labels.txt")]
# Unpersists graph from file
with tf.io.gfile.GFile("tf_files/retrained_graph.pb", 'rb') as f:
graph_def = tf.compat.v1.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
with tf.compat.v1.Session() as sess:
# Feed the image_data as input to the graph and get first prediction
softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
predictions = sess.run(softmax_tensor, \
{'DecodeJpeg/contents:0': image_data})
# Sort to show labels of first prediction in order of confidence
top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
obj = {}
for node_id in top_k:
human_string = label_lines[node_id]
score = predictions[0][node_id]
obj[human_string] = float(score)
return obj | [
"bbouhafs@dxc.com"
] | bbouhafs@dxc.com |
26a4deb38675a8c8a8ed12f89b75937b21c93aec | 62e240f67cd8f92ef41ce33dafdb38436f5a9c14 | /tests/parsers/bencode_parser.py | f012685073c77212fcc29cb216201a18d37e4779 | [
"Apache-2.0"
] | permissive | joshlemon/plaso | 5eb434772fa1037f22b10fa1bda3c3cc83183c3a | 9f8e05f21fa23793bfdade6af1d617e9dd092531 | refs/heads/master | 2022-10-14T18:29:57.211910 | 2020-06-08T13:08:31 | 2020-06-08T13:08:31 | 270,702,592 | 1 | 0 | Apache-2.0 | 2020-06-08T14:36:56 | 2020-06-08T14:36:56 | null | UTF-8 | Python | false | false | 839 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Bencode file parser."""
from __future__ import unicode_literals
import unittest
from plaso.parsers import bencode_parser
# Register all plugins.
from plaso.parsers import bencode_plugins # pylint: disable=unused-import
from tests.parsers import test_lib
class BencodeTest(test_lib.ParserTestCase):
"""Tests for the Bencode file parser."""
# pylint: disable=protected-access
def testEnablePlugins(self):
"""Tests the EnablePlugins function."""
parser = bencode_parser.BencodeParser()
parser.EnablePlugins(['bencode_transmission'])
self.assertIsNotNone(parser)
self.assertIsNone(parser._default_plugin)
self.assertNotEqual(parser._plugins, [])
self.assertEqual(len(parser._plugins), 1)
if __name__ == '__main__':
unittest.main()
| [
"joachim.metz@gmail.com"
] | joachim.metz@gmail.com |
20bb207a7f45ed8feba83492f4c9fc1e97d488ca | 59b67908c20267f033c600deecccda0d22d83ff1 | /PyBank/main.py | 65f1a9155a87639b91b982e0b7915a70cb1b484b | [] | no_license | 8135tao/python-challenge | 6ca4073dcdbb6101fc6e040a26f34b37b4eb8974 | 43a99c4609a4c68a994c87dc78015abcc2a895a3 | refs/heads/master | 2020-03-27T18:57:15.804154 | 2018-09-04T03:28:45 | 2018-09-04T03:28:45 | 146,955,661 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,565 | py | import os
import csv
# define the average function, used to caculate the average in a list
def average(list):
average = sum(list)/len(list)
return average
open_bank_csv = os.path.join("Resources", "budget_data.csv")
output_bank_csv = os.path.join("Output", "bank_report.csv")
with open(open_bank_csv, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
bank_data = list(csvreader)
enumerated_bankdata = list(enumerate(bank_data))
row_count = 0
net_total = 0
#create a list to store the average change by using enumerate
list_avgchange = [int(bankrow[1])-int(bank_data[i-1][1])
for i, bankrow in enumerated_bankdata][1:]
# can also do the same using zip (more elegant!): https://stackoverflow.com/questions/5314241/difference-between-consecutive-elements-in-list
# list_raw = [int(bankrow[1]) for bankrow in bank_data]
# list_avgchange = [j-i for i,j in zip(list_raw,list_raw[1:])]
list_avgchange.insert(0,-100000000.00)
average_change = average(list_avgchange[1:])
max_change = max(list_avgchange[1:])
min_change = min(list_avgchange[1:])
max_index = list_avgchange.index(max_change)
min_index = list_avgchange.index(min_change)
for i,bankrow in enumerated_bankdata:
row_count +=1
net_total += int(bankrow[1])
# create the list of things to report.
reports = [
"Total number of months: " + str(row_count),
"Total: " + str("${:10.2f}".format(net_total)),
"Greatest increase in profits at: " +bank_data[max_index][0] +" (" +str("${:10.2f}".format(max_change)) +")",
"Greatest decrease in profits at: " +bank_data[min_index][0] +" (" +str("${:10.2f}".format(min_change)) +")",
f"Average change: ${average_change:.2f}"
]
print("Financial Analysis \n")
print("-------------------------------- \n")
print(*reports, sep = "\n")
# can also output not using the csv class
# with open(output_bank_csv,"w", newline="") as export:
# export.write("Financial Analysis\n")
# export.write("--------------------------\n")
# for report in reports:
# export.write("{}\n".format(report))
with open(output_bank_csv,"w", newline="") as outputfile:
csvwriter = csv.writer(outputfile, lineterminator='\n')
csvwriter.writerow(["Financial Analysis"])
csvwriter.writerow(["---------------------------"])
for report in reports:
csvwriter.writerow([report]) | [
"8135tao@gmail.com"
] | 8135tao@gmail.com |
8dfce7048c04d01ecfe51beabd1a5db76f678f55 | 8f7b120d62555db30cce59f3fae2265e940e45dd | /pwsh2python/recursion/palindrome.py | 6a002ebada0dcf87227261bee9e45252c7cabc78 | [] | no_license | carrba/python-stuff | 82861716a5cd32b23fba4d184ec07b4f8f5a9fa8 | 3b92505347d1135ed519f157b3a7c298b161c1f5 | refs/heads/master | 2023-03-31T13:42:31.148805 | 2021-04-06T11:04:57 | 2021-04-06T11:04:57 | 355,154,703 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 456 | py | #!/usr/bin/python3.6
# To "dot source" these functions: "python -i iteration_v_recursion.py"
def isPalindrome(s):
def toChars(s):
s = s.lower()
ans = ''
for c in s:
if c in 'abcdefghijklmnopqrstuvwxyz':
ans = ans + c
return ans
def isPal(s):
if len(s) <= 1:
return True
else:
return s[0] == s[-1] and isPal(s[1:-1])
return isPal(toChars(s)) | [
"b.carr@btinternet.com"
] | b.carr@btinternet.com |
ad88385c51c5f4ddc6060cb87917f350ee2eb21a | 26ba5338c82b40bb8a55d42a5aa46e46b0793995 | /Codigo/Introducción_a_las_ciencias_de_la_computación/Proyecto/JuegoVidaProcessing.py | 20e4662b1605fdd6ca724d73bb526daa25da33c1 | [] | no_license | Miguelburitica/La-carpeta-compartida | c6b5a588b0e6984bbe01fea01bfe3dfd74f2c57e | 4ff007bec5fc6d49d25e9d2ac0992d4dbde51f5a | refs/heads/master | 2023-08-23T17:51:44.116999 | 2021-09-19T18:01:55 | 2021-09-19T18:01:55 | 364,123,821 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,824 | py | import pygame
import time
def zeros(n):
n1 = n[0]
n2 = n[1]
A = []
B = []
for i in range(0, n1):
A.append(0)
for j in range(0, n2):
B.append(A)
return B
def copy(A):
B = []
for i in A:
B.append(i)
return B
def flur(A):
cont = 0
B = []
if type(A) == list:
for i in A:
if type(i) == list:
for j in i:
j = int(j)
j = float(j)
i[cont] = j
cont += 1
else:
i = int(i)
i = float(i)
A[cont] = i
cont += 1
cont = 0
B.append(i)
else:
A = int(A)
A = float(A)
B = A
return B
pygame.init()
width, height = 1000, 1000
screen = pygame.display.set_mode((height, width))
bg = 25, 25, 25
screen.fill(bg)
nxC = 100
nyC = 100
dimCW = width / nxC
dimCH = height / nyC
gameState = zeros(nxC, nyC)
gameState[21][21] = 1
gameState[22][22] = 1
gameState[22][23] = 1
gameState[21][23] = 1
gameState[20][23] = 1
pauseExect = False
clock = pygame.time.Clock()
while True:
newGameState = copy(gameState)
screen.fill(bg)
#time.sleep(0.000000000000000000000000001)
ev = pygame.event.get()
for event in ev:
if event.type == pygame.KEYDOWN:
pauseExect = not pauseExect
mouseClick = pygame.mouse.get_pressed()
for y in range(0, nxC):
for x in range(0, nyC):
if not pauseExect:
n_neigh = gameState[(x - 1) % nxC][(y - 1) % nyC] + \
gameState[(x) % nxC][(y - 1) % nyC] + \
gameState[(x + 1) % nxC][(y - 1) % nyC] + \
gameState[(x - 1) % nxC][(y) % nyC] + \
gameState[(x + 1) % nxC][(y) % nyC] + \
gameState[(x - 1) % nxC][(y + 1) % nyC] + \
gameState[(x) % nxC][(y + 1) % nyC] + \
gameState[(x + 1) % nxC][(y + 1) % nyC]
if gameState[x][y] == 0 and n_neigh == 3:
newGameState[x][y] = 1
elif gameState[x][y] == 1 and (n_neigh > 3 or n_neigh < 2):
newGameState[x][y] = 0
poly = [((x) * dimCW, y * dimCH),
((x+1) * dimCW, y * dimCH),
((x+1) * dimCW, (y+1) * dimCH),
((x) * dimCW, (y+1) * dimCH)]
if newGameState[x][y] == 0:
pygame.draw.polygon(screen, (128, 128, 128), poly, 1)
else:
pygame.draw.polygon(screen, (255, 255, 255), poly, 0)
gameState = copy(newGameState)
clock.tick(60)
pygame.display.flip()
| [
"79605328+Miguelburitica@users.noreply.github.com"
] | 79605328+Miguelburitica@users.noreply.github.com |
3de7f46bd8f298104d797f1472d4f3b509ac8a36 | 5e1c4ef03d4c6e78f5eba6927ed6398aa6f4ef15 | /dirganize/dirganize/main.py | d95fa54ed762abf4f329eaab8ca8cd6749db6c7f | [
"WTFPL"
] | permissive | DanKrt82/py-utility-pack | d2dd0e18d407b041e968f3b24cf69ea0ed194f15 | fb76c0e39f6cb3cbe9413779bc3273d4208208a6 | refs/heads/main | 2023-03-27T01:56:03.003943 | 2021-03-30T07:49:44 | 2021-03-30T07:49:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,091 | py | ''' the main script to get the job done '''
import os
import logging
import yaml
from rich.progress import track
from rich.logging import RichHandler
import typer
app = typer.Typer()
@app.command()
def main(path: str = os.getcwd(), loud: bool = False):
''' Organizes files into folders
'''
if loud:
logging.basicConfig(level=logging.INFO,
format='[dim]%(name)s[/dim]\t%(message)s',
handlers=[RichHandler(markup=True, show_path=False,)])
os.chdir(path)
logging.info(f'Current working directory is {os.getcwd()}')
structure = {'images': ['png', 'jpg', 'jpeg'],
'videos': ['mp4', 'webp'],
'docs': ['pdf', 'txt', 'md'],
'animations': ['gif'],
'ebooks': ['epub'],
'archives': ['zip', 'tar', 'gz'],
'databases': ['csv', 'xlsx', 'xls', 'db'],
'configs': ['yaml', 'ini', 'env', 'yml'],
'android': ['apk'],
'webpages': ['html'],
'scripts': ['py', 'sh', 'java', 'cpp', 'c', 'js']}
config_file = '.dirganize.yml'
if os.path.isfile(config_file):
with open(config_file) as stream:
structure = (yaml.full_load(stream))
logging.info(structure)
mapping = {}
for folder, extensions in track(structure.items(), description='Creating mapping '):
for ext in extensions:
mapping[ext] = folder
logging.info(mapping)
all_files = [file for file in os.listdir() if os.path.isfile(file)]
logging.info(all_files)
for file in track(all_files, description='Moving files '):
ext = file.split('.')[-1]
new_parent_dir = mapping.get(ext)
if new_parent_dir:
new_file = os.path.join(new_parent_dir, file)
if not os.path.isdir(new_parent_dir):
os.makedirs(new_parent_dir)
os.rename(file, new_file)
logging.info('%s renamed to %s', file, new_file)
if __name__ == "__main__":
app()
| [
"66209958+aahnik@users.noreply.github.com"
] | 66209958+aahnik@users.noreply.github.com |
fafd0630281dead30fd586d58a20022f1dbf6a41 | c88f443442d50bc921f58e5a74268b095b7b260e | /ANN_cnn.py | 0fe6b27f79c1530f2a03ef6898d11d0430e494b4 | [] | no_license | ShiuLab/ANN_Pipeline | ee1f43d042de201cbbe072e62aff6da4f498a3d1 | 8e8ce322757c5f4465723a251734216539d06ab1 | refs/heads/master | 2020-05-15T07:56:48.413551 | 2019-02-22T19:03:18 | 2019-02-22T19:03:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,999 | py | """
PURPOSE: Run Parameter Sweep for Convolutional Neural Network Regressor using Tensorflow
cnn_a.py : Grid search through parameter space
cnn_b.py : Build CNN using provided parameters
INPUTS:
REQUIRED:
-x Option 1: File with input data. Images should be processed so all pixle data is in one line:
Example: Original Input
Pic1 Pix1 Pix2 Pix3 Pix1 Pix2 Pix3 Pix4 Pix5 Pix6
Pix4 Pix5 Pix6 Pic1 0 0 1 1 0 1
Pic2 Pix1 Pix2 Pix3 Pic2 1 0 0 1 0 0
Pix4 Pix5 Pix6
Option 2: Directory with image files. Will resize to fit -shape given. Note: Saves a copy of the
processed data to the image dir, if re-processing is needed, delete 'dir/X_processed.csv'.
-y File with dependent variable to predict.
-ho With with list of testing instances to holdout from training. (Generate using ML_Pipeline/holdout.py)
-save Prefix for grid search output file - note make unique for each pred problem.
-shape Dimensions of image: row,col. For the above sample -shape 2,3
OPTIONAL:
-f Select function to perform (gs, run, full*) *Default
-y_name Name of column from -y to use if more than one column present
-norm T/F Normalize Y (default = T)
-sep Specify seperator in -x and -y (Default = '\t')
-actfun Activation function. Default = relu, suggested GridSearch: [relu, sigmoid]
-lrate Value for learning rate (L2). Default = 0.01, suggested GridSearch: [0.001, 0.01, 0.1]
-dropout Value for dropout regularization (dropout). Default = 0.25, suggested GridSearch: [0.0, 0.1, 0.25, 0.5]
-l2 Value for shrinkage regularization (L2). Default = 0.1, suggested GridSearch: [0.0, 0.1, 0.25, 0.5]
-conv_shape Dimensions of convolutions: row,col. Default = 5,5
-feat List of columns in -x to use. Can also be used to re-order columns in -x
-max_epoch Max number of epochs to iterate through
-epoch_thresh** Threshold for percent change in MSE before training stops. Default: 0.001
-s_losses T/F Save the training, validation, and testing losses from final model training
-s_yhat T/F Apply trained model to all data and save output
** The number of training epochs (i.e. iterations) is dynamic, based on the -epoch_threshold.
After an initial burnin period (100 epochs here), every time the abs(% change in MSE) for the
validation set is below the epoch_threshold. After 10 epochs with a %change below the threshold
training stops and the final training and validation MSE are reported
Example:
source /mnt/home/azodichr/python3-tfcpu/bin/activate
python ANN_cnn.py -f gs -x geno.csv -y pheno.csv -ho holdout.txt -feat rice_YLD_RF_1_2000.txt -y_name YLD -sep ',' -save test -norm t -gs_reps 10
Roughly based off: https://pythonprogramming.net/cnn-tensorflow-convolutional-nerual-network-machine-learning-tutorial/
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, sys
import numpy as np
import pandas as pd
import tensorflow as tf
import math
import timeit
from scipy.stats.stats import pearsonr
import ANN_Functions as ANN
tf.logging.set_verbosity(tf.logging.INFO)
start_time = timeit.default_timer()
def main():
#####################
### Default Input ###
#####################
FUNCTION = 'full'
# Input and Output info
SEP, TAG, FEAT, SAVE, y_name, norm = '\t', '', '', 'test', 'Y', 't'
save_weights = save_losses = save_yhat = 'f'
# Hyperparameters
actfun, lrate, dropout, l2 = 'sigmoid', 0.01, 0.25, 0.0
params = ''
# Grid Search Hyperparameter Space
gs_reps = 10
list_dropout = list_l2 = [0.0, 0.1, 0.25, 0.5]
list_lrate = [0.01, 0.001]
list_actfun = ["sigmoid", "relu"]
# Training Parameters
max_epochs = 50000
epoch_thresh = 0.001
burnin = 10
loss_type = 'mse'
val_perc = 0.1
# Default CNN structure
conv_r, conv_c = 5, 5
shape_r, shape_c = int(50), int(40)
for i in range (1,len(sys.argv),2):
if sys.argv[i].lower() == "-x":
X_file = sys.argv[i+1]
if sys.argv[i].lower() == "-y":
Y_file = sys.argv[i+1]
if sys.argv[i].lower() == '-ho':
ho = sys.argv[i+1]
if sys.argv[i].lower() == '-sep':
SEP = sys.argv[i+1]
if sys.argv[i].lower() == "-feat":
FEAT = sys.argv[i+1]
if sys.argv[i].lower() == "-y_name":
y_name = sys.argv[i+1]
if sys.argv[i].lower() == "-norm":
norm = sys.argv[i+1]
if sys.argv[i].lower() == "-save":
SAVE = sys.argv[i+1]
if sys.argv[i].lower() == "-actfun":
actfun = sys.argv[i+1]
if sys.argv[i].lower() == "-loss_type":
loss_type = sys.argv[i+1]
if sys.argv[i].lower() == '-val_perc':
val_perc = float(sys.argv[i+1])
if sys.argv[i].lower() == "-epoch_thresh":
epoch_thresh = float(sys.argv[i+1])
if sys.argv[i].lower() == "-epoch_max":
epoch_thresh = int(sys.argv[i+1])
if sys.argv[i].lower() == "-burnin":
burnin = int(sys.argv[i+1])
if sys.argv[i].lower() == "-lrate":
lrate = float(sys.argv[i+1])
if sys.argv[i].lower() == "-l2":
l2 = float(sys.argv[i+1])
if sys.argv[i].lower() == "-dropout":
dropout = float(sys.argv[i+1])
if sys.argv[i].lower() == "-shape":
temp_shape = sys.argv[i+1]
shape_r,shape_c = temp_shape.strip().split(',')
shape_r = int(shape_r)
shape_c = int(shape_c)
if sys.argv[i].lower() == "-conv_shape":
temp_shape = sys.argv[i+1]
conv_r,conv_c = temp_shape.strip().split(',')
conv_r = int(conv_r)
conv_c = int(conv_c)
if sys.argv[i].lower() == "-s_losses":
save_losses = sys.argv[i+1]
if sys.argv[i].lower() == "-s_yhat":
save_yhat = sys.argv[i+1]
if sys.argv[i].lower() == "-gs_reps":
gs_reps = int(sys.argv[i+1])
################
### Features: read in file, keep only those in FEAT if given, and define feature_cols for DNNReg.
################
if os.path.isfile(X_file):
x = pd.read_csv(X_file, sep=SEP, index_col = 0)
if FEAT != '':
with open(FEAT) as f:
features = f.read().strip().splitlines()
x = x.loc[:,features]
elif os.path.isdir(X_file):
x = ANN.fun.Image2Features(X_file, shape_r, shape_c)
feat_list = list(x.columns)
print("\n\nTotal number of instances: %s" % (str(x.shape[0])))
print("\nNumber of features used: %s" % (str(x.shape[1])))
################
### Y: read in file, keep only column to predict, normalize if needed, and merge with features
################
y = pd.read_csv(Y_file, sep=SEP, index_col = 0)
if y_name != 'pass':
print('Building model to predict: %s' % str(y_name))
y = y[[y_name]]
if norm == 't':
mean = y.mean(axis=0)
std = y.std(axis=0)
y = (y - mean) / std
y = y.convert_objects(convert_numeric=True)
df = pd.merge(y, x, left_index=True, right_index=True)
print('\nSnapshot of data order being used:')
print(df.head())
################
### Holdout: Drop holdout set as it will not be used during grid search
################
X, Y, X_train, X_valid, X_test, Y_train, Y_valid, Y_test = ANN.fun.train_valid_test_split(df, ho, y_name, val_perc)
# TF Graph Placeholders
x = tf.placeholder(tf.float32, [None, X_train.shape[1]])
y = tf.placeholder(tf.float32, [None, 1])
dropout_rate = tf.placeholder(tf.float32) # For dropout, allows it to be turned on during training and off during testing
if FUNCTION == 'gs' or FUNCTION == 'full':
print('Starting Grid Search...')
gs_results = pd.DataFrame()
gs_count = 0
gs_length = len(list_dropout) * len(list_l2) * len(list_lrate) * len(list_actfun) * gs_reps
for r in range(0,gs_reps):
for dropout in list_dropout:
for l2 in list_l2:
for lrate in list_lrate:
for actfun in list_actfun:
if gs_count % 10 == 0:
print('Grid Search Status: %i out of %i' % (gs_count, gs_length))
### Define CNN Model ###
pred = ANN.fun.convolutional_neural_network(x, conv_r, conv_c, shape_r, shape_c, dropout, actfun)
train_vars = tf.trainable_variables()
loss = tf.reduce_mean(tf.squared_difference(pred, Y_train)) + tf.add_n([tf.nn.l2_loss(v) for v in train_vars]) * l2
optimizer = tf.train.AdamOptimizer(lrate).minimize(loss)
### Launch the graph ###
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
epoch_count = stop_count = 0
train='yes'
old_c = 1
while train == 'yes':
epoch_count += 1
_, c = sess.run([optimizer, loss], feed_dict={x:X_train, y:pd.DataFrame(Y_train), dropout_rate:dropout}) # Maybe add keep_prob:dropout to the feed_dict
valid_c = sess.run(loss,feed_dict = {x:X_valid, y:pd.DataFrame(Y_valid), dropout_rate:1})
pchange = (old_c-valid_c)/old_c
if epoch_count >= burnin:
if abs(pchange) < epoch_thresh:
stop_count += 1
print('Early stopping after %i more below threshold' % (10-stop_count))
if stop_count >= 10:
train='no'
old_c = valid_c
if epoch_count == max_epochs:
train='no'
# Apply trained network to validation data and gather performance metrics
valid_pred = sess.run(pred, feed_dict={x: X_valid, y:pd.DataFrame(Y_valid), dropout_rate:0})
val_cor = pearsonr(valid_pred[:,0],Y_valid)
gs_results = gs_results.append({'ActFun': actfun, 'dropout': dropout, 'L2':l2, 'lrate':lrate, 'Epochs':epoch_count, 'Train_MSE':c, 'Valid_MSE':valid_c, 'Valid_PCC': val_cor[0]}, ignore_index=True)
if not os.path.isfile(SAVE + "_GridSearch.txt"):
gs_results.to_csv(SAVE + "_GridSearch.txt", header='column_names', sep='\t')
else:
gs_results.to_csv(SAVE + "_GridSearch.txt", mode='a', header=False, sep='\t')
print('\n\n Grid Search results saved to: %s_GridSearch.txt\n' % SAVE)
################
### Run final model
################
if FUNCTION == 'full' or FUNCTION == 'run':
# Grab parameters from grid search results
if FUNCTION == 'full' or params != '':
if FUNCTION == 'full':
gs_res = gs_results
if params != '':
gs_res = pd.read_csv(params, sep='\t')
gs_ave = gs_res.groupby(['ActFun','dropout','L2','lrate']).agg({
'Valid_Loss': 'median', 'Train_Loss': 'median', 'Valid_PCC': 'mean', 'Epochs': 'mean'}).reset_index()
gs_ave.columns = ['ActFun','dropout','L2','LRate', 'VLoss_med', 'TLoss_med', 'VPCC_med', 'Epochs_mean']
results_sorted = gs_ave.sort_values(by='VPCC_med', ascending=False)
print('\nSnapshot of grid search results:')
print(results_sorted.head())
actfun = results_sorted['ActFun'].iloc[0]
dropout = float(results_sorted['dropout'].iloc[0])
l2 = float(results_sorted['L2'].iloc[0])
lrate = float(results_sorted['LRate'].iloc[0])
print("\n\n##########\nBuilding MLP with the following parameters:\n")
print('Regularization: dropout = %f L2 = %f' % (dropout, l2))
print('Learning rate: %f' % lrate)
print('Activation Function: %s\n\n\n' % actfun)
### Define CNN Model ###
pred = ANN.fun.convolutional_neural_network(x, conv_r, conv_c, shape_r, shape_c, dropout, actfun)
train_vars = tf.trainable_variables()
loss = tf.reduce_mean(tf.squared_difference(pred, Y_train)) + tf.add_n([tf.nn.l2_loss(v) for v in train_vars]) * l2
optimizer = tf.train.AdamOptimizer(lrate).minimize(loss)
### Launch the graph ###
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
epoch_count = stop_count = 0
train='yes'
old_c = 1
while train == 'yes':
epoch_count += 1
_, c = sess.run([optimizer, loss], feed_dict={x:X_train, y:pd.DataFrame(Y_train), dropout_rate:dropout}) # Maybe add keep_prob:dropout to the feed_dict
valid_c = sess.run(loss,feed_dict = {x:X_valid, y:pd.DataFrame(Y_valid), dropout_rate:1})
test_c = sess.run(loss,feed_dict = {x:X_test, y:pd.DataFrame(Y_test), dropout_rate:1})
losses.append([epoch_count, c, valid_c, test_c])
pchange = (old_c-valid_c)/old_c
if epoch_count >= burnin:
if abs(pchange) < epoch_thresh:
stop_count += 1
print('Early stopping after %i more below threshold' % (10-stop_count))
if stop_count >= 10:
train='no'
old_c = valid_c
if epoch_count == max_epochs or train=='no':
train='no'
print('Final MSE after %i epochs for training: %.5f and validation: %.5f' % (epoch_count, c, valid_c))
# Predict test set and add to yhat output
test_pred = sess.run(pred, feed_dict={x: X_test, dropout_rate:1})
valid_pred = sess.run(pred, feed_dict={x: X_valid, dropout_rate:1})
print('Snapshot of predicted Y values:')
print(test_pred[:,0][0:10])
ho_cor = np.corrcoef(Y_test, test_pred[:,0])
valid_cor = np.corrcoef(Y_valid, valid_pred[:,0])
print('Valid correlation coef (r): %.5f' % valid_cor[0,1])
print('Holdout correlation coef (r): %.5f' % ho_cor[0,1])
##### Optional Outputs ####
if save_losses == 't':
losses_df = pd.DataFrame(losses, columns=['epoch', 'MSE_train', 'MSE_valid', 'MSE_test'])
losses_df.to_csv(SAVE+'_losses.csv', index=False)
if save_yhat == 't':
pred_all = sess.run(pred, feed_dict={x:X, dropout_rate:1})
pred_all_res = pd.DataFrame({'Y': Y, 'Yhat': pred_all[:,0]})
pred_all_res.to_csv(SAVE+'_yhat.csv', index=False)
run_time = timeit.default_timer() - start_time
if not os.path.isfile('RESULTS.txt'):
out1 = open('RESULTS.txt', 'w')
out1.write('DateTime\tRunTime\tTag\tDFs\tDFy\tTrait\tFeatSel\tWeights\tNumFeat\tHoldout\tNumHidLay\tArchit\tActFun\tEpochs\tdropout\tL2\tLearnRate\tMSE_Train\tMSE_Valid\tMSE_test\tPCC_test\n')
out1.close()
out2 = open('RESULTS.txt', 'a')
out2.write('%s\t%0.5f\t%s\t%s\t%s\t%s\t%s\t%s\t%i\t%s\t%i\t%s\t%s\t%i\t%f\t%f\t%f\t%0.5f\t%0.5f\t%0.5f\t%0.5f\n' % (
timestamp, run_time, TAG, X_file, Y_file, y_name, FEAT, WEIGHTS, x.shape[1], ho, layer_number, str(arc), actfun, epoch_count, dropout, l2, lrate, c, valid_c, test_c, ho_cor[0,1]))
out2.close()
print('\nfinished!')
if __name__ == '__main__':
main()
| [
"azodichr@msu.edu"
] | azodichr@msu.edu |
e839ecd9be455305da0ddb3de1c37545ff326c83 | eae37356b50189eb846948a621bd680e981f23e5 | /dataloader/cocodataset/COCOBBox.py | 9caccac83cd3f3518ecee34b87a75fd7688f1743 | [] | no_license | PuAnysh/LightPoseEstimation | 63f0996029cec8d7259c085131e83c4ec846f7a6 | 905aa61a3e68b6e63304877cd08b9c5c16115a8f | refs/heads/master | 2020-05-15T03:55:47.515244 | 2019-05-03T15:01:49 | 2019-05-03T15:01:49 | 182,074,712 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 10,159 | py | import os
import cv2
import random
import imgaug as ia
from imgaug import augmenters as iaa
import numpy as np
from pycocotools.coco import COCO
from dataloader.cocodataset.coco_process_utils import *
from dataloader.cocodataset.process_utils import *
import torch
MIN_KEYPOINTS = 5
MIN_AREA = 32 * 32
class COCOBBox():
def __init__(self, cfg, train=True):
self.coco_year = 2017
self.cfg = cfg
if train:
self.cocobbox = COCO(cfg.Instances_ANNOTATION_train_DIR)
#self.cocokypt = COCO(cfg.keyPoints_ANNOTATION_train_DIR)
self.data_path = cfg.IMG_DIR
self.do_augment = train
self.indices = self._clean_annot(self.cocobbox , 'train')
self.input_size = cfg.INPUT_SIZE
self.HEAT_MAP_SIZE = cfg.HEAT_MAP_SIZE
self.sigmaHM = cfg.sigmaHM
self.sigma_limb = cfg.sigma_limb
self.seq = self.__getIAAseq__(cfg.INPUT_SIZE)
self.seq_size = self.__getIAAseq_scale__(cfg.INPUT_SIZE)
#print('Loaded {} images for {}'.format(len(self.indices), 'train'))
# load annotations that meet specific standards
self.img_dir = cfg.IMG_DIR
#print('Loaded {} images for {}'.format(len(self.indices), split))
def bbox2imgbbox(self , image , bbox_):
bbox = []
for row in bbox_:
bbox.append(ia.BoundingBox(x1 = row[0] ,y1 = row[1] ,x2 = row[0]+row[2] , y2= row[1]+row[3]))
return ia.BoundingBoxesOnImage(bbox , shape=image.shape)
def imgbbox2bbox(self,bbox_aug):
bbox = []
for row in bbox_aug.bounding_boxes:
tmp_bbox = [row.x1 , row.y1 , row.x2 , row.y2]
bbox.append(tmp_bbox)
return np.array(bbox)
def pose2keypoints(self, image, pose):
keypoints = []
for row in range(int(pose.shape[0])):
x = pose[row,0]
y = pose[row,1]
keypoints.append(ia.Keypoint(x=x, y=y))
return ia.KeypointsOnImage(keypoints, shape=image.shape)
def keypoints2pose(self, keypoints_aug):
one_person = []
for kp_idx, keypoint in enumerate(keypoints_aug.keypoints):
x_new, y_new = keypoint.x, keypoint.y
one_person.append(np.array(x_new).astype(np.float32))
one_person.append(np.array(y_new).astype(np.float32))
return np.array(one_person).reshape([-1,2])
def __getIAAseq__(self,size):
seq = iaa.Sequential(
[
# Apply the following augmenters to most images.
# iaa.CropAndPad(percent=(-0.25, 0.25), pad_mode=["edge"], keep_size=False),
#
iaa.Affine(
# scale={"x": (0.75, 1.25), "y": (0.75, 1.25)},
# translate_percent={"x": (-0.1, 0.1), "y": (-0.1, 0.1)},
rotate=(-5, 5),
shear=(-2, 2),
order=[0, 1],
cval=0,
mode="constant"
)
]
)
# augmentation choices
# seq_det = seq.to_deterministic()
return seq
def __getIAAseq_scale__(self, size):
seq = iaa.Sequential(
[
# Apply the following augmenters to most images.
# iaa.CropAndPad(percent=(-0.25, 0.25), pad_mode=["edge"], keep_size=False),
#
iaa.Scale(size,
interpolation='nearest',
name=None,
deterministic=False,
random_state=None)
]
)
# augmentation choices
# seq_det = seq.to_deterministic()
return seq
def __getAug__(self , img , keypoint , heat_maps , limb_sigma , mask):
seq_det = self.seq.to_deterministic()
img = seq_det.augment_image(img)
mask = seq_det.augment_image(mask)
heat = []
limbs = []
for i in range(heat_maps.shape[0]):
heat_map = heat_maps[i]
heat_map = seq_det.augment_image(heat_map)
heat.append(heat_map)
heat = np.array(heat)
for i in range(limb_sigma.shape[0]):
limb = limb_sigma[i]
limb = seq_det.augment_image(limb)
limbs.append(limb)
limbs = np.array(limbs)
_keypoint = self.pose2keypoints(img , keypoint)
_keypoint = seq_det.augment_keypoints(_keypoint)
keypoint[:,0:2] = self.keypoints2pose(_keypoint)
return img , keypoint , heat , limbs , mask
def __getitem__(self, index):
index = self.indices[index]
anno_ids = self.cocobbox.getAnnIds(index)
annots = self.cocobbox.loadAnns(anno_ids)
annots = list(filter(lambda annot: check_annot(annot), annots))
img_path = os.path.join(self.data_path, self.cocobbox.loadImgs([index])[0]['file_name'])
#print(img_path)
img = cv2.imread(img_path)
img = img.astype('float32') / 255.
keypoints , bboxes = get_keypoints_bbox(self.cocobbox, img, annots)
ignore_mask = get_ignore_mask(self.cocobbox, img, annots)
idx = random.randint(0,1007)%(keypoints.shape[0])
y1, x1, y2, x2 = bboxes[idx].astype(np.int32)
x2 = x2 + x1
y2 = y2 + y1
keypoint = keypoints[idx]
for i in range(keypoint.shape[0]):
keypoint[i, 0] -= y1
keypoint[i, 1] -= x1
img = img[x1:x2 , y1:y2 , :]
ignore_mask = ignore_mask[x1:x2 , y1:y2]
heat_map = get_heatmap(self.cocobbox, img, keypoint.reshape(-1,18,3), self.sigmaHM)
limb_sigma = get_limbSigma(self.cocobbox, img, keypoint.reshape(-1,18,3), self.sigma_limb)
#heat_map = heat_map[: , x1:x2 , y1:y2]
#limb_sigma = limb_sigma[: , x1:x2 , y1:y2]
img , keypoint , heat_map , limb_sigma, ignore_mask = self.__getAug__(img , keypoint , heat_map , limb_sigma, ignore_mask)
# resize
img = cv2.resize(img , (self.input_size , self.input_size)).astype(np.float32)
heat_map = cv2.resize(heat_map.transpose(1 ,2 ,0) , (self.HEAT_MAP_SIZE , self.HEAT_MAP_SIZE)).transpose(2,0,1).astype(np.float32)
limb_sigma = cv2.resize(limb_sigma.transpose(1 ,2 ,0) , (self.HEAT_MAP_SIZE , self.HEAT_MAP_SIZE)).transpose(2,0,1).astype(np.float32)
ignore_mask = cv2.resize(ignore_mask , (self.HEAT_MAP_SIZE , self.HEAT_MAP_SIZE)).astype(np.float32)
scale_x = self.input_size/(x2-x1)
scale_y = self.input_size / (y2 - y1)
keypoint[:,0] *= scale_y
keypoint[:, 1] *= scale_x
img = normalize(img)
img = torch.from_numpy(img.astype(np.float32))
heat_map = torch.from_numpy(heat_map.astype(np.float32))
limb_sigma = torch.from_numpy(limb_sigma.astype(np.float32))
ignore_mask = torch.from_numpy(ignore_mask.astype(np.float32))
bbox = torch.from_numpy(bboxes[idx].reshape(-1,4).astype(np.float32))
return img , keypoint , bbox , heat_map , limb_sigma , ignore_mask
def _clean_annot(self,coco,split):
# 返回包含有效人体的图片index,包括清理一下垃圾的数据
#print('Filtering annotations for {}'.format(split))
person_ids = coco.getCatIds(catNms=['person'])
indices_tmp = sorted(coco.getImgIds(catIds=person_ids))
indices = np.zeros(len(indices_tmp))
valid_count = 0
for i in range(len(indices_tmp)):
anno_ids = coco.getAnnIds(indices_tmp[i])
annots = coco.loadAnns(anno_ids)
# Coco standard constants
annots = list(filter(lambda annot: check_annot(annot), annots))
if len(annots) > 0:
indices[valid_count] = indices_tmp[i]
valid_count += 1
indices = indices[:valid_count]
return indices
def __len__(self):
return len(self.indices)
def visualize_heatmap(img, heat_maps, displayname = 'heatmaps'):
heat_maps = heat_maps.max(axis=0)
heat_maps = (heat_maps/heat_maps.max() * 255.).astype('uint8')
heat_maps = cv2.resize(heat_maps, (img.shape[0] , img.shape[1]))
img = img.copy()
colored = cv2.applyColorMap(heat_maps, cv2.COLORMAP_JET)
#img = img*0.1+colored*0.8
img = img * 0.5 + colored * 0.5
#img = heat_maps
#img = cv2.addWeighted(img, 0.6, colored, 0.4, 0)
cv2.imshow(displayname, heat_maps)
cv2.waitKey()
def visualize_keypoints(img, keypoints, body_part_map):
img = img.copy()
keypoints = keypoints.astype('int32')
for i in range(keypoints.shape[0]):
x = keypoints[i, 0]
y = keypoints[i, 1]
if keypoints[i, 2] > 0:
cv2.circle(img, (x, y), 3, (0, 1, 0), -1)
for part in body_part_map:
keypoint_1 = keypoints[part[0]]
x_1 = keypoint_1[0]
y_1 = keypoint_1[1]
keypoint_2 = keypoints[part[1]]
x_2 = keypoint_2[0]
y_2 = keypoint_2[1]
if keypoint_1[2] > 0 and keypoint_2[2] > 0:
cv2.line(img, (x_1, y_1), (x_2, y_2), (1, 0, 0), 2)
cv2.imshow('keypoints', img)
cv2.waitKey()
if __name__ == '__main__':
import config as cfg
import time
data = COCOBBox(cfg)
while(True):
s = time.time()
idx = random.randint(1,100007)%30000
img , keypoints , bboxes , heat_maps , limb_sigma , ignore_mask = data.__getitem__(idx)
print(img.shape)
print(keypoints.shape)
print(bboxes.shape)
print(heat_maps.shape)
print(limb_sigma.shape)
e = time.time()
print('time :{}'.format(e - s))
img = denormalize(img.cpu().numpy())
visualize_keypoints(img, keypoints.reshape(18,3), BODY_PARTS)
#for i in range(17):
# heat = limb_sigma[i,:,:].cpu().numpy()
# heat = cv2.resize(heat , (img.shape[0] , img.shape[1]))
# cv2.imshow('234',heat*255)
# cv2.waitKey()
#visualize_keypoints(img, keypoints, BODY_PARTS)
visualize_heatmap(img, heat_maps.cpu().numpy())
visualize_heatmap(img, limb_sigma.cpu().numpy())
| [
"34938360+PuAnysh@users.noreply.github.com"
] | 34938360+PuAnysh@users.noreply.github.com |
d7113fb61d1221530d82a3c6c1499407ae4b16eb | f2e4235cf1f585983d9bfcde4b243be47f591931 | /python/turbodbc_test/test_data_types.py | eb1ecc9d322fe38babd51bdcea621513499ca960 | [
"MIT"
] | permissive | xhochy/turbodbc | 09e5d0a41fd5f366befd1c7f8f82ef5606c535d8 | 7f9c1ed9712212325acc0d09f01f37fda70689fa | refs/heads/master | 2021-01-12T09:44:45.149082 | 2016-12-02T10:32:51 | 2016-12-02T10:32:51 | 76,235,575 | 3 | 0 | null | 2016-12-12T08:10:26 | 2016-12-12T08:10:26 | null | UTF-8 | Python | false | false | 924 | py | import turbodbc.data_types
from turbodbc import STRING, BINARY, NUMBER, DATETIME, ROWID
ALL_TYPE_CODES = [turbodbc.data_types._BOOLEAN_CODE,
turbodbc.data_types._INTEGER_CODE,
turbodbc.data_types._FLOATING_POINT_CODE,
turbodbc.data_types._STRING_CODE,
turbodbc.data_types._TIMESTAMP_CODE,
turbodbc.data_types._DATE_CODE]
ALL_DATA_TYPES = [STRING, BINARY, NUMBER, DATETIME, ROWID]
def test_each_type_code_matches_one_data_type():
for type_code in ALL_TYPE_CODES:
matches = [type for type in ALL_DATA_TYPES if type_code == type]
assert 1 == len(matches)
def test_each_type_code_matches_all_but_one_data_type():
for type_code in ALL_TYPE_CODES:
mismatches = [type for type in ALL_DATA_TYPES if type_code != type]
expected = len(ALL_DATA_TYPES) - 1
assert expected == len(mismatches)
| [
"michael.koenig@blue-yonder.com"
] | michael.koenig@blue-yonder.com |
a3b9d0e4df5d91fa2810ce61bd6197ef16fe11f7 | 8b6d20bcfd8261e57f0e6a2e4ce663a1aaa80589 | /test/mpitest.py | 167074e90340b703f4f8b65a94310cb063277ff0 | [] | no_license | ulno/boxworld | 61b9c3b8232359d99ab7ca2c0526cf713f35f4c3 | d9a8dc75189af45150073ba13dd886179c71ca2c | refs/heads/master | 2020-04-17T08:22:53.782088 | 2011-10-11T08:47:38 | 2011-10-11T08:47:38 | 33,189,462 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 359 | py | #! /usr/bin/python
'''
Run as
$mpirun -np X mpitest.py
where X is any integer > 0
'''
from mpi4py import MPI
from boxworld.MpiChannel import MpiChannel
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
print "World size = %d" % comm.Get_size()
print "My rank = %d" % rank
channel = MpiChannel((rank + 1) % 2)
channel.send("foobar")
print channel.receive()
| [
"chris.willmore@yahoo.com@445e7b20-2786-1b12-35be-a1b6363c6c07"
] | chris.willmore@yahoo.com@445e7b20-2786-1b12-35be-a1b6363c6c07 |
a4751d4abd26f3fe4f502c5a17a59ff8645a749d | 26a41203694014098e96a7bdb38ef641439b68f2 | /machine-learning/adult-census-classification/scripts/common_classes.py | 680394b7bced4e882dcf1ca209e7bb04353050f6 | [
"Apache-2.0"
] | permissive | Kyledmw/student-projects | 42035d41cb4db04ef47e783d32424903436f5c8a | 766ef9d4b879c8c2d2086c2abe0fa224e2e051c6 | refs/heads/master | 2021-09-06T22:42:01.507696 | 2018-02-12T18:51:41 | 2018-02-12T18:51:41 | 100,615,064 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 238 | py | class DataFrameWrapper:
def __init__(self, data_frame, classification_col):
self.data_frame = data_frame
self.target = data_frame[classification_col]
self.data = data_frame.drop([classification_col], axis=1)
| [
"kyle.williamson@mycit.ie"
] | kyle.williamson@mycit.ie |
818274c60e5102029821cbe724453034b68eb740 | ebb06a29a99f6ae4f820321a4bc03f401cf307df | /File5.2 Threshold.py | c83c1ede18c1d186a566a3592e5352cc32df5576 | [] | no_license | ed-word/OpenCV | 0201351868bb83cefe7bdadfca6375f6a8394932 | 7484b3a518eefb4cebf0b7288e7ac5ba831b0efc | refs/heads/master | 2021-01-19T16:02:03.656923 | 2017-04-14T06:38:05 | 2017-04-14T06:38:05 | 88,239,550 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 298 | py | import cv2
import numpy as np
img = cv2.imread('bookpage.jpg')
grayscaled = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
retval, threshold = cv2.threshold(grayscaled, 10, 255, cv2.THRESH_BINARY)
cv2.imshow('original',img)
cv2.imshow('threshold',threshold)
cv2.waitKey(0)
cv2.destroyAllWindows()
| [
"noreply@github.com"
] | ed-word.noreply@github.com |
3d82aea556022fc260397c29a753c5ffa68f69ad | 815f70b6a6e1c58676de2def893baf4f70b0f72c | /apps/restapi/twee/serializers/tip.py | 54ce2848966860f92faa422cc2ccd5e4a37a538b | [
"MIT"
] | permissive | adepeter/pythondailytip | ed6e25578f84c985eea048f4bc711b411cdc4eff | 8b114b68d417e7631d139f1ee2267f6f0e061cdf | refs/heads/main | 2023-05-30T11:07:57.452009 | 2021-06-11T13:42:19 | 2021-06-11T13:42:19 | 375,838,410 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 303 | py | from rest_framework import serializers
from ....twee.models import PythonTip
class TipSerializer(serializers.ModelSerializer):
class Meta:
model = PythonTip
fields = '__all__'
extra_kwargs = {
'tip': {
'max_length': 140
}
}
| [
"adepeter26@gmail.com"
] | adepeter26@gmail.com |
6f5f72cfb9a38ad98b64f5045409d1e549053e0b | 1ad172412200d1d329f6ae4d9a15cb0c3552f3b8 | /test_cases/Order_query/OrderSearch_case.py | 3f5d4d418ccca6181c201e0c7e0e56d21e7d6996 | [] | no_license | RenAnt2020/MMC_Test | cb15682cba83b7e232fc3c67461052ac215e98c1 | 24ad8bc94a09213bdad95dc1b64cba714d26c86e | refs/heads/master | 2022-05-07T08:47:59.121063 | 2020-04-18T10:35:45 | 2020-04-18T10:35:45 | 255,606,000 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 651 | py | import os
import time
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from common import set_driver,config,login
class Orderquery_test(unittest.TestCase):
def setUp(self):
self.driver = set_driver.set_driver()
login.login(self.driver, config.username(), config.password()) #登录
def tearDown(self) -> None:
time.sleep(2)
self.driver.quit()
def test_query_success(self):
self.driver.find_element(By.XPATH,'//div/ul/div/li/ul/li[1]').click()
if __name__ == '__main__':
unittest.main()
| [
"rensh_sh@ushareit.com"
] | rensh_sh@ushareit.com |
3b2d5bc2538d9e0b0e3a1a82073383ceeb399786 | c22ecfb26d050859200a94dd5e7f621ae7b90f56 | /store/admin.py | f08f23bdac7811385c3dec719bb48887665c748c | [] | no_license | egyping/greatkart-django | 781d97ccdbf137608999d0c7c33bef6cdbd38063 | be7c55f5dc5f5ed0ea90bc0af94bb50cf6eec024 | refs/heads/main | 2023-04-28T17:45:35.187057 | 2021-05-05T14:10:09 | 2021-05-05T14:10:09 | 368,433,292 | 1 | 0 | null | 2021-05-18T07:05:53 | 2021-05-18T07:05:52 | null | UTF-8 | Python | false | false | 580 | py | from django.contrib import admin
from .models import Product,Variation
class ProductAdmin(admin.ModelAdmin):
list_display = ('product_name', 'stock', 'category', 'modified_date', 'is_available')
prepopulated_fields = {'slug': ('product_name',)}
class VariationAdmin(admin.ModelAdmin):
list_display = ('product', 'variation_category', 'variation_value', 'is_active')
list_editable = ('is_active',)
list_filter = ('product', 'variation_category', 'variation_value')
admin.site.register(Product, ProductAdmin)
admin.site.register(Variation, VariationAdmin)
| [
"tniketsuryabhan40@gmail.com"
] | tniketsuryabhan40@gmail.com |
692efcfd69ad0780a0063b2fb0230e9fe0e34af1 | 5d434b255037add0268f73914cf3fa7e63f3a320 | /orchestra/migrations/0041_alter_payrate_fields.py | 63fb69bd571e21fa3cd4c5f67cdbd8e47ed20e1c | [
"Apache-2.0",
"CC-BY-3.0"
] | permissive | ksbek/orchestra | 781c7cc599ca85c347772a241330c7261203d25b | 07556717feb57efcf8fb29a1e2e98eebe2313b8c | refs/heads/master | 2021-01-01T18:52:43.068533 | 2017-07-19T18:45:19 | 2017-07-19T18:45:19 | 98,458,290 | 0 | 1 | null | 2017-07-26T19:24:48 | 2017-07-26T19:24:48 | null | UTF-8 | Python | false | false | 979 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-19 20:39
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('orchestra', '0040_timeentry_created_at'),
]
operations = [
migrations.AlterField(
model_name='payrate',
name='end_datetime',
field=models.DateField(blank=True, null=True),
),
migrations.AlterField(
model_name='payrate',
name='start_datetime',
field=models.DateField(default=django.utils.timezone.now),
),
migrations.RenameField(
model_name='payrate',
old_name='end_datetime',
new_name='end_date',
),
migrations.RenameField(
model_name='payrate',
old_name='start_datetime',
new_name='start_date',
),
]
| [
"zhenya.gu@gmail.com"
] | zhenya.gu@gmail.com |
05e4769270b3841f5e381d31587a16fbd8d3d651 | ddd766ad2c618fe5029e8f3513cc2d118ebab297 | /自动化第二周/函数_02.py | 61a7b912c5abc3b1345b0fcb94cd3cf13e4ef5b2 | [] | no_license | zouzhuwen/PycharmProject | 12aa44c5c2774b603cae3e03182404d1007e7879 | 99b2da6469f086e60d17a080e42f465ae3c3148f | refs/heads/master | 2023-04-02T04:49:19.764297 | 2021-04-01T14:41:01 | 2021-04-01T14:41:01 | 353,390,874 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 643 | py | #2.写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作
import os
f_name = 'f_name'
f_new_name = 'f_new_name'
old_str = '2'
new_str = '*'
f = open(f_name, 'r', encoding='utf-8')
f_new = open(f_new_name, 'w', encoding='utf-8')
for line in f:
if old_str in line:#读取每一行内容 查看old_str是否在当前内容中
new_line = line.replace(old_str, new_str)#将就字符串替换成新字符串
f_new.writelines(new_line)
else:
new_line = line
f_new.write(new_line)
f.close()
f_new.close()
#os.replace(f_new_name, f_name)
| [
"13543418221@163.com"
] | 13543418221@163.com |
fffb4050755f90b92c1d70fa81a6436320201dab | 74bc5d0205d96e1c97baca9daa4119d26d5c6c7c | /tictactoe.py | a2a8f3629866ae79ed09a15f597454a895ea88c0 | [] | no_license | Malidrisi/Tic-Tac-Toe | 44caa3b18f50b47c881dcc3d8a44c6374789e3a6 | e2042e82c2cd0c192b95f8fe196c57b51c726abb | refs/heads/master | 2021-09-05T14:36:10.354944 | 2018-01-28T23:09:51 | 2018-01-28T23:09:51 | 119,305,803 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,508 | py | # -*- coding: utf-8 -*-
#Author:Maha Alidrisi
import random
import numpy as np
from prettytable import PrettyTable
class TicTactoe:
def __init__(self, n):
"""create a board of X's and O's of given size n"""
self.board = np.random.choice(a=['X', 'O'], size=(n, n))
def scan_lines(self, lines):
"""returns the winner of the first occurance or no winner """
for line in lines:
if all(i == 'X' for i in line):
return 'The winner is: X'
elif all(i == 'O' for i in line):
return 'The winner is: O'
return 'No winner'
def get_the_winner(self):
"""returns the winner by scaning rows, columns, left and right digonal - in order - """
winner = self.scan_lines(self.board) #sending the rows to scan_lines
if winner == 'No winner':
winner = self.scan_lines(self.board.T) #sending the columns to scan_lines
if winner == 'No winner':
winner = self.scan_lines([np.diagonal(self.board), np.diag(np.fliplr(self.board))]) #sending the left and right digonal to scan_lines
return winner
def __str__(self):
"""returns the board as a string"""
pt = PrettyTable()
for row in self.board:
pt.add_row(row)
return str(pt.get_string(header=False, border=False))
def main():
t = TicTactoe(4)
print(t)
print('\n', t.get_the_winner(), '\n')
if __name__ == '__main__':
main()
| [
"noreply@github.com"
] | Malidrisi.noreply@github.com |
e7f4cc1a6a2cad26cc4bdadff3dd2dcffbc159a3 | da1ecce9a364a6fb9b70f1d62d2e3e896a800823 | /src/old_version/src/TextClassifier/business_logic/w2v_helper.py | 631cb81f3c07642b1f9e9f6b3d4663edd13c8159 | [] | no_license | Carried-by-Compiler/Text-Classification-Using-Neural-Networks | da6cd984039929404d946eeeb21cfeda9c44dcf5 | 171ceba986405565a9468decd8e3c48832c746f6 | refs/heads/master | 2022-01-15T06:17:35.822579 | 2019-06-06T18:35:29 | 2019-06-06T18:35:29 | 148,683,600 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 442 | py | from os import listdir, path
from gensim.utils import simple_preprocess
class Word2VecHelper:
def __init__(self):
self.__file_path = ""
def __iter__(self):
files = listdir(self.__file_path)
for file in files:
for line in open(path.join(self.__file_path, file), "r", encoding="utf-8"):
yield simple_preprocess(line)
def set_path(self, p: str):
self.__file_path = p
| [
"15167798@studentmail.ul.ie"
] | 15167798@studentmail.ul.ie |
c38cccf1ff61bbe5a597c326d2cabdb66a7189be | dff51e4a3bbcc464c0069a16f1394d36c31e2372 | /omaha_server/omaha/migrations/0032_auto_20170918_0418.py | 527d8d1fe68e6985f5c4df58504a44075d93c4de | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | tuladhar/omaha-server | 3264de057221322038c7af704ea268c9e267d7da | 6cfd86e4319e03af0eb319fae6c867691ffc2c36 | refs/heads/master | 2022-11-21T19:38:50.335963 | 2020-06-09T14:14:03 | 2020-06-09T14:14:03 | 281,736,223 | 1 | 0 | NOASSERTION | 2020-07-22T17:02:48 | 2020-07-22T17:02:47 | null | UTF-8 | Python | false | false | 597 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2017-09-18 04:18
from __future__ import unicode_literals
import django.core.files.storage
from django.db import migrations, models
import omaha.models
class Migration(migrations.Migration):
dependencies = [
('omaha', '0031_platform_verbose_name'),
]
operations = [
migrations.AlterField(
model_name='version',
name='file',
field=models.FileField(null=True, storage=django.core.files.storage.FileSystemStorage(), upload_to=omaha.models._version_upload_to),
),
]
| [
"anmekin@gmail.com"
] | anmekin@gmail.com |
6f8c5602cdedb6aeec199294867b756d7b4aef58 | 372647ad5f8a40754116c2b79914708e46960aef | /ivi/agilent/agilentMSOX3024A.py | 612461f32a85d96ab8c7187f5deb332e6e19ab84 | [
"MIT"
] | permissive | edupo/python-ivi | 52392decb01bc89c6e1b42cbcbd1295a131e91f5 | 8105d8064503725dde781f0378d75db58defaecb | refs/heads/master | 2020-03-31T21:06:02.059885 | 2018-10-04T12:34:38 | 2018-10-04T12:34:38 | 152,567,486 | 0 | 0 | MIT | 2018-10-11T09:40:35 | 2018-10-11T09:40:32 | Python | UTF-8 | Python | false | false | 1,695 | py | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from .agilent3000A import *
class agilentMSOX3024A(agilent3000A):
"Agilent InfiniiVision MSOX3024A IVI oscilloscope driver"
def __init__(self, *args, **kwargs):
self.__dict__.setdefault('_instrument_id', 'MSO-X 3024A')
super(agilentMSOX3024A, self).__init__(*args, **kwargs)
self._analog_channel_count = 4
self._digital_channel_count = 16
self._channel_count = self._analog_channel_count + self._digital_channel_count
self._bandwidth = 200e6
self._init_channels()
| [
"alex@alexforencich.com"
] | alex@alexforencich.com |
2576b89ff2ae1242fbaefbd20eb4c1e8edd6d6d0 | fdf5afd24ad58068589a3d5947b7b5c958509ef9 | /spo-final/spo-final/purchaseorder/views.py | 46b24f2906369c55691938283cb7f8a3ed789e47 | [] | no_license | mpruitt441/Secure-Purchase-Order | 48a656e8748ae3d6be9c6a641e26100413e8ac2f | ae7b71753cdc2fca190b3a900cfe481b4565f4e4 | refs/heads/master | 2021-05-23T14:23:37.481853 | 2020-04-05T21:42:26 | 2020-04-05T21:42:26 | 253,337,165 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,311 | py | from django.shortcuts import render
from .models import order
from django.contrib.auth.mixins import UserPassesTestMixin
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from datetime import datetime
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from pathlib import Path
# Create your views here.
def home(response):
context = {
'orders': order.objects.all()
}
return render(response, 'purchaseorder/home.html', context)
def about(response):
return render(response, 'purchaseorder/about.html',{'title': 'About'})
class orderListView(ListView):
model = order
template_name = 'purchaseorder/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'orders'
ordering = ['-date_ordered']
class orderDetailView(UserPassesTestMixin,DetailView):
model = order
def test_func(self):
order = self.get_object()
if self.request.user == order.author:
return True
elif self.request.user.is_supervisor:
return True
elif self.request.user.is_purchasing:
return True
else:
return False
class orderCreateView(CreateView):
model = order
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class orderUpdateView(UserPassesTestMixin, UpdateView):
model = order
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
order = self.get_object()
if self.request.user == order.author:
return True
elif self.request.user.is_supervisor:
return True
elif self.request.user.is_purchasing:
return True
else:
return False
class orderDeleteView(UserPassesTestMixin, DeleteView):
model = order
success_url = '/'
def test_func(self):
order = self.get_object()
if self.request.user == order.author:
return True
elif self.request.user.is_supervisor:
return True
elif self.request.user.is_purchasing:
return True
else:
return False
class orderApproveView(UserPassesTestMixin, DetailView):
model = order
#model.approve()
def test_func(self):
order = self.get_object()
if self.request.user == order.author:
return False
elif self.request.user.is_supervisor and not order.approved:
# set status to signed
order.approved = True
order.dateApproved = datetime.now().strftime("%m/%d/%Y %H:%M:%S")
order.approvedBy = str(self.request.user.username)
# create a signature to verify the signing
key = RSA.importKey(open('supervisor.pem').read())
h = SHA256.new(order.content)
signer = PKCS1_v1_5.new(key)
order.signedSupervisor = signer.sign(h)
#save changes
order.save(update_fields=['approved','dateApproved','approvedBy', 'signedSupervisor'])
return True
else:
return False
class orderPurchaseView(UserPassesTestMixin, DetailView):
model = order
def test_func(self):
order = self.get_object()
if self.request.user == order.author:
return False
elif self.request.user.is_purchasing and not order.purchased:
# Set signed status
order.purchased = True
order.datePurchased = datetime.now().strftime("%m/%d/%Y %H:%M:%S")
order.purchasedBy = str(self.request.user.username)
# create a signature to verify the signing
key = RSA.importKey(open('purchasing.pem').read())
h = SHA256.new(order.content)
signer = PKCS1_v1_5.new(key)
order.signedPurchase = signer.sign(h)
#save changes, django convention
order.save(update_fields=['purchased','datePurchased', 'purchasedBy', 'signedPurchase'])
return True
else:
return False
| [
"mpruitt441@gmail.com"
] | mpruitt441@gmail.com |
ef082f9bb3bf1cae4397163bfce43ab59d77dfac | 90e6860b5370b742f01c0664ac84f14dc1272155 | /examples/helloZiggurat/src/ziggHello/models/zigguratTest/ZigguratTestBase.py | 6f82ebfb51611a2d85ce9a0b6f6c0667be506880 | [] | no_license | sernst/Ziggurat | e63f876b8f2cb3f78c7a7a4dcf79af810a540722 | 4ae09bbd9c467b2ad740e117ed00354c04951e22 | refs/heads/master | 2021-01-17T07:20:17.138440 | 2016-05-27T14:27:43 | 2016-05-27T14:27:43 | 9,278,283 | 6 | 1 | null | null | null | null | UTF-8 | Python | false | false | 530 | py | # ZigguratTestBase.py
# (C)2013
# Scott Ernst
from ziggurat.sqlalchemy.ZigguratModelsBase import ZigguratModelsBase
#___________________________________________________________________________________________________ ZigguratTestBase
class ZigguratTestBase(ZigguratModelsBase):
"""A class for..."""
#===================================================================================================
# C L A S S
__abstract__ = True
| [
"swernst@gmail.com"
] | swernst@gmail.com |
8388f8030a73aadaee38927b0b428af3eca40429 | 4713416e5ba6dde475ad5cc6df45a9e1ffbe55c6 | /model/plotter.py | 880405ad3898d2720a11b7d1c126f66de561e64a | [] | no_license | NicklasLallo/AnimatMath | 1fd2e6e48998f51e9eaa3925558b54c40988e988 | af982df71d51c52c5beefcfa6121e8970c736eff | refs/heads/master | 2021-09-14T23:47:41.063118 | 2018-05-22T13:59:05 | 2018-05-22T13:59:05 | 120,452,851 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,696 | py | import matplotlib.pyplot as plt
import math
import numpy as np
def plot(xs, ys, xaxis = [0, 100], yaxis = [0, 100], title = "", xlabel = "", ylabel = "", figname = "untitled"):
plt.clf()
plt.plot(xs, ys)
plt.axis(xaxis+yaxis) #([0,int(training_iters/display_step),0,100])
#xLabels = range(0,training_iters+display_step, display_step)
#xTLabels = [""]*int(training_iters/display_step+1)
#for x in range(int(training_iters/display_step)+1):
# if x % 20 == 0: #How often we want the label written
# xTLabels[x] = str(xLabels[x])
# else:
# xTLabels[x] = ""
#xnums = map(str, np.linspace(xaxis[0], xaxis[1], xticks))
#ynums = map(str, np.linspace(yaxis[0], yaxis[1], yticks))
#plt.xticks(range(int(training_iters/display_step)+1),xTLabels)
#plt.xticks(range(xticks), xnums)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
plt.title(title)
plt.grid(True)
plt.savefig(figname)
def improvedPlot(xs, ys, title = "", xlabel = "", ylabel = "", figname = "untitled"):
xaxis = [min(xs)*0.95,max(xs)*1.05]
yaxis = [min(ys)*0.95,max(ys)*1.05]
plot(xs, ys, xaxis, yaxis, title, xlabel, ylabel, figname)
def errplot(xs, ys, xerrs = None, yerrs = None, xaxis = [0, 100], yaxis = [0, 100], title = "", xlabel = "", ylabel = "", figname = "untitled"):
plt.clf()
#plt.errorbar(xs,ys,xerrs,yerrs,fmt = "none")
plt.plot(xs, ys)
if yerrs != None:
for ys2 in yerrs:
plt.plot(xs,ys2, color = "orange")
plt.axis(xaxis+yaxis) #([0,int(training_iters/display_step),0,100])
#xLabels = range(0,training_iters+display_step, display_step)
#xTLabels = [""]*int(training_iters/display_step+1)
#for x in range(int(training_iters/display_step)+1):
# if x % 20 == 0: #How often we want the label written
# xTLabels[x] = str(xLabels[x])
# else:
# xTLabels[x] = ""
#xnums = map(str, np.linspace(xaxis[0], xaxis[1], xticks))
#ynums = map(str, np.linspace(yaxis[0], yaxis[1], yticks))
#plt.xticks(range(int(training_iters/display_step)+1),xTLabels)
#plt.xticks(range(xticks), xnums)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
plt.title(title)
plt.grid(True)
plt.savefig(figname)
def improvedErrplot(xs, ys, xerrs = None, yerrs = None, title = "", xlabel = "", ylabel = "", figname = "untitled"):
xaxis = [min(xs)*0.95,max(xs)*1.05]
yaxis = [min(yerrs[1])*0.95,max(yerrs[0])*1.05]
errplot(xs, ys, xerrs, yerrs, xaxis, yaxis, title, xlabel, ylabel, figname)
#improvedPlot(range(0, 3000000000,10000000), list(map(math.sin, range(0,3000000000, 10000000))))
| [
"guspih@student.chalmers.se"
] | guspih@student.chalmers.se |
98de90d7168cb6b55b4790469f058e69491e8651 | 6e8b2b1141c21558f96a5f47c94f9999bf9c48ec | /01_celeb_base/utils/imgs.py | 99e8bd2390735839479908f9c920b7ec56ae81ac | [] | no_license | DigitalNegatives/DataScience-Celebrity_Image_Classification | 6eba11dc8a1a473c139727cc9e4f933b3c8d3c4e | 38363626f86a939e7e5fda093bcc9a6cd85764d5 | refs/heads/master | 2021-01-20T08:08:03.949579 | 2017-07-07T14:29:10 | 2017-07-07T14:29:10 | 90,104,625 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,851 | py | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.animation as animation
# Taken from lab3
def montage(images, saveto='montage.png'):
"""Draw all images as a montage separated by 1 pixel borders.
Also saves the file to the destination specified by `saveto`.
Parameters
----------
images : numpy.ndarray
Input array to create montage of. Array should be:
batch x height x width x channels.
saveto : str
Location to save the resulting montage image.
Returns
-------
m : numpy.ndarray
Montage image.
"""
if isinstance(images, list):
images = np.array(images)
img_h = images.shape[1]
img_w = images.shape[2]
n_plots = int(np.ceil(np.sqrt(images.shape[0])))
if len(images.shape) == 4 and images.shape[3] == 3:
m = np.ones(
(images.shape[1] * n_plots + n_plots + 1,
images.shape[2] * n_plots + n_plots + 1, 3)) * 0.5
else:
m = np.ones(
(images.shape[1] * n_plots + n_plots + 1,
images.shape[2] * n_plots + n_plots + 1)) * 0.5
for i in range(n_plots):
for j in range(n_plots):
this_filter = i * n_plots + j
if this_filter < images.shape[0]:
this_img = images[this_filter]
m[1 + i + i * img_h:1 + i + (i + 1) * img_h,
1 + j + j * img_w:1 + j + (j + 1) * img_w] = this_img
plt.imsave(arr=m, fname=saveto)
return m
def imcrop_tosquare(img):
"""Make any image a square image.
Parameters
----------
img : np.ndarray
Input image to crop, assumed at least 2d.
Returns
-------
crop : np.ndarray
Cropped image.
"""
size = np.min(img.shape[:2])
extra = img.shape[:2] - size
crop = img
for i in np.flatnonzero(extra):
crop = np.take(crop, extra[i] // 2 + np.r_[:size], axis=i)
return crop
# UNTESTED in the utils file
def build_gif(imgs, interval=0.1, dpi=72,
save_gif=True, saveto='animation.gif',
show_gif=False, cmap=None):
"""Take an array or list of images and create a GIF.
Parameters
----------
imgs : np.ndarray or list
List of images to create a GIF of
interval : float, optional
Spacing in seconds between successive images.
dpi : int, optional
Dots per inch.
save_gif : bool, optional
Whether or not to save the GIF.
saveto : str, optional
Filename of GIF to save.
show_gif : bool, optional
Whether or not to render the GIF using plt.
cmap : None, optional
Optional colormap to apply to the images.
Returns
-------
ani : matplotlib.animation.ArtistAnimation
The artist animation from matplotlib. Likely not useful.
"""
imgs = np.asarray(imgs)
h, w, *c = imgs[0].shape
fig, ax = plt.subplots(figsize=(np.round(w / dpi), np.round(h/dpi)))
fig.subplots_adjust(bottom=0)
fig.subplots_adjust(top=1)
fig.subplots_adjust(right=1)
fig.subplots_adjust(left=0)
ax.set_axis_off()
if cmap is not None:
axs = list(map(lambda x: [ax.imshow(x, cmap=cmap)], imgs))
else:
axs = list(map(lambda x: [ax.imshow(x)], imgs))
ani = animation.ArtistAnimation(fig, axs, interval=interval*1000,
repeat_delay=0, blit=False)
if save_gif:
ani.save(saveto, writer='imagemagick', dpi=dpi)
if show_gif:
plt.show()
return ani
def montage_filters(W):
"""Draws all filters (n_input * n_output filters) as a
montage image separated by 1 pixel borders.
Parameters
----------
W : Tensor
Input tensor to create montage of.
Returns
-------
m : numpy.ndarray
Montage image.
"""
W = np.reshape(W, [W.shape[0], W.shape[1], 1, W.shape[2] * W.shape[3]])
n_plots = int(np.ceil(np.sqrt(W.shape[-1])))
m = np.ones(
(W.shape[0] * n_plots + n_plots + 1,
W.shape[1] * n_plots + n_plots + 1)) * 0.5
for i in range(n_plots):
for j in range(n_plots):
this_filter = i * n_plots + j
if this_filter < W.shape[-1]:
m[1 + i + i * W.shape[0]:1 + i + (i + 1) * W.shape[0],
1 + j + j * W.shape[1]:1 + j + (j + 1) * W.shape[1]] = (
np.squeeze(W[:, :, :, this_filter]))
return m
####
# Functions to normalise and denormalise images from Dataset:
####
def normalization(img, ds):
norm_img = (img - ds.mean()) / ds.std()
return norm_img
def denormalization(norm_img, ds):
img = norm_img * ds.std() + ds.mean()
return img
import cv2
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.misc import imread
from skimage.transform import resize
from utils.imgs import *
from utils.celeb import *
def qualify_crop(entity, images_list, data_dir, img_dims):
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
face_images = []
entity_list = []
num_face = 0
num_eyes = 0
num_qual = 0
#entity = df.entities[0]
# images_list = os.listdir(data_dir + '/' + entity)
#print(entity)
for image in images_list:
#print(image)
image_name = data_dir + '/' + entity + '/' + image
#print(image_name)
img = cv2.imread(image_name)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_c = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
if len(faces) <= 1:
for (x,y,w,h) in faces:
roi_gray = gray[y:y+h, x:x+w]
#roi_color = img_c[y:y+h, x:x+w]
num_face = num_face + 1
eyes = eye_cascade.detectMultiScale(roi_gray)
if (len(eyes) != 2):
continue
ex1,ey1,ew1,eh1 = eyes[0]
ex2,ey2,ew2,eh2 = eyes[1]
if np.abs( ey1 - ey2 ) > eh1 or np.abs( ex1 - ex2 ) < (ew1/2):
continue
num_eyes+=1
new_img = img_c.copy()
x,y,w,h = faces[0]
border = 0
new_img = cv2.resize(new_img[y-border:y+h-1+border, x-border:x+w-1+border],
(img_dims, img_dims), interpolation = cv2.INTER_CUBIC)
#crop_converted = crop_img
face_images.append( new_img )
entity_list.append( image )
print("face", num_face)
print("eyes", num_eyes)
return face_images, entity_list
| [
"Anton@ANTONs-MacBook-Pro.local"
] | Anton@ANTONs-MacBook-Pro.local |
181bea7d54fb0745488710e8786442854b224d20 | 0894f07a04ddaafd8ddec7f3fb6fdfdf03751c4f | /Week 4/Assignment 4/Lab_03_skeleton.py | fa28dd3e56a853256521ede22b88267eae1af077 | [] | no_license | tanyhb1/YSC2221-Intro-To-Python | f66a7fac1344610a3c69a6a5a55e1396c6d9f594 | 20168b85124bff73dff5e308ae2556831110b089 | refs/heads/master | 2020-04-12T14:44:33.937075 | 2019-01-11T10:04:40 | 2019-01-11T10:04:40 | 162,560,121 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,354 | py | '''
Full Name: TAN YAO HONG, BRYAN
Matric No.: A0171585X
Email: bryantanyh@u.yale-nus.edu.sg
'''
# Complete Q1 below
def describe_data(L):
for item in L:
print("The type of the element " + str(item) + " is " + str(type(item)))
# Complete Q2 below
# Remember NOT to use the "count" function!
# No need to be 'deep'
def count(L,x):
counter = 0
for item in L:
if item == x:
counter += 1
return(counter)
# Complete Q3 below
# Remember NOT to use the "sort" function!
def largest_three(L):
if len(L) < 3:
print('Please insert a list with three or more elements.')
else:
stor = [0,0,0]
for i in range(2, -1, -1):
stor[i] = max(L)
L.remove(max(L))
return(tuple(stor))
import matplotlib.pyplot as plt
original_wave_sample = [0, 3, 7, 14, 18, 24, 23, 29, 28, 30, 32, 35, 31, 34, 32, 30, 25, 25, 24, 23, 18, 14, 15, 14, 12, 12, 7, 8, 10, 9, 5, 8, 8, 8, 8, 5, 6, 4, 2, 2, 3, -1, -5, -4, -9, -9, -14, -16, -17, -18, -23, -24, -25, -25, -23, -20, -20, -16, -17, -11, -7, -7, 0, 3, 6, 8, 15, 18, 19, 24, 27, 24, 28, 25, 29, 27, 26, 22, 20, 16, 13, 13, 11, 7, 4, 0, 0, 0, 0, -3, -6, -6, -7, -6, -5, -7, -6, -6, -6, -6, -7, -9, -13, -11, -17, -16, -22, -24, -23, -27, -29, -30, -34, -33, -34, -37, -34, -32, -33, -28, -28, -23, -18, -13, -10, -8, 0, 3, 10, 12, 15, 22, 22, 27, 29, 31, 31, 29, 31, 27, 26, 27, 24, 20, 17, 17, 14, 11, 12, 8, 6, 5, 8, 6, 3, 6, 7, 4, 7, 6, 7, 6, 5, 4, 2, 0, -2, -3, -6, -7, -12, -14, -16, -15, -18, -21, -22, -23, -26, -26, -22, -23, -21, -18, -13, -9, -8, -3, -1, 6, 10, 12, 17, 20, 23, 25, 28, 30, 30, 30, 27, 25, 26, 24, 19, 18, 17, 12, 12, 8, 7, 4, 0, -2, -2, -1, -1, -6, -4, -4, -3, -5, -7, -8, -5, -5, -7, -10, -10, -12, -17, -17, -22, -21, -25, -29, -29, -32, -35, -34, -32, -33, -33, -33, -33, -28, -24, -22, -18, -15, -9, -6, 0, 6, 9, 11, 16, 22, 22, 24, 25, 29, 30, 31, 28, 29, 27, 22, 22, 20, 16, 17, 15, 14, 10, 10, 6, 8, 4, 4, 7, 4, 7, 7, 6, 6, 3, 7, 2, 2, 4, 1, 0, -2, -3, -7, -8, -13, -14, -16]
t = [i for i in range(len(original_wave_sample))]
''' Uncomment next 2 lines to show plot '''
#plt.plot(t,original_wave_sample)
#plt.show()
# Question 4
def detect_noise(wave):
signal_noise, gap_noise = [], []
for i in range(0, len(wave)):
if wave[i] > 34 or wave[i] < -34:
signal_noise.append((i, wave[i]))
for i in range(1, len(wave)-1):
if abs(wave[i] - wave[i+1]) > 6:
gap_noise.append((i, i+1, wave[i], wave[i+1]))
if signal_noise or gap_noise:
print("Noise(s) detected!")
for item in signal_noise:
print("Signal out of bound at position " + str(item[0]) + " with value " + str(item[1]))
for item in gap_noise:
print("The gap is too big between the positions at " + str(item[0]) + " and " + str(item[1]) + ' with values ' + str(item[2]) + ' , ' + str(item[3]))
else:
print("No noise detected!")
# Question 5
def repair_signal(wave):
#include first element of wave into new_sig_l
new_sig_l = [wave[0]]
for i in range(1, len(wave)-1):
if wave[i] > 34 or wave[i] < -34:
new_sig = (wave[i-1] + wave[i+1])/2
new_sig_l.append(new_sig)
elif abs(wave[i] - wave[i+1]) > 6:
new_sig = (wave[i-1] + wave[i+1])/2
new_sig_l.append(new_sig)
else:
new_sig_l.append(wave[i])
#include last element of wave into new_sig_l since the for-loop excludes it
new_sig_l.append(wave[len(wave)-1])
return(new_sig_l)
''' TESTING '''
print('Detecting noise in the original signal')
detect_noise(original_wave_sample)
new_signal = repair_signal(original_wave_sample)
print()
print('Detecting noise in the repaired signal')
detect_noise(new_signal)
print()
print('Detecting noise in the original signal again')
detect_noise(original_wave_sample)
'''Testing for other questions
if __name__ == '__main__':
input_list = [3.145, True, 42, '88', (1,3)]
describe_data(input_list)
A, B = [5,2,1,'5',9,5,True], [1,(5,3),True]
print(count(A, 5))
print(count(B, 5))
a,b,c = largest_three([9,8,7,6,5,4,3,2,1]), largest_three([1,2,3]), largest_three([-1,-2,-3,-4])
print(a,b,c)
'''
| [
"bryantanyh@gmail.com"
] | bryantanyh@gmail.com |
ce6ba4e14a0939871961f34fbb9541e478074c53 | 623cf714ea1046ccefa3978946be4341a4f5a8eb | /chapter6/6-5.py | 6345a93f5c988472ececa8230fb426f587311b35 | [] | no_license | Layla7120/think_python | a93358d9c02ca3dba57c1107fafa305db2b64690 | 102bed3f6085c368b00e9244415b86ca49780387 | refs/heads/main | 2023-03-10T22:27:22.554731 | 2021-03-01T11:26:46 | 2021-03-01T11:26:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 155 | py | def gcd(a,b):
if b == 0:
return a
else:
r = a % b
return gcd(b, r)
print(gcd(10, 3))
print(gcd(16, 32))
print(gcd(42,49)) | [
"jenny7120@naver.com"
] | jenny7120@naver.com |
e3c099ce14720d63eda95a3524e002822cfee87f | 2417cdceb80e884ebc997c00a4203202e1e4bfe6 | /src/202.happy-number/202.happy-number.py | fb3333b1d8d791433ee60317f2a2768c98c93418 | [
"MIT"
] | permissive | AnestLarry/LeetCodeAnswer | 20a7aa78d1aaaa9b20a7149a72725889d0447017 | f15d1f8435cf7b6c7746b42139225e5102a2e401 | refs/heads/master | 2023-06-23T07:20:44.839587 | 2023-06-15T14:47:46 | 2023-06-15T14:47:46 | 191,561,490 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,194 | py | #
# @lc app=leetcode id=202 lang=python3
#
# [202] Happy Number
#
# Write an algorithm to determine if a number is "happy".
# A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
# Example:
# Input: 19
# Output: true
# Explanation:
# 12 + 92 = 82
# 82 + 22 = 68
# 62 + 82 = 100
# 12 + 02 + 02 = 1
class Solution:
def isHappy(self, n: int) -> bool:
# Accepted
# 401/401 cases passed (32 ms)
# Your runtime beats 99.46 % of python3 submissions
# Your memory usage beats 76.66 % of python3 submissions (13.6 MB)
repeat = set()
repeat.add(n)
while n != 1:
nn = 0
while n > 0:
d = n % 10
nn += d * d
n = int(n / 10)
if nn in repeat:
return False
else:
repeat.add(nn)
n = nn
return True
| [
"anest@66ws.cc"
] | anest@66ws.cc |
e6d7612b2e6c8dcd4672e16d3ccc956d5f5c52d4 | 5f254feaaaccf72f888ee732c8251ebbecd31c0e | /posts/models.py | f83a03eaad4d678cd99edbd81c996c10bc3796f3 | [] | no_license | Iki-oops/hw04_tests | e8e6bbac024564dc8bdf9689ee2f573f674b4376 | 76d9ca64a9373922b52d20f84f0ae200e74a1a2b | refs/heads/master | 2023-07-07T01:53:54.899812 | 2021-03-13T13:03:01 | 2021-03-13T13:03:01 | 338,635,085 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,578 | py | from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Group(models.Model):
title = models.CharField(max_length=200, verbose_name='Оглавление',
help_text='Оглавление группы')
slug = models.SlugField(unique=True, verbose_name='URL',
help_text='URL для группы')
description = models.TextField(verbose_name='Описание',
help_text='Описание группы')
class Meta:
verbose_name_plural = 'Сообщества'
verbose_name = 'Сообщество'
def __str__(self):
return self.title
class Post(models.Model):
text = models.TextField(verbose_name='Текст',
help_text='Текст поста')
pub_date = models.DateTimeField('date published', auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE,
verbose_name='Автор', related_name='posts',
help_text='Автор поста')
group = models.ForeignKey(Group, on_delete=models.SET_NULL, blank=True,
verbose_name='Группа', related_name='posts',
null=True, help_text='Ссылка на группу')
class Meta:
ordering = ['-pub_date']
verbose_name_plural = 'Посты'
verbose_name = 'Пост'
def __str__(self):
return self.text[:15]
| [
"bambagaevdmitrij@gmail.com"
] | bambagaevdmitrij@gmail.com |
99b79165de6a81ea03820f1e6b825469ff8e643b | 85e007823fa2dbfb3791550ec99840df3087df7f | /PCソ・jungsanbot_PC.py | 93906a5578ebe3874a3012bd5fd6da0304641f43 | [
"MIT",
"Apache-2.0"
] | permissive | sikote/item | c41cce448b3b429e6d91a59c6939b9796d12f37f | 0950557435656916b445ea9d05f2d8c218f86289 | refs/heads/main | 2023-06-05T12:47:39.546683 | 2021-06-30T12:45:22 | 2021-06-30T12:45:22 | 381,698,703 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 252,196 | py | # -*- coding: utf-8 -*-
##################################### PC V16 #############################################
#########################################################################################
#########################################################################################
#########################################################################################
###### 개발환경 : python 3.7.3 ######
###### discord = 1.0.1 ######
###### discord.py = 1.6.0 ######
###### 모듈설치 : pip install setuptools --upgrade ######
###### pip install discord ######
###### pip install discord.py[voice] ######
###### pip install pyinstaller ######
###### pip install pymongo ######
###### pip install pandas ######
###### pip install openpyxl ######
###### pip install discord-components ######
#########################################################################################
#########################################################################################
#########################################################################################
import os
import sys
import asyncio
import discord
import datetime, copy
import logging
from discord.ext import tasks, commands
from discord.ext.commands import CommandNotFound, MissingRequiredArgument
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
from io import StringIO
import aiohttp
from pymongo import MongoClient
import pymongo, ssl, traceback, random
import pandas as pd
log_stream = StringIO()
logging.basicConfig(stream=log_stream, level=logging.WARNING)
##################### 로깅 ###########################
#ilsanglog = logging.getLogger('discord')
#ilsanglog.setLevel(level = logging.WARNING)
#handler = logging.FileHandler(filename = 'discord.log', encoding='utf-8',mode='a')
#handler.setFormatter(logging.Formatter('%(asctime)s: %(levelname)s: %(name)s: %(message)s'))
#ilsanglog.addHandler(handler)
#####################################################
def init():
global commandSetting
global basicSetting
basicSetting = []
commandSetting = []
fc = []
inidata = open('test_setting.ini', 'r', encoding = 'utf-8')
inputData = inidata.readlines()
commanddata = open('command.ini', 'r', encoding = 'utf-8')
commandData = commanddata.readlines()
for i in range(inputData.count('\n')):
inputData.remove('\n')
for i in range(commandData.count('\n')):
commandData.remove('\n')
del(commandData[0])
############## 분배봇 초기 설정 리스트 #####################
for i in range(len(inputData)):
basicSetting.append(inputData[i][(inputData[i].find("="))+2:].rstrip('\n'))
# basicSetting[0] = bot_token
# basicSetting[1] = host
# basicSetting[2] = user_ID
# basicSetting[3] = user_PASSWORD
############## 보탐봇 명령어 리스트 #####################
for i in range(len(commandData)):
tmp_command = commandData[i][(commandData[0].find("="))+2:].rstrip('\n')
fc = tmp_command.split(', ')
commandSetting.append(fc)
fc = []
init()
def is_manager():
async def pred(ctx : commands.Context) -> bool:
user_info : dict = ctx.bot.db.jungsan.member.find_one({"_id":ctx.author.id})
if not user_info:
return False
if "manager" in user_info["permissions"]:
return True
return False
return commands.check(pred)
#서버(길드) 정보
def get_guild_channel_info(bot):
text_channel_name : list = []
text_channel_id : list = []
for guild in bot.guilds:
for text_channel in guild.text_channels:
text_channel_name.append(text_channel.name)
text_channel_id.append(str(text_channel.id))
return text_channel_name, text_channel_id
#detail embed
def get_detail_embed(info : dict = {}):
# "_id" : int = 순번
# "regist_ID" : str = 등록자ID
# "regist" : str = 등록자 겜 ID
# "getdate" : datetime = 등록날짜
# "boss" : str = 보스명
# "item" : str = 아이템명
# "toggle" : str = 루팅자 게임 ID
# "toggle_ID" : str = 루팅자ID
# "itemstatus" : str = 아이템상태(미판매, 분배중, 분배완료)
# "price" : int = 가격
# "each_price" : int = 분배가격
# "before_jungsan_ID" : list = 참석명단(분배전)
# "after_jungsan_ID" : list = 참석명단(분배후)
# "modifydate" : datetime = 수정날짜
# "gulid_money_insert" : bool = 혈비등록여부
# "bank_money_insert" : bool = 은행입금여부
# "image_url":이미지 url
embed = discord.Embed(
title = "📜 등록 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{info['_id']}```")
embed.add_field(name = "[ 등록 ]", value = f"```{info['regist']}```")
embed.add_field(name = "[ 일시 ]", value = f"```{info['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{info['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{info['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{info['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{info['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{info['price']}```")
if int(basicSetting[8]) != 0 and info['bank_money_insert']:
embed.add_field(name = "[ 혈비적립 ]", value = f"```{info['price'] - (info['each_price'] * (len(info['before_jungsan_ID'])+len(info['after_jungsan_ID'])))}```")
if info['itemstatus'] in ["분배완료", "분배중"]:
embed.add_field(name = "[ 인당금액 ]", value = f"```{info['each_price']}```")
if info['before_jungsan_ID']:
embed.add_field(name = "[ 정산전 ]", value = f"```{', '.join(info['before_jungsan_ID'])}```", inline = False)
if info['after_jungsan_ID']:
embed.add_field(name = "[ 정산후 ]", value = f"```{', '.join(info['after_jungsan_ID'])}```")
if 'image_url' in info.keys():
if info['image_url'] is not None:
embed.set_image(url = info['image_url'])
return embed
class IlsangDistributionBot(commands.AutoShardedBot):
def __init__(self):
self.cog_list : list = ["admin", "manage", "member", "bank"]
self.db = None
self.mongoDB_connect_info : dict = {
"host" : basicSetting[1],
"username" : basicSetting[2],
"password" : basicSetting[3]
}
INTENTS = discord.Intents.all()
super().__init__(command_prefix=[""], help_command=None, intents=INTENTS)
# db 설정
self.db = None
try:
self.db = MongoClient(ssl=True, ssl_cert_reqs=ssl.CERT_NONE, **self.mongoDB_connect_info)
self.db.admin.command("ismaster") # 연결 완료되었는지 체크
print(f"db 연결 완료. 아이디:{self.mongoDB_connect_info['username']}")
except pymongo.errors.ServerSelectionTimeoutError:
return print("db 연결 실패! host 리스트를 확인할 것.")
except pymongo.errors.OperationFailure:
return print("db 로그인 실패! username과 password를 확인할 것.")
except:
return print("db 연결 실패! 오류 발생:")
guild_data : dict = self.db.jungsan.guild.find_one({"_id":"guild"})
if not guild_data:
init_guild_data : dict = {
"guild_money":0,
"back_up_period":14,
"checktime":15,
"distributionchannel":0,
"tax":5,
"guild_save_tax":0
}
update_guild_data : dict = self.db.jungsan.guild.update_one({"_id":"guild"}, {"$set":init_guild_data}, upsert = True)
basicSetting.append(init_guild_data['back_up_period'])
basicSetting.append(init_guild_data['checktime'])
basicSetting.append(init_guild_data['distributionchannel'])
basicSetting.append(init_guild_data['tax'])
basicSetting.append(init_guild_data['guild_save_tax'])
else:
if "guild_save_tax" not in guild_data:
self.db.jungsan.guild.update_one({"_id":"guild"}, {"$set":{"guild_save_tax":int(0)}}, upsert = True)
guild_data : dict = self.db.jungsan.guild.find_one({"_id":"guild"})
basicSetting.append(guild_data['back_up_period'])
basicSetting.append(guild_data['checktime'])
basicSetting.append(guild_data['distributionchannel'])
basicSetting.append(guild_data['tax'])
basicSetting.append(guild_data['guild_save_tax'])
# basicSetting[4] = backup_period
# basicSetting[5] = checktime
# basicSetting[6] = distributionchannel
# basicSetting[7] = tax
# basicSetting[8] = guild_save_tax
self.backup_data.start()
def run(self):
super().run(basicSetting[0], reconnect=True)
@tasks.loop(hours=12.0)
async def backup_data(self):
await self.wait_until_ready()
if basicSetting[6] != "" and basicSetting[6] != 0 :
backup_date = datetime.datetime.now() - datetime.timedelta(days = int(basicSetting[4]))
log_delete_date = datetime.datetime.now() - datetime.timedelta(days = int(30))
jungsan_document :list = []
delete_jungsan_id : list = []
backup_jungsan_document : list = []
total_save_money : int = 0
cnt : int = 0
jungsan_document = list(self.db.jungsan.jungsandata.find({"modifydate":{"$lt":backup_date}, "itemstatus":"분배중"}))
for jungsan_data in jungsan_document:
cnt += 1
total_save_money += int(jungsan_data['each_price']*len(jungsan_data['before_jungsan_ID'])*(1-(basicSetting[7]/100)))
delete_jungsan_id.append(jungsan_data['_id'])
del jungsan_data['_id']
jungsan_data["getdate"] = datetime.datetime.now()
backup_jungsan_document.append(jungsan_data)
self.db.jungsan.guild_log.delete_many({'log_date':{"$lt":log_delete_date}})
self.db.jungsan.jungsandata.delete_many({"$and": [{'modifydate':{"$lt":log_delete_date}}, {"itemstatus":"분배완료"}]})
self.db.jungsan.jungsandata.delete_many({'_id':{'$in':delete_jungsan_id}})
if len(backup_jungsan_document) > 0:
tmp : list = list(map(str,delete_jungsan_id))
self.db.backup.backupdata.insert_many(backup_jungsan_document)
result_guild_update : dict = self.db.jungsan.guild.update_one({"_id":"guild"}, {"$inc":{"guild_money":total_save_money}}, upsert = True)
total_guild_money : dict = self.db.jungsan.guild.find_one({"_id":"guild"})
insert_log_data = {
"in_out_check":True, # True : 입금, False : 출금
"log_date":datetime.datetime.now(),
"money":str(total_save_money),
"member_list":[],
"reason":"정산 자동 삭제 후 적립"
}
result_guild_log = self.db.jungsan.guild_log.insert_one(insert_log_data)
embed = discord.Embed(
title = f"💰 혈비 자동 적립 ({datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')})",
description = f"",
color=0x00ff00
)
embed.add_field(name = f"**삭제순번**", value = f"**```fix\n{' '.join(tmp)}```**", inline = False)
embed.add_field(name = f"**적립**", value = f"**```fix\n{total_save_money}```**")
embed.add_field(name = f"**혈비**", value = f"**```fix\n{total_guild_money['guild_money']}```**")
embed.set_footer(text = f"기간({basicSetting[4]}일) 경과로 인하여 총 {cnt}건 혈비 자동적립 완료\n(총 혈비 {total_guild_money['guild_money']})")
await self.get_channel(int(basicSetting[6])).send(embed = embed)
async def on_ready(self):
DiscordComponents(self)
print("Logged in as ") #화면에 봇의 아이디, 닉네임이 출력됩니다.
print(self.user.name)
print(self.user.id)
print("===========")
channel_name, channel_id = get_guild_channel_info(self)
if str(basicSetting[6]) in channel_id:
print(f"< 접속시간 [{datetime.datetime.now().strftime('%y-%m-%d ') + datetime.datetime.now().strftime('%H:%M:%S')}] >")
print(f"< 텍스트채널 [{self.get_channel(int(basicSetting[6])).name}] 접속완료 >")
else:
basicSetting[6] = 0
print(f"설정된 채널 값이 없거나 잘못 됐습니다. [{commandSetting[36][0]}] 명령어를 먼저 입력하여 사용해주시기 바랍니다.")
await self.change_presence(status=discord.Status.dnd, activity=discord.Game(name=f"{commandSetting[39][0]}", type=1), afk = False)
async def on_command_error(self, ctx : commands.Context, error : commands.CommandError):
if isinstance(error, CommandNotFound):
return
elif isinstance(error, MissingRequiredArgument):
return
elif isinstance(error, discord.ext.commands.MissingPermissions):
return await ctx.send(f"**[{ctx.message.content.split()[0]}]** 명령을 사용할 권한이 없습니다.!")
elif isinstance(error, discord.ext.commands.CheckFailure):
return await ctx.send(f"**[{ctx.message.content.split()[0]}]** 명령을 사용할 권한이 없습니다.!")
raise error
async def close(self):
await super().close()
os.system("jungsanbot_PC.exe")
print("일상분배봇 재시작 완료.")
class settingCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.member_db = self.bot.db.jungsan.member
self.jungsan_db = self.bot.db.jungsan.jungsandata
self.guild_db = self.bot.db.jungsan.guild
self.guild_db_log = self.bot.db.jungsan.guild_log
################ 재시작 ################
@is_manager()
@commands.command(name=commandSetting[55][0], aliases=commandSetting[55][1:])
async def restart_bot(self, ctx, *, args : str = None):
await ctx.send("분배봇 재시작 중...")
return await self.bot.close()
################ 채널등록 ################
@commands.has_permissions(manage_guild=True)
@commands.command(name=commandSetting[36][0], aliases=commandSetting[36][1:])
async def join_channel(self, ctx, *, args : str = None):
global basicSetting
if basicSetting[6] == "" or basicSetting[6] == 0:
channel = ctx.message.channel.id #메세지가 들어온 채널 ID
print (f"[ {basicSetting[6]} ]")
print (f"] {ctx.message.channel.name} [")
basicSetting[6] = str(channel)
result = self.guild_db.update_one({"_id":"guild"}, {"$set":{"distributionchannel":str(channel)}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 채널 등록 실패.")
await ctx.send(f"< 텍스트채널 [{ctx.message.channel.name}] 접속완료 >", tts=False)
print(f"< 텍스트채널 [ {self.bot.get_channel(int(basicSetting[6])).name} ] 접속완료>")
else:
curr_guild_info = None
for guild in self.bot.guilds:
for text_channel in guild.text_channels:
if basicSetting[6] == str(text_channel.id):
curr_guild_info = guild
emoji_list : list = ["⭕", "❌"]
guild_error_message = await ctx.send(f"이미 **[{curr_guild_info.name}]** 서버 **[{curr_guild_info.get_channel(int(basicSetting[6])).name}]** 채널이 명령어 채널로 설정되어 있습니다.\n해당 채널로 명령어 채널을 변경 하시려면 ⭕ 그대로 사용하시려면 ❌ 를 눌러주세요.\n({basicSetting[5]}초 이내 미입력시 기존 설정 그대로 설정됩니다.)", tts=False)
for emoji in emoji_list:
await guild_error_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == guild_error_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
return await ctx.send(f"시간이 초과됐습니다. **[{curr_guild_info.name}]** 서버 **[{curr_guild_info.get_channel(int(basicSetting[6])).name}]** 채널에서 사용해주세요!")
if str(reaction) == "⭕":
basicSetting[6] = str(ctx.message.channel.id)
print ('[ ', basicSetting[6], ' ]')
print ('] ', ctx.message.channel.name, ' [')
result = self.guild_db.update_one({"_id":"guild"}, {"$set":{"distributionchannel":str(basicSetting[6])}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 채널 등록 실패.")
return await ctx.send(f"명령어 채널이 **[{ctx.author.guild.name}]** 서버 **[{ctx.message.channel.name}]** 채널로 새로 설정되었습니다.")
else:
return await ctx.send(f"명령어 채널 설정이 취소되었습니다.\n**[{curr_guild_info.name}]** 서버 **[{curr_guild_info.get_channel(int(basicSetting[6])).name}]** 채널에서 사용해주세요!")
################ 백업주기 설정 ################
@is_manager()
@commands.command(name=commandSetting[40][0], aliases=commandSetting[40][1:])
async def set_backup_time(self, ctx, *, args : str = None):
global basicSetting
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[40][0]} [숫자]** 양식으로 등록 해주세요")
try:
args = int(args)
except ValueError:
return await ctx.send(f"**정산 내역 삭제 주기는 [숫자]** 로 입력 해주세요")
basicSetting[4] = args
result = self.guild_db.update_one({"_id":"guild"}, {"$set":{"back_up_period":args}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 내역 삭제 주기 설정 실패.")
return await ctx.send(f"정산 내역 삭제 주기를 **[{args}]**일로 설정 하였습니다.")
################ 확인시간 설정 ################
@is_manager()
@commands.command(name=commandSetting[41][0], aliases=commandSetting[41][1:])
async def set_check_time(self, ctx, *, args : str = None):
global basicSetting
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[41][0]} [숫자]** 양식으로 등록 해주세요")
try:
args = int(args)
except ValueError:
return await ctx.send(f"**이모지 확인 시간은 [숫자]** 로 입력 해주세요")
basicSetting[5] = args
result = self.guild_db.update_one({"_id":"guild"}, {"$set":{"checktime":args}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 이모지 확인 시간 설정 실패.")
return await ctx.send(f"이모지 확인 시간을 **[{args}]**초로 설정 하였습니다.")
################ 혈비적립 수수료 설정 ################
@is_manager()
@commands.command(name=commandSetting[58][0], aliases=commandSetting[58][1:])
async def set_guild_tax(self, ctx, *, args : str = None):
global basicSetting
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[58][0]} [숫자]** 양식으로 등록 해주세요")
try:
args = int(args)
except ValueError:
return await ctx.send(f"**혈비적립 수수료는 [숫자]** 로 입력 해주세요")
basicSetting[8] = args
result = self.guild_db.update_one({"_id":"guild"}, {"$set":{"guild_save_tax":args}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 혈비적립 수수료 설정 실패.")
return await ctx.send(f"혈비적립 수수료를 **[{args}%]**로 설정 하였습니다.")
################ 세금 설정 ################
@is_manager()
@commands.command(name=commandSetting[42][0], aliases=commandSetting[42][1:])
async def set_tax(self, ctx, *, args : str = None):
global basicSetting
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[42][0]} [숫자]** 양식으로 등록 해주세요")
try:
args = int(args)
except ValueError:
return await ctx.send(f"**세율은 [숫자]** 로 입력 해주세요")
basicSetting[7] = args
result = self.guild_db.update_one({"_id":"guild"}, {"$set":{"tax":args}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 세율 설정 실패.")
return await ctx.send(f"세율을 **[{args}%]**로 설정 하였습니다.")
class adminCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.member_db = self.bot.db.jungsan.member
self.jungsan_db = self.bot.db.jungsan.jungsandata
self.guild_db = self.bot.db.jungsan.guild
self.guild_db_log = self.bot.db.jungsan.guild_log
self.backup_db = self.bot.db.backup.backupdata
################ 기본설정확인 ################
@commands.command(name=commandSetting[46][0], aliases=commandSetting[46][1:])
async def setting_info(self, ctx):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
embed = discord.Embed(
title = f"⚙️ 기본 설정(PC. v13)",
color=0xff00ff
)
embed.add_field(name = f"🚫 삭제 주기", value = f"```{basicSetting[4]} 일```")
embed.add_field(name = f"⌛ 체크 시간", value = f"```{basicSetting[5]} 초```")
embed.add_field(name = f"🏧 혈비적립", value = f"```{basicSetting[8]} %```")
embed.add_field(name = f"⚖️ 수수료", value = f"```{basicSetting[7]} %```")
embed.add_field(name = f"🗨️ 명령 채널", value = f"```{ctx.message.channel.name}```")
return await ctx.send(embed = embed, tts=False)
################ 현재시간 확인 ################
@commands.command(name=commandSetting[37][0], aliases=commandSetting[37][1:])
async def current_time_check(self, ctx):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
embed = discord.Embed(
title = f"현재시간은 {datetime.datetime.now().strftime('%H')}시 {datetime.datetime.now().strftime('%M')}분 {datetime.datetime.now().strftime('%S')}초 입니다.",
color=0xff00ff
)
return await ctx.send(embed = embed, tts=False)
################ 상태메세지 변경 ################
@commands.command(name=commandSetting[38][0], aliases=commandSetting[38][1:])
async def status_modify(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
if not args:
return await ctx.send(f"**{commandSetting[38][0]} [내용]** 양식으로 변경 해주세요")
await self.bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name=args, type=1), afk = False)
return await ctx.send(f"< 상태메세지 **[ {args} ]**로 변경완료 >", tts=False)
################ 도움말 ################
@commands.command(name=commandSetting[39][0], aliases=commandSetting[39][1:])
async def command_help(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
if args:
return await ctx.send(f"**{commandSetting[39][0]}만 입력 해주세요!**", tts=False)
else:
admin_command_list : str = ""
admin_command_list += f"{','.join(commandSetting[36])}\n" # 분배채널설정
admin_command_list += f"{','.join(commandSetting[4])} [아이디]\n" # 총무등록
admin_command_list += f"{','.join(commandSetting[5])} [아이디]\n" # 총무삭제
manager_command_list : str = ""
manager_command_list += f"{','.join(commandSetting[0])} ※ 관리자권한도 필요\n" # 혈원데이터초기화
manager_command_list += f"{','.join(commandSetting[1])} ※ 관리자권한도 필요\n" # 정산데이터초기화
manager_command_list += f"{','.join(commandSetting[2])} ※ 관리자권한도 필요\n" # 혈비데이터초기화
manager_command_list += f"{','.join(commandSetting[3])} ※ 관리자권한도 필요\n" # 백업데이터초기화
manager_command_list += f"{','.join(commandSetting[52])} ※ 관리자권한도 필요\n" # db백업
manager_command_list += f"{','.join(commandSetting[40])} [숫자(일)]\n" # 삭제주기설정
manager_command_list += f"{','.join(commandSetting[41])} [숫자(초)]\n" # 확인시간설정
manager_command_list += f"{','.join(commandSetting[58])} [숫자(%)]\n" # 혈비적립수수료설정
manager_command_list += f"{','.join(commandSetting[42])} [숫자(%)]\n" # 세금설정
manager_command_list += f"{','.join(commandSetting[47])} ※ 30일 이후 데이터는 삭제됨\n" # 혈비로그확인
manager_command_list += f"{','.join(commandSetting[43])} (상세)\n" # 전체확인
manager_command_list += f"{','.join(commandSetting[43])} (상세) (검색조건) (검색값)\n" # 전체확인
manager_command_list += f"{','.join(commandSetting[57])} [아이디]\n" # 혈원정보
manager_command_list += f"{','.join(commandSetting[9])} [아이디] [디스코드ID]\n" # 혈원입력
manager_command_list += f"{','.join(commandSetting[56])} [변경아이디] [디스코드ID]\n" # 혈원변경
manager_command_list += f"{','.join(commandSetting[10])} [아이디]\n" # 혈원삭제
manager_command_list += f"{','.join(commandSetting[30])} [금액] [아이디1] [아이디2]...\n" # 은행입금
manager_command_list += f"{','.join(commandSetting[31])} [금액] [아이디1] [아이디2]...\n" # 은행출금
manager_command_list += f"{','.join(commandSetting[32])} [금액] (*사유)\n" # 혈비입금
manager_command_list += f"{','.join(commandSetting[49])} [금액] *[사유]\n" # 혈비출금
manager_command_list += f"{','.join(commandSetting[33])} [금액] [아이디1] [아이디2]... *[사유]\n" # 혈비지원
manager_command_list += f"{','.join(commandSetting[54])} [순번] [변경아이디]\n" # 등록자수정
manager_command_list += f"{','.join(commandSetting[55])}\n" # 재시작
member_command_list : str = ""
member_command_list += f"{','.join(commandSetting[6])}\n" # 혈원
member_command_list += f"{','.join(commandSetting[7])} [아이디]\n" # 혈원등록
member_command_list += f"{','.join(commandSetting[8])} [아이디]\n\n" # 혈원수정
member_command_list += f"{','.join(commandSetting[28])}\n" # 계좌
member_command_list += f"{','.join(commandSetting[60])} [금액] [대상아이디]\n" # 이체
member_command_list += f"{','.join(commandSetting[44])} (아이템명)\n" # 창고
member_command_list += f"{','.join(commandSetting[11])} (아이디)\n" # 정산확인
member_command_list += f"{','.join(commandSetting[11])} (검색조건) (검색값)\n\n" # 정산확인
member_command_list += f"{','.join(commandSetting[12])} [보스명] [아이템] [루팅자] [아이디1] [아이디2] ... (참고이미지 url)\n" # 등록
member_command_list += f"{','.join(commandSetting[12])} [보스명] [아이템1] [아이템2] [아이템3] *[루팅자] [아이디1] [아이디2] ... (참고이미지 url)\n※ 루팅자 앞에 [*]을 넣어서 아이템 여러개 동시 등록 가능\n" # 멀티등록
member_command_list += f"{','.join(commandSetting[53])} [보스명] [아이템] [루팅자] [뽑을인원] [아이디1] [아이디2] ... (참고이미지 url)\n\n" # 뽑기등록
member_command_list += f"----- 등록자만 가능 -----\n" # 등록자
member_command_list += f"{','.join(commandSetting[13])} (상세)\n" # 등록확인1
member_command_list += f"{','.join(commandSetting[13])} (상세) (검색조건) (검색값)\n" # 등록확인2
member_command_list += f"{','.join(commandSetting[14])} [순번] [보스명] [아이템] [루팅자] [아이디1] [아이디2] ...\n" # 등록수정
member_command_list += f"{','.join(commandSetting[15])} [순번]\n\n" # 등록삭제
member_command_list += f"----- 루팅자만 가능 -----\n" # 루팅자
member_command_list += f"{','.join(commandSetting[16])} (상세)\n" # 루팅확인1
member_command_list += f"{','.join(commandSetting[16])} (상세) (검색조건) (검색값)\n" # 루팅확인2
member_command_list += f"{','.join(commandSetting[17])} [순번] [보스명] [아이템] [루팅자] [아이디1] [아이디2] ...\n" # 루팅수정
member_command_list += f"{','.join(commandSetting[18])} [순번]\n\n" # 루팅삭제
member_command_list += f"----- 등록자, 루팅자만 가능 -----\n" # 등록자, 루팅자
member_command_list += f"{','.join(commandSetting[19])} [순번] [변경보스명]\n" # 보스수정
member_command_list += f"{','.join(commandSetting[20])} [순번] [변경아이템명]\n" # 템수정
member_command_list += f"{','.join(commandSetting[21])} [순번] [변경아이디]\n" # 토글수정
member_command_list += f"{','.join(commandSetting[22])} [순번] [추가아이디]\n" # 참여자추가
member_command_list += f"{','.join(commandSetting[23])} [순번] [삭제아이디]\n" # 참여자삭제
member_command_list += f"{','.join(commandSetting[50])} [순번] [수정이미지 url]\n" # 이미지수정
member_command_list += f"{','.join(commandSetting[24])} [순번] [금액]\n" # 판매
member_command_list += f"{','.join(commandSetting[45])} [순번] [금액] [뽑을인원]\n" # 뽑기판매
member_command_list += f"{','.join(commandSetting[51])} [순번]\n" # 판매취소
member_command_list += f"{','.join(commandSetting[29])} [순번] [금액]\n" # 저축
member_command_list += f"{','.join(commandSetting[48])} [순번] [금액] [뽑을인원]\n" # 뽑기저축
member_command_list += f"{','.join(commandSetting[25])} [순번] [아이디]\n" # 정산
member_command_list += f"{','.join(commandSetting[26])} [순번] [아이디]\n" # 정산취소
member_command_list += f"{','.join(commandSetting[27])}\n" # 일괄정산1
member_command_list += f"{','.join(commandSetting[27])} (검색조건) (검색값)\n" # 일괄정산2
member_command_list += f"{','.join(commandSetting[59])} (검색조건) (검색값)\n" # 부분정산
etc_command_list : str = ""
etc_command_list += f"{','.join(commandSetting[46])}\n" # 기본설정확인
etc_command_list += f"{','.join(commandSetting[37])}\n" # 현재시간
etc_command_list += f"{','.join(commandSetting[38])} [변경메세지]\n" # 상태
etc_command_list += f"{','.join(commandSetting[34])} [금액] (거래소세금)\n" # 수수료
etc_command_list += f"{','.join(commandSetting[35])} [거래소금액] [실거래가] (거래소세금)\n" # 페이백
embed = discord.Embed(
title = "🕹️ 분배봇 사용법",
description= f"```득템 → 정산등록 → 판매입력 → 정산처리 → 끝!```",
color=0xff00ff
)
embed.add_field(name = f"⚙️ [ 관리자 전용 명령어 ]", value = f"```css\n{admin_command_list}```", inline = False)
embed.add_field(name = f"🤴 [ 총무 전용 명령어 ]", value = f"```css\n{manager_command_list}```", inline = False)
embed.add_field(name = f"🧑 [ 일반 명령어 ]", value = f"```css\n{member_command_list}```", inline = False)
embed.add_field(name = f"🔧 [ 기타 명령어 ]", value = f"```css\n{etc_command_list}```", inline = False)
embed.set_footer(text = f"※ '분배완료'된 것 중 30일이 지난 건은 자동으로 삭제\n '미입력' 상태의 등록건만 수정 가능\n '분배중' 상태의 등록건만 정산 가능\n 거래소세금 : 미입력시 {basicSetting[7]}%\n 등록시 참고이미지url은 [ https:// ]로 시작해야함")
return await ctx.send( embed=embed, tts=False)
################ member_db초기화 ################ .
@is_manager()
@commands.has_permissions(manage_guild=True)
@commands.command(name=commandSetting[0][0], aliases=commandSetting[0][1:])
async def initialize_all_member_data(self, ctx):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
emoji_list : list = ["⭕", "❌"]
delete_warning_message = await ctx.send(f"**혈원데이터를 초기화 하시면 다시는 복구할 수 없습니다. 정말로 초기화하시겠습니까?**\n**초기화 : ⭕ 취소: ❌**\n({int(basicSetting[5])*2}초 동안 입력이 없을시 초기화가 취소됩니다.)", tts=False)
for emoji in emoji_list:
await delete_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == delete_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5])*2)
except asyncio.TimeoutError:
for emoji in emoji_list:
await delete_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **초기화**를 취소합니다!")
if str(reaction) == "⭕":
self.member_db.delete_many({})
print(f"< 혈원데이터 초기화 완료 >")
return await ctx.send(f"☠️ 혈원데이터 초기화 완료! ☠️")
else:
return await ctx.send(f"**초기화**가 취소되었습니다.\n")
################ jungsan_db초기화 ################
@is_manager()
@commands.has_permissions(manage_guild=True)
@commands.command(name=commandSetting[1][0], aliases=commandSetting[1][1:])
async def initialize_all_jungsan_data(self, ctx):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
emoji_list : list = ["⭕", "❌"]
delete_warning_message = await ctx.send(f"**정산데이터를 초기화 하시면 다시는 복구할 수 없습니다. 정말로 초기화하시겠습니까?**\n**초기화 : ⭕ 취소: ❌**\n({int(basicSetting[5])*2}초 동안 입력이 없을시 초기화가 취소됩니다.)", tts=False)
for emoji in emoji_list:
await delete_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == delete_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5])*2)
except asyncio.TimeoutError:
for emoji in emoji_list:
await delete_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **초기화**를 취소합니다!")
if str(reaction) == "⭕":
self.jungsan_db.delete_many({})
print(f"< 정산데이터 초기화 완료 >")
return await ctx.send(f"☠️ 정산데이터 초기화 완료! ☠️")
else:
return await ctx.send(f"**초기화**가 취소되었습니다.\n")
################ guild_db초기화 ################
@is_manager()
@commands.has_permissions(manage_guild=True)
@commands.command(name=commandSetting[2][0], aliases=commandSetting[2][1:])
async def initialize_all_guild_data(self, ctx):
global basicSetting
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
emoji_list : list = ["⭕", "❌"]
delete_warning_message = await ctx.send(f"**혈비데이터를 초기화 하시면 다시는 복구할 수 없습니다. 정말로 초기화하시겠습니까?**\n**초기화 : ⭕ 취소: ❌**\n({int(basicSetting[5])*2}초 동안 입력이 없을시 초기화가 취소됩니다.)", tts=False)
for emoji in emoji_list:
await delete_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == delete_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5])*2)
except asyncio.TimeoutError:
for emoji in emoji_list:
await delete_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **초기화**를 취소합니다!")
if str(reaction) == "⭕":
self.guild_db.delete_many({})
self.guild_db_log.delete_many({})
init_guild_data : dict = {
"guild_money":0,
"back_up_period":14,
"checktime":15,
"distributionchannel":0,
"tax":5,
"guild_save_tax":0
}
update_guild_data : dict = self.guild_db.update_one({"_id":"guild"}, {"$set":init_guild_data}, upsert = True)
basicSetting[4] = init_guild_data['back_up_period']
basicSetting[5] = init_guild_data['checktime']
basicSetting[6] = init_guild_data['distributionchannel']
basicSetting[7] = init_guild_data['tax']
basicSetting[8] = init_guild_data['guild_save_tax']
# basicSetting[4] = backup_period
# basicSetting[5] = checktime
# basicSetting[6] = distributionchannel
# basicSetting[7] = tax
# basicSetting[8] = guild_save_tax
print(f"< 혈비/로그 데이터 초기화 완료 >")
return await ctx.send(f"☠️ 혈비/로그 데이터 초기화 완료! ☠️\n**[{commandSetting[36][0]}]** 명령어를 입력하신 후 사용해주시기 바랍니다.")
else:
return await ctx.send(f"**초기화**가 취소되었습니다.\n")
################ backup_db초기화 ################
@is_manager()
@commands.has_permissions(manage_guild=True)
@commands.command(name=commandSetting[3][0], aliases=commandSetting[3][1:])
async def initialize_all_backup_data(self, ctx):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
emoji_list : list = ["⭕", "❌"]
delete_warning_message = await ctx.send(f"**백업데이터를 초기화 하시면 다시는 복구할 수 없습니다. 정말로 초기화하시겠습니까?**\n**초기화 : ⭕ 취소: ❌**\n({int(basicSetting[5])*2}초 동안 입력이 없을시 초기화가 취소됩니다.)", tts=False)
for emoji in emoji_list:
await delete_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == delete_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5])*2)
except asyncio.TimeoutError:
for emoji in emoji_list:
await delete_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **초기화**를 취소합니다!")
if str(reaction) == "⭕":
self.backup_db.delete_many({})
print(f"< 백업데이터 초기화 완료 >")
return await ctx.send(f"☠️ 백업데이터 초기화 완료! ☠️")
else:
return await ctx.send(f"**초기화**가 취소되었습니다.\n")
################ db백업 ################
@is_manager()
@commands.has_permissions(manage_guild=True)
@commands.command(name=commandSetting[52][0], aliases=commandSetting[52][1:])
async def command_db_backup(self, ctx):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
emoji_list : list = ["⭕", "❌"]
db_backup_message = await ctx.send(f"**db데이터를 백업하시겠습니까?**\n**백업 : ⭕ 취소: ❌**\n({int(basicSetting[5])*2}초 동안 입력이 없을시 백업이 취소됩니다.)", tts=False)
for emoji in emoji_list:
await db_backup_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == db_backup_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5])*2)
except asyncio.TimeoutError:
for emoji in emoji_list:
await db_backup_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **백업**을 취소합니다!")
if str(reaction) == "⭕":
# self.member_db = self.bot.db.jungsan.member
# self.jungsan_db = self.bot.db.jungsan.jungsandata
# self.guild_db = self.bot.db.jungsan.guild
# self.guild_db_log = self.bot.db.jungsan.guild_log
# self.backup_db = self.bot.db.backup.backupdata
jungsan_number : list = []
jungsan_date : list = []
jungsan_boss_name : list = []
jungsan_item_name : list = []
jungsan_loot_member : list = []
jungsan_item_status : list = []
jungsan_price : list = []
jungsan_each_price : list = []
jungsan_guild_save_money : list = []
jungsan_num_member : list = []
jungsan_member : list = []
jungsan_guild : list = []
jungsan_bank : list = []
jungsan_before_member : list = []
jungsan_after_member : list = []
jungsan_image_url : list = []
jungsan_db_backup_documents : list = list(self.jungsan_db.find({}).sort("_id", pymongo.ASCENDING))
for document in jungsan_db_backup_documents:
jungsan_number.append(document["_id"])
jungsan_date.append(document["modifydate"].strftime('%y-%m-%d %H:%M:%S'))
jungsan_boss_name.append(document["boss"])
jungsan_item_name.append(document["item"])
jungsan_loot_member.append(document["toggle"])
jungsan_item_status.append(document["itemstatus"])
jungsan_price.append(document["price"])
jungsan_each_price.append(document["each_price"])
if int(basicSetting[8]) != 0 and document["bank_money_insert"]:
jungsan_guild_save_money.append(int(document["price"]) - (int(document["each_price"])*len(document["before_jungsan_ID"])+len(document["after_jungsan_ID"])))
else:
jungsan_guild_save_money.append(0)
jungsan_num_member.append(len(document["before_jungsan_ID"])+len(document["after_jungsan_ID"]))
jungsan_member.append(f"{', '.join(document['before_jungsan_ID'] + document['after_jungsan_ID'])}")
if document["gulid_money_insert"]:
jungsan_guild.append("O")
else:
jungsan_guild.append("X")
if document["bank_money_insert"]:
jungsan_bank.append("O")
else:
jungsan_bank.append("X")
jungsan_before_member.append(", ".join(document["before_jungsan_ID"]))
jungsan_after_member.append(", ".join(document["after_jungsan_ID"]))
try:
jungsan_image_url.append(document["image_url"])
except KeyError:
jungsan_image_url.append("")
jungsan_raw_data = {'순번' : jungsan_number,
'일자' : jungsan_date,
'보스명' : jungsan_boss_name,
'아이템명' : jungsan_item_name,
'루팅자' : jungsan_loot_member,
'아이템상태' : jungsan_item_status,
'가격' : jungsan_price,
'인당분배금' : jungsan_each_price,
'혈비적립금' : jungsan_guild_save_money,
'참여인원' : jungsan_num_member,
'참여자' : jungsan_member,
'미정산인원' : jungsan_before_member,
'정산완료인원' : jungsan_after_member,
'길드적립' : jungsan_guild,
'은행저축' : jungsan_bank,
'이미지url' : jungsan_image_url
}
guild_money_date : list = []
guild_money_in_out_check : list = []
guild_money_each_money : list = []
guild_money_money : list = []
guild_money_member : list = []
guild_money_num_member : list = []
guild_money_reason : list = []
multiplier : int = 1
guild_money_db_backup_documents : list = list(self.guild_db_log.find({}))
for document in guild_money_db_backup_documents:
guild_money_date.append(document["log_date"].strftime('%y-%m-%d %H:%M:%S'))
if document["in_out_check"]:
guild_money_in_out_check.append("입금")
multiplier = 1
else:
guild_money_in_out_check.append("출금")
multiplier = -1
try:
guild_money_each_money.append(int(document["money"])//len(document["member_list"]))
except ZeroDivisionError:
guild_money_each_money.append(0)
guild_money_money.append(multiplier*int(document["money"]))
guild_money_member.append(f"{', '.join(document['member_list'])}")
guild_money_num_member.append(len(document["member_list"]))
guild_money_reason.append(document["reason"])
guild_money_raw_data = {
'일자' : guild_money_date,
'입/출금' : guild_money_in_out_check,
'인당지급액' : guild_money_each_money,
'변동금액' : guild_money_money,
'명단' : guild_money_member,
'인원' : guild_money_num_member,
'사유' : guild_money_reason
}
backup_number : list = []
backup_date : list = []
backup_modifydate : list = []
backup_boss_name : list = []
backup_item_name : list = []
backup_loot_member : list = []
backup_item_status : list = []
backup_price : list = []
backup_each_price : list = []
backup_num_member : list = []
backup_save_money : list = []
backup_member : list = []
backup_guild : list = []
backup_bank : list = []
backup_before_member : list = []
backup_after_member : list = []
backup_image_url : list = []
backup_db_backup_documents : list = list(self.backup_db.find({}))
for document in backup_db_backup_documents:
backup_number.append(document["_id"])
backup_date.append(document["getdate"].strftime('%y-%m-%d %H:%M:%S'))
backup_modifydate.append(document["modifydate"].strftime('%y-%m-%d %H:%M:%S'))
backup_boss_name.append(document["boss"])
backup_item_name.append(document["item"])
backup_loot_member.append(document["toggle"])
backup_item_status.append(document["itemstatus"])
backup_price.append(document["price"])
backup_each_price.append(document["each_price"])
backup_save_money.append(int(document['each_price']*len(document['before_jungsan_ID'])*(1-(basicSetting[7]/100))))
backup_num_member.append(len(document["before_jungsan_ID"])+len(document["after_jungsan_ID"]))
backup_member.append(f"{', '.join(document['before_jungsan_ID'] + document['after_jungsan_ID'])}")
if document["gulid_money_insert"]:
backup_guild.append("O")
else:
backup_guild.append("X")
if document["bank_money_insert"]:
backup_bank.append("O")
else:
backup_bank.append("X")
backup_before_member.append(", ".join(document["before_jungsan_ID"]))
backup_after_member.append(", ".join(document["after_jungsan_ID"]))
try:
backup_image_url.append(document["image_url"])
except KeyError:
backup_image_url.append("")
backup_raw_data = {'백업ID' : backup_number,
'백업일자' : backup_date,
'등록(수정)일자' : backup_modifydate,
'보스명' : backup_boss_name,
'아이템명' : backup_item_name,
'루팅자' : backup_loot_member,
'아이템상태' : backup_item_status,
'가격' : backup_price,
'인당분배금' : backup_each_price,
'혈비적립금' : backup_save_money,
'참여인원' : backup_num_member,
'참여자' : backup_member,
'미정산인원' : backup_before_member,
'정산완료인원' : backup_after_member,
'길드적립' : backup_guild,
'은행저축' : backup_bank,
'이미지url' : backup_image_url
}
jungsan_raw_datas = pd.DataFrame(jungsan_raw_data) #데이터 프레임으로 전환 및 생성
guild_money_datas = pd.DataFrame(guild_money_raw_data) #데이터 프레임으로 전환 및 생성
backup_datas = pd.DataFrame(backup_raw_data) #데이터 프레임으로 전환 및 생성
xlxs_dir= f"{datetime.datetime.now().strftime('%y%m%d%H%M%S')}_db_data.xlsx" #경로 및 파일명 설정
with pd.ExcelWriter(xlxs_dir) as writer:
jungsan_raw_datas.to_excel(writer, sheet_name = 'jungsan_data') #jungsan_data 시트에 저장
guild_money_datas.to_excel(writer, sheet_name = 'guild_money_data') #guild_money_data 시트에 저장
backup_datas.to_excel(writer, sheet_name = 'backup_data') #guild_money_data 시트에 저장
print(f"< db 백업 완료 >")
return await ctx.send(f"✅ db 백업 완료!")
else:
return await ctx.send(f"**백업**이 취소되었습니다.\n")
################ 혈비로그확인 ################
@is_manager()
@commands.command(name=commandSetting[47][0], aliases=commandSetting[47][1:])
async def guild_log_load(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if args:
return await ctx.send(f"**{commandSetting[47][0]}** 양식으로 등록 해주세요")
result : list = []
result = list(self.guild_db_log.find({}))
if len(result) == 0:
return await ctx.send(f"```혈비 로그가 없습니다!```")
sorted_result = sorted(list([result_data['log_date'] for result_data in result]))
log_date_list : list = []
log_date_list = sorted(list(set([result_data['log_date'].strftime('%y-%m-%d') for result_data in result])))
total_distribute_money : int = 0
embed_list : list = []
embed_limit_checker : int = 0
embed_cnt : int = 0
detail_title_info : str = ""
detail_info : str = ""
embed = discord.Embed(
title = f"📜 혈비 로그",
description = "",
color=0x00ff00
)
embed_list.append(embed)
for date in log_date_list:
embed_limit_checker = 0
detail_info : str = ""
for result_data1 in result:
if embed_limit_checker == 50:
embed_limit_checker = 0
embed_cnt += 1
tmp_embed = discord.Embed(
title = "",
description = "",
color=0x00ff00
)
embed_list.append(tmp_embed)
if result_data1['log_date'].strftime('%y-%m-%d') == date:
embed_limit_checker += 1
if result_data1['in_out_check']:
if result_data1['reason'] != "":
if not result_data1['member_list']:
detail_info += f"+ 💰 {result_data1['money']} : {result_data1['reason']}\n"
else:
detail_info += f"+ 💰 {result_data1['money']} : {', '.join(result_data1['member_list'])} (사유 : {result_data1['reason']})\n"
else:
detail_info += f"+ 💰 {result_data1['money']} : 혈비 입금\n"
else:
if result_data1['reason'] != "":
detail_info += f"- 💰 {result_data1['money']} : {', '.join(result_data1['member_list'])} (사유:{result_data1['reason']})\n"
else:
detail_info += f"- 💰 {result_data1['money']} : {', '.join(result_data1['member_list'])}\n"
embed_list[embed_cnt].title = f"🗓️ {date}"
embed_list[embed_cnt].description = f"```diff\n{detail_info}```"
if len(embed_list) > 1:
for embed_data in embed_list:
await asyncio.sleep(0.1)
await ctx.send(embed = embed_data)
else:
await asyncio.sleep(0.1)
await ctx.send(embed = embed)
return
class memberCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.member_db = self.bot.db.jungsan.member
self.jungsan_db = self.bot.db.jungsan.jungsandata
self.guild_db = self.bot.db.jungsan.guild
self.guild_db_log = self.bot.db.jungsan.guild_log
################ 총무등록 ################
@commands.has_permissions(manage_guild=True)
@commands.command(name=commandSetting[4][0], aliases=commandSetting[4][1:])
async def set_manager(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"game_ID":args})
if not member_data:
return await ctx.send(f"**[{args}]**님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[4][0]} [아이디]** 양식으로 등록 해주세요")
result = self.member_db.update_one({"game_ID":member_data["game_ID"]}, {"$set":{"permissions":"manager"}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 총무 등록 실패.")
return await ctx.send(f"**[{args}]**님을 총무로 등록 하였습니다.")
################ 총무삭제 ################
@commands.has_permissions(manage_guild=True)
@commands.command(name=commandSetting[5][0], aliases=commandSetting[5][1:])
async def delete_manager(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"game_ID":args})
if not member_data:
return await ctx.send(f"**[{args}]**님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[5][0]} [아이디]** 양식으로 삭제 해주세요")
result = self.member_db.update_one({"game_ID":member_data["game_ID"]}, {"$set":{"permissions":"member"}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 총무 삭제 실패.")
return await ctx.send(f"**[{args}]**님을 총무에서 삭제 하였습니다.")
################ 혈원목록 확인 ################
@commands.command(name=commandSetting[6][0], aliases=commandSetting[6][1:])
async def member_list(self, ctx):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
remain_guild_money : int = 0
guild_data : dict = self.guild_db.find_one({"_id":"guild"})
if not guild_data:
remain_guild_money = 0
else:
remain_guild_money = guild_data["guild_money"]
member_list : str = ""
manager_list : str = ""
member_document : list = list(self.member_db.find({}))
sorted_member_document : dict = sorted(member_document, key=lambda member_document:member_document['account'], reverse = True)
total_account : int = sum(member['account'] for member in sorted_member_document)
for member_info in sorted_member_document:
if member_info["permissions"] == "manager":
if member_info['account'] != 0:
manager_list += f"{member_info['game_ID']}({member_info['account']}) "
else:
manager_list += f"{member_info['game_ID']} "
else:
if member_info['account'] != 0:
member_list += f"{member_info['game_ID']}({member_info['account']}) "
else:
member_list += f"{member_info['game_ID']} "
embed = discord.Embed(
title = "👥 혈원 목록",
description = "",
color=0x00ff00
)
if len(manager_list) == 0:
embed.add_field(name = f"**🤴 총무**",value = f"**```cs\n등록된 총무가 없습니다.```**")
else:
embed.add_field(name = f"**🤴 총무**",value = f"**```cs\n{manager_list}```**")
if len(member_list) == 0:
embed.add_field(name = f"**🧑 혈원**",value = f"**```cs\n등록된 혈원이 없습니다.```**", inline = False)
else:
embed.add_field(name = f"**🧑 혈원**",value = f"**```cs\n{member_list}```**", inline = False)
embed.add_field(name = f"**👤 혈원수**",value = f"**```fix\n{len(sorted_member_document)}```**")
embed.add_field(name = f"**🏦 잔고**",value = f"**```fix\n{total_account}```**")
embed.add_field(name = f"**💰 혈비**",value = f"**```fix\n{remain_guild_money}```**")
#embed.set_footer(text = f"👑 표시는 총무!")
return await ctx.send(embed = embed)
################ 혈원아이디 등록 ################
@commands.command(name=commandSetting[7][0], aliases=commandSetting[7][1:])
async def member_add(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
if not args:
return await ctx.send(f"**{commandSetting[7][0]} [아이디]** 양식으로 추가 해주세요")
member_document : dict = self.member_db.find_one({ "_id":ctx.author.id})
member_game_ID_document : dict = self.member_db.find_one({ "game_ID":args})
if member_document:
return await ctx.send(f"```이미 등록되어 있습니다!```")
if member_game_ID_document:
return await ctx.send(f"```이미 등록된 [아이디]입니다!```")
result = self.member_db.update_one({"_id":ctx.author.id}, {"$set":{"game_ID":args, "discord_name":self.bot.get_user(ctx.author.id).display_name, "permissions":"member", "account":0}}, upsert = True)
# "_id" : int = discord_ID
# "game_ID" : str = game_ID
# "discord_name" : str = discord_nickname
# "permissiotns" : str = 권한 ["manager", "member"]
# "account" : int = 은행잔고
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 혈원 등록 실패.")
return await ctx.send(f"{ctx.author.mention}님! **[{args}] [{ctx.author.id}]**(으)로 혈원 등록 완료!")
################ 혈원아이디 수정 ################
@commands.command(name=commandSetting[8][0], aliases=commandSetting[8][1:])
async def member_modify(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({ "_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[8][0]} [아이디]** 양식으로 수정 해주세요")
member_game_ID_document : dict = self.member_db.find_one({ "game_ID":args})
if member_game_ID_document:
return await ctx.send(f"```이미 등록된 [ 아이디 ] 입니다!```")
jungsan_document = list(self.jungsan_db.find({"$and" : [{"$or" : [{"before_jungsan_ID" : member_data['game_ID']}, {"after_jungsan_ID" : member_data['game_ID']}, {"toggle" : member_data['game_ID']}, {"regist" : member_data['game_ID']}]}, {"$or" : [{"itemstatus" : "분배중"}, {"itemstatus" : "미판매"}]}]}).sort("_id", pymongo.ASCENDING))
len_jungsan_document : int = len(jungsan_document)
tmp_before_data : list = []
tmp_after_data : list = []
tmp_toggle_data : str = ""
tmp_regist_data : str = ""
if len_jungsan_document != 0:
for jungsan_data in jungsan_document:
tmp_before_data = jungsan_data["before_jungsan_ID"]
tmp_after_data = jungsan_data["after_jungsan_ID"]
tmp_toggle_data = jungsan_data["toggle"]
tmp_regist_data = jungsan_data["regist"]
if member_data['game_ID'] in jungsan_data["before_jungsan_ID"]:
jungsan_data["before_jungsan_ID"].remove(member_data['game_ID'])
jungsan_data["before_jungsan_ID"].append(args)
tmp_before_data = jungsan_data["before_jungsan_ID"]
#result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":{"before_jungsan_ID":jungsan_data["before_jungsan_ID"]}}, upsert = False)
if member_data['game_ID'] in jungsan_data["after_jungsan_ID"]:
jungsan_data["after_jungsan_ID"].remove(member_data['game_ID'])
jungsan_data["after_jungsan_ID"].append(args)
tmp_after_data = jungsan_data["after_jungsan_ID"]
#result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":{"after_jungsan_ID":jungsan_data["after_jungsan_ID"]}}, upsert = False)
if member_data['game_ID'] in jungsan_data["toggle"]:
tmp_toggle_data = args
#result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":{"toggle":args}}, upsert = False)
if member_data['game_ID'] in jungsan_data["regist"]:
tmp_regist_data = args
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":{"regist":tmp_regist_data, "toggle":tmp_toggle_data,"before_jungsan_ID":sorted(tmp_before_data) , "after_jungsan_ID":sorted(tmp_after_data)}}, upsert = False)
result = self.member_db.update_one({"_id":ctx.author.id}, {"$set":{"game_ID":args}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 아이디 수정 실패.")
return await ctx.send(f"{ctx.author.mention}님, 아이디를 **[{member_data['game_ID']}]**에서 **[{args}]**로 변경하였습니다.")
################ 혈원아이디 정보 ################
@commands.command(name=commandSetting[57][0], aliases=commandSetting[57][1:])
async def member_infomation(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
if not args:
return await ctx.send(f"**{commandSetting[57][0]} [아이디]** 양식으로 입력 해주세요")
member_data : dict = self.member_db.find_one({"game_ID":args})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
embed = discord.Embed(
title = f"👤 **[{member_data['game_ID']}]님의 정보**",
color=0x00ff00
)
embed.add_field(name = "디스코드 🆔", value = f"```fix\n{member_data['_id']}```", inline=False)
if member_data['permissions'] == "manager":
embed.add_field(name = "💪 권한", value = f"```fix\n총무```")
else:
embed.add_field(name = "💪 권한", value = f"```fix\n혈원```")
embed.add_field(name = "🏦 잔고", value = f"```fix\n{member_data['account']}```")
return await ctx.send(embed=embed)
################ 혈원아이디 입력 ################
@is_manager()
@commands.command(name=commandSetting[9][0], aliases=commandSetting[9][1:])
async def member_input_add(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
if not args:
return await ctx.send(f"**{commandSetting[9][0]} [아이디] [디코ID]** 양식으로 추가 해주세요")
input_regist_data : list = args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data < 2:
return await ctx.send(f"**{commandSetting[9][0]} [아이디] [디코ID]** 양식으로 추가 해주세요")
member_document : dict = self.member_db.find_one({"_id":int(input_regist_data[1])})
member_game_ID_document : dict = self.member_db.find_one({"game_ID":input_regist_data[0]})
if member_document:
return await ctx.send(f"```이미 등록되어 있습니다!```")
if member_game_ID_document:
return await ctx.send(f"```이미 등록된 [ 아이디 ] 입니다!```")
result = self.member_db.update_one({"_id":int(input_regist_data[1])}, {"$set":{"game_ID":input_regist_data[0], "discord_name":self.bot.get_user(int(input_regist_data[1])).display_name, "permissions":"member", "account":0}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"**[{input_regist_data[0]}] [{input_regist_data[1]}]**(으)로 혈원 등록 실패.")
return await ctx.send(f"**[{input_regist_data[0]}] [{input_regist_data[1]}]**(으)로 혈원 등록 완료!")
################ 혈원아이디 변경 ################
@commands.command(name=commandSetting[56][0], aliases=commandSetting[56][1:])
async def member_forced_modify(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
if not args:
return await ctx.send(f"**{commandSetting[56][0]} [아이디] [디코ID]** 양식으로 변경 해주세요")
input_regist_data : list = args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data < 2:
return await ctx.send(f"**{commandSetting[56][0]} [아이디] [디코ID]** 양식으로 변경 해주세요")
member_data : dict = self.member_db.find_one({"_id":int(input_regist_data[1])})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님, 해당 아이디를 가진 혈원은 등록되어 있지 않습니다!")
if member_data["game_ID"] == input_regist_data[0]:
return await ctx.send(f"{ctx.author.mention}님, 기존 아이디와 변경 아이디가 동일합니다!")
member_game_ID_document : dict = self.member_db.find_one({"game_ID":input_regist_data[0]})
if member_game_ID_document:
return await ctx.send(f"```이미 등록된 [ 아이디 ] 입니다!```")
jungsan_document = list(self.jungsan_db.find({"$and" : [{"$or" : [{"before_jungsan_ID" : member_data['game_ID']}, {"after_jungsan_ID" : member_data['game_ID']}, {"toggle" : member_data['game_ID']}, {"regist" : member_data['game_ID']}]}, {"$or" : [{"itemstatus" : "분배중"}, {"itemstatus" : "미판매"}]}]}).sort("_id", pymongo.ASCENDING))
len_jungsan_document : int = len(jungsan_document)
tmp_before_data : list = []
tmp_after_data : list = []
tmp_toggle_data : str = ""
tmp_regist_data : str = ""
if len_jungsan_document != 0:
for jungsan_data in jungsan_document:
tmp_before_data = jungsan_data["before_jungsan_ID"]
tmp_after_data = jungsan_data["after_jungsan_ID"]
tmp_toggle_data = jungsan_data["toggle"]
tmp_regist_data = jungsan_data["regist"]
if member_data['game_ID'] in jungsan_data["before_jungsan_ID"]:
jungsan_data["before_jungsan_ID"].remove(member_data['game_ID'])
jungsan_data["before_jungsan_ID"].append(input_regist_data[0])
tmp_before_data = jungsan_data["before_jungsan_ID"]
if member_data['game_ID'] in jungsan_data["after_jungsan_ID"]:
jungsan_data["after_jungsan_ID"].remove(member_data['game_ID'])
jungsan_data["after_jungsan_ID"].append(input_regist_data[0])
tmp_after_data = jungsan_data["after_jungsan_ID"]
if member_data['game_ID'] in jungsan_data["toggle"]:
tmp_toggle_data = input_regist_data[0]
if member_data['game_ID'] in jungsan_data["regist"]:
tmp_regist_data = input_regist_data[0]
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":{"regist":tmp_regist_data, "toggle":tmp_toggle_data,"before_jungsan_ID":sorted(tmp_before_data) , "after_jungsan_ID":sorted(tmp_after_data)}}, upsert = False)
result = self.member_db.update_one({"_id":int(input_regist_data[1])}, {"$set":{"game_ID":input_regist_data[0]}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, {member_data['game_ID']}님 아이디 변경 실패.")
return await ctx.send(f"{ctx.author.mention}님, **{member_data['game_ID']}**님 아이디를 **[{input_regist_data[0]}]**로 변경하였습니다.")
################ 혈원아이디 삭제 ################
@is_manager()
@commands.command(name=commandSetting[10][0], aliases=commandSetting[10][1:])
async def member_delete(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"game_ID":args})
if not member_data:
return await ctx.send(f"**[{args}]**님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[10][0]} [아이디]** 양식으로 삭제 해주세요")
jungsan_document = list(self.jungsan_db.find({"$and" : [{"$or": [{"before_jungsan_ID" : args}, {"toggle" : args}, {"regist" : args}]}, {"$or": [{"itemstatus" : "분배중"}, {"itemstatus" : "미판매"}]}]}).sort("_id", pymongo.ASCENDING))
len_jungsan_document : int = len(jungsan_document)
if len_jungsan_document != 0:
remain_jungsan_info : str = ""
plus_remain_money : int = 0
minus_remain_money : int = 0
total_remain_money : int = 0
for jungsan_data in jungsan_document:
tmp_str : str = f"[순번:{jungsan_data['_id']}]({jungsan_data['itemstatus']}) "
if jungsan_data["regist"] == args:
tmp_str += f"[등록] "
if jungsan_data["toggle"] == args:
tmp_str += f"[루팅] "
if jungsan_data['price'] != 0:
minus_remain_money += jungsan_data['price']
tmp_str += f"<-{jungsan_data['price']}> "
if args in jungsan_data["before_jungsan_ID"]:
if jungsan_data["itemstatus"] == "분배중":
plus_remain_money += jungsan_data["each_price"]
tmp_str += f"[참여]|{jungsan_data['price']}/{len(jungsan_data['before_jungsan_ID'])}| < +{jungsan_data['each_price']} >"
else:
tmp_str += f"[참여]"
remain_jungsan_info += f"{tmp_str}\n"
total_remain_money = plus_remain_money - minus_remain_money
await ctx.send(f"```잔여 등록/루팅/정산 목록이 있어 혈원을 삭제할 수 없습니다.```")
embed = discord.Embed(
title = "📜 잔여 등록/루팅/정산 목록",
description = f"```md\n{remain_jungsan_info}```",
color=0x00ff00
)
embed.add_field(name = "\u200b", value = f"은행 잔고 : 💰 **{member_data['account']}**\n정산 금액 : 💰 **{total_remain_money}**")
embed.add_field(name = "\u200b", value = f"잔여 목록을 `일괄정산`하고 혈원[`{args}`]을(를) `삭제` 하고 싶으면 `{int(basicSetting[5])*2}초`내로 ✅를 `클릭`해 주세요!", inline = False)
embed.set_footer(text = f"일괄정산 처리를 원하지 않는 경우 등록내역 수정 등을 통해 혈원[{args}]에 대한 정보를 삭제 후 다시 삭제요청 바랍니다.")
remain_jungsan_info_msg = await ctx.send(embed = embed)
emoji_list : list = ["✅", "❌"]
for emoji in emoji_list:
await remain_jungsan_info_msg.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == remain_jungsan_info_msg.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5])*2)
except asyncio.TimeoutError:
for emoji in emoji_list:
await remain_jungsan_info_msg.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **혈원삭제**를 취소합니다!")
if str(reaction) == "✅":
for jungsan_data in jungsan_document:
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":{"before_jungsan_ID":[], "after_jungsan_ID":sorted(jungsan_data['after_jungsan_ID']+jungsan_data['before_jungsan_ID']), "modifydate":datetime.datetime.now(), "itemstatus":"분배완료"}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
await ctx.send(f"{ctx.author.mention}, 일괄정산 실패.")
await ctx.send(f"📥 일괄정산 완료! 📥")
else:
return await ctx.send(f"**혈원삭제**를 취소하였습니다!")
result = self.member_db.delete_one({"game_ID":args})
return await ctx.send(f"**[{args}]**님을 혈원에서 삭제 하였습니다.")
class manageCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.index_value = 0
self.member_db = self.bot.db.jungsan.member
self.jungsan_db = self.bot.db.jungsan.jungsandata
self.guild_db = self.bot.db.jungsan.guild
self.guild_db_log = self.bot.db.jungsan.guild_log
try:
self.db_index = self.jungsan_db.find().sort([("_id",-1)]).limit(1)
self.index_value = list(self.db_index)[0]["_id"]
except:
pass
################ 참여자 ################
################ 참여내역 및 정산금 확인 ################
@commands.command(name=commandSetting[11][0], aliases=commandSetting[11][1:])
async def participant_data_check(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
title_str : str = f"📜 [{member_data['game_ID']}]님 정산 내역"
member_account = member_data['account']
jungsan_document : list = []
if not args:
jungsan_document = list(self.jungsan_db.find({"$and" : [{"before_jungsan_ID" : member_data['game_ID']}, {"$or" : [{"itemstatus" : "분배중"}, {"itemstatus" : "미판매"}]}]}).sort("_id", pymongo.ASCENDING))
else:
input_distribute_all_finish : list = args.split()
len_input_distribute_all_finish = len(input_distribute_all_finish)
if len_input_distribute_all_finish == 1:
search_member_data : dict = self.member_db.find_one({"game_ID":input_distribute_all_finish[0]})
if not search_member_data:
return await ctx.send(f"**[{input_distribute_all_finish[0]}]**님은 혈원으로 등록되어 있지 않습니다!")
jungsan_document = list(self.jungsan_db.find({"$and" : [{"before_jungsan_ID" : input_distribute_all_finish[0]}, {"$or" : [{"itemstatus" : "분배중"}, {"itemstatus" : "미판매"}]}]}).sort("_id", pymongo.ASCENDING))
if not jungsan_document:
return await ctx.send(f"{ctx.author.mention}님! **[{search_member_data['game_ID']}]**님은 수령할 정산 내역이 없습니다.")
title_str = f"📜 [{search_member_data['game_ID']}]님 정산 내역"
member_account = search_member_data['account']
else:
if input_distribute_all_finish[0] == "순번":
try:
input_distribute_all_finish[1] = int(input_distribute_all_finish[1])
except:
return await ctx.send(f"**[순번] [검색값]**은 \"숫자\"로 입력 해주세요!")
jungsan_document : dict = self.jungsan_db.find_one({"$and" : [{"before_jungsan_ID" : member_data['game_ID']}, {"_id":input_distribute_all_finish[1]}, {"$or" : [{"itemstatus" : "분배중"}, {"itemstatus" : "미판매"}]}]})
if not jungsan_document:
return await ctx.send(f"{ctx.author.mention}님! 수령할 정산 내역이 없습니다.")
embed = get_detail_embed(jungsan_document)
try:
return await ctx.send(embed = embed)
except Exception:
embed.add_field(name = "🚫 이미지 링크 확인 필요 🚫", value = f"```저장된 이미지가 삭제됐습니다.```")
embed.set_image(url = "")
result1 = self.jungsan_db.update_one({"_id":input_distribute_all_finish[1]}, {"$set":{"image_url":""}}, upsert = True)
if result1.raw_result["nModified"] < 1 and "upserted" not in result1.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 실패.")
return await ctx.send(embed = embed)
elif input_distribute_all_finish[0] == "보스명":
jungsan_document = list(self.jungsan_db.find({"$and" : [{"before_jungsan_ID" : member_data['game_ID']}, {"boss":input_distribute_all_finish[1]}, {"$or" : [{"itemstatus" : "분배중"}, {"itemstatus" : "미판매"}]}]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "아이템":
jungsan_document = list(self.jungsan_db.find({"$and" : [{"before_jungsan_ID" : member_data['game_ID']}, {"item":input_distribute_all_finish[1]}, {"$or" : [{"itemstatus" : "분배중"}, {"itemstatus" : "미판매"}]}]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "날짜":
try:
start_search_date : str = datetime.datetime.now().replace(year = int(input_distribute_all_finish[1][:4]), month = int(input_distribute_all_finish[1][5:7]), day = int(input_distribute_all_finish[1][8:10]), hour = 0, minute = 0, second = 0)
end_search_date : str = start_search_date + datetime.timedelta(days = 1)
except:
return await ctx.send(f"**[날짜] [검색값]**은 0000-00-00 형식으로 입력 해주세요!")
jungsan_document = list(self.jungsan_db.find({"$and" : [{"before_jungsan_ID" : member_data['game_ID']}, {"getdate":{"$gte":start_search_date, "$lt":end_search_date}}, {"$or" : [{"itemstatus" : "분배중"}, {"itemstatus" : "미판매"}]}]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "분배상태":
if input_distribute_all_finish[1] == "분배중":
jungsan_document = list(self.jungsan_db.find({"$and" : [{"before_jungsan_ID" : member_data['game_ID']}, {"itemstatus" : "분배중"}]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[1] == "미판매":
jungsan_document = list(self.jungsan_db.find({"$and" : [{"before_jungsan_ID" : member_data['game_ID']}, {"itemstatus" : "미판매"}]}).sort("_id", pymongo.ASCENDING))
else:
return await ctx.send(f"**[분배상태] [검색값]**은 \"미판매\" 혹은 \"분배중\"로 입력 해주세요!")
else:
return await ctx.send(f"**[검색조건]**이 잘못 됐습니다. **[검색조건]**은 **[순번, 보스명, 아이템, 날짜, 분배상태]** 다섯가지 중 **1개**를 입력 하셔야합니다!")
if len(jungsan_document) == 0:
return await ctx.send(f"{ctx.author.mention}님! 수령할 정산 내역이 없습니다.")
total_money : int = 0
toggle_list : list = []
toggle_list = sorted(list(set([jungsan_data['toggle'] for jungsan_data in jungsan_document])))
if "혈비" in toggle_list:
toggle_list.remove("혈비")
embed = discord.Embed(
title = title_str,
description = "",
color=0x00ff00
)
embed.add_field(name = f"🏦 **[ 은행 ]**", value = f"**```fix\n {member_account}```**")
for game_id in toggle_list:
each_price : int = 0
info_cnt : int = 0
tmp_info : list = []
tmp_info.append("")
for jungsan_data in jungsan_document:
if jungsan_data['toggle'] == game_id:
if len(tmp_info[info_cnt]) > 900:
tmp_info.append("")
info_cnt += 1
if jungsan_data['itemstatus'] == "미판매":
tmp_info[info_cnt] += f"-[순번:{jungsan_data['_id']}]|{jungsan_data['getdate'].strftime('%y-%m-%d')}|{jungsan_data['boss']}|{jungsan_data['item']}|{jungsan_data['itemstatus']}\n"
else:
each_price += jungsan_data['each_price']
if jungsan_data["ladder_check"]:
tmp_info[info_cnt] += f"+[순번:{jungsan_data['_id']}]|{jungsan_data['getdate'].strftime('%y-%m-%d')}|{jungsan_data['boss']}|{jungsan_data['item']}|🌟|💰{jungsan_data['each_price']}\n"
else:
tmp_info[info_cnt] += f"+[순번:{jungsan_data['_id']}]|{jungsan_data['getdate'].strftime('%y-%m-%d')}|{jungsan_data['boss']}|{jungsan_data['item']}|💰{jungsan_data['each_price']}\n"
total_money += each_price
if len(tmp_info) > 1:
embed.add_field(
name = f"[ {game_id} ]님께 받을 내역 (총 💰 {each_price} )",
value = f"```diff\n{tmp_info[0]}```",
inline = False
)
for i in range(len(tmp_info)-1):
embed.add_field(
name = f"\u200b",
value = f"```diff\n{tmp_info[i+1]}```",
inline = False
)
else:
embed.add_field(
name = f"[ {game_id} ]님께 받을 내역 (총 💰 {each_price} )",
value = f"```diff\n{tmp_info[0]}```",
inline = False
)
await ctx.send(embed = embed)
if int(total_money) == 0:
return
else:
embed1 = discord.Embed(
title = f"총 수령 예정 금액 : 💰 {total_money}",
description = "",
color=0x00ff00
)
return await ctx.send(embed = embed1)
################ 등록자 ################
################ 분배등록 ################
@commands.command(name=commandSetting[12][0], aliases=commandSetting[12][1:])
async def regist_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[12][0]} [보스명] [아이템명] [루팅자] [참여자1] [참여자2]...**\n**{commandSetting[12][0]} [보스명] [아이템명1] [아이템명2].. *[루팅자] [참여자1] [참여자2]...**\n양식으로 등록 해주세요")
input_data : list = []
input_data_list : list = []
tmp_args : str = ""
tmp_image_url : str = ""
boss_data : list = []
join_member_data : list = []
loot_member_data : list = []
items_list : list = []
result_list : list = []
init_index_value = self.index_value
tmp_args = args
if args.find("https://") != -1:
input_data = args.split("https://")
tmp_args = input_data[0]
tmp_image_url = f"https://{input_data[1]}"
try:
if tmp_args.find("*") != -1:
input_data = tmp_args.split("*")
input_data_list = input_data[0].split()
boss_data = [input_data_list[0]]
items_list = input_data_list[1:]
loot_member_data = [input_data[1].split()[0]]
join_member_data = input_data[1].split()[1:]
else:
input_data = tmp_args.split()
boss_data = [input_data[0]]
items_list = [input_data[1]]
loot_member_data = [input_data[2]]
join_member_data = input_data[3:]
except:
return await ctx.send(f"**{commandSetting[12][0]} [보스명] [아이템명] [루팅자] [참여자1] [참여자2]...**\n**{commandSetting[12][0]} [보스명] [아이템명1] [아이템명2].. *[루팅자] [참여자1] [참여자2]...**\n양식으로 등록 해주세요")
if len(boss_data) < 1 or len(items_list) < 1 or len(join_member_data) < 1 or len(loot_member_data) < 1:
return await ctx.send(f"**{commandSetting[12][0]} [보스명] [아이템명] [루팅자] [참여자1] [참여자2]...** 양식으로 등록 해주세요\n**{commandSetting[12][0]} [보스명] [아이템명1] [아이템명2].. *[루팅자] [참여자1] [참여자2]...**\n양식으로 등록 해주세요")
check_member_data : list = []
check_member_list : list = []
wrong_input_id : list = []
gulid_money_insert_check : bool = False
loot_member_info : dict = {}
if loot_member_data[0] == "혈비":
gulid_money_insert_check = True
loot_member_info = {"_id":ctx.author.id}
else:
gulid_money_insert_check = False
loot_member_info = self.member_db.find_one({"game_ID":loot_member_data[0]})
if not loot_member_info:
wrong_input_id.append(f"💥{loot_member_data[0]}")
#return await ctx.send(f"```루팅자 [{input_regist_data[2]}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
check_member_data = list(self.member_db.find())
for game_id in check_member_data:
check_member_list.append(game_id['game_ID'])
for game_id in join_member_data:
if game_id not in check_member_list:
wrong_input_id.append(game_id)
if len(wrong_input_id) > 0:
return await ctx.send(f"```[{', '.join(wrong_input_id)}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
for item_data in items_list:
self.index_value += 1
input_time : datetime = datetime.datetime.now()
insert_data : dict = {}
insert_data = {"_id":self.index_value,
"regist_ID":str(ctx.author.id),
"regist":member_data["game_ID"],
"getdate":input_time,
"boss":boss_data[0],
"item":item_data,
"toggle":loot_member_data[0],
"toggle_ID":str(loot_member_info["_id"]),
"itemstatus":"미판매",
"price":0,
"each_price":0,
"before_jungsan_ID":sorted(list(set(join_member_data))),
"after_jungsan_ID":[],
"modifydate":input_time,
"gulid_money_insert":gulid_money_insert_check,
"bank_money_insert":False,
"ladder_check":False,
"image_url":tmp_image_url
}
# "_id" : int = 순번
# "regist_ID" : str = 등록자ID
# "regist" : str = 등록자 겜 ID
# "getdate" : datetime = 등록날짜
# "boss" : str = 보스명
# "item" : str = 아이템명
# "toggle" : str = 루팅자 게임 ID
# "toggle_ID" : str = 루팅자ID
# "itemstatus" : str = 아이템상태(미판매, 분배중, 분배완료)
# "price" : int = 가격
# "each_price" : int = 분배가격
# "before_jungsan_ID" : list = 참석명단(분배전)
# "after_jungsan_ID" : list = 참석명단(분배후)
# "modifydate" : datetime = 수정날짜
# "gulid_money_insert" : bool = 혈비등록여부
# "bank_money_insert" : bool = 은행입금여부
# "ladder_check":False
# "image_url":이미지 url
result_list.append(insert_data)
embed = discord.Embed(
title = "📜 등록 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 일시 ]", value = f"```{insert_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{insert_data['boss']}```")
if len(items_list) < 2:
embed.add_field(name = "[ 아이템 ]", value = f"```{insert_data['item']}```")
else:
embed.add_field(name = "[ 아이템 ]", value = f"```{', '.join(items_list)}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{insert_data['toggle']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(insert_data['before_jungsan_ID'])}```")
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**입력하신 등록 내역을 확인해 보세요!**\n**등록 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 등록이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
self.index_value = init_index_value
return await ctx.send(f"시간이 초과됐습니다. **등록**를 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.insert_many(result_list)
if len(result.inserted_ids) != len(items_list):
return await ctx.send(f"{ctx.author.mention}, 정산 뽑기등록 실패.")
return await ctx.send(f"📥 **[ 순번 : {', '.join(map(str, result.inserted_ids))} ]** 정산 등록 완료! 📥")
else:
self.index_value = init_index_value
return await ctx.send(f"**등록**이 취소되었습니다.\n")
################ 분배뽑기등록 ################
@commands.command(name=commandSetting[53][0], aliases=commandSetting[53][1:])
async def ladder_regist_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[53][0]} [보스명] [아이템명] [루팅자] [뽑을인원] [참여자1] [참여자2]...** 양식으로 등록 해주세요")
tmp_args : str = ""
tmp_image_url : str = ""
if args.find("https://") != -1:
tmp_data = args.split("https://")
tmp_args = tmp_data[0]
tmp_image_url = f"https://{tmp_data[1]}"
else:
tmp_args = args
input_regist_data : list = tmp_args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data < 5:
return await ctx.send(f"**{commandSetting[53][0]} [보스명] [아이템명] [루팅자] [뽑을인원] [참여자1] [참여자2]...** 양식으로 등록 해주세요")
check_member_data : list = []
check_member_list : list = []
wrong_input_id : list = []
gulid_money_insert_check : bool = False
loot_member_data : dict = {}
if input_regist_data[2] == "혈비":
gulid_money_insert_check = True
loot_member_data = {"_id":ctx.author.id}
else:
gulid_money_insert_check = False
loot_member_data = self.member_db.find_one({"game_ID":input_regist_data[2]})
if not loot_member_data:
wrong_input_id.append(f"💥{input_regist_data[2]}")
#return await ctx.send(f"```루팅자 [{input_regist_data[2]}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
try:
ladder_num = int(input_regist_data[3])
except ValueError:
return await ctx.send(f"**[뽑을인원]**은 숫자로 입력해주세요")
tmp_before_jungsan_ID : list = []
tmp_before_jungsan_ID = input_regist_data[4:]
# tmp_before_jungsan_ID = list(set(input_regist_data[4:])) # 중복제거
if ladder_num <= 0:
return await ctx.send(f"**[뽑을인원]**이 0보다 작거나 같습니다. 재입력 해주세요")
if ladder_num >= len(input_regist_data[4:]):
return await ctx.send(f"**[뽑을인원]**이 총 인원과 같거나 많습니다. 재입력 해주세요")
check_member_data = list(self.member_db.find())
for game_id in check_member_data:
check_member_list.append(game_id['game_ID'])
for game_id in input_regist_data[4:]:
if game_id not in check_member_list:
wrong_input_id.append(game_id)
if len(wrong_input_id) > 0:
return await ctx.send(f"```[{', '.join(wrong_input_id)}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
result_before_jungsan_ID : list = []
for _ in range(ladder_num + 5):
random.shuffle(tmp_before_jungsan_ID)
for _ in range(ladder_num + 5):
result_before_jungsan_ID = random.sample(tmp_before_jungsan_ID, ladder_num)
input_time : datetime = datetime.datetime.now()
insert_data : dict = {}
insert_data = {"regist_ID":str(ctx.author.id),
"regist":member_data["game_ID"],
"getdate":input_time,
"boss":input_regist_data[0],
"item":input_regist_data[1],
"toggle":input_regist_data[2],
"toggle_ID":str(loot_member_data["_id"]),
"itemstatus":"미판매",
"price":0,
"each_price":0,
"before_jungsan_ID":sorted(result_before_jungsan_ID),
"after_jungsan_ID":[],
"modifydate":input_time,
"gulid_money_insert":gulid_money_insert_check,
"bank_money_insert":False,
"ladder_check":True,
"image_url":tmp_image_url
}
embed = discord.Embed(
title = "📜 뽑기등록 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 일시 ]", value = f"```{insert_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{insert_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{insert_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{insert_data['toggle']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(insert_data['before_jungsan_ID'])}```")
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**입력하신 등록 내역을 확인해 보세요!**\n**등록 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 등록이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **뽑기등록**를 취소합니다!")
if str(reaction) == "⭕":
self.index_value += 1
result = self.jungsan_db.update_one({"_id":self.index_value}, {"$set":insert_data}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 뽑기등록 실패.")
return await ctx.send(f"📥 **[ 순번 : {self.index_value} ]** 정산 뽑기등록 완료! 📥")
else:
return await ctx.send(f"**뽑기등록**이 취소되었습니다.\n")
################ 전체내역확인 ################
@is_manager()
@commands.command(name=commandSetting[43][0], aliases=commandSetting[43][1:])
async def all_distribute_check(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
visual_flag : int = 0
jungsan_document : list = []
if not args:
jungsan_document : list = list(self.jungsan_db.find({}).sort("_id", pymongo.ASCENDING))
else:
input_distribute_all_finish : list = args.split()
if input_distribute_all_finish[0] == "상세":
visual_flag = 1
del(input_distribute_all_finish[0])
len_input_distribute_all_finish = len(input_distribute_all_finish)
if len_input_distribute_all_finish == 0:
jungsan_document : list = list(self.jungsan_db.find({}).sort("_id", pymongo.ASCENDING))
elif len_input_distribute_all_finish != 2:
return await ctx.send(f"**{commandSetting[43][0]} (상세) [검색조건] [검색값]** 형식으로 입력 해주세요! **[검색조건]**은 **[순번, 보스명, 아이템, 루팅, 등록, 날짜, 분배상태]** 일곱가지 중 **1개**를 입력 하셔야합니다!")
else:
if input_distribute_all_finish[0] == "순번":
try:
input_distribute_all_finish[1] = int(input_distribute_all_finish[1])
except:
return await ctx.send(f"**[순번] [검색값]**은 \"숫자\"로 입력 해주세요!")
jungsan_document : dict = self.jungsan_db.find_one({"_id":input_distribute_all_finish[1]})
if not jungsan_document:
return await ctx.send(f"{ctx.author.mention}님! 등록된 정산 목록이 없습니다.")
embed = get_detail_embed(jungsan_document)
try:
return await ctx.send(embed = embed)
except Exception:
embed.add_field(name = "🚫 이미지 링크 확인 필요 🚫", value = f"```저장된 이미지가 삭제됐습니다.```")
embed.set_image(url = "")
result1 = self.jungsan_db.update_one({"_id":input_distribute_all_finish[1]}, {"$set":{"image_url":""}}, upsert = True)
if result1.raw_result["nModified"] < 1 and "upserted" not in result1.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 실패.")
return await ctx.send(embed = embed)
elif input_distribute_all_finish[0] == "보스명":
jungsan_document : list = list(self.jungsan_db.find({"boss":input_distribute_all_finish[1]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "아이템":
jungsan_document : list = list(self.jungsan_db.find({"item":input_distribute_all_finish[1]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "루팅":
jungsan_document : list = list(self.jungsan_db.find({"toggle":input_distribute_all_finish[1]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "등록":
jungsan_document : list = list(self.jungsan_db.find({"regist":input_distribute_all_finish[1]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "날짜":
try:
start_search_date : str = datetime.datetime.now().replace(year = int(input_distribute_all_finish[1][:4]), month = int(input_distribute_all_finish[1][5:7]), day = int(input_distribute_all_finish[1][8:10]), hour = 0, minute = 0, second = 0)
end_search_date : str = start_search_date + datetime.timedelta(days = 1)
except:
return await ctx.send(f"**[날짜] [검색값]**은 0000-00-00 형식으로 입력 해주세요!")
jungsan_document : list = list(self.jungsan_db.find({"getdate":{"$gte":start_search_date, "$lt":end_search_date}}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "분배상태":
if input_distribute_all_finish[1] == "분배중":
jungsan_document : list = list(self.jungsan_db.find({"itemstatus" : "분배중"}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[1] == "미판매":
jungsan_document : list = list(self.jungsan_db.find({"itemstatus" : "미판매"}).sort("_id", pymongo.ASCENDING))
else:
return await ctx.send(f"**[분배상태] [검색값]**은 \"미판매\" 혹은 \"분배중\"로 입력 해주세요!")
else:
return await ctx.send(f"**[검색조건]**이 잘못 됐습니다. **[검색조건]**은 **[순번, 보스명, 아이템, 루팅, 등록, 날짜, 분배상태]** 일곱가지 중 **1개**를 입력 하셔야합니다!")
if len(jungsan_document) == 0:
return await ctx.send(f"{ctx.author.mention}님! 등록된 정산 목록이 없습니다.")
total_distribute_money : int = 0
embed_list : list = []
embed_limit_checker : int = 0
embed_cnt : int = 0
detail_title_info : str = ""
detail_info : str = ""
embed = discord.Embed(
title = f"📜 전체 등록 내역",
description = "",
color=0x00ff00
)
embed_list.append(embed)
for jungsan_data in jungsan_document:
embed_limit_checker += 1
if embed_limit_checker == 20:
embed_limit_checker = 0
embed_cnt += 1
tmp_embed = discord.Embed(
title = "",
description = "",
color=0x00ff00
)
embed_list.append(tmp_embed)
guild_save_money : str = ""
if basicSetting[8] != 0 and jungsan_data['bank_money_insert']:
guild_save_money = f"[ 혈비적립 : 💰{jungsan_data['price'] - (jungsan_data['each_price'] * (len(jungsan_data['before_jungsan_ID'])+len(jungsan_data['after_jungsan_ID'])))} ]"
if jungsan_data['gulid_money_insert']:
if jungsan_data['itemstatus'] == "미판매":
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | 혈비적립예정\n[ 등록자 : {jungsan_data['regist']} ]"
detail_info = f"```fix\n[ 혈비적립 ]```"
else:
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | 혈비적립완료\n[ 등록자 : {jungsan_data['regist']} ]"
detail_info = f"~~```fix\n[ 혈비적립 ]```~~"
elif jungsan_data['bank_money_insert']:
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | 은행저축완료\n[ 등록자 : {jungsan_data['regist']} ] {guild_save_money}"
detail_info = f"~~```fix\n[ 은행저축 ]```~~"
else:
if jungsan_data['itemstatus'] == "분배중":
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | {jungsan_data['itemstatus']} : 1인당 💰{jungsan_data['each_price']}\n[ 등록자 : {jungsan_data['regist']} ] {guild_save_money}"
if visual_flag == 0:
detail_info = f"```fix\n[ 분배중 ] : {len(jungsan_data['before_jungsan_ID'])}명 [ 분배완료 ] : {len(jungsan_data['after_jungsan_ID'])}명```"
else:
detail_info = f"```diff\n+ 분 배 중 : {len(jungsan_data['before_jungsan_ID'])}명 (💰{len(jungsan_data['before_jungsan_ID'])*jungsan_data['each_price']})\n{', '.join(jungsan_data['before_jungsan_ID'])}\n- 분배완료 : {len(jungsan_data['after_jungsan_ID'])}명 (💰{len(jungsan_data['after_jungsan_ID'])*jungsan_data['each_price']})\n{', '.join(jungsan_data['after_jungsan_ID'])}```"
total_distribute_money += len(jungsan_data['before_jungsan_ID'])*int(jungsan_data['each_price'])
elif jungsan_data['itemstatus'] == "미판매":
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | {jungsan_data['itemstatus']}\n[ 등록자 : {jungsan_data['regist']} ] {guild_save_money}"
if visual_flag == 0:
detail_info = f"```ini\n[ 참여자 ] : {len(jungsan_data['before_jungsan_ID'])}명```"
else:
detail_info = f"```ini\n[ 참여자 ] : {len(jungsan_data['before_jungsan_ID'])}명\n{', '.join(jungsan_data['before_jungsan_ID'])}```"
else:
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | {jungsan_data['itemstatus']} | 💰~~{jungsan_data['price']}~~\n[ 등록자 : {jungsan_data['regist']} ] {guild_save_money}"
if visual_flag == 0:
detail_info = f"~~```yaml\n[ 분배완료 ] : {len(jungsan_data['after_jungsan_ID'])}명```~~"
else:
detail_info = f"~~```yaml\n[ 분배완료 ] : {len(jungsan_data['after_jungsan_ID'])}명\n{', '.join(jungsan_data['after_jungsan_ID'])}```~~"
if 'image_url' in jungsan_data.keys():
if jungsan_data['image_url'] != "":
detail_title_info += " 📸"
if jungsan_data['ladder_check']:
detail_title_info += " 🌟"
embed_list[embed_cnt].add_field(name = detail_title_info,
value = detail_info,
inline = False)
if len(embed_list) > 1:
for embed_data in embed_list:
await asyncio.sleep(0.1)
await ctx.send(embed = embed_data)
else:
await ctx.send(embed = embed)
embed1 = discord.Embed(
title = f"총 정산 금액 : 💰 {str(total_distribute_money)}",
description = "",
color=0x00ff00
)
return await ctx.send(embed = embed1)
################ 등록내역확인 ################
@commands.command(name=commandSetting[13][0], aliases=commandSetting[13][1:])
async def distribute_check(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
visual_flag : int = 0
jungsan_document : list = []
if not args:
jungsan_document : list = list(self.jungsan_db.find({"regist_ID":str(ctx.author.id)}).sort("_id", pymongo.ASCENDING))
else:
input_distribute_all_finish : list = args.split()
if input_distribute_all_finish[0] == "상세":
visual_flag = 1
del(input_distribute_all_finish[0])
len_input_distribute_all_finish = len(input_distribute_all_finish)
if len_input_distribute_all_finish == 0:
jungsan_document : list = list(self.jungsan_db.find({"regist_ID":str(ctx.author.id)}).sort("_id", pymongo.ASCENDING))
elif len_input_distribute_all_finish != 2:
return await ctx.send(f"**{commandSetting[13][0]} (상세) [검색조건] [검색값]** 형식으로 입력 해주세요! **[검색조건]**은 **[순번, 보스명, 아이템, 날짜, 분배상태]** 다섯가지 중 **1개**를 입력 하셔야합니다!")
else:
if input_distribute_all_finish[0] == "순번":
try:
input_distribute_all_finish[1] = int(input_distribute_all_finish[1])
except:
return await ctx.send(f"**[순번] [검색값]**은 \"숫자\"로 입력 해주세요!")
jungsan_document : dict = self.jungsan_db.find_one({"regist_ID":str(ctx.author.id), "_id":input_distribute_all_finish[1]})
if not jungsan_document:
return await ctx.send(f"{ctx.author.mention}님! 등록된 정산 목록이 없습니다.")
embed = get_detail_embed(jungsan_document)
try:
return await ctx.send(embed = embed)
except Exception:
embed.add_field(name = "🚫 이미지 링크 확인 필요 🚫", value = f"```저장된 이미지가 삭제됐습니다.```")
embed.set_image(url = "")
result1 = self.jungsan_db.update_one({"_id":input_distribute_all_finish[1]}, {"$set":{"image_url":""}}, upsert = True)
if result1.raw_result["nModified"] < 1 and "upserted" not in result1.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 실패.")
return await ctx.send(embed = embed)
elif input_distribute_all_finish[0] == "보스명":
jungsan_document : list = list(self.jungsan_db.find({"regist_ID":str(ctx.author.id), "boss":input_distribute_all_finish[1]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "아이템":
jungsan_document : list = list(self.jungsan_db.find({"regist_ID":str(ctx.author.id), "item":input_distribute_all_finish[1]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "날짜":
try:
start_search_date : str = datetime.datetime.now().replace(year = int(input_distribute_all_finish[1][:4]), month = int(input_distribute_all_finish[1][5:7]), day = int(input_distribute_all_finish[1][8:10]), hour = 0, minute = 0, second = 0)
end_search_date : str = start_search_date + datetime.timedelta(days = 1)
except:
return await ctx.send(f"**[날짜] [검색값]**은 0000-00-00 형식으로 입력 해주세요!")
jungsan_document : list = list(self.jungsan_db.find({"regist_ID":str(ctx.author.id), "getdate":{"$gte":start_search_date, "$lt":end_search_date}}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "분배상태":
if input_distribute_all_finish[1] == "분배중":
jungsan_document : list = list(self.jungsan_db.find({"regist_ID":str(ctx.author.id), "itemstatus" : "분배중"}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[1] == "미판매":
jungsan_document : list = list(self.jungsan_db.find({"regist_ID":str(ctx.author.id), "itemstatus" : "미판매"}).sort("_id", pymongo.ASCENDING))
else:
return await ctx.send(f"**[분배상태] [검색값]**은 \"미판매\" 혹은 \"분배중\"로 입력 해주세요!")
else:
return await ctx.send(f"**[검색조건]**이 잘못 됐습니다. **[검색조건]**은 **[순번, 보스명, 아이템, 날짜, 분배상태]** 다섯가지 중 **1개**를 입력 하셔야합니다!")
if len(jungsan_document) == 0:
return await ctx.send(f"{ctx.author.mention}님! 등록된 정산 목록이 없습니다.")
total_distribute_money : int = 0
embed_list : list = []
embed_limit_checker : int = 0
embed_cnt : int = 0
detail_title_info : str = ""
detail_info : str = ""
embed = discord.Embed(
title = f"📜 [{member_data['game_ID']}]님 등록 내역",
description = "",
color=0x00ff00
)
embed_list.append(embed)
for jungsan_data in jungsan_document:
embed_limit_checker += 1
if embed_limit_checker == 20:
embed_limit_checker = 0
embed_cnt += 1
tmp_embed = discord.Embed(
title = "",
description = "",
color=0x00ff00
)
embed_list.append(tmp_embed)
guild_save_money : str = ""
if basicSetting[8] != 0 and jungsan_data['bank_money_insert']:
guild_save_money = f"\n[ 혈비적립 : 💰{jungsan_data['price'] - (jungsan_data['each_price'] * (len(jungsan_data['before_jungsan_ID'])+len(jungsan_data['after_jungsan_ID'])))} ]"
if jungsan_data['gulid_money_insert']:
if jungsan_data['itemstatus'] == "미판매":
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | 혈비적립예정"
detail_info = f"```fix\n[ 혈비적립 ]```"
else:
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | 혈비적립완료"
detail_info = f"~~```fix\n[ 혈비적립 ]```~~"
elif jungsan_data['bank_money_insert']:
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | 은행저축완료{guild_save_money}"
detail_info = f"~~```fix\n[ 은행저축 ]```~~"
else:
if jungsan_data['itemstatus'] == "분배중":
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | {jungsan_data['itemstatus']} : 1인당 💰{jungsan_data['each_price']}{guild_save_money}"
if visual_flag == 0:
detail_info = f"```fix\n[ 분배중 ] : {len(jungsan_data['before_jungsan_ID'])}명 [ 분배완료 ] : {len(jungsan_data['after_jungsan_ID'])}명```"
else:
detail_info = f"```diff\n+ 분 배 중 : {len(jungsan_data['before_jungsan_ID'])}명 (💰{len(jungsan_data['before_jungsan_ID'])*jungsan_data['each_price']})\n{', '.join(jungsan_data['before_jungsan_ID'])}\n- 분배완료 : {len(jungsan_data['after_jungsan_ID'])}명 (💰{len(jungsan_data['after_jungsan_ID'])*jungsan_data['each_price']})\n{', '.join(jungsan_data['after_jungsan_ID'])}```"
total_distribute_money += len(jungsan_data['before_jungsan_ID'])*int(jungsan_data['each_price'])
elif jungsan_data['itemstatus'] == "미판매":
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | {jungsan_data['itemstatus']}{guild_save_money}"
if visual_flag == 0:
detail_info = f"```ini\n[ 참여자 ] : {len(jungsan_data['before_jungsan_ID'])}명```"
else:
detail_info = f"```ini\n[ 참여자 ] : {len(jungsan_data['before_jungsan_ID'])}명\n{', '.join(jungsan_data['before_jungsan_ID'])}```"
else:
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | {jungsan_data['itemstatus']} | 💰~~{jungsan_data['price']}~~{guild_save_money}"
if visual_flag == 0:
detail_info = f"~~```yaml\n[ 분배완료 ] : {len(jungsan_data['after_jungsan_ID'])}명```~~"
else:
detail_info = f"~~```yaml\n[ 분배완료 ] : {len(jungsan_data['after_jungsan_ID'])}명\n{', '.join(jungsan_data['after_jungsan_ID'])}```~~"
if 'image_url' in jungsan_data.keys():
if jungsan_data['image_url'] != "":
detail_title_info += " 📸"
if jungsan_data['ladder_check']:
detail_title_info += " 🌟"
embed_list[embed_cnt].add_field(name = detail_title_info,
value = detail_info,
inline = False)
if len(embed_list) > 1:
for embed_data in embed_list:
await asyncio.sleep(0.1)
await ctx.send(embed = embed_data)
else:
await ctx.send(embed = embed)
embed1 = discord.Embed(
title = f"총 정산 금액 : 💰 {str(total_distribute_money)}",
description = "",
color=0x00ff00
)
return await ctx.send(embed = embed1)
################ 등록내역수정 ################
@commands.command(name=commandSetting[14][0], aliases=commandSetting[14][1:])
async def modify_regist_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[14][0]} [순번] [보스명] [아이템명] [루팅자] [참여자1] [참여자2]...** 양식으로 등록 해주세요")
input_regist_data : list = args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data < 5:
return await ctx.send(f"**{commandSetting[14][0]} [순번] [보스명] [아이템명] [루팅자] [참여자1] [참여자2]...** 양식으로 등록 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"_id":int(input_regist_data[0]), "itemstatus":"미판매"})
else:
jungsan_data : dict = self.jungsan_db.find_one({"_id":int(input_regist_data[0]), "regist_ID":str(member_data['_id']), "itemstatus":"미판매"})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]**중이 아니거나 없습니다. **[ {commandSetting[13][0]} ]** 명령을 통해 확인해주세요.\n※정산 등록 내역 수정은 **[ 분배상태 ]**가 **[ 미판매 ]** 중인 등록건만 수정 가능합니다!")
del(input_regist_data[0])
check_member_data : list = []
check_member_list : list = []
check_member_id_list : list = []
wrong_input_id : list = []
gulid_money_insert_check : bool = False
loot_member_data : dict = {}
if input_regist_data[2] == "혈비":
gulid_money_insert_check = True
loot_member_data["_id"] = ctx.author.id
else:
gulid_money_insert_check = False
loot_member_data = self.member_db.find_one({"game_ID":input_regist_data[2]})
if not loot_member_data:
wrong_input_id.append(f"💥{input_regist_data[2]}")
#return await ctx.send(f"```루팅자 [{input_regist_data[2]}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
check_member_data = list(self.member_db.find())
for game_id in check_member_data:
check_member_list.append(game_id['game_ID'])
if game_id['game_ID'] == input_regist_data[2]:
loot_member_data["_id"] = game_id['_id']
for game_id in input_regist_data[3:]:
if game_id not in check_member_list:
wrong_input_id.append(game_id)
if len(wrong_input_id) > 0:
return await ctx.send(f"```[{', '.join(wrong_input_id)}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
input_time : datetime = datetime.datetime.now()
insert_data : dict = {}
insert_data = jungsan_data.copy()
insert_data["boss"] = input_regist_data[0]
insert_data["item"] = input_regist_data[1]
insert_data["toggle"] = input_regist_data[2]
insert_data["toggle_ID"] = str(loot_member_data["_id"])
insert_data["before_jungsan_ID"] = list(set(input_regist_data[3:]))
insert_data["modifydate"] = input_time
insert_data["gulid_money_insert"] = gulid_money_insert_check
embed = discord.Embed(
title = "📜 수정 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
if jungsan_data['boss'] == insert_data['boss']:
embed.add_field(name = "[ 보스 ]", value = f"```{insert_data['boss']}```")
else:
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']} → {insert_data['boss']}```")
if jungsan_data['item'] == insert_data['item']:
embed.add_field(name = "[ 아이템 ]", value = f"```{insert_data['item']}```")
else:
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']} → {insert_data['item']}```")
if jungsan_data['toggle'] == insert_data['toggle']:
embed.add_field(name = "[ 루팅 ]", value = f"```{insert_data['toggle']}```")
else:
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']} → {insert_data['toggle']}```")
if jungsan_data['before_jungsan_ID'] == insert_data['before_jungsan_ID']:
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(insert_data['before_jungsan_ID'])}```")
else:
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID'])} → {', '.join(insert_data['before_jungsan_ID'])}```")
embed.set_footer(text = f"{insert_data['modifydate'].strftime('%y-%m-%d %H:%M:%S')} 수정!")
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**입력하신 수정 내역을 확인해 보세요!**\n**수정 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 수정이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **수정**을 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":insert_data}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 내역 수정 실패.")
return await ctx.send(f"📥 정산 등록 내역 수정 완료! 📥")
else:
return await ctx.send(f"**수정**이 취소되었습니다.\n")
################ 등록삭제 ################
@commands.command(name=commandSetting[15][0], aliases=commandSetting[15][1:])
async def distribute_delete(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[15][0]} [순번]** 양식으로 확인 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(args)}, {"$or" : [{"itemstatus" : "분배완료"}, {"itemstatus" : "미판매"}]}]})
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"regist_ID":str(ctx.author.id)}, {"_id":int(args)}, {"$or" : [{"itemstatus" : "분배완료"}, {"itemstatus" : "미판매"}]}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 분배중 ]**이거나 없습니다. **[ {commandSetting[13][0]} ]** 명령을 통해 확인해주세요.\n※정산 등록 내역 삭제는 **[ 분배상태 ]**가 **[ 미판매/분배완료 ]** 인 등록건만 수정 가능합니다!")
embed = discord.Embed(
title = "⚠️☠️⚠️ 삭제 내역 ⚠️☠️⚠️",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{jungsan_data['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{jungsan_data['price']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID']+jungsan_data['after_jungsan_ID'])}```")
await ctx.send(embed = embed)
delete_warning_message = await ctx.send(f"**등록 내역을 삭제하시면 다시는 복구할 수 없습니다. 정말로 삭제하시겠습니까?**\n**삭제 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 삭제가 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await delete_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == delete_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await delete_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **삭제**를 취소합니다!")
if str(reaction) == "⭕":
self.jungsan_db.delete_one({"_id":int(args)})
return await ctx.send(f"☠️ 정산 내역 삭제 완료! ☠️")
else:
return await ctx.send(f"**삭제**가 취소되었습니다.\n")
################ 루팅자 ################
@commands.command(name=commandSetting[16][0], aliases=commandSetting[16][1:])
async def loot_distribute_check(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
visual_flag : int = 0
jungsan_document : list = []
if not args:
jungsan_document : list = list(self.jungsan_db.find({"toggle_ID":str(ctx.author.id)}).sort("_id", pymongo.ASCENDING))
else:
input_distribute_all_finish : list = args.split()
if input_distribute_all_finish[0] == "상세":
visual_flag = 1
del(input_distribute_all_finish[0])
len_input_distribute_all_finish = len(input_distribute_all_finish)
if len_input_distribute_all_finish == 0:
jungsan_document : list = list(self.jungsan_db.find({"toggle_ID":str(ctx.author.id)}).sort("_id", pymongo.ASCENDING))
elif len_input_distribute_all_finish != 2:
return await ctx.send(f"**{commandSetting[16][0]} (상세) [검색조건] [검색값]** 형식으로 입력 해주세요! **[검색조건]**은 **[순번, 보스명, 아이템, 날짜, 분배상태]** 다섯가지 중 **1개**를 입력 하셔야합니다!")
else:
if input_distribute_all_finish[0] == "순번":
try:
input_distribute_all_finish[1] = int(input_distribute_all_finish[1])
except:
return await ctx.send(f"**[순번] [검색값]**은 \"숫자\"로 입력 해주세요!")
jungsan_document : dict = self.jungsan_db.find_one({"toggle_ID":str(ctx.author.id), "_id":input_distribute_all_finish[1]})
if not jungsan_document:
return await ctx.send(f"{ctx.author.mention}님! 등록된 정산 목록이 없습니다.")
embed = get_detail_embed(jungsan_document)
try:
return await ctx.send(embed = embed)
except Exception:
embed.add_field(name = "🚫 이미지 링크 확인 필요 🚫", value = f"```저장된 이미지가 삭제됐습니다.```")
embed.set_image(url = "")
result1 = self.jungsan_db.update_one({"_id":input_distribute_all_finish[1]}, {"$set":{"image_url":""}}, upsert = True)
if result1.raw_result["nModified"] < 1 and "upserted" not in result1.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 실패.")
return await ctx.send(embed = embed)
elif input_distribute_all_finish[0] == "보스명":
jungsan_document : list = list(self.jungsan_db.find({"toggle_ID":str(ctx.author.id), "boss":input_distribute_all_finish[1]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "아이템":
jungsan_document : list = list(self.jungsan_db.find({"toggle_ID":str(ctx.author.id), "item":input_distribute_all_finish[1]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "날짜":
try:
start_search_date : str = datetime.datetime.now().replace(year = int(input_distribute_all_finish[1][:4]), month = int(input_distribute_all_finish[1][5:7]), day = int(input_distribute_all_finish[1][8:10]), hour = 0, minute = 0, second = 0)
end_search_date : str = start_search_date + datetime.timedelta(days = 1)
except:
return await ctx.send(f"**[날짜] [검색값]**은 0000-00-00 형식으로 입력 해주세요!")
jungsan_document : list = list(self.jungsan_db.find({"toggle_ID":str(ctx.author.id), "getdate":{"$gte":start_search_date, "$lt":end_search_date}}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "분배상태":
if input_distribute_all_finish[1] == "분배중":
jungsan_document : list = list(self.jungsan_db.find({"toggle_ID":str(ctx.author.id), "itemstatus" : "분배중"}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[1] == "미판매":
jungsan_document : list = list(self.jungsan_db.find({"toggle_ID":str(ctx.author.id), "itemstatus" : "미판매"}).sort("_id", pymongo.ASCENDING))
else:
return await ctx.send(f"**[분배상태] [검색값]**은 \"미판매\" 혹은 \"분배중\"로 입력 해주세요!")
else:
return await ctx.send(f"**[검색조건]**이 잘못 됐습니다. **[검색조건]**은 **[순번, 보스명, 아이템, 날짜, 분배상태]** 다섯가지 중 **1개**를 입력 하셔야합니다!")
if len(jungsan_document) == 0:
return await ctx.send(f"{ctx.author.mention}님! 루팅한 정산 목록이 없습니다.")
total_distribute_money : int = 0
embed_list : list = []
embed_limit_checker : int = 0
embed_cnt : int = 0
detail_title_info : str = ""
detail_info : str = ""
embed = discord.Embed(
title = f"📜 [{member_data['game_ID']}]님 루팅 내역",
description = "",
color=0x00ff00
)
embed_list.append(embed)
for jungsan_data in jungsan_document:
embed_limit_checker += 1
if embed_limit_checker == 20:
embed_limit_checker = 0
embed_cnt += 1
tmp_embed = discord.Embed(
title = "",
description = "",
color=0x00ff00
)
embed_list.append(tmp_embed)
guild_save_money : str = ""
if basicSetting[8] != 0 and jungsan_data['bank_money_insert']:
guild_save_money = f"\n[ 혈비적립 : 💰{jungsan_data['price'] - (jungsan_data['each_price'] * (len(jungsan_data['before_jungsan_ID'])+len(jungsan_data['after_jungsan_ID'])))} ]"
if jungsan_data['gulid_money_insert']:
if jungsan_data['itemstatus'] == "미판매":
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | 혈비적립예정"
detail_info = f"```fix\n[ 혈비적립 ]```"
else:
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | 혈비적립완료"
detail_info = f"~~```fix\n[ 혈비적립 ]```~~"
elif jungsan_data['bank_money_insert']:
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | 은행저축{guild_save_money}"
detail_info = f"~~```fix\n[ 은행저축 ]```~~"
else:
if jungsan_data['itemstatus'] == "분배중":
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | {jungsan_data['itemstatus']} : 1인당 💰{jungsan_data['each_price']}{guild_save_money}"
if visual_flag == 0:
detail_info = f"```fix\n[ 분배중 ] : {len(jungsan_data['before_jungsan_ID'])}명 [ 분배완료 ] : {len(jungsan_data['after_jungsan_ID'])}명```"
else:
detail_info = f"```diff\n+ 분 배 중 : {len(jungsan_data['before_jungsan_ID'])}명 (💰{len(jungsan_data['before_jungsan_ID'])*jungsan_data['each_price']})\n{', '.join(jungsan_data['before_jungsan_ID'])}\n- 분배완료 : {len(jungsan_data['after_jungsan_ID'])}명 (💰{len(jungsan_data['after_jungsan_ID'])*jungsan_data['each_price']})\n{', '.join(jungsan_data['after_jungsan_ID'])}```"
total_distribute_money += len(jungsan_data['before_jungsan_ID'])*int(jungsan_data['each_price'])
elif jungsan_data['itemstatus'] == "미판매":
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | {jungsan_data['itemstatus']}{guild_save_money}"
if visual_flag == 0:
detail_info = f"```ini\n[ 참여자 ] : {len(jungsan_data['before_jungsan_ID'])}명```"
else:
detail_info = f"```ini\n[ 참여자 ] : {len(jungsan_data['before_jungsan_ID'])}명\n{', '.join(jungsan_data['before_jungsan_ID'])}```"
else:
detail_title_info = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | {jungsan_data['itemstatus']} | 💰~~{jungsan_data['price']}~~{guild_save_money}"
if visual_flag == 0:
detail_info = f"~~```yaml\n[ 분배완료 ] : {len(jungsan_data['after_jungsan_ID'])}명```~~"
else:
detail_info = f"~~```yaml\n[ 분배완료 ] : {len(jungsan_data['after_jungsan_ID'])}명\n{', '.join(jungsan_data['after_jungsan_ID'])}```~~"
if 'image_url' in jungsan_data.keys():
if jungsan_data['image_url'] != "":
detail_title_info += " 📸"
if jungsan_data['ladder_check']:
detail_title_info += " 🌟"
embed_list[embed_cnt].add_field(name = detail_title_info,
value = detail_info,
inline = False)
if len(embed_list) > 1:
for embed_data in embed_list:
await asyncio.sleep(0.1)
await ctx.send(embed = embed_data)
else:
await ctx.send(embed = embed)
embed1 = discord.Embed(
title = f"총 정산 금액 : 💰 {str(total_distribute_money)}",
description = "",
color=0x00ff00
)
return await ctx.send(embed = embed1)
################ 루팅내역수정 ################
@commands.command(name=commandSetting[17][0], aliases=commandSetting[17][1:])
async def loot_modify_regist_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[17][0]} [순번] [보스명] [아이템명] [루팅자] [참여자1] [참여자2]...** 양식으로 등록 해주세요")
input_regist_data : list = args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data < 5:
return await ctx.send(f"**{commandSetting[17][0]} [순번] [보스명] [아이템명] [루팅자] [참여자1] [참여자2]...** 양식으로 등록 해주세요")
jungsan_data : dict = self.jungsan_db.find_one({"_id":int(input_regist_data[0]), "toggle_ID":str(member_data['_id']), "itemstatus":"미판매"})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 루팅하신 정산 내역이 **[ 미판매 ]**중이 아니거나 없습니다. **[ {commandSetting[16][0]} ]** 명령을 통해 확인해주세요.\n※정산 등록 내역 수정은 **[ 분배상태 ]**가 **[ 미판매 ]** 중인 루팅건만 수정 가능합니다!")
del(input_regist_data[0])
check_member_data : list = []
check_member_list : list = []
check_member_id_list : list = []
wrong_input_id : list = []
gulid_money_insert_check : bool = False
loot_member_data : dict = {}
if input_regist_data[2] == "혈비":
gulid_money_insert_check = True
loot_member_data["_id"] = ctx.author.id
else:
gulid_money_insert_check = False
loot_member_data = self.member_db.find_one({"game_ID":input_regist_data[2]})
if not loot_member_data:
wrong_input_id.append(f"💥{input_regist_data[2]}")
#return await ctx.send(f"```루팅자 [{input_regist_data[2]}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
check_member_data = list(self.member_db.find())
for game_id in check_member_data:
check_member_list.append(game_id['game_ID'])
if game_id['game_ID'] == input_regist_data[2]:
loot_member_data["_id"] = game_id['_id']
for game_id in input_regist_data[3:]:
if game_id not in check_member_list:
wrong_input_id.append(game_id)
if len(wrong_input_id) > 0:
return await ctx.send(f"```[{', '.join(wrong_input_id)}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
input_time : datetime = datetime.datetime.now()
insert_data : dict = {}
insert_data = jungsan_data.copy()
insert_data["boss"] = input_regist_data[0]
insert_data["item"] = input_regist_data[1]
insert_data["toggle"] = input_regist_data[2]
insert_data["toggle_ID"] = str(loot_member_data["_id"])
insert_data["before_jungsan_ID"] = list(set(input_regist_data[3:]))
insert_data["modifydate"] = input_time
insert_data["gulid_money_insert"] = gulid_money_insert_check
embed = discord.Embed(
title = "📜 수정 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
if jungsan_data['boss'] == insert_data['boss']:
embed.add_field(name = "[ 보스 ]", value = f"```{insert_data['boss']}```")
else:
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']} → {insert_data['boss']}```")
if jungsan_data['item'] == insert_data['item']:
embed.add_field(name = "[ 아이템 ]", value = f"```{insert_data['item']}```")
else:
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']} → {insert_data['item']}```")
if jungsan_data['toggle'] == insert_data['toggle']:
embed.add_field(name = "[ 루팅 ]", value = f"```{insert_data['toggle']}```")
else:
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']} → {insert_data['toggle']}```")
if jungsan_data['before_jungsan_ID'] == insert_data['before_jungsan_ID']:
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(insert_data['before_jungsan_ID'])}```")
else:
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID'])} → {', '.join(insert_data['before_jungsan_ID'])}```")
embed.set_footer(text = f"{insert_data['modifydate'].strftime('%y-%m-%d %H:%M:%S')} 수정!")
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**입력하신 수정 내역을 확인해 보세요!**\n**수정 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 수정이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **수정**을 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":insert_data}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 내역 수정 실패.")
return await ctx.send(f"📥 정산 내역 수정 완료! 📥")
else:
return await ctx.send(f"**수정**이 취소되었습니다.\n")
################ 루팅삭제 ################
@commands.command(name=commandSetting[18][0], aliases=commandSetting[18][1:])
async def loot_distribute_delete(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[18][0]} [순번]** 양식으로 확인 해주세요")
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"toggle_ID":str(ctx.author.id)}, {"_id":int(args)}, {"$or" : [{"itemstatus" : "분배완료"}, {"itemstatus" : "미판매"}]}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 분배중 ]**이거나 없습니다. **[ {commandSetting[16][0]} ]** 명령을 통해 확인해주세요.\n※정산 등록 내역 삭제는 **[ 분배상태 ]**가 **[ 미판매/분배완료 ]** 인 등록건만 수정 가능합니다!")
embed = discord.Embed(
title = "⚠️☠️⚠️ 삭제 내역 ⚠️☠️⚠️",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{jungsan_data['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{jungsan_data['price']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID']+jungsan_data['after_jungsan_ID'])}```")
await ctx.send(embed = embed)
delete_warning_message = await ctx.send(f"**정산 내역을 삭제하시면 다시는 복구할 수 없습니다. 정말로 삭제하시겠습니까?**\n**삭제 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 삭제가 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await delete_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == delete_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await delete_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **삭제**를 취소합니다!")
if str(reaction) == "⭕":
self.jungsan_db.delete_one({"_id":int(args)})
return await ctx.send(f"☠️ 정산 내역 삭제 완료! ☠️")
else:
return await ctx.send(f"**삭제**가 취소되었습니다.\n")
################ 보스수정 ################
@commands.command(name=commandSetting[19][0], aliases=commandSetting[19][1:])
async def modify_regist_boss_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[19][0]} [순번] [보스명]** 양식으로 등록 해주세요")
input_regist_data : list = args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data != 2:
return await ctx.send(f"**{commandSetting[19][0]} [순번] [보스명]** 양식으로 등록 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"$or" : [{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]**중이 아니거나 없습니다. **[ {commandSetting[13][0]}/{commandSetting[16][0]} ]** 명령을 통해 확인해주세요.\n※정산 등록 내역 수정은 **[ 분배상태 ]**가 **[ 미판매 ]** 중인 등록건만 수정 가능합니다!")
if jungsan_data['boss'] == input_regist_data[1]:
return await ctx.send(f"```수정하려는 [보스명:{input_regist_data[1]}](이)가 등록된 [보스명]과 같습니다!```")
input_time : datetime = datetime.datetime.now()
insert_data : dict = {}
insert_data = jungsan_data.copy()
insert_data["boss"] = input_regist_data[1]
insert_data["modifydate"] = input_time
embed = discord.Embed(
title = "📜 수정 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']} → {insert_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{jungsan_data['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{jungsan_data['price']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID'])}```")
embed.set_footer(text = f"{insert_data['modifydate'].strftime('%y-%m-%d %H:%M:%S')} 수정!")
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**입력하신 수정 내역을 확인해 보세요!**\n**수정 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 수정이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **수정**을 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":insert_data}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 내역 수정 실패.")
return await ctx.send(f"📥 정산 등록 내역 수정 완료! 📥")
else:
return await ctx.send(f"**수정**이 취소되었습니다.\n")
################ 템수정 ################
@commands.command(name=commandSetting[20][0], aliases=commandSetting[20][1:])
async def modify_regist_item_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[20][0]} [순번] [아이템명]** 양식으로 등록 해주세요")
input_regist_data : list = args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data != 2:
return await ctx.send(f"**{commandSetting[20][0]} [순번] [아이템명]** 양식으로 등록 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"$or" : [{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]**중이 아니거나 없습니다. **[ {commandSetting[13][0]}/{commandSetting[16][0]} ]** 명령을 통해 확인해주세요.\n※정산 등록 내역 수정은 **[ 분배상태 ]**가 **[ 미판매 ]** 중인 등록건만 수정 가능합니다!")
if jungsan_data['item'] == input_regist_data[1]:
return await ctx.send(f"```수정하려는 [아이템명:{input_regist_data[1]}](이)가 등록된 [아이템명]과 같습니다!```")
input_time : datetime = datetime.datetime.now()
insert_data : dict = {}
insert_data = jungsan_data.copy()
insert_data["item"] = input_regist_data[1]
insert_data["modifydate"] = input_time
embed = discord.Embed(
title = "📜 수정 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']} → {insert_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{jungsan_data['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{jungsan_data['price']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID'])}```")
embed.set_footer(text = f"{insert_data['modifydate'].strftime('%y-%m-%d %H:%M:%S')} 수정!")
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**입력하신 수정 내역을 확인해 보세요!**\n**수정 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 수정이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **수정**을 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":insert_data}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 내역 수정 실패.")
return await ctx.send(f"📥 정산 등록 내역 수정 완료! 📥")
else:
return await ctx.send(f"**수정**이 취소되었습니다.\n")
################ 등록자수정 ################
@is_manager()
@commands.command(name=commandSetting[54][0], aliases=commandSetting[54][1:])
async def modify_regist_user_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[54][0]} [순번] [아이디]** 양식으로 등록 해주세요")
input_regist_data : list = args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data != 2:
return await ctx.send(f"**{commandSetting[54][0]} [순번] [아이디]** 양식으로 등록 해주세요")
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]**중이 아니거나 없습니다. **[ {commandSetting[13][0]}/{commandSetting[16][0]} ]** 명령을 통해 확인해주세요.\n※정산 등록 내역 수정은 **[ 분배상태 ]**가 **[ 미판매 ]** 중인 등록건만 수정 가능합니다!")
if jungsan_data['regist'] == input_regist_data[1]:
return await ctx.send(f"```수정하려는 [등록자:{input_regist_data[1]}](이)가 등록된 [등록자]와 같습니다!```")
check_member_data : list = []
regist_member_data : dict = {}
regist_member_data = self.member_db.find_one({"game_ID":input_regist_data[1]})
if not regist_member_data:
return await ctx.send(f"```등록자 [{input_regist_data[1]}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
check_member_data = list(self.member_db.find())
for game_id in check_member_data:
if game_id['game_ID'] == input_regist_data[1]:
regist_member_data["_id"] = game_id['_id']
input_time : datetime = datetime.datetime.now()
insert_data : dict = {}
insert_data = jungsan_data.copy()
insert_data["regist"] = input_regist_data[1]
insert_data["regist_ID"] = str(regist_member_data["_id"])
insert_data["modifydate"] = input_time
embed = discord.Embed(
title = "📜 수정 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 등록 ]", value = f"```{jungsan_data['regist']} → {insert_data['regist']}```")
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{jungsan_data['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{jungsan_data['price']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID'])}```")
embed.set_footer(text = f"{insert_data['modifydate'].strftime('%y-%m-%d %H:%M:%S')} 수정!")
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**입력하신 수정 내역을 확인해 보세요!**\n**수정 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 수정이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **수정**을 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":insert_data}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 내역 수정 실패.")
return await ctx.send(f"📥 정산 등록 내역 수정 완료! 📥")
else:
return await ctx.send(f"**수정**이 취소되었습니다.\n")
################ 토글수정 ################
@commands.command(name=commandSetting[21][0], aliases=commandSetting[21][1:])
async def modify_regist_toggle_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[21][0]} [순번] [아이디]** 양식으로 등록 해주세요")
input_regist_data : list = args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data != 2:
return await ctx.send(f"**{commandSetting[21][0]} [순번] [아이디]** 양식으로 등록 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"$or" : [{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]**중이 아니거나 없습니다. **[ {commandSetting[13][0]}/{commandSetting[16][0]} ]** 명령을 통해 확인해주세요.\n※정산 등록 내역 수정은 **[ 분배상태 ]**가 **[ 미판매 ]** 중인 등록건만 수정 가능합니다!")
if jungsan_data['toggle'] == input_regist_data[1]:
return await ctx.send(f"```수정하려는 [토글자:{input_regist_data[1]}](이)가 등록된 [토글자]와 같습니다!```")
check_member_data : list = []
gulid_money_insert_check : bool = False
loot_member_data : dict = {}
if input_regist_data[1] == "혈비":
gulid_money_insert_check = True
loot_member_data["_id"] = ctx.author.id
else:
gulid_money_insert_check = False
loot_member_data = self.member_db.find_one({"game_ID":input_regist_data[1]})
if not loot_member_data:
return await ctx.send(f"```루팅자 [{input_regist_data[1]}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
check_member_data = list(self.member_db.find())
for game_id in check_member_data:
if game_id['game_ID'] == input_regist_data[1]:
loot_member_data["_id"] = game_id['_id']
input_time : datetime = datetime.datetime.now()
insert_data : dict = {}
insert_data = jungsan_data.copy()
insert_data["toggle"] = input_regist_data[1]
insert_data["toggle_ID"] = str(loot_member_data["_id"])
insert_data["gulid_money_insert"] = gulid_money_insert_check
insert_data["modifydate"] = input_time
embed = discord.Embed(
title = "📜 수정 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']} → {insert_data['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{jungsan_data['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{jungsan_data['price']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID'])}```")
embed.set_footer(text = f"{insert_data['modifydate'].strftime('%y-%m-%d %H:%M:%S')} 수정!")
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**입력하신 수정 내역을 확인해 보세요!**\n**수정 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 수정이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **수정**을 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":insert_data}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 내역 수정 실패.")
return await ctx.send(f"📥 정산 등록 내역 수정 완료! 📥")
else:
return await ctx.send(f"**수정**이 취소되었습니다.\n")
################ 참여자추가 ################
@commands.command(name=commandSetting[22][0], aliases=commandSetting[22][1:])
async def modify_regist_add_member_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[22][0]} [순번] [아이디]** 양식으로 등록 해주세요")
input_regist_data : list = args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data != 2:
return await ctx.send(f"**{commandSetting[22][0]} [순번] [아이디]** 양식으로 등록 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"$or" : [{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]**중이 아니거나 없습니다. **[ {commandSetting[13][0]}/{commandSetting[16][0]} ]** 명령을 통해 확인해주세요.\n※정산 등록 내역 수정은 **[ 분배상태 ]**가 **[ 미판매 ]** 중인 등록건만 수정 가능합니다!")
if input_regist_data[1] in jungsan_data['before_jungsan_ID']:
return await ctx.send(f"```추가하려는 [참여자:{input_regist_data[1]}](이)가 등록된 [참여자] 목록에 있습니다!```")
check_member_data : dict = {}
tmp_member_list : list = []
check_member_data = self.member_db.find_one({"game_ID":input_regist_data[1]})
if not check_member_data:
return await ctx.send(f"```참여자 [{input_regist_data[1]}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
tmp_member_list = jungsan_data["before_jungsan_ID"].copy()
tmp_member_list.append(check_member_data["game_ID"])
input_time : datetime = datetime.datetime.now()
insert_data : dict = {}
insert_data = jungsan_data.copy()
insert_data["before_jungsan_ID"] = sorted(tmp_member_list)
embed = discord.Embed(
title = "📜 수정 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{jungsan_data['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{jungsan_data['price']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID'])} → {', '.join(insert_data['before_jungsan_ID'])}```")
embed.set_footer(text = f"{insert_data['modifydate'].strftime('%y-%m-%d %H:%M:%S')} 수정!")
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**입력하신 수정 내역을 확인해 보세요!**\n**수정 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 수정이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **수정**을 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":insert_data}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 내역 수정 실패.")
return await ctx.send(f"📥 정산 등록 내역 수정 완료! 📥")
else:
return await ctx.send(f"**수정**이 취소되었습니다.\n")
################ 참여자삭제 ################
@commands.command(name=commandSetting[23][0], aliases=commandSetting[23][1:])
async def modify_regist_remove_member_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[23][0]} [순번] [아이디]** 양식으로 등록 해주세요")
input_regist_data : list = args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data != 2:
return await ctx.send(f"**{commandSetting[23][0]} [순번] [아이디]** 양식으로 등록 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"$or" : [{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]**중이 아니거나 없습니다. **[ {commandSetting[13][0]}/{commandSetting[16][0]} ]** 명령을 통해 확인해주세요.\n※정산 등록 내역 수정은 **[ 분배상태 ]**가 **[ 미판매 ]** 중인 등록건만 수정 가능합니다!")
if input_regist_data[1] not in jungsan_data['before_jungsan_ID']:
return await ctx.send(f"```삭제하려는 [참여자:{input_regist_data[1]}](이)가 등록된 [참여자] 목록에 없습니다!```")
check_member_data : dict = {}
tmp_member_list : list = []
check_member_data = self.member_db.find_one({"game_ID":input_regist_data[1]})
if not check_member_data:
return await ctx.send(f"```참여자 [{input_regist_data[1]}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
tmp_member_list = jungsan_data["before_jungsan_ID"].copy()
tmp_member_list.remove(check_member_data["game_ID"])
if len(tmp_member_list) <= 0:
return await ctx.send(f"```참여자 [{input_regist_data[1]}]를 삭제하면 참여자가 [0]명이 되므로 삭제할 수 없습니다!```")
input_time : datetime = datetime.datetime.now()
insert_data : dict = {}
insert_data = jungsan_data.copy()
insert_data["before_jungsan_ID"] = sorted(tmp_member_list)
embed = discord.Embed(
title = "📜 수정 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{jungsan_data['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{jungsan_data['price']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID'])} → {', '.join(insert_data['before_jungsan_ID'])}```")
embed.set_footer(text = f"{insert_data['modifydate'].strftime('%y-%m-%d %H:%M:%S')} 수정!")
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**입력하신 수정 내역을 확인해 보세요!**\n**수정 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 수정이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **수정**을 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":insert_data}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 내역 수정 실패.")
return await ctx.send(f"📥 정산 등록 내역 수정 완료! 📥")
else:
return await ctx.send(f"**수정**이 취소되었습니다.\n")
################ 이미지 수정 ################
@commands.command(name=commandSetting[50][0], aliases=commandSetting[50][1:])
async def modify_regist_image_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[50][0]} [순번] [수정이미지 url]** 양식으로 등록 해주세요")
input_regist_data : list = args.split()
len_input_regist_data = len(input_regist_data)
if len_input_regist_data != 2:
return await ctx.send(f"**{commandSetting[50][0]} [순번] [수정이미지 url]** 양식으로 등록 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"$or" : [{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_regist_data[0])}, {"itemstatus":"미판매"}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]**중이 아니거나 없습니다. **[ {commandSetting[13][0]}/{commandSetting[16][0]} ]** 명령을 통해 확인해주세요.\n※정산 등록 내역 수정은 **[ 분배상태 ]**가 **[ 미판매 ]** 중인 등록건만 수정 가능합니다!")
input_time : datetime = datetime.datetime.now()
insert_data : dict = {}
insert_data = jungsan_data.copy()
insert_data["image_url"] = input_regist_data[1]
insert_data["modifydate"] = input_time
embed = discord.Embed(
title = "📜 수정 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{jungsan_data['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{jungsan_data['price']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID'])}```")
embed.set_footer(text = f"{insert_data['modifydate'].strftime('%y-%m-%d %H:%M:%S')} 수정!")
embed.set_image(url = insert_data["image_url"])
try:
await ctx.send(embed = embed)
except Exception:
embed.add_field(name = "🚫 이미지 링크 확인 필요 🚫", value = f"```저장된 이미지가 삭제됩니다.```")
insert_data["image_url"] = ""
embed.set_image(url = insert_data["image_url"])
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**입력하신 수정 내역을 확인해 보세요!**\n**수정 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 수정이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **수정**을 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":insert_data}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 등록 내역 수정 실패.")
return await ctx.send(f"📥 정산 등록 내역 수정 완료! 📥")
else:
return await ctx.send(f"**수정**이 취소되었습니다.\n")
################ 판매입력 ################
@commands.command(name=commandSetting[24][0], aliases=commandSetting[24][1:])
async def input_sell_price(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[24][0]} [순번] [금액]** 양식으로 입력 해주세요")
input_sell_price_data : list = args.split()
len_input_sell_price_data = len(input_sell_price_data)
if len_input_sell_price_data != 2:
return await ctx.send(f"**{commandSetting[24][0]} [순번] [금액]** 양식으로 입력 해주세요")
try:
input_sell_price_data[0] = int(input_sell_price_data[0])
input_sell_price_data[1] = int(input_sell_price_data[1])
except ValueError:
return await ctx.send(f"**[순번]** 및 **[금액]**은 숫자로 입력 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_sell_price_data[0])}, {"itemstatus":"미판매"}]})
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"$or" : [{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_sell_price_data[0])}, {"itemstatus":"미판매"}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]** 중이 아니거나 없습니다. **[ {commandSetting[13][0]} ]** 명령을 통해 확인해주세요")
result_each_price = int(input_sell_price_data[1]//len(jungsan_data["before_jungsan_ID"])) # 혈비일 경우 수수로 계산 입력 예정
if jungsan_data["gulid_money_insert"]:
after_tax_price : int = int(input_sell_price_data[1]*(1-(basicSetting[7]/100)))
result_each_price : int = int(after_tax_price//len(jungsan_data["before_jungsan_ID"]))
result = self.jungsan_db.update_one({"_id":input_sell_price_data[0]}, {"$set":{"price":after_tax_price, "each_price":int(input_sell_price_data[1]), "modifydate":datetime.datetime.now(), "before_jungsan_ID":[], "after_jungsan_ID":sorted(jungsan_data["before_jungsan_ID"]), "itemstatus":"분배완료"}}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 혈비 등록 실패.")
result_guild = self.guild_db.update_one({"_id":"guild"}, {"$inc":{"guild_money":after_tax_price}}, upsert = True)
if result_guild.raw_result["nModified"] < 1 and "upserted" not in result_guild.raw_result:
return await ctx.send(f"{ctx.author.mention}, 혈비 적립 실패.")
insert_log_data = {
"in_out_check":True, # True : 입금, False : 출금
"log_date":datetime.datetime.now(),
"money":str(after_tax_price),
"member_list":jungsan_data["before_jungsan_ID"],
"reason":f"[순번:{input_sell_price_data[0]}] - 정산금 혈비 적립"
}
result_guild_log = self.guild_db_log.insert_one(insert_log_data)
return await ctx.send(f"**[ 순번 : {input_sell_price_data[0]} ]** 💰판매금 **[ {after_tax_price} ]**(세율 {basicSetting[7]}% 적용) 혈비 적립 완료!")
result = self.jungsan_db.update_one({"_id":input_sell_price_data[0]}, {"$set":{"price":input_sell_price_data[1], "each_price":result_each_price, "modifydate":datetime.datetime.now(), "itemstatus":"분배중"}}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 판매 등록 실패.")
return await ctx.send(f"**[ 순번 : {input_sell_price_data[0]} ]** 💰판매금 **[ {input_sell_price_data[1]} ]** 등록 완료! 분배를 시작합니다.")
################ 뽑기판매입력 ################
@commands.command(name=commandSetting[45][0], aliases=commandSetting[45][1:])
async def input_ladder_sell_price(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[45][0]} [순번] [금액] [뽑을인원]** 양식으로 입력 해주세요")
input_sell_price_data : list = args.split()
len_input_sell_price_data = len(input_sell_price_data)
if len_input_sell_price_data != 3:
return await ctx.send(f"**{commandSetting[45][0]} [순번] [금액] [뽑을인원]** 양식으로 입력 해주세요")
try:
input_sell_price_data[0] = int(input_sell_price_data[0])
input_sell_price_data[1] = int(input_sell_price_data[1])
input_sell_price_data[2] = int(input_sell_price_data[2])
except ValueError:
return await ctx.send(f"**[순번]**, **[금액]** 및 **[뽑을인원]**은 숫자로 입력 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_sell_price_data[0])}, {"itemstatus":"미판매"}]})
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"$or" : [{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_sell_price_data[0])}, {"itemstatus":"미판매"}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]** 중이 아니거나 없습니다. **[ {commandSetting[45][0]} ]** 명령을 통해 확인해주세요")
if input_sell_price_data[2] < 1:
return await ctx.send(f"{ctx.author.mention}님! 추첨인원이 0보다 작거나 같습니다. 재입력 해주세요")
ladder_check : bool = False
result_ladder = None
if len(jungsan_data["before_jungsan_ID"]) > input_sell_price_data[2]:
tmp_before_jungsan_ID : list = []
tmp_before_jungsan_ID = jungsan_data["before_jungsan_ID"]
for _ in range(input_sell_price_data[2] + 5):
random.shuffle(tmp_before_jungsan_ID)
for _ in range(input_sell_price_data[2] + 5):
result_ladder = random.sample(tmp_before_jungsan_ID, input_sell_price_data[2])
await ctx.send(f"**[ {', '.join(sorted(jungsan_data['before_jungsan_ID']))} ]** 중 **[ {', '.join(sorted(result_ladder))} ]** 당첨! 분배를 시작합니다.")
result_each_price = int(input_sell_price_data[1]//input_sell_price_data[2])
ladder_check = True
else:
return await ctx.send(f"{ctx.author.mention}님! 추첨인원이 총 인원과 같거나 많습니다. 재입력 해주세요")
if jungsan_data["gulid_money_insert"]:
after_tax_price : int = int(input_sell_price_data[1]*(1-(basicSetting[7]/100)))
result_each_price : int = int(after_tax_price//input_sell_price_data[2])
result = self.jungsan_db.update_one({"_id":input_sell_price_data[0]}, {"$set":{"price":after_tax_price, "each_price":int(input_sell_price_data[1]), "modifydate":datetime.datetime.now(), "before_jungsan_ID":[], "after_jungsan_ID":sorted(result_ladder), "itemstatus":"분배완료", "ladder_check":ladder_check}}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 혈비 등록 실패.")
result_guild = self.guild_db.update_one({"_id":"guild"}, {"$inc":{"guild_money":after_tax_price}}, upsert = True)
if result_guild.raw_result["nModified"] < 1 and "upserted" not in result_guild.raw_result:
return await ctx.send(f"{ctx.author.mention}, 혈비 적립 실패.")
insert_log_data = {
"in_out_check":True, # True : 입금, False : 출금
"log_date":datetime.datetime.now(),
"money":str(after_tax_price),
"member_list":sorted(result_ladder),
"reason":f"[순번:{input_sell_price_data[0]}] - 정산금 혈비 적립"
}
result_guild_log = self.guild_db_log.insert_one(insert_log_data)
return await ctx.send(f"**[ 순번 : {input_sell_price_data[0]} ]** 💰판매금 **[ {after_tax_price} ]**(세율 {basicSetting[7]}% 적용) 혈비 적립 완료!")
result = self.jungsan_db.update_one({"_id":input_sell_price_data[0]}, {"$set":{"price":input_sell_price_data[1], "each_price":result_each_price, "modifydate":datetime.datetime.now(), "before_jungsan_ID":sorted(result_ladder), "itemstatus":"분배중", "ladder_check":ladder_check}}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 판매 등록 실패.")
return await ctx.send(f"**[ 순번 : {input_sell_price_data[0]} ]** 💰판매금 **[ {input_sell_price_data[1]} ]** 등록 완료! 분배를 시작합니다.")
################ 판매 취소 ################
@commands.command(name=commandSetting[51][0], aliases=commandSetting[51][1:])
async def cancel_sell_data(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[51][0]} [순번]** 양식으로 정산 해주세요")
input_distribute_finish_data = args.split()
len_input_distribute_finish_data = len(input_distribute_finish_data)
if len_input_distribute_finish_data != 1:
return await ctx.send(f"**{commandSetting[51][0]} [순번]** 양식으로 정산 해주세요")
try:
input_distribute_finish_data[0] = int(input_distribute_finish_data[0])
except ValueError:
return await ctx.send(f"**[순번]**은 숫자로 입력 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"_id":int(input_distribute_finish_data[0])})
if jungsan_data["gulid_money_insert"]:
embed = discord.Embed(
title = "📜 판매취소 정보(혈비등록건)",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 등록 ]", value = f"```{jungsan_data['regist']}```")
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{jungsan_data['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{jungsan_data['each_price']}```")
embed.add_field(name = "[ 적립금 ]", value = f"```{jungsan_data['price']}```")
if jungsan_data["image_url"] != "":
embed.set_image(url = jungsan_data["image_url"])
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**판매취소하실 등록 내역을 확인해 보세요!**\n**판매취소 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 판매취소가 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **판매취소**를 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.update_one({"_id":input_distribute_finish_data[0]}, {"$set":{"price":0, "each_price":0, "modifydate":datetime.datetime.now(), "itemstatus":"미판매", "before_jungsan_ID":jungsan_data["after_jungsan_ID"],"after_jungsan_ID":[] }}, upsert = False)
result_guild = self.guild_db.update_one({"_id":"guild"}, {"$inc":{"guild_money":-jungsan_data["price"]}}, upsert = True)
if result_guild.raw_result["nModified"] < 1 and "upserted" not in result_guild.raw_result:
return await ctx.send(f"{ctx.author.mention}, 혈비 적립 실패.")
insert_log_data = {
"in_out_check":False, # True : 입금, False : 출금
"log_date":datetime.datetime.now(),
"money":str(jungsan_data["price"]),
"member_list":[],
"reason":f"[순번:{input_distribute_finish_data[0]}] - 판매 취소"
}
result_guild_log = self.guild_db_log.insert_one(insert_log_data)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 판매 취소 실패.")
await ctx.send(f"📥 **[ 순번 : {input_distribute_finish_data[0]} ]** 판매취소 완료! 📥")
if jungsan_data["ladder_check"]:
await ctx.send(f"⚠️ `해당 판매`건은 `뽑기판매`건이므로 `참여자 정보를 확인`해야 합니다.")
return
else:
return await ctx.send(f"**판매취소**가 취소되었습니다.\n")
else:
if jungsan_data["itemstatus"] != "분배중" and not jungsan_data["after_jungsan_ID"]:
jungsan_data = {}
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"$or" : [{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_distribute_finish_data[0])}, {"itemstatus":"분배중"}, {"after_jungsan_ID":[]}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 분배중 ]**이 아니거나 **[정산]**처리된 인원이 있거나 정산 목록에 없습니다. **[ {commandSetting[13][0]} ]** 명령을 통해 확인해주세요")
embed = discord.Embed(
title = "📜 판매취소 정보",
description = "",
color=0x00ff00
)
embed.add_field(name = "[ 순번 ]", value = f"```{jungsan_data['_id']}```", inline = False)
embed.add_field(name = "[ 등록 ]", value = f"```{jungsan_data['regist']}```")
embed.add_field(name = "[ 일시 ]", value = f"```{jungsan_data['getdate'].strftime('%y-%m-%d %H:%M:%S')}```", inline = False)
embed.add_field(name = "[ 보스 ]", value = f"```{jungsan_data['boss']}```")
embed.add_field(name = "[ 아이템 ]", value = f"```{jungsan_data['item']}```")
embed.add_field(name = "[ 루팅 ]", value = f"```{jungsan_data['toggle']}```")
embed.add_field(name = "[ 상태 ]", value = f"```{jungsan_data['itemstatus']}```")
embed.add_field(name = "[ 판매금 ]", value = f"```{jungsan_data['price']}```")
embed.add_field(name = "[ 참여자 ]", value = f"```{', '.join(jungsan_data['before_jungsan_ID'])}```")
if jungsan_data["image_url"] != "":
embed.set_image(url = jungsan_data["image_url"])
await ctx.send(embed = embed)
data_regist_warning_message = await ctx.send(f"**판매취소하실 등록 내역을 확인해 보세요!**\n**판매취소 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 판매취소가 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await data_regist_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == data_regist_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await data_regist_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **판매취소**를 취소합니다!")
if str(reaction) == "⭕":
result = self.jungsan_db.update_one({"_id":input_distribute_finish_data[0]}, {"$set":{"price":0, "each_price":0, "modifydate":datetime.datetime.now(), "itemstatus":"미판매"}}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 판매 취소 실패.")
await ctx.send(f"📥 **[ 순번 : {input_distribute_finish_data[0]} ]** 판매취소 완료! 📥")
if jungsan_data["ladder_check"]:
await ctx.send(f"⚠️ `해당 판매`건은 `뽑기판매`건이므로 `참여자 정보를 확인`해야 합니다.")
return
else:
return await ctx.send(f"**판매취소**가 취소되었습니다.\n")
################ 정산 처리 입력 ################
@commands.command(name=commandSetting[25][0], aliases=commandSetting[25][1:])
async def distribute_finish(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[25][0]} [순번] [아이디]** 양식으로 정산 해주세요")
input_distribute_finish_data : list = args.split()
len_input_distribute_finish_data = len(input_distribute_finish_data)
if len_input_distribute_finish_data != 2:
return await ctx.send(f"**{commandSetting[25][0]} [순번] [아이디]** 양식으로 정산 해주세요")
try:
input_distribute_finish_data[0] = int(input_distribute_finish_data[0])
except ValueError:
return await ctx.send(f"**[순번]**은 숫자로 입력 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_distribute_finish_data[0])}, {"itemstatus":"분배중"}]})
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"$or" : [{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_distribute_finish_data[0])}, {"itemstatus":"분배중"}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 분배중 ]**이 아니거나 없습니다. **[ {commandSetting[13][0]} ]** 명령을 통해 확인해주세요")
else:
if input_distribute_finish_data[1] in jungsan_data["after_jungsan_ID"]:
return await ctx.send(f"**[ {input_distribute_finish_data[1]} ]**님은 **[ 순번 : {input_distribute_finish_data[0]} ]**의 정산 내역에 대하여 이미 💰**[ {jungsan_data['each_price']} ]** 정산 받았습니다!")
elif input_distribute_finish_data[1] not in jungsan_data["before_jungsan_ID"]:
return await ctx.send(f"**[ {input_distribute_finish_data[1]} ]**님은 **[ 순번 : {input_distribute_finish_data[0]} ]**의 정산 전 명단에 존재하지 않습니다!")
else:
pass
jungsan_data["before_jungsan_ID"].remove(input_distribute_finish_data[1])
jungsan_data["after_jungsan_ID"].append(input_distribute_finish_data[1])
len_before_jungsan_data :int = 0
len_before_jungsan_data = len(jungsan_data["before_jungsan_ID"])
if len_before_jungsan_data == 0:
result = self.jungsan_db.update_one({"_id":int(input_distribute_finish_data[0])}, {"$set":{"before_jungsan_ID":sorted(jungsan_data["before_jungsan_ID"]), "after_jungsan_ID":sorted(jungsan_data["after_jungsan_ID"]), "modifydate":datetime.datetime.now(), "itemstatus" : "분배완료"}}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 실패.")
return await ctx.send(f"**[ 순번 : {input_distribute_finish_data[0]} ]** : **[ {input_distribute_finish_data[1]} ]**님 정산 완료!\n**[ 순번 : {input_distribute_finish_data[0]} ]** 분배 완료!🎉")
else:
result = self.jungsan_db.update_one({"_id":int(input_distribute_finish_data[0])}, {"$set":{"before_jungsan_ID":sorted(jungsan_data["before_jungsan_ID"]), "after_jungsan_ID":sorted(jungsan_data["after_jungsan_ID"]), "modifydate":datetime.datetime.now()}}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 실패.")
return await ctx.send(f"**[ 순번 : {input_distribute_finish_data[0]} ]** : **[ {input_distribute_finish_data[1]} ]**님 정산 완료!")
################ 정산 처리 취소 ################
@commands.command(name=commandSetting[26][0], aliases=commandSetting[26][1:])
async def cancel_distribute_finish(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[26][0]} [순번] [아이디]** 양식으로 정산 해주세요")
input_distribute_finish_data : list = args.split()
len_input_distribute_finish_data = len(input_distribute_finish_data)
if len_input_distribute_finish_data != 2:
return await ctx.send(f"**{commandSetting[26][0]} [순번] [아이디]** 양식으로 정산 해주세요")
try:
input_distribute_finish_data[0] = int(input_distribute_finish_data[0])
except ValueError:
return await ctx.send(f"**[순번]**은 숫자로 입력 해주세요")
if "manager" in member_data['permissions']:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_distribute_finish_data[0])}, {"itemstatus":"분배중"}]})
else:
jungsan_data : dict = self.jungsan_db.find_one({"$and" : [{"$or" : [{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_distribute_finish_data[0])}, {"itemstatus":"분배중"}]})
if not jungsan_data:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 분배중 ]**이 아니거나 없습니다. **[ {commandSetting[13][0]} ]** 명령을 통해 확인해주세요")
else:
if input_distribute_finish_data[1] in jungsan_data["before_jungsan_ID"]:
return await ctx.send(f"**[ {input_distribute_finish_data[1]} ]**님은 **[ 순번 : {input_distribute_finish_data[0]} ]**의 정산 내역에 대하여 아직 정산 받지 않았습니다!")
elif input_distribute_finish_data[1] not in jungsan_data["after_jungsan_ID"]:
return await ctx.send(f"**[ {input_distribute_finish_data[1]} ]**님은 **[ 순번 : {input_distribute_finish_data[0]} ]**의 정산 후 명단에 존재하지 않습니다!")
else:
pass
jungsan_data["after_jungsan_ID"].remove(input_distribute_finish_data[1])
jungsan_data["before_jungsan_ID"].append(input_distribute_finish_data[1])
result = self.jungsan_db.update_one({"_id":int(input_distribute_finish_data[0])}, {"$set":{"before_jungsan_ID":sorted(jungsan_data["before_jungsan_ID"]), "after_jungsan_ID":sorted(jungsan_data["after_jungsan_ID"]), "modifydate":datetime.datetime.now()}}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 정산 취소 실패.")
return await ctx.send(f"**[ 순번 : {input_distribute_finish_data[0]} ]** : **[ {input_distribute_finish_data[1]} ]**님 정산 취소 완료!")
################ 일괄정산 ################
@commands.command(name=commandSetting[27][0], aliases=commandSetting[27][1:])
async def distribute_all_finish(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
jungsan_document : list = []
if not args:
jungsan_document : list = list(self.jungsan_db.find({"$and" : [{"$or":[{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"itemstatus":"분배중"}]}).sort("_id", pymongo.ASCENDING))
else:
input_distribute_all_finish : list = args.split()
len_input_distribute_all_finish = len(input_distribute_all_finish)
if len_input_distribute_all_finish != 2:
return await ctx.send(f"**{commandSetting[27][0]} [검색조건] [검색값]** 형식으로 입력 해주세요! **[검색조건]**은 **[순번, 보스명, 아이템, 날짜]** 네가지 중 **1개**를 입력 하셔야합니다!")
else:
if input_distribute_all_finish[0] == "순번":
try:
input_distribute_all_finish[1] = int(input_distribute_all_finish[1])
except:
return await ctx.send(f"**[순번] [검색값]**은 숫자로 입력 해주세요!")
jungsan_document = list(self.jungsan_db.find({"$and" : [{"$or":[{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":input_distribute_all_finish[1]}, {"itemstatus":"분배중"}]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "보스명":
jungsan_document = list(self.jungsan_db.find({"$and" : [{"$or":[{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"boss":input_distribute_all_finish[1]}, {"itemstatus":"분배중"}]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "아이템":
jungsan_document = list(self.jungsan_db.find({"$and" : [{"$or":[{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"item":input_distribute_all_finish[1]}, {"itemstatus":"분배중"}]}).sort("_id", pymongo.ASCENDING))
elif input_distribute_all_finish[0] == "날짜":
try:
start_search_date : str = datetime.datetime.now().replace(year = int(input_distribute_all_finish[1][:4]), month = int(input_distribute_all_finish[1][5:7]), day = int(input_distribute_all_finish[1][8:10]), hour = 0, minute = 0, second = 0)
end_search_date : str = start_search_date + datetime.timedelta(days = 1)
except:
return await ctx.send(f"**[날짜] [검색값]**은 0000-00-00 형식으로 입력 해주세요!")
jungsan_document = list(self.jungsan_db.find({"$and" : [{"$or":[{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"getdate":{"$gte":start_search_date, "$lt":end_search_date}}, {"itemstatus":"분배중"}]}).sort("_id", pymongo.ASCENDING))
else:
return await ctx.send(f"**[검색조건]**이 잘못 됐습니다. **[검색조건]**은 **[순번, 보스명, 아이템, 날짜]** 네가지 중 **1개**를 입력 하셔야합니다!")
if len(jungsan_document) == 0:
return await ctx.send(f"{ctx.author.mention}님! **[ 분배중 ]**인 정산 내역이 없거나 등록된 정산 내역이 없습니다. **[ {commandSetting[13][0]} ]** 명령을 통해 확인해주세요")
total_distribute_money : int = 0
detail_info_ing : str = ""
embed_list : list = []
embed_limit_checker : int = 0
embed_cnt : int = 0
init_data : dict = {}
embed = discord.Embed(
title = f"📜 [{member_data['game_ID']}]님 등록 내역",
description = "",
color=0x00ff00
)
embed_list.append(embed)
for jungsan_data in jungsan_document:
embed_limit_checker += 1
if embed_limit_checker == 20:
embed_limit_checker = 0
embed_cnt += 1
tmp_embed = discord.Embed(
title = "",
description = "",
color=0x00ff00
)
embed_list.append(tmp_embed)
detail_info_ing = f"```diff\n+ 분 배 중 : {len(jungsan_data['before_jungsan_ID'])}명 (💰{len(jungsan_data['before_jungsan_ID'])*jungsan_data['each_price']})\n{', '.join(jungsan_data['before_jungsan_ID'])}\n- 분배완료 : {len(jungsan_data['after_jungsan_ID'])}명 (💰{len(jungsan_data['after_jungsan_ID'])*jungsan_data['each_price']})\n{', '.join(jungsan_data['after_jungsan_ID'])}```"
embed_list[embed_cnt].add_field(name = f"[ 순번 : {jungsan_data['_id']} ] | {jungsan_data['getdate'].strftime('%y-%m-%d')} | {jungsan_data['boss']} | {jungsan_data['item']} | {jungsan_data['toggle']} | {jungsan_data['itemstatus']} : 1인당 💰{jungsan_data['each_price']}",
value = detail_info_ing,
inline = False)
total_distribute_money += len(jungsan_data['before_jungsan_ID'])*int(jungsan_data['each_price'])
init_data[jungsan_data['_id']] = jungsan_data['after_jungsan_ID']
if len(embed_list) > 1:
for embed_data in embed_list:
await asyncio.sleep(0.1)
await ctx.send(embed = embed_data)
else:
await ctx.send(embed = embed)
embed1 = discord.Embed(
title = f"일괄정산 예정 금액 : 💰 {str(total_distribute_money)}",
description = "",
color=0x00ff00
)
await ctx.send(embed = embed1)
distribute_all_finish_warning_message = await ctx.send(f"**일괄 정산 예정인 등록 내역을 확인해 보세요!**\n**일괄정산 : ⭕ 취소: ❌**\n({basicSetting[5]}초 동안 입력이 없을시 일괄정산이 취소됩니다.)", tts=False)
emoji_list : list = ["⭕", "❌"]
for emoji in emoji_list:
await distribute_all_finish_warning_message.add_reaction(emoji)
def reaction_check(reaction, user):
return (reaction.message.id == distribute_all_finish_warning_message.id) and (user.id == ctx.author.id) and (str(reaction) in emoji_list)
try:
reaction, user = await self.bot.wait_for('reaction_add', check = reaction_check, timeout = int(basicSetting[5]))
except asyncio.TimeoutError:
for emoji in emoji_list:
await distribute_all_finish_warning_message.remove_reaction(emoji, self.bot.user)
return await ctx.send(f"시간이 초과됐습니다. **일괄정산**을 취소합니다!")
if str(reaction) == "⭕":
for jungsan_data in jungsan_document:
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":{"before_jungsan_ID":[], "after_jungsan_ID":sorted(init_data[jungsan_data['_id']]+jungsan_data['before_jungsan_ID']), "modifydate":datetime.datetime.now(), "itemstatus":"분배완료"}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
await ctx.send(f"{ctx.author.mention}, 일괄정산 실패.")
return await ctx.send(f"📥 일괄정산 완료! 📥")
else:
return await ctx.send(f"**일괄정산**이 취소되었습니다.\n")
class bankCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.member_db = self.bot.db.jungsan.member
self.jungsan_db = self.bot.db.jungsan.jungsandata
self.guild_db = self.bot.db.jungsan.guild
self.guild_db_log = self.bot.db.jungsan.guild_log
################ 수수료 계산기 ################
@commands.command(name=commandSetting[34][0], aliases=commandSetting[34][1:])
async def tax_check(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[34][0]} [판매금액] (거래소세금)** 양식으로 입력 해주세요\n※ 거래소세금은 미입력시 {basicSetting[7]}%입니다.")
input_money_data : list = args.split()
len_input_money_data = len(input_money_data)
try:
for i in range(len_input_money_data):
input_money_data[i] = int(input_money_data[i])
except ValueError:
return await ctx.send(f"**[판매금액] (거래소세금)**은 숫자로 입력 해주세요.")
if len_input_money_data < 1 or len_input_money_data > 3:
return await ctx.send(f"**{commandSetting[34][0]} [판매금액] (거래소세금)** 양식으로 입력 해주세요\n※ 거래소세금은 미입력시 {basicSetting[7]}%입니다.")
elif len_input_money_data == 2:
tax = input_money_data[1]
else:
tax = basicSetting[7]
price_first_tax = int(input_money_data[0] * ((100-tax)/100))
price_second_tax = int(price_first_tax * ((100-tax)/100))
price_rev_tax = int((input_money_data[0] * 100)/(100-tax)+0.5)
embed = discord.Embed(
title = f"🧮 수수료 계산결과 (세율 {tax}% 기준) ",
description = f"",
color=0x00ff00
)
embed.add_field(name = "⚖️ 수수료 지원", value = f"```등록가 : {price_rev_tax}\n수령가 : {input_money_data[0]}\n세 금 : {price_rev_tax-input_money_data[0]}```")
embed.add_field(name = "⚖️ 1차 거래", value = f"```등록가 : {input_money_data[0]}\n정산가 : {price_first_tax}\n세 금 : {input_money_data[0]-price_first_tax}```")
embed.add_field(name = "⚖️ 2차 거래", value = f"```등록가 : {price_first_tax}\n정산가 : {price_second_tax}\n세 금 : {price_first_tax-price_second_tax}```")
return await ctx.send(embed = embed)
################ 페이백 계산기 ################
@commands.command(name=commandSetting[35][0], aliases=commandSetting[35][1:])
async def payback_check(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[35][0]} 거래소가격] [실거래가] (거래소세금)** 양식으로 입력 해주세요\n※ 거래소세금은 미입력시 {basicSetting[7]}%입니다.")
input_money_data : list = args.split()
len_input_money_data = len(input_money_data)
try:
for i in range(len_input_money_data):
input_money_data[i] = int(input_money_data[i])
except ValueError:
return await ctx.send(f"**[판매금액] (거래소세금)**은 숫자로 입력 해주세요.")
if len_input_money_data < 2 or len_input_money_data > 4:
return await ctx.send(f"**{commandSetting[35][0]} [거래소가격] [실거래가] (거래소세금)** 양식으로 입력 해주세요\n※ 거래소세금은 미입력시 {basicSetting[7]}%입니다.")
elif len_input_money_data == 3:
tax = input_money_data[2]
else:
tax = basicSetting[7]
price_reg_tax = int(input_money_data[0] * ((100-tax)/100))
price_real_tax = int(input_money_data[1] * ((100-tax)/100))
reault_payback = price_reg_tax - price_real_tax
reault_payback1= price_reg_tax - input_money_data[1]
embed = discord.Embed(
title = f"🧮 페이백 계산결과1 (세율 {tax}% 기준) ",
description = f"**```fix\n{reault_payback}```**",
color=0x00ff00
)
embed.add_field(name = "⚖️ 거래소", value = f"```등록가 : {input_money_data[0]}\n정산가 : {price_reg_tax}\n세 금 : {input_money_data[0]-price_reg_tax}```")
embed.add_field(name = "🕵️ 실거래", value = f"```등록가 : {input_money_data[1]}\n정산가 : {price_real_tax}\n세 금 : {input_money_data[1]-price_real_tax}```")
await ctx.send(embed = embed)
embed2 = discord.Embed(
title = f"🧮 페이백 계산결과2 (세율 {tax}% 기준) ",
description = f"**```fix\n{reault_payback1}```**",
color=0x00ff00
)
embed2.add_field(name = "⚖️ 거래소", value = f"```등록가 : {input_money_data[0]}\n정산가 : {price_reg_tax}\n세 금 : {input_money_data[0]-price_reg_tax}```")
embed2.add_field(name = "🕵️ 실거래", value = f"```내판가 : {input_money_data[1]}```")
return await ctx.send(embed = embed2)
################ 계좌확인 ################
@commands.command(name=commandSetting[28][0], aliases=commandSetting[28][1:])
async def account_check(self, ctx):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
embed = discord.Embed(
title = f"[{member_data['game_ID']}]님 은행 잔고 📝",
description = f"**```diff\n{member_data['account']}```**",
color=0x00ff00
)
embed.set_thumbnail(url = ctx.author.avatar_url)
return await ctx.send(embed = embed)
################ 저축 ################
@commands.command(name=commandSetting[29][0], aliases=commandSetting[29][1:])
async def bank_save_money(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]):
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[29][0]} [순번] [금액]** 양식으로 입력 해주세요")
input_sell_price_data : list = args.split()
len_input_sell_price_data = len(input_sell_price_data)
if len_input_sell_price_data != 2:
return await ctx.send(f"**{commandSetting[29][0]} [순번] [금액]** 양식으로 입력 해주세요")
try:
input_sell_price_data[0] = int(input_sell_price_data[0])
input_sell_price_data[1] = int(input_sell_price_data[1])
except ValueError:
return await ctx.send(f"**[순번]** 및 **[금액]**은 숫자로 입력 해주세요")
if "manager" in member_data['permissions']:
jungsan_document : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_sell_price_data[0])}, {"itemstatus":"미판매"}]})
else:
jungsan_document : dict = self.jungsan_db.find_one({"$and" : [{"$or":[{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_sell_price_data[0])}, {"itemstatus":"미판매"}]})
if not jungsan_document:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]** 중이 아니거나 없습니다. **[ {commandSetting[13][0]}/{commandSetting[16][0]} ]** 명령을 통해 확인해주세요")
if jungsan_document["gulid_money_insert"]:
return await ctx.send(f"{ctx.author.mention}님! 해당 정산 내역은 **[ 혈비 ]**로 적립 예정입니다. **[ {commandSetting[24][0]} ]** 명령을 통해 정산해 주세요!")
after_tax_price : int = int(input_sell_price_data[1]*(1-(basicSetting[7]/100)))
tmp_result_each_price : int = int(after_tax_price//len(jungsan_document["before_jungsan_ID"]))
guild_save_money = 0
if basicSetting[8] != 0:
tmp_remain_money = int(after_tax_price - int(after_tax_price * (int(basicSetting[8])/100)))
tmp_result_each_price = int(tmp_remain_money//len(jungsan_document["before_jungsan_ID"]))
guild_save_money = after_tax_price - (tmp_result_each_price * len(jungsan_document["before_jungsan_ID"]))
result_guild = self.guild_db.update_one({"_id":"guild"}, {"$inc":{"guild_money":guild_save_money}}, upsert = True)
if result_guild.raw_result["nModified"] < 1 and "upserted" not in result_guild.raw_result:
return await ctx.send(f"{ctx.author.mention}, 혈비 적립 실패.")
insert_log_data = {
"in_out_check":True, # True : 입금, False : 출금
"log_date":datetime.datetime.now(),
"money":str(guild_save_money),
"member_list":sorted(jungsan_document["before_jungsan_ID"]),
"reason":f"[순번:{input_sell_price_data[0]}] - 정산금 혈비 적립"
}
result_guild_log = self.guild_db_log.insert_one(insert_log_data)
result_each_price : int = tmp_result_each_price
participant_list : list = jungsan_document["before_jungsan_ID"]
self.member_db.update_many({"game_ID":{"$in":participant_list}}, {"$inc":{"account":result_each_price}})
insert_data : dict = {}
insert_data = {
"itemstatus":"분배완료",
"price":after_tax_price,
"each_price":result_each_price,
"before_jungsan_ID":[],
"after_jungsan_ID":sorted(jungsan_document["before_jungsan_ID"]),
"modifydate":datetime.datetime.now(),
"bank_money_insert":True
}
result = self.jungsan_db.update_one({"_id":input_sell_price_data[0]}, {"$set":insert_data}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 은행 저축 실패.")
if basicSetting[8] != 0:
await ctx.send(f"**[ 순번 : {input_sell_price_data[0]} ]** 💰판매금 **[ {after_tax_price} ]**(세율 {basicSetting[7]}% 적용)\n**{jungsan_document['before_jungsan_ID']}**계좌로 혈비 **💰 [ {guild_save_money} ]** / 1인당 **💰 [ {result_each_price} ]** 은행 저축 완료!")
else:
await ctx.send(f"**[ 순번 : {input_sell_price_data[0]} ]** 💰판매금 **[ {after_tax_price} ]**(세율 {basicSetting[7]}% 적용)\n**{jungsan_document['before_jungsan_ID']}**계좌로 1인당 **💰 [ {result_each_price} ]** 은행 저축 완료!")
return
################ 뽑기저축 ################
@commands.command(name=commandSetting[48][0], aliases=commandSetting[48][1:])
async def bank_ladder_save_money(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]):
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[48][0]} [순번] [금액] [뽑을인원]** 양식으로 입력 해주세요")
input_sell_price_data : list = args.split()
len_input_sell_price_data = len(input_sell_price_data)
if len_input_sell_price_data != 3:
return await ctx.send(f"**{commandSetting[48][0]} [순번] [금액] [뽑을인원]** 양식으로 입력 해주세요")
try:
input_sell_price_data[0] = int(input_sell_price_data[0])
input_sell_price_data[1] = int(input_sell_price_data[1])
input_sell_price_data[2] = int(input_sell_price_data[2])
except ValueError:
return await ctx.send(f"**[순번]**, **[금액]** 및 **[뽑을인원]**은 숫자로 입력 해주세요")
if "manager" in member_data['permissions']:
jungsan_document : dict = self.jungsan_db.find_one({"$and" : [{"_id":int(input_sell_price_data[0])}, {"itemstatus":"미판매"}]})
else:
jungsan_document : dict = self.jungsan_db.find_one({"$and" : [{"$or":[{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"_id":int(input_sell_price_data[0])}, {"itemstatus":"미판매"}]})
if not jungsan_document:
return await ctx.send(f"{ctx.author.mention}님! 등록하신 정산 내역이 **[ 미판매 ]** 중이 아니거나 없습니다. **[ {commandSetting[13][0]}/{commandSetting[16][0]} ]** 명령을 통해 확인해주세요")
if jungsan_document["gulid_money_insert"]:
return await ctx.send(f"{ctx.author.mention}님! 해당 정산 내역은 **[ 혈비 ]**로 적립 예정입니다. **[ {commandSetting[24][0]} ]** 명령을 통해 정산해 주세요!")
if input_sell_price_data[2] < 1:
return await ctx.send(f"{ctx.author.mention}님! 추첨인원이 0보다 작거나 같습니다. 재입력 해주세요")
ladder_check : bool = False
result_ladder = None
if len(jungsan_document["before_jungsan_ID"]) > input_sell_price_data[2]:
tmp_before_jungsan_ID : list = []
tmp_before_jungsan_ID = jungsan_document["before_jungsan_ID"]
for _ in range(input_sell_price_data[2] + 5):
random.shuffle(tmp_before_jungsan_ID)
for _ in range(input_sell_price_data[2] + 5):
result_ladder = random.sample(tmp_before_jungsan_ID, input_sell_price_data[2])
await ctx.send(f"**[ {', '.join(sorted(jungsan_document['before_jungsan_ID']))} ]** 중 **[ {', '.join(sorted(result_ladder))} ]** 당첨! 해당 인원의 계좌로 저축합니다.")
ladder_check = True
else:
return await ctx.send(f"{ctx.author.mention}님! 추첨인원이 총 인원과 같거나 많습니다. 재입력 해주세요")
after_tax_price : int = int(input_sell_price_data[1]*(1-(basicSetting[7]/100)))
tmp_result_each_price : int = int(after_tax_price//input_sell_price_data[2])
guild_save_money = 0
if basicSetting[8] != 0:
tmp_remain_money = int(after_tax_price - int(after_tax_price * (int(basicSetting[8])/100)))
tmp_result_each_price = int(tmp_remain_money//input_sell_price_data[2])
guild_save_money = after_tax_price - (tmp_result_each_price * input_sell_price_data[2])
result_guild = self.guild_db.update_one({"_id":"guild"}, {"$inc":{"guild_money":guild_save_money}}, upsert = True)
if result_guild.raw_result["nModified"] < 1 and "upserted" not in result_guild.raw_result:
return await ctx.send(f"{ctx.author.mention}, 혈비 적립 실패.")
insert_log_data = {
"in_out_check":True, # True : 입금, False : 출금
"log_date":datetime.datetime.now(),
"money":str(guild_save_money),
"member_list":sorted(result_ladder),
"reason":f"[순번:{input_sell_price_data[0]}] - 정산금 혈비 적립"
}
result_guild_log = self.guild_db_log.insert_one(insert_log_data)
result_each_price : int = tmp_result_each_price
participant_list : list = sorted(result_ladder)
self.member_db.update_many({"game_ID":{"$in":participant_list}}, {"$inc":{"account":result_each_price}})
insert_data : dict = {}
insert_data = {
"itemstatus":"분배완료",
"price":after_tax_price,
"each_price":result_each_price,
"before_jungsan_ID":[],
"after_jungsan_ID":sorted(participant_list),
"bank_money_insert":True,
"modifydate":datetime.datetime.now(),
"ladder_check":ladder_check
}
result = self.jungsan_db.update_one({"_id":input_sell_price_data[0]}, {"$set":insert_data}, upsert = False)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
return await ctx.send(f"{ctx.author.mention}, 은행 저축 실패.")
if basicSetting[8] != 0:
await ctx.send(f"**[ 순번 : {input_sell_price_data[0]} ]** 💰판매금 **[ {after_tax_price} ]**(세율 {basicSetting[7]}% 적용)\n**{participant_list}**계좌로 혈비 **💰 [ {guild_save_money} ]** / 1인당 **💰 [ {result_each_price} ]** 은행 저축 완료!")
else:
await ctx.send(f"**[ 순번 : {input_sell_price_data[0]} ]** 💰판매금 **[ {after_tax_price} ]**(세율 {basicSetting[7]}% 적용)\n**{participant_list}**계좌로 1인당 **💰 [ {result_each_price} ]** 은행 저축 완료!")
return
################ 입금 #################
@is_manager()
@commands.command(name=commandSetting[30][0], aliases=commandSetting[30][1:])
async def bank_deposit_money(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[30][0]} [금액] [아이디] [아이디]...** 양식으로 입력 해주세요")
input_bank_deposit_data : list = args.split()
len_input_sell_price_data : int = len(input_bank_deposit_data)
if len_input_sell_price_data < 2:
return await ctx.send(f"**{commandSetting[30][0]} [금액] [아이디] [아이디]...** 양식으로 입력 해주세요")
try:
input_bank_deposit_data[0] = int(input_bank_deposit_data[0])
except ValueError:
return await ctx.send(f"**[금액]**은 숫자로 입력 해주세요")
check_member_data : list = []
check_member_list : list = []
wrong_input_id : list = []
check_member_data = list(self.member_db.find())
for game_id in check_member_data:
check_member_list.append(game_id['game_ID'])
for game_id in input_bank_deposit_data[1:]:
if game_id not in check_member_list:
wrong_input_id.append(game_id)
if len(wrong_input_id) > 0:
return await ctx.send(f"```입금자 [{', '.join(wrong_input_id)}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
result_update = self.member_db.update_many({"game_ID":{"$in":input_bank_deposit_data[1:]}}, {"$inc":{"account":input_bank_deposit_data[0]}})
if result_update.modified_count != len(input_bank_deposit_data[1:]):
return await ctx.send(f"```은행 입금 실패. 정확한 [아이디]를 입력 후 다시 시도 해보세요!```")
return await ctx.send(f"```ml\n{input_bank_deposit_data[1:]}님 💰[{input_bank_deposit_data[0]}] 은행 입금 완료!.```")
################ 출금 #################
@is_manager()
@commands.command(name=commandSetting[31][0], aliases=commandSetting[31][1:])
async def bank_withdraw_money(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[31][0]} [금액] [아이디] [아이디]...** 양식으로 입력 해주세요")
input_bank_withdraw_data : list = args.split()
len_input_bank_withdraw_data : int = len(input_bank_withdraw_data)
if len_input_bank_withdraw_data < 2:
return await ctx.send(f"**{commandSetting[31][0]} [금액] [아이디] [아이디]...** 양식으로 입력 해주세요")
try:
input_bank_withdraw_data[0] = int(input_bank_withdraw_data[0])
except ValueError:
return await ctx.send(f"**[금액]**은 숫자로 입력 해주세요")
check_member_data : list = []
check_member_list : list = []
wrong_input_id : list = []
check_member_data = list(self.member_db.find())
for game_id in check_member_data:
check_member_list.append(game_id['game_ID'])
for game_id in input_bank_withdraw_data[1:]:
if game_id not in check_member_list:
wrong_input_id.append(game_id)
if len(wrong_input_id) > 0:
return await ctx.send(f"```출금자 [{', '.join(wrong_input_id)}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
result_update = self.member_db.update_many({"game_ID":{"$in":input_bank_withdraw_data[1:]}}, {"$inc":{"account":-input_bank_withdraw_data[0]}})
if result_update.modified_count != len(input_bank_withdraw_data[1:]):
return await ctx.send(f"```은행 출금 실패. 정확한 [아이디]를 입력 후 다시 시도 해보세요!```")
return await ctx.send(f"```ml\n{input_bank_withdraw_data[1:]}님 💰[{input_bank_withdraw_data[0]}] 은행 출금 완료!.```")
################ 혈비입금 #################
@is_manager()
@commands.command(name=commandSetting[32][0], aliases=commandSetting[32][1:])
async def guild_support_money_save(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[32][0]} [금액] (*사유)** 양식으로 입력 해주세요")
reason : str = ""
if args.find("*") != -1:
reason = args[args.find("*")+1:]
args = args[:args.find("*")]
try:
args = int(args)
except ValueError:
return await ctx.send(f"**[금액]**은 숫자로 입력 해주세요")
result_guild_update : dict = self.guild_db.update_one({"_id":"guild"}, {"$inc":{"guild_money":args}}, upsert = True)
if result_guild_update.raw_result["nModified"] < 1 and "upserted" not in result_guild_update.raw_result:
return await ctx.send(f"```혈비 입금 실패!```")
insert_log_data = {
"in_out_check":True, # True : 입금, False : 출금
"log_date":datetime.datetime.now(),
"money":args,
"member_list":[],
"reason":reason
}
result_guild_log = self.guild_db_log.insert_one(insert_log_data)
total_guild_money : dict = self.guild_db.find_one({"_id":"guild"})
embed = discord.Embed(
title = f"💰 혈비 입금 완료",
description = f"",
color=0x00ff00
)
embed.add_field(name = f"**입금**", value = f"**```fix\n{args}```**")
embed.add_field(name = f"**혈비**", value = f"**```fix\n{total_guild_money['guild_money']}```**")
if reason != "":
embed.add_field(name = f"**사유**", value = f"**```fix\n{reason}```**", inline=False)
return await ctx.send(embed = embed)
################ 혈비출금 #################
@is_manager()
@commands.command(name=commandSetting[49][0], aliases=commandSetting[49][1:])
async def guild_support_money_withdraw(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[49][0]} [금액]** 양식으로 입력 해주세요")
guild_support_money_withdraw_data : list = args.split(" *")
if len(guild_support_money_withdraw_data) != 2:
return await ctx.send(f"**{commandSetting[49][0]} [금액] *[사유]** 양식으로 입력 해주세요")
try:
guild_support_money_withdraw_data[0] = int(guild_support_money_withdraw_data[0])
except ValueError:
return await ctx.send(f"**[금액]**은 숫자로 입력 해주세요")
result_guild_update : dict = self.guild_db.update_one({"_id":"guild"}, {"$inc":{"guild_money":-guild_support_money_withdraw_data[0]}}, upsert = True)
if result_guild_update.raw_result["nModified"] < 1 and "upserted" not in result_guild_update.raw_result:
return await ctx.send(f"```혈비 출금 실패!```")
insert_log_data = {
"in_out_check":False, # True : 입금, False : 출금
"log_date":datetime.datetime.now(),
"money":guild_support_money_withdraw_data[0],
"member_list":[],
"reason":guild_support_money_withdraw_data[1]
}
result_guild_log = self.guild_db_log.insert_one(insert_log_data)
total_guild_money : dict = self.guild_db.find_one({"_id":"guild"})
embed = discord.Embed(
title = f"💰 혈비 출금 완료",
description = f"",
color=0x00ff00
)
embed.add_field(name = f"**출금**", value = f"**```fix\n{guild_support_money_withdraw_data[0]}```**")
embed.add_field(name = f"**혈비**", value = f"**```fix\n{total_guild_money['guild_money']}```**")
return await ctx.send(embed = embed)
################ 혈비지원 #################
@is_manager()
@commands.command(name=commandSetting[33][0], aliases=commandSetting[33][1:])
async def guild_support_money(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
guild_data : dict = self.guild_db.find_one({"_id":"guild"})
if not guild_data:
return await ctx.send(f"등록된 혈비가 없습니다!")
if not args:
return await ctx.send(f"**{commandSetting[33][0]} [금액] [아이디1] [아이디2] ... *[사유]** 양식으로 입력 해주세요")
input_guild_support_money_data : list = args.split(" *")
if len(input_guild_support_money_data) != 2:
return await ctx.send(f"**{commandSetting[33][0]} [금액] [아이디] [아이디2] ... *[사유]** 양식으로 입력 해주세요")
input_guild_support_money_ID_data : list = input_guild_support_money_data[0].split(" ")
input_guild_support_money_ID_data = [input_guild_support_money_ID_data[0]] + list(set(input_guild_support_money_ID_data[1:]))
try:
input_guild_support_money_ID_data[0] = int(input_guild_support_money_ID_data[0])
except ValueError:
return await ctx.send(f"**[금액]**은 숫자로 입력 해주세요")
check_member_data : list = []
check_member_list : list = []
wrong_input_id : list = []
check_member_data = list(self.member_db.find())
for game_id in check_member_data:
check_member_list.append(game_id['game_ID'])
for game_id in input_guild_support_money_ID_data[1:]:
if game_id not in check_member_list:
wrong_input_id.append(game_id)
if len(wrong_input_id) > 0:
return await ctx.send(f"```지원자 [{', '.join(wrong_input_id)}](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
result_update = self.member_db.update_many({"game_ID":{"$in":input_guild_support_money_ID_data[1:]}}, {"$inc":{"account":input_guild_support_money_ID_data[0]}})
if result_update.modified_count != len(input_guild_support_money_ID_data[1:]):
return await ctx.send(f"```혈비 지원 실패. 정확한 [아이디]를 입력 후 다시 시도 해보세요!```")
insert_log_data = {
"in_out_check":False, # True : 입금, False : 출금
"log_date":datetime.datetime.now(),
"money":str(input_guild_support_money_ID_data[0]*len(input_guild_support_money_ID_data[1:])),
"member_list":input_guild_support_money_ID_data[1:],
"reason":input_guild_support_money_data[1]
}
result_guild_log = self.guild_db_log.insert_one(insert_log_data)
total_support_money : int = len(input_guild_support_money_ID_data[1:]) * input_guild_support_money_ID_data[0]
result_guild_update = self.guild_db.update_one({"_id":"guild"}, {"$inc":{"guild_money":-total_support_money}}, upsert = False)
if result_guild_update.raw_result["nModified"] < 1 and "upserted" not in result_guild_update.raw_result:
return await ctx.send(f"```혈비 지원 실패!```")
embed = discord.Embed(
title = f"🤑 혈비 지원 완료",
description = f"```css\n[{input_guild_support_money_data[1]}] 사유로 💰[{input_guild_support_money_ID_data[0]}]씩 혈비에서 지원했습니다.```",
color=0x00ff00
)
embed.add_field(name = f"**👥 명단**", value = f"**```fix\n{', '.join(input_guild_support_money_ID_data[1:])}```**")
embed.add_field(name = f"**💰 인당지원금**", value = f"**```fix\n{input_guild_support_money_ID_data[0]}```**")
embed.add_field(name = f"**💰 토탈지원금**", value = f"**```fix\n{int(input_guild_support_money_ID_data[0])*len(input_guild_support_money_ID_data[1:])}```**")
return await ctx.send(embed = embed)
################ 창고검색 #################
@commands.command(name=commandSetting[44][0], aliases=commandSetting[44][1:])
async def guild_inventory_search(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
pipeline = [
{"$match": {"itemstatus":"미판매"}}, # 조건
{"$group": {"_id": "$item", "count": {"$sum":1}}} # 요런식으로 변환해준다.
]
item_counts = self.jungsan_db.aggregate(pipeline)
sorted_item_counts : dict = sorted(item_counts, key=lambda item_counts:item_counts['count'], reverse = True)
len_sorted_item_counts = len(sorted_item_counts)
#print(sorted_item_counts)
embed_list : list = []
embed_index : int = 0
embed_cnt : int = 0
embed = discord.Embed(title = f'📦 `창고 내역`', description = "", color = 0x00ff00)
embed_list.append(embed)
if len_sorted_item_counts > 0 :
for item_data in sorted_item_counts:
embed_cnt += 1
if embed_cnt > 24 :
embed_cnt = 0
embed_index += 1
tmp_embed = discord.Embed(
title = "",
description = "",
color=0x00ff00
)
embed_list.append(tmp_embed)
embed_list[embed_index].add_field(name = item_data['_id'], value = f"```{item_data['count']}```")
embed.set_footer(text = f"전체 아이템 종류 : {len_sorted_item_counts}개")
if len(embed_list) > 1:
for embed_data in embed_list:
await asyncio.sleep(0.1)
await ctx.send(embed = embed_data)
return
else:
return await ctx.send(embed=embed, tts=False)
else :
embed.add_field(name = '\u200b\n', value = '창고가 비었습니다.\n\u200b')
return await ctx.send(embed=embed, tts=False)
else:
toggle_documents = list(self.jungsan_db.find({"itemstatus" : "미판매", "item" : args}).sort("_id", pymongo.ASCENDING))
if len(toggle_documents) == 0:
return await ctx.send(f"`창고`에 해당 아이템(`{args}`)이 없습니다!")
toggle_list : list = []
tmp_toggle_list : list = []
for toggle in toggle_documents:
tmp_toggle_list.append(toggle["toggle"])
toggle_name_list = list(set(tmp_toggle_list))
for name in toggle_name_list:
toggle_list.append(f"{name}({tmp_toggle_list.count(name)}개)")
embed = discord.Embed(title = f'📦 `{args}` 소지자 (총 `{len(toggle_name_list)}`명)', description = "", color = 0x00ff00)
embed.description = f"```{', '.join(toggle_list)}```"
return await ctx.send(embed = embed)
################ 부분정산 #################
@commands.command(name=commandSetting[59][0], aliases=commandSetting[59][1:])
async def partial_jungsan(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
jungsan_document : list = []
input_distribute_partial_finish = []
if not args:
return await ctx.send(f"**[검색조건]**이 잘못 됐습니다. **[검색조건]**은 **[아이디, 보스명, 아이템, 날짜]** 네가지 중 **1개**를 입력 하셔야합니다!")
else:
input_distribute_partial_finish : list = args.split()
len_input_distribute_partial_finish = len(input_distribute_partial_finish)
if len_input_distribute_partial_finish != 2:
return await ctx.send(f"**{commandSetting[59][0]} [검색조건] [검색값]** 형식으로 입력 해주세요! **[검색조건]**은 **[아이디, 보스명, 아이템, 날짜]** 네가지 중 **1개**를 입력 하셔야합니다!")
else:
if input_distribute_partial_finish[0] == "아이디":
jungsan_document = list(self.jungsan_db.find({"$and" : [{"$or":[{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"before_jungsan_ID":{"$in":[input_distribute_partial_finish[1]]}}, {"itemstatus":"분배중"}]}).limit(25).sort("_id", pymongo.ASCENDING))
elif input_distribute_partial_finish[0] == "보스명":
jungsan_document = list(self.jungsan_db.find({"$and" : [{"$or":[{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"boss":input_distribute_partial_finish[1]}, {"itemstatus":"분배중"}]}).limit(25).sort("_id", pymongo.ASCENDING))
elif input_distribute_partial_finish[0] == "아이템":
jungsan_document = list(self.jungsan_db.find({"$and" : [{"$or":[{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"item":input_distribute_partial_finish[1]}, {"itemstatus":"분배중"}]}).limit(25).sort("_id", pymongo.ASCENDING))
elif input_distribute_partial_finish[0] == "날짜":
try:
start_search_date : str = datetime.datetime.now().replace(year = int(input_distribute_partial_finish[1][:4]), month = int(input_distribute_partial_finish[1][5:7]), day = int(input_distribute_partial_finish[1][8:10]), hour = 0, minute = 0, second = 0)
end_search_date : str = start_search_date + datetime.timedelta(days = 1)
except:
return await ctx.send(f"**[날짜] [검색값]**은 0000-00-00 형식으로 입력 해주세요!")
jungsan_document = list(self.jungsan_db.find({"$and" : [{"$or":[{"toggle_ID" : str(ctx.author.id)}, {"regist_ID" : str(ctx.author.id)}]}, {"getdate":{"$gte":start_search_date, "$lt":end_search_date}}, {"itemstatus":"분배중"}]}).limit(25).sort("_id", pymongo.ASCENDING))
else:
return await ctx.send(f"**[검색조건]**이 잘못 됐습니다. **[검색조건]**은 **[아이디, 보스명, 아이템, 날짜]** 네가지 중 **1개**를 입력 하셔야합니다!")
if len(jungsan_document) == 0:
return await ctx.send(f"{ctx.author.mention}님! **[ 분배중 ]**인 정산 내역이 없거나 등록된 정산 내역이 없습니다. **[ {commandSetting[13][0]} ]** 명령을 통해 확인해주세요")
temp_jungsan_document : list = copy.deepcopy(jungsan_document)
init_button_list : list = []
button_list : list = []
list_height : int = 0
result_jungsan_list : list = []
result_jungsan_str_list : list = []
result_jungsan_str : str = ""
result_total_money : int = 0
while len(temp_jungsan_document) > 0:
temp : list = []
for i in range(5):
data_dict = temp_jungsan_document.pop(0)
if input_distribute_partial_finish[0] == "아이디":
temp.append(Button(style=ButtonStyle.gray, id=f"{list_height}_{i}:{data_dict['_id']}>{data_dict['each_price']}", label=f"{data_dict['each_price']} [순번 : {data_dict['_id']}]", emoji="💰"))
else:
temp.append(Button(style=ButtonStyle.gray, id=f"{list_height}_{i}:{data_dict['_id']}>{int(data_dict['each_price'])*len(data_dict['before_jungsan_ID'])}", label=f"{int(data_dict['each_price'])*len(data_dict['before_jungsan_ID'])} [순번 : {data_dict['_id']}]", emoji="💰"))
if len(temp_jungsan_document) <= 0:
break
list_height += 1
button_list.append(temp)
command_button : list = [Button(style=ButtonStyle.blue, id="refresh", label="초기화"), Button(style=ButtonStyle.green, id="confirm",label="정산"), Button(style=ButtonStyle.red, id="exit", label="취소")]
button_list.append(command_button)
init_button_list = copy.deepcopy(button_list)
waiting_time : str = 120
embed_result = discord.Embed(title = f"📜 [{input_distribute_partial_finish[1]}]에 대한 정산 예정목록",description = "",color=0x00ff00)
embed_result.add_field(name = "\u200b", value = f"정산예정금액 : 💰 **{0}**")
embed_result.set_footer(text="정산목록은 최대 25개까지 표시됩니다.")
msg = await ctx.send(embed = embed_result, components = button_list)
def check(interaction):
return interaction.user.id == ctx.author.id and interaction.channel.id == ctx.channel.id and interaction.message.id == msg.id
while True:
try:
interaction = await self.bot.wait_for("button_click", check=check, timeout=waiting_time)
await interaction.respond(type=6)
listid = interaction.component.id
if listid == "confirm":
break
elif listid == "exit":
embed_result.title = f"📜 {input_distribute_partial_finish[1]}]에 대한 정산취소!"
embed_result.description = f""
await msg.edit(embed = embed_result, components=[])
return
elif listid == "refresh":
result_jungsan_list = []
result_jungsan_str_list = []
result_total_money = 0
result_jungsan_str = ""
embed = interaction.message.embeds[0]
embed.title = f"📜 {input_distribute_partial_finish[1]}]에 대한 정산 예정목록 초기화!"
embed.description = f""
embed.set_field_at(index = len(embed.fields)-1, name = "\u200b", value = f"정산예정금액 : 💰 **{result_total_money}**", inline=False)
button_list = copy.deepcopy(init_button_list)
await msg.edit(embed = embed, components=init_button_list)
pass
else:
if listid.find("_") != -1:
firstpart, secondpart = listid.split('_')
button_list[int(firstpart)][int(secondpart[:1])] = Button(style=ButtonStyle.green, label=f"{interaction.component.label}", id=listid, emoji="💰", disabled=True)
embed = interaction.message.embeds[0]
jungsan_index : int = int(listid[listid.find(':')+1:listid.find('>')])
jungsan_money : int = int(f"{listid[listid.find('>')+1:]}")
result_total_money += jungsan_money
result_jungsan_list.append(jungsan_index)
result_jungsan_str_list.append(f"[{jungsan_index}](💰{jungsan_money})")
embed.title = f"📜 {input_distribute_partial_finish[1]}]에 대한 정산 예정목록"
result_jungsan_str = "\n".join(result_jungsan_str_list)
embed.description = f"```md\n{result_jungsan_str}```"
embed.set_field_at(index = len(embed.fields)-1, name = "\u200b", value = f"정산예정금액 : 💰 **{result_total_money}**", inline=False)
await msg.edit(embed = embed, components=button_list)
except asyncio.TimeoutError:
embed_result.title = f"📜 {input_distribute_partial_finish[1]}]에 대한 정산취소!"
embed.description = f"시간초과!"
await msg.edit(embed = embed_result, components=[])
return
result_jungsan_list = sorted(result_jungsan_list)
for jungsan_data in jungsan_document:
if jungsan_data["_id"] in result_jungsan_list:
if input_distribute_partial_finish[0] == "아이디":
jungsan_data['before_jungsan_ID'].remove(input_distribute_partial_finish[1])
if len(jungsan_data['before_jungsan_ID']) == 0:
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":{"before_jungsan_ID":[], "after_jungsan_ID":sorted(jungsan_data['after_jungsan_ID']+[input_distribute_partial_finish[1]]), "modifydate":datetime.datetime.now(), "itemstatus":"분배완료"}}, upsert = True)
else:
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":{"before_jungsan_ID":jungsan_data['before_jungsan_ID'], "after_jungsan_ID":sorted(jungsan_data['after_jungsan_ID']+[input_distribute_partial_finish[1]]), "modifydate":datetime.datetime.now()}}, upsert = True)
else:
result = self.jungsan_db.update_one({"_id":jungsan_data['_id']}, {"$set":{"before_jungsan_ID":[], "after_jungsan_ID":sorted(jungsan_data['after_jungsan_ID']+jungsan_data['before_jungsan_ID']), "modifydate":datetime.datetime.now(), "itemstatus":"분배완료"}}, upsert = True)
if result.raw_result["nModified"] < 1 and "upserted" not in result.raw_result:
await ctx.send(f"{ctx.author.mention}, 일괄정산 실패.")
embed_result.title = f"📜 {input_distribute_partial_finish[1]}]에 대한 정산완료!"
embed_result.description = f"```md\n{result_jungsan_str}```"
embed_result.set_field_at(index = len(embed_result.fields)-1, name = "\u200b", value = f"정산완료금액 : 💰 **{result_total_money}**", inline=False)
await msg.edit(embed = embed_result, components=[])
return
################ 이체 #################
@commands.command(name=commandSetting[60][0], aliases=commandSetting[60][1:])
async def bank_transfer_money(self, ctx, *, args : str = None):
if ctx.message.channel.id != int(basicSetting[6]) or basicSetting[6] == "":
return
member_data : dict = self.member_db.find_one({"_id":ctx.author.id})
if not member_data:
return await ctx.send(f"{ctx.author.mention}님은 혈원으로 등록되어 있지 않습니다!")
if not args:
return await ctx.send(f"**{commandSetting[60][0]} [금액] [대상아이디]** 양식으로 입력 해주세요")
input_bank_withdraw_data : list = args.split()
len_input_bank_withdraw_data : int = len(input_bank_withdraw_data)
if len_input_bank_withdraw_data < 2:
return await ctx.send(f"**{commandSetting[60][0]} [금액] [아이디]** 양식으로 입력 해주세요")
try:
input_bank_withdraw_data[0] = int(input_bank_withdraw_data[0])
except ValueError:
return await ctx.send(f"**[금액]**은 숫자로 입력 해주세요")
if member_data["account"] < input_bank_withdraw_data[0]:
return await ctx.send(f"이체 요청 금액(`{input_bank_withdraw_data[0]}`)이 소지한 금액(`{member_data['account']}`) 보다 작습니다.")
check_member_data : list = []
check_member_data = list(self.member_db.find({"game_ID":input_bank_withdraw_data[1]}))
if not check_member_data:
return await ctx.send(f"```이체 대상 [`{input_bank_withdraw_data[1]}`](은)는 혈원으로 등록되지 않은 아이디 입니다.```")
result_update = self.member_db.update_one({"game_ID":input_bank_withdraw_data[1]}, {"$inc":{"account":input_bank_withdraw_data[0]}})
result_update1 = self.member_db.update_one({"game_ID":member_data["game_ID"]}, {"$inc":{"account":-input_bank_withdraw_data[0]}})
result_transfer_list : list = list(self.member_db.find({"game_ID":{"$in":[input_bank_withdraw_data[1], member_data['game_ID']]}}))
result_str : str = ""
for data in result_transfer_list:
if member_data["game_ID"] == data["game_ID"]:
result_str += f"📤 {data['game_ID']} : 💰 **{data['account']}** (-{input_bank_withdraw_data[0]})\n"
else:
result_str += f"📥 {data['game_ID']} : 💰 **{data['account']}** (+{input_bank_withdraw_data[0]})\n"
await ctx.reply(f"[`{member_data['game_ID']}`]님이 [`{input_bank_withdraw_data[1]}`]님께 💰[**{input_bank_withdraw_data[0]}**] 이체 완료!\n이체결과\n{result_str}")
return
ilsang_distribution_bot : IlsangDistributionBot = IlsangDistributionBot()
ilsang_distribution_bot.add_cog(settingCog(ilsang_distribution_bot))
ilsang_distribution_bot.add_cog(adminCog(ilsang_distribution_bot))
ilsang_distribution_bot.add_cog(memberCog(ilsang_distribution_bot))
ilsang_distribution_bot.add_cog(manageCog(ilsang_distribution_bot))
ilsang_distribution_bot.add_cog(bankCog(ilsang_distribution_bot))
ilsang_distribution_bot.run() | [
"noreply@github.com"
] | sikote.noreply@github.com |
8de3381b4bf1330627995867f8533aa971e31273 | 8a77b3a993b5ad9aaa7da0eeca4e02462e336dcd | /IPTVPlayer/hosts/hosturllist.py | f20088c05a692f45a988dd1d1ea5115e84830f55 | [] | no_license | gorr2016/iptvplayer-for-e2 | cc6a6004ff04a5aca1145860abd09791d762ea20 | 74b4320feca9079293b19c837b14cfc402d77673 | refs/heads/master | 2021-01-01T05:00:41.155592 | 2016-04-27T09:28:41 | 2016-04-27T09:28:41 | 57,188,687 | 1 | 1 | null | 2016-04-27T09:28:42 | 2016-04-27T06:20:30 | Python | UTF-8 | Python | false | false | 15,857 | py | # -*- coding: utf-8 -*-
###################################################
# LOCAL import
###################################################
from Plugins.Extensions.IPTVPlayer.components.iptvplayerinit import TranslateTXT as _
from Plugins.Extensions.IPTVPlayer.components.ihost import CHostBase, CBaseHostClass, CDisplayListItem, ArticleContent, RetHost, CUrlItem
from Plugins.Extensions.IPTVPlayer.tools.iptvtools import CSelOneLink, printDBG, printExc, CSearchHistoryHelper, GetLogoDir, GetCookieDir
from Plugins.Extensions.IPTVPlayer.tools.iptvfilehost import IPTVFileHost
from Plugins.Extensions.IPTVPlayer.libs.youtube_dl.utils import clean_html
from Plugins.Extensions.IPTVPlayer.libs.urlparserhelper import getDirectM3U8Playlist, getF4MLinksWithMeta
from Plugins.Extensions.IPTVPlayer.libs.urlparser import urlparser
from Plugins.Extensions.IPTVPlayer.iptvdm.iptvdh import DMHelper
###################################################
###################################################
# FOREIGN import
###################################################
from Components.config import config, ConfigSelection, ConfigYesNo, ConfigDirectory, getConfigListEntry
import re
import codecs
import time
###################################################
###################################################
# E2 GUI COMMPONENTS
###################################################
###################################################
###################################################
# Config options for HOST
###################################################
config.plugins.iptvplayer.Sciezkaurllist = ConfigDirectory(default = "/hdd/")
config.plugins.iptvplayer.grupujurllist = ConfigYesNo(default = True)
config.plugins.iptvplayer.sortuj = ConfigYesNo(default = True)
config.plugins.iptvplayer.urllist_showrafalcool1 = ConfigYesNo(default = True)
def GetConfigList():
optionList = []
optionList.append(getConfigListEntry(_('Text files ytlist and urllist are in:'), config.plugins.iptvplayer.Sciezkaurllist))
optionList.append(getConfigListEntry(_('Show recommended by Rafalcool1:'), config.plugins.iptvplayer.urllist_showrafalcool1))
optionList.append(getConfigListEntry(_('Sort the list:'), config.plugins.iptvplayer.sortuj))
optionList.append(getConfigListEntry(_('Group links into categories: '), config.plugins.iptvplayer.grupujurllist))
return optionList
###################################################
def gettytul():
return (_('Urllists player'))
class Urllist(CBaseHostClass):
RAFALCOOL1_FILE = 'urllist.rafalcool1'
URLLIST_FILE = 'urllist.txt'
URRLIST_STREAMS = 'urllist.stream'
URRLIST_USER = 'urllist.user'
def __init__(self):
printDBG("Urllist.__init__")
self.MAIN_GROUPED_TAB = [{'category': 'all', 'title': (_("All in one")), 'desc': (_("Links are videos and messages, without division into categories")), 'icon':'http://osvita.mediasapiens.ua/content/news/001000-002000/shyfrovanie_dannyh_1415.jpg'}]
if config.plugins.iptvplayer.urllist_showrafalcool1.value:
self.MAIN_GROUPED_TAB.append({'category': Urllist.RAFALCOOL1_FILE, 'title': (_("Recommended by Rafalcool1")), 'desc': (_("List of movies prepared by Rafalcool1")), 'icon':'http://s1.bild.me/bilder/030315/3925071iconFilm.jpg'})
self.MAIN_GROUPED_TAB.extend( [{'category': Urllist.URLLIST_FILE, 'title': (_("Videos")), 'desc': (_("Links to the video files from the file urllist.txt")), 'icon':'http://mohov.h15.ru/logotip_kino.jpg'}, \
{'category': Urllist.URRLIST_STREAMS, 'title': (_("live transfers")), 'desc': (_("Live broadcasts from the file urllist.stream")), 'icon':'http://asiamh.ru.images.1c-bitrix-cdn.ru/images/media_logo.jpg?136879146733721'}, \
{'category': Urllist.URRLIST_USER, 'title': (_("User files")), 'desc': (_("Favorite addresses are stored under the file urllist.user")), 'icon':'http://kinovesti.ru/uploads/posts/2014-12/1419918660_1404722920_02.jpg'}])
CBaseHostClass.__init__(self)
self.currFileHost = None
def _cleanHtmlStr(self, str):
str = self.cm.ph.replaceHtmlTags(str, ' ').replace('\n', ' ')
return clean_html(self.cm.ph.removeDoubles(str, ' ').replace(' )', ')').strip())
def _getHostingName(self, url):
if 0 != self.up.checkHostSupport(url):
return self.up.getHostName(url)
elif self._uriIsValid(url):
return (_('direct link'))
else:
return (_('unknown'))
def _uriIsValid(self, url):
if '://' in url:
return True
return False
def updateRafalcoolFile(self, filePath, encoding):
printDBG("Urllist.updateRafalcoolFile filePath[%s]" % filePath)
remoteVersion = -1
localVersion = -1
# get version from file
try:
with codecs.open(filePath, 'r', encoding, 'replace') as fp:
# version should be in first line
line = fp.readline()
localVersion = int(self.cm.ph.getSearchGroups(line + '|', '#file_version=([0-9]+?)[^0-9]')[0])
except:
printExc()
# generate timestamp to add to url to skip possible cacheing
timestamp = str(time.time())
# if we have loacal version get remote version for comparison
if localVersion != '':
sts, data = self.cm.getPage("http://hybrid.xunil.pl/IPTVPlayer_resources/UsersFiles/urllist.txt.version")
if sts:
try:
remoteVersion = int(data.strip())
except:
printExc()
# uaktualnij versje
printDBG('Urllist.updateRafalcoolFile localVersion[%d] remoteVersion[%d]' % (localVersion, remoteVersion))
if remoteVersion > -1 and localVersion < remoteVersion:
sts, data = self.cm.getPage("http://hybrid.xunil.pl/IPTVPlayer_resources/UsersFiles/urllist.txt?t=" + timestamp)
if sts:
# confirm version
line = data[0:data.find('\n')]
try:
newVersion = int(self.cm.ph.getSearchGroups(line + '|', '#file_version=([0-9]+?)[^0-9]')[0])
if newVersion != remoteVersion:
printDBG("Version mismatches localVersion[%d], remoteVersion[%d], newVersion[%d]" % (localVersion, remoteVersion, newVersion) )
file = open(filePath, 'wb')
file.write(data)
file.close()
except:
printExc()
def listCategory(self, cItem, searchMode=False):
printDBG("Urllist.listCategory cItem[%s]" % cItem)
sortList = config.plugins.iptvplayer.sortuj.value
filespath = config.plugins.iptvplayer.Sciezkaurllist.value
groupList = config.plugins.iptvplayer.grupujurllist.value
if cItem['category'] in ['all', Urllist.URLLIST_FILE, Urllist.URRLIST_STREAMS, Urllist.URRLIST_USER, Urllist.RAFALCOOL1_FILE]:
self.currFileHost = IPTVFileHost()
if cItem['category'] in ['all', Urllist.RAFALCOOL1_FILE] and config.plugins.iptvplayer.urllist_showrafalcool1.value:
self.updateRafalcoolFile(filespath + Urllist.RAFALCOOL1_FILE, encoding='utf-8')
self.currFileHost.addFile(filespath + Urllist.RAFALCOOL1_FILE, encoding='utf-8')
if cItem['category'] in ['all', Urllist.URLLIST_FILE]:
self.currFileHost.addFile(filespath + Urllist.URLLIST_FILE, encoding='utf-8')
if cItem['category'] in ['all', Urllist.URRLIST_STREAMS]:
self.currFileHost.addFile(filespath + Urllist.URRLIST_STREAMS, encoding='utf-8')
if cItem['category'] in ['all', Urllist.URRLIST_USER]:
self.currFileHost.addFile(filespath + Urllist.URRLIST_USER, encoding='utf-8')
if 'all' != cItem['category'] and groupList:
tmpList = self.currFileHost.getGroups(sortList)
for item in tmpList:
if '' == item: title = (_("Other"))
else: title = item
params = {'name': 'category', 'category':'group', 'title':title, 'group':item}
self.addDir(params)
else:
tmpList = self.currFileHost.getAllItems(sortList)
for item in tmpList:
desc = (_("Hosting: %s, %s")) % (self._getHostingName(item['url']), item['url'])
if item['desc'] != '':
desc = item['desc']
params = {'title':item['full_title'], 'url':item['url'], 'desc':desc, 'icon':item['icon']}
self.addVideo(params)
elif 'group' in cItem:
tmpList = self.currFileHost.getItemsInGroup(cItem['group'], sortList)
for item in tmpList:
if '' == item['title_in_group']:
title = item['full_title']
else:
title = item['title_in_group']
desc = (_("Hosting: %s, %s")) % (self._getHostingName(item['url']), item['url'])
if item.get('desc', '') != '':
desc = item['desc']
params = {'title':title, 'url':item['url'], 'desc': desc, 'icon':item.get('icon', '')}
self.addVideo(params)
def getLinksForVideo(self, cItem):
printDBG("Urllist.getLinksForVideo url[%s]" % cItem['url'])
videoUrls = []
uri, params = DMHelper.getDownloaderParamFromUrl(cItem['url'])
printDBG(params)
uri = urlparser.decorateUrl(uri, params)
urlSupport = self.up.checkHostSupport( uri )
if 1 == urlSupport:
retTab = self.up.getVideoLinkExt( uri )
videoUrls.extend(retTab)
elif 0 == urlSupport and self._uriIsValid(uri):
if uri.split('?')[0].endswith('.m3u8'):
retTab = getDirectM3U8Playlist(uri)
videoUrls.extend(retTab)
elif uri.split('?')[0].endswith('.f4m'):
retTab = getF4MLinksWithMeta(uri)
videoUrls.extend(retTab)
else:
videoUrls.append({'name':'direct link', 'url':uri})
return videoUrls
def handleService(self, index, refresh=0, searchPattern='', searchType=''):
printDBG('Urllist.handleService start')
CBaseHostClass.handleService(self, index, refresh, searchPattern, searchType)
name = self.currItem.get("name", None)
category = self.currItem.get("category", '')
printDBG( "Urllist.handleService: ---------> name[%s], category[%s] " % (name, category) )
self.currList = []
if None == name:
self.listsTab(self.MAIN_GROUPED_TAB, self.currItem)
else:
self.listCategory(self.currItem)
CBaseHostClass.endHandleService(self, index, refresh)
class IPTVHost(CHostBase):
def __init__(self):
CHostBase.__init__(self, Urllist(), True)
def _isPicture(self, url):
def _checkExtension(url):
return url.endswith(".jpeg") or url.endswith(".jpg") or url.endswith(".png")
if _checkExtension(url): return True
if _checkExtension(url.split('|')[0]): return True
if _checkExtension(url.split('?')[0]): return True
return False
def getLogoPath(self):
return RetHost(RetHost.OK, value = [GetLogoDir('urllistlogo.png')])
def getLinksForVideo(self, Index = 0, selItem = None):
listLen = len(self.host.currList)
if listLen < Index and listLen > 0:
printDBG( "ERROR getLinksForVideo - current list is to short len: %d, Index: %d" % (listLen, Index) )
return RetHost(RetHost.ERROR, value = [])
if self.host.currList[Index]["type"] != 'video':
printDBG( "ERROR getLinksForVideo - current item has wrong type" )
return RetHost(RetHost.ERROR, value = [])
retlist = []
uri = self.host.currList[Index].get('url', '')
if not self._isPicture(uri):
urlList = self.host.getLinksForVideo(self.host.currList[Index])
for item in urlList:
retlist.append(CUrlItem(item["name"], item["url"], 0))
else: retlist.append(CUrlItem('picture link', urlparser.decorateParamsFromUrl(uri, True), 0))
return RetHost(RetHost.OK, value = retlist)
# end getLinksForVideo
def convertList(self, cList):
hostList = []
searchTypesOptions = [] # ustawione alfabetycznie
#searchTypesOptions.append(("Filmy", "filmy"))
#searchTypesOptions.append(("Seriale", "seriale"))
for cItem in cList:
hostLinks = []
type = CDisplayListItem.TYPE_UNKNOWN
possibleTypesOfSearch = None
if cItem['type'] == 'category':
if cItem['title'] == 'Wyszukaj':
type = CDisplayListItem.TYPE_SEARCH
possibleTypesOfSearch = searchTypesOptions
else:
type = CDisplayListItem.TYPE_CATEGORY
elif cItem['type'] == 'video':
type = CDisplayListItem.TYPE_VIDEO
url = cItem.get('url', '')
if self._isPicture(url):
type = CDisplayListItem.TYPE_PICTURE
else:
type = CDisplayListItem.TYPE_VIDEO
if '' != url:
hostLinks.append(CUrlItem("Link", url, 1))
title = cItem.get('title', '')
description = clean_html(cItem.get('desc', ''))
icon = cItem.get('icon', '')
hostItem = CDisplayListItem(name = title,
description = description,
type = type,
urlItems = hostLinks,
urlSeparateRequest = 1,
iconimage = icon,
possibleTypesOfSearch = possibleTypesOfSearch)
hostList.append(hostItem)
return hostList
# end convertList
def getSearchItemInx(self):
# Find 'Wyszukaj' item
try:
list = self.host.getCurrList()
for i in range( len(list) ):
if list[i]['category'] == 'Wyszukaj':
return i
except:
printDBG('getSearchItemInx EXCEPTION')
return -1
def setSearchPattern(self):
try:
list = self.host.getCurrList()
if 'history' == list[self.currIndex]['name']:
pattern = list[self.currIndex]['title']
search_type = list[self.currIndex]['search_type']
self.host.history.addHistoryItem( pattern, search_type)
self.searchPattern = pattern
self.searchType = search_type
except:
printDBG('setSearchPattern EXCEPTION')
self.searchPattern = ''
self.searchType = ''
return | [
"samsamsam@o2.pl"
] | samsamsam@o2.pl |
dcbce63a4f635b820872afd1af848c2461144de0 | e0c634e40dd267a78ea10beb7f5fe9c1f1c790a8 | /heuristics.py | 0b0f9887ca2f2cf76040bc52f7feb124230aeb1d | [] | no_license | IIT-Lab/distgcn | 0fdbae47813639d2001035e7afdfdcd70e006b7f | 42edc47d9a0967c478fcd1d74728da9dfac52530 | refs/heads/main | 2023-01-22T23:42:07.854165 | 2020-11-21T22:58:04 | 2020-11-21T22:58:04 | 315,986,061 | 1 | 0 | null | 2020-11-25T15:52:41 | 2020-11-25T15:52:41 | null | UTF-8 | Python | false | false | 12,687 | py | import networkx as nx
import dwave_networkx as dnx
import igraph as ig
import pulp as plp
from pulp import GLPK
import numpy as np
import pandas as pd
import scipy.sparse as sp
import time
print(nx.__version__)
def greedy_search(adj, wts):
'''
Return MWIS set and the total weights of MWIS
:param adj: adjacency matrix (sparse)
:param wts: weights of vertices
:return: mwis, total_wt
'''
wts = np.array(wts).flatten()
verts = np.array(range(wts.size))
ranks = np.argsort(-wts.flatten())
wts_desc = wts[ranks]
verts_desc = verts[ranks]
mwis = set()
nb_is = set()
total_ws = 0.0
for i in ranks:
if i in nb_is:
continue
_, nb_set = np.nonzero(adj[i])
mwis.add(i)
nb_is = nb_is.union(set(nb_set))
total_ws = np.sum(wts[list(mwis)])
return mwis, total_ws
def dist_greedy_search(adj, wts, epislon=0.5):
'''
Return MWIS set and the total weights of MWIS
:param adj: adjacency matrix (sparse)
:param wts: weights of vertices
:param epislon: 0<epislon<1, to determin alpha and beta
:return: mwis, total_wt
'''
alpha = 1.0 + (epislon / 3.0)
beta = 3.0 / epislon
wts = np.array(wts).flatten()
verts = np.array(range(wts.size))
mwis = set()
remain = set(verts.flatten())
nb_is = set()
while len(remain) > 0:
seta = set()
for v in remain:
_, nb_set = np.nonzero(adj[v])
nb_set = set(nb_set).intersection(remain)
if len(nb_set) == 0:
seta.add(v)
continue
w_bar_v = wts[list(nb_set)].max()
if wts[v] >= w_bar_v / alpha:
seta.add(v)
mis_i = set()
for v in seta:
_, nb_set = np.nonzero(adj[v])
nb_set = set(nb_set)
if len(mis_i.intersection(nb_set)) == 0:
mis_i.add(v)
nb_is = nb_is.union(nb_set)
mwis = mwis.union(mis_i)
remain = remain - mwis - nb_is
total_ws = np.sum(wts[list(mwis)])
return mwis, total_ws
def local_greedy_search(adj, wts):
'''
Return MWIS set and the total weights of MWIS
:param adj: adjacency matrix (sparse)
:param wts: weights of vertices
:return: mwis, total_wt
'''
wts = np.array(wts).flatten()
verts = np.array(range(wts.size))
mwis = set()
remain = set(verts.flatten())
vidx = list(remain)
nb_is = set()
while len(remain) > 0:
for v in remain:
# if v in nb_is:
# continue
_, nb_set = np.nonzero(adj[v])
nb_set = set(nb_set).intersection(remain)
if len(nb_set) == 0:
mwis.add(v)
continue
nb_list = list(nb_set)
nb_list.sort()
wts_nb = wts[nb_list]
w_bar_v = wts_nb.max()
if wts[v] > w_bar_v:
mwis.add(v)
nb_is = nb_is.union(set(nb_set))
elif wts[v] == w_bar_v:
i = list(wts_nb).index(wts[v])
nbv = nb_list[i]
if v < nbv:
mwis.add(v)
nb_is = nb_is.union(set(nb_set))
else:
pass
remain = remain - mwis - nb_is
total_ws = np.sum(wts[list(mwis)])
return mwis, total_ws
def get_all_mis(adj):
# G = ig.Graph()
# G.Read_Adjacency(adj)
g2 = ig.Graph.Adjacency(adj)
# assert G.get_adjacency() == g2.get_adjacency()
mis_all1 = g2.maximal_independent_vertex_sets()
mis_all = np.zeros((len(adj), len(mis_all1)))
for i in range(len(mis_all1)):
mis_all[mis_all1[i],i] = 1
return mis_all
def get_mwis(mis_all, wts):
wts1 = np.expand_dims(wts, axis=1)
utilities = np.multiply(mis_all,wts1).sum(axis=0)
idx = np.argmax(utilities)
return np.nonzero(mis_all[:, idx])[0], utilities[idx]
def mlp_gurobi(adj, wts, timeout=300):
wts = np.array(wts).flatten()
opt_model = plp.LpProblem(name="MIP_Model")
x_vars = {i: plp.LpVariable(cat=plp.LpBinary, name="x_{0}".format(i)) for i in range(wts.size)}
set_V = set(range(wts.size))
constraints = {}
ei = 0
for j in set_V:
_, set_N = np.nonzero(adj[j])
# print(set_N)
for i in set_N:
constraints[ei] = opt_model.addConstraint(
plp.LpConstraint(
e=plp.lpSum([x_vars[i], x_vars[j]]),
sense=plp.LpConstraintLE,
rhs=1,
name="constraint_{0}_{1}".format(j,i)))
ei += 1
objective = plp.lpSum(x_vars[i] * wts[i] for i in set_V )
opt_model.sense = plp.LpMaximize
opt_model.setObjective(objective)
opt_model.solve(solver=plp.apis.GUROBI(mip=True, msg=True,
timeLimit=timeout*1.1,
# NodeLimit=35000,
ImproveStartTime=timeout))
opt_df = pd.DataFrame.from_dict(x_vars, orient="index", columns=["variable_object"])
opt_df["solution_value"] = opt_df["variable_object"].apply(lambda item: item.varValue)
solu = opt_df[opt_df['solution_value'] > 0].index.to_numpy()
return solu, wts[solu].sum(), plp.LpStatus[opt_model.status]
def mwis_mip_edge_relax(adj, wts):
wts = np.array(wts).flatten()
opt_model = plp.LpProblem(name="MIP_Model", sense=plp.LpMaximize)
x_vars = {i: plp.LpVariable(lowBound=0.0, upBound=1.0, name="x_{0}".format(i)) for i in range(wts.size)}
set_V = set(range(wts.size))
constraints = {}
ei = 0
for j in set_V:
_, set_N = np.nonzero(adj[j])
for i in set_N:
constraints[ei] = opt_model.addConstraint(
plp.LpConstraint(
e=plp.lpSum([x_vars[i], x_vars[j]]),
sense=plp.LpConstraintLE,
rhs=1,
name="constraint_{0}_{1}".format(j, i)))
ei += 1
objective = plp.lpSum(x_vars[i] * wts[i] for i in set_V)
opt_model.setObjective(objective)
# opt_model.solve(solver=plp.apis.GUROBI(mip=False, msg=True))
opt_model.solve(solver=GLPK(msg=True))
opt_df = pd.DataFrame.from_dict(x_vars, orient="index", columns=["variable_object"])
opt_df["solution_value"] = opt_df["variable_object"].apply(lambda item: item.varValue)
solu_relax = opt_df['solution_value'].to_numpy()
return solu_relax
def mwis_mip_clique_relax(adj, wts):
g = nx.from_scipy_sparse_matrix(adj)
max_cliques = list(nx.algorithms.clique.find_cliques(g))
opt_model = plp.LpProblem(name="MIP_Model", sense=plp.LpMaximize)
x_vars = {i: plp.LpVariable(lowBound=0.0, upBound=1.0, name="x_{0}".format(i)) for i in range(wts.size)}
set_V = set(range(wts.size))
constraints = {}
ei = 0
for j in range(len(max_cliques)):
clique = max_cliques[j]
constraints[ei] = opt_model.addConstraint(
plp.LpConstraint(
e=plp.lpSum(x_vars[i] for i in clique),
sense=plp.LpConstraintLE,
rhs=1.0,
name="constraint_{0}".format(j)))
ei += 1
objective = plp.lpSum(x_vars[i] * wts[i] for i in set_V)
opt_model.setObjective(objective)
# opt_model.solve(solver=plp.apis.GUROBI(mip=False, msg=True))
opt_model.solve(solver=GLPK(msg=True))
opt_df = pd.DataFrame.from_dict(x_vars, orient="index", columns=["variable_object"])
opt_df["solution_value"] = opt_df["variable_object"].apply(lambda item: item.varValue)
solu_relax = opt_df['solution_value'].to_numpy()
return solu_relax
def mp_greedy(adj, wts):
wts = np.array(wts).flatten()
solu_relax = mwis_mip_clique_relax(adj, wts)
print(solu_relax)
vec_x = np.full_like(wts, fill_value=np.nan)
vec_x[solu_relax == 0.0] = 0
vec_x[solu_relax == 1.0] = 1
N = wts.size
for n in range(N):
vec_x1 = vec_x.copy()
Vi = np.argwhere(np.isnan(vec_x1))
if Vi.size == 0:
break
for v in Vi:
neighbors = adj[v, :].toarray()[0, :].nonzero()[0]
vec_nb = vec_x1[neighbors]
if (vec_nb == 1.0).astype(float).sum() > 0:
vec_x[v] = 0
elif wts[v] > np.amax(wts[neighbors]):
vec_x[v] = 1
elif wts[v] == np.amax(wts[neighbors]):
vn = np.argmax(wts[neighbors])
if v < neighbors[vn]:
vec_x[v] = 1
elif (vec_nb == 0.0).astype(int).sum() == neighbors.size:
vec_x[v] = 1
else:
pass
Vn = np.argwhere(np.isnan(vec_x))
if Vn.size == Vi.size:
v = np.argmax(wts[Vn])
vec_x[Vn[v]] = 1
solu = (vec_x == 1.0).astype(int).nonzero()[0]
return set(solu), wts[solu].sum()
def mwis_mip_edge_dual(adj, wts):
wts = np.array(wts).flatten()
g = nx.from_scipy_sparse_matrix(adj)
max_cliques = list(nx.algorithms.clique.find_cliques(g))
opt_model = plp.LpProblem(name="MIP_Model", sense=plp.LpMinimize)
x0, x1 = adj.nonzero()
x_vars = {(x0[i], x1[i]): plp.LpVariable(lowBound=0.0, name="x_{0}_{1}".format(x0[i], x1[i])) for i in range(x0.size)}
constraints = {}
ei = 0
for v in range(wts.size):
neighbors = adj[v, :].toarray()[0, :].nonzero()[0]
constraints[ei] = opt_model.addConstraint(
plp.LpConstraint(
e=plp.lpSum(x_vars[(v,i)] for i in neighbors),
sense=plp.LpConstraintGE,
rhs=wts[v],
name="constraint_{0}".format(v)))
ei += 1
objective = plp.lpSum(x_var for x_var in x_vars.values())
opt_model.setObjective(objective)
# opt_model.solve(solver=plp.apis.GUROBI(mip=False, msg=True))
opt_model.solve(solver=GLPK(msg=True))
opt_df = pd.DataFrame.from_dict(x_vars, orient="index", columns=["variable_object"])
opt_df["solution_value"] = opt_df["variable_object"].apply(lambda item: item.varValue)
opt_df["name"] = opt_df["variable_object"].apply(lambda item: item.name)
opt_df.set_index("name", inplace=True)
solu_relax = adj.copy().astype(float)
x0, x1 = solu_relax.nonzero()
for i in range(x0.size):
idx = 'x_{}_{}'.format(x0[i], x1[i])
solu_relax[x0[i], x1[i]] = opt_df.loc[idx, 'solution_value']
return solu_relax
def test_heuristic():
# Create a random graph
t = time.time()
graph = nx.generators.random_graphs.fast_gnp_random_graph(120, 0.05)
for u in graph:
graph.nodes[u]['weight'] = np.random.uniform(0, 1) # np.square(np.random.randn())
graph.nodes[u]['id'] = u
print("Time to create graph: {}".format(time.time()-t))
# Run Neighborhood Removal
adj = nx.adjacency_matrix(graph)
weights = np.array([graph.nodes[u]['weight'] for u in graph])
vertices = np.array(range(len(weights)))
t = time.time()
mwis, total_wt = mp_greedy(adj, weights)
print("Time of message passing (MP Greedy): {}".format(time.time()-t))
print("Original Graph: {} nodes, {} edges.".format(graph.number_of_nodes(), graph.number_of_edges()))
print("Partial MWIS Solution:\nTotal Weights: {}, IS size: {}\n{}".format(total_wt, len(mwis), mwis))
print(dnx.is_independent_set(graph, list(mwis)))
t = time.time()
mwis, total_wt = greedy_search(adj, weights)
print("Time of greedy search: {}".format(time.time()-t))
print("Original Graph: {} nodes, {} edges.".format(graph.number_of_nodes(), graph.number_of_edges()))
print("Partial MWIS Solution:\nTotal Weights: {}, IS size: {}\n{}".format(total_wt, len(mwis), mwis))
print(dnx.is_independent_set(graph, list(mwis)))
t = time.time()
mwis, total_wt = dist_greedy_search(adj, weights, 0.1)
print("Time of distributed greedy approximation: {}".format(time.time()-t))
print("Original Graph: {} nodes, {} edges.".format(graph.number_of_nodes(), graph.number_of_edges()))
print("Partial MWIS Solution:\nTotal Weights: {}, IS size: {}\n{}".format(total_wt, len(mwis), mwis))
print(dnx.is_independent_set(graph, list(mwis)))
t = time.time()
mwis, total_wt = local_greedy_search(adj, weights)
print("Time of local greedy approximation: {}".format(time.time()-t))
print("Original Graph: {} nodes, {} edges.".format(graph.number_of_nodes(), graph.number_of_edges()))
print("Partial MWIS Solution:\nTotal Weights: {}, IS size: {}\n{}".format(total_wt, len(mwis), mwis))
print(dnx.is_independent_set(graph, list(mwis)))
if __name__ == "__main__":
test_heuristic()
| [
"zhongyuan.zhao@rice.edu"
] | zhongyuan.zhao@rice.edu |
474ca8e491dd7c8a564d196843a5593c517b1619 | 7533acbcf36b196e5513fad2b3c9623411500f0f | /0x0F-python-object_relational_mapping/model_state.py | 9b22628ad72e4f2739e3630bec79c475e4db1008 | [] | no_license | AndrewKalil/holbertonschool-higher_level_programming | 97ce8af5ad7e8e9f0b1a25d7fa7dcb1a2b40810e | 9bef1f7c8ff9d8e90ec2aed7a29f37cec3a5e590 | refs/heads/master | 2022-12-17T19:02:12.096913 | 2020-09-23T00:00:44 | 2020-09-23T00:00:44 | 259,439,815 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 400 | py | #!/usr/bin/python3
"""First state model"""
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class State(Base):
"""Class State"""
__tablename__ = 'states'
id = Column(Integer, autoincrement=True, primary_key=True,
nullable=False, unique=True)
name = Column(String(128), nullable=False)
| [
"1541@holbertonschool.com"
] | 1541@holbertonschool.com |
b34c607bedf72bb9aa8b628f15795fddc255adb9 | fe1b7d3ea2b8996729354d87cca43defd7b2f194 | /exerc22.py | a7b68a57e164039c0ab2d7908bf813c5c6a18924 | [] | no_license | Raggiiz/Exercicios-repeti-o-python | 539df748a5b2299d6c10f5d448af331619d75b9b | 32221824205d830b504ff7a171bbbe43b09690a4 | refs/heads/master | 2021-05-24T16:21:44.126027 | 2020-04-07T01:12:37 | 2020-04-07T01:12:37 | 253,653,474 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 313 | py | print("exercício 22")
numero = int(input("\nDigite um número: "))
lista = []
if numero % 2 != 0 or numero == 2:
print("primo")
else:
for i in range(numero):
if numero % (i + 1) == 0:
lista.append(i + 1)
print("Os números divisiveis por ", numero, " são ", lista) | [
"noreply@github.com"
] | Raggiiz.noreply@github.com |
bead46da9ad05509cdffb58698655e11cfcebd2c | 3f55706d4679e1c6d0f622de7f208b6c4efeba35 | /Round_1/437. Path Sum III/solution_1.py | d2e2c9e40f8b0c0402a19c25c6ca54d77608c378 | [] | no_license | buptwxd2/leetcode | 37649f95ea3eed6f02761e77f525e66e1f7c1379 | 3f5ad6164c147e7b51b7850dcd279150fa8a7600 | refs/heads/master | 2020-12-10T03:35:25.511610 | 2020-10-08T07:55:10 | 2020-10-08T07:55:10 | 233,490,657 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,109 | py | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
if root is None:
return 0
return self.count_root_node(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
# count the path number equals with sum starting with the node: root
def count_root_node(self, root, sum):
if root is None:
return 0
# root.val is equal to the sum
only_root = int(root.val == sum)
# check the left sub-tree
left_count = self.count_root_node(root.left, sum - root.val)
# check the right sub-tree
right_count = self.count_root_node(root.right, sum - root.val)
return only_root + left_count + right_count
"""
Results:
Runtime: 1020 ms, faster than 10.63% of Python3 online submissions for Path Sum III.
Memory Usage: 14.8 MB, less than 56.49% of Python3 online submissions for Path Sum III
"""
| [
"buptwxd@163.com"
] | buptwxd@163.com |
9afc4200eacafdbebe20217fe3f7491121e55325 | 06e51cd96f2788f87c7c426244167ddbfcc0d551 | /integer_solutions.py | cc8d955bf497fb094c54cccbe9ef48050297b32e | [] | no_license | Lisolo/ACM | 683724184dc2af31ef45073a9cd3ef7f2cdabfba | 231d80dd72768ca97c3e9795af94910f94cc0643 | refs/heads/master | 2016-09-06T16:04:11.910067 | 2014-11-26T12:25:50 | 2014-11-26T12:25:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 904 | py | # coding=utf-8
"""
给你两个整数a和b(-10000<a,b<10000),请你判断是否存在两个整数,他们的和为a,乘积为b。
若存在,输出Yes,否则输出No
例如:a=9,b=15, 此时不存在两个整数满足上述条件,所以应该输出No。
"""
a = 6
b = 9
divisors = []
flag = 0
if b >= 0:
for x in xrange(-b, b+1):
if x == 0:
pass
else:
b % x == 0
divisors.append([x, b/x])
else:
for x in xrange(b,-(b-1)):
if x == 0:
pass
else:
b % x == 0
divisors.append([x, b/x])
for x in divisors:
if sum(x) == a:
flag = 1
if a == 0 and b == 0:
print 'YES'
else:
if flag:
print 'YES'
else:
print 'NO'
"""solution 2:"""
delta = a**2 - 4 * b
if delta >= 0 and int(delta**0.5) == delta**0.5:
print 'YES'
else:
print 'NO' | [
"iamsoloa@gmail.com"
] | iamsoloa@gmail.com |
c014798865331ef81d1e07c344df553a92294cac | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03031/s125157001.py | 4ac1006ad6aa89f188ff8caaa0a4a2b77a42ef94 | [] | 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 | 654 | py | n, m = map(int, input().split())
switch_list = []
for i in range(m):
s = list(map(int, input().split()))
s.pop(0)
switch_list.append(s)
p_list = list(map(int, input().split()))
#print(switch_list)
#print(p_list)
ans = 0
for bit in range(1 << n): #100・・0(n+1桁)-1 = 111・・・1(n桁)となりn桁のビット演算をfor文で回す
cnt = 0
for j in range(0,m):
switch_sum = 0
for i in range(n):
if (bit >> i) & 1 and i+1 in switch_list[j]:
switch_sum += 1
if switch_sum%2 == p_list[j]:
cnt += 1
if cnt == m:
ans += 1
print(ans) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
a60350b213f426911d7492c6dfbd215092a9d023 | b65a4926083b3b951d12dcdc549fc64031f637cd | /InterfaceSimulator.py | 01275ca53024780fe2dbf086a5821a535b9bd420 | [] | no_license | leongersen/afstuderen | 94170c6c4f4284ee6839ce23114a6be77e492115 | 80f554eb17d02b62171d472d8e2611f4948ffa9f | refs/heads/master | 2023-08-26T14:47:39.082999 | 2015-06-22T06:42:13 | 2015-06-22T06:42:13 | 35,265,091 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 908 | py | count = []
scount = []
data = []
SECTOR_COUNT = 150
SECTOR_SIZE = 32
CHUNK_SIZE = 8
def end():
print scount
for w in count:
print w
def keepCount ( a, b ):
global count
count[a][b] = count[a][b] + 1
for i in range(0, SECTOR_COUNT):
data.append([0xFF] * SECTOR_SIZE)
count.append([0] * SECTOR_SIZE)
scount.append(0)
def eraseSector ( sector_address ):
global data
# track sector erases
global scount
scount[sector_address] = scount[sector_address] + 1
data[sector_address] = [0xFF] * SECTOR_SIZE
def writeData ( sector_address, cursor_address, value ):
global data
index = 0;
for c in value:
keepCount(sector_address, cursor_address + index)
data[sector_address][cursor_address + index] = c
index = index + 1
def readFirstSectorByte ( sector_address ):
global data
return data[sector_address][0]
def readSector ( sector_address ):
return "".join(data[sector_address])
| [
"leongersen@gmail.com"
] | leongersen@gmail.com |
39141509439abd9f0a6b15b5b4ff62a6ad30bd59 | db33d917da9de935e907b0f879733dcfd615bab0 | /AndilePackage/Setup.py | c75582047bffd0fd0c3cc1657da156feffea10fd | [] | no_license | AndileMasi/HandyAndiPkg | c97489864769d7d840ee81f5d80dc3287e8d4cdb | 892cd65e2ae0ca6d3f748ebc1796de97beabd924 | refs/heads/master | 2020-04-30T23:24:39.050836 | 2019-03-22T16:36:51 | 2019-03-22T16:36:51 | 177,143,411 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 454 | py | from setuptools import setup, find_packages
setup(
name='HandyAndi',
version='0.1',
packages=find_packages(exclude=['tests*']),
license='MIT',
description='Handy Andi is a project that Andi created for school.',
long_description=open('README.md').read(),
install_requires=['numpy'],
url='https://github.com/AndileMasi/HandyAndyPkg/AndilePackage',
author='Andile Skosana',
author_email='msikamhlanga@gmail.com'
)
| [
"msikamhlanga@gmail.com"
] | msikamhlanga@gmail.com |
534cc8440706e06fc068160b53f229350ac9b500 | 3c9ef8977c79c759e38024490eb48d3ef28156a1 | /homiechat/homiechat/settings/production.py | 06ac00b660240c642ae191490b44b29d847ec0da | [] | no_license | CdogDuBoss/HomieChat | e97cf285faa113c191d2ad81dd4c3502ddf5dd9d | 9797e18dcea4ffb54a04971cc4d54edaf858fdf1 | refs/heads/main | 2023-04-04T15:09:39.340227 | 2021-04-14T01:30:12 | 2021-04-14T01:30:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 891 | py | from .base import *
DEBUG = False
ALLOWED_HOSTS = [config('HOST1')]
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': config('MYSQL_DB_NAME'),
'USER': config('MYSQL_DB_USERNAME'),
'PASSWORD': config('MYSQL_DB_PASSWORD'),
'HOST': config('MYSQL_DB_HOSTNAME'),
}
}
# set STATIC_ROOT for pythonanywhere
# otherwise admin styling will not manifest
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# HTTPS settings
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
# HSTS settings
SECURE_HSTS_SECONDS = 31536000 # 1 year
SECURE_HSTS_PRELOAD = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
# Channels
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
} | [
"tmakpk@gmail.com"
] | tmakpk@gmail.com |
1adaca04826c2a450f792d08797e3de2da6ea791 | 5714362f0b714c0010008620de7046c77e475924 | /Documentos/Sistema Cadastro/projetoalunossite/alunos/migrations/0011_auto_20150914_1614.py | cb08636fa84ee130da1735cc7783acb6f6fce743 | [] | no_license | nicholasqms/Sistema-Cadastro-LPS | 6d78588790a8b8116836093d4a8274acec38582c | 733dd5fc930cf183e973b5316be26c7a41ef50c2 | refs/heads/master | 2021-01-10T07:07:08.446653 | 2017-09-20T22:44:53 | 2017-09-20T22:44:53 | 46,052,692 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,083 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('alunos', '0010_auto_20150914_1222'),
]
operations = [
migrations.RemoveField(
model_name='teacheruser',
name='department',
),
migrations.AddField(
model_name='teacheruser',
name='CPF',
field=models.PositiveIntegerField(null=True, blank=True),
),
migrations.AddField(
model_name='teacheruser',
name='contact',
field=models.PositiveIntegerField(null=True, blank=True),
),
migrations.AddField(
model_name='teacheruser',
name='email',
field=models.CharField(default=b'your_email@service.com', max_length=100),
),
migrations.AddField(
model_name='teacheruser',
name='register_number',
field=models.PositiveIntegerField(null=True, blank=True),
),
]
| [
"nquagliani@poli.ufrj.br"
] | nquagliani@poli.ufrj.br |
78bd30b9f9da63a19232ab8b64f033c27041abab | 13c78dd8a97796d4027de75570c24bcab9ee57f9 | /0017/0017.py | f99d1974a8e762b4c8bd53dc3165dccc9c877c9b | [] | no_license | Magicwangs/show-me-the-code | b48f1ba9c845c0c17fb1f82127869dff22433edd | 5ad6b6b259f4f0f0f9e907549374de07abcb9185 | refs/heads/master | 2020-12-27T15:04:52.259544 | 2016-11-01T07:27:35 | 2016-11-01T07:27:35 | 67,112,421 | 1 | 0 | null | 2016-09-01T08:21:47 | 2016-09-01T08:21:47 | null | UTF-8 | Python | false | false | 1,210 | py | # -*- coding: utf-8 -*-
# python2.7
"""
Created on Thu Oct 27 20:31:11 2016
@author: MagicWang
"""
import json
import xlrd
from lxml import etree
def getConentOfExcel(xlsName):
xls = xlrd.open_workbook(xlsName)
sheet = xls.sheet_by_name('Student')
retDict = dict()
for i in range(sheet.nrows):
line = list()
for j in range(1,sheet.ncols):
value = sheet.cell_value(i,j)
try:
value = int(value)
except UnicodeEncodeError:
pass #此时出错时因为值为中文,仅将float转化为int
line.append(value)
retDict[sheet.cell_value(i,0)] = line
return retDict
def ToXML(xmlName, data):
root = etree.Element('root')
student = etree.SubElement(root, 'students')
student.append(etree.Comment(u"""学生信息表\n"id" : [名字, 数学, 语文, 英文]\n"""))
student.text = data
tree = etree.ElementTree(root)
tree.write(xmlName, pretty_print=True, xml_declaration=True, encoding='utf-8')
if __name__=="__main__":
contentDict = getConentOfExcel('student.xls')
dataStr = unicode(json.dumps(contentDict).decode('utf-8'))
ToXML('student.xml', dataStr)
| [
"752106129@qq.com"
] | 752106129@qq.com |
a8bfde75fc2cf284a72e5f69140fbf309caf8038 | 46c318dbfedfb95d38207431bbf14bacf12d185f | /NLP/II_Process/Matching/RegEx.py | d738c2ca0c9f6a0f8c5f444a610746577f70e4b9 | [] | no_license | miltonluaces/problem_solving | 2e92877ee736c0920ce6e94dcc73fd01a52e3e46 | bccb89d8aadef4a2e409fc6c66ccad2fb84b6976 | refs/heads/master | 2023-01-08T15:58:51.002478 | 2020-10-28T21:31:46 | 2020-10-28T21:31:46 | 308,143,277 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 379 | py | import regex
# Normal matching.
m1 = regex.search(r'Mr|Mrs', 'Mrs'); print(m1.expandf('{0}'))
m2 = regex.search(r'one(self)?(selfsufficient)?', 'oneselfsufficient'); print(m2.expandf('{0}'))
# POSIX matching.
m3 = regex.search(r'(?p)Mr|Mrs', 'Mrs'); print(m3.expandf('{0}'))
m4 = regex.search(r'(?p)one(self)?(selfsufficient)?', 'oneselfsufficient'); print(m4.expandf('{0}'))
| [
"miltonluacs@gmail.com"
] | miltonluacs@gmail.com |
ec4ec2e3c77321eb2a7abae34fafaa6174cbf408 | 18c8564e197df26d256297b2b25e55f4e68f90e6 | /practice/random_walk.py | eebd8a516999fa6cca3f73d3844a1f71a29b9a7b | [] | no_license | Emni194/Data_Visualization | a303d4a7f606836b36bac42bb03c2e2e060fcaa6 | facb8e1d1f47379873dee272ffa3197515a52686 | refs/heads/master | 2023-03-14T17:47:15.129103 | 2021-03-05T18:34:40 | 2021-03-05T18:34:40 | 344,900,768 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 843 | py | from random import choice
class RandomWalk:
"""Initialize the random walk"""
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4, 5])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4, 5])
y_step = y_direction * y_distance
if x_step == 0 and y_step == 0:
continue
# Calculate new position
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y)
| [
"emasladojevic@yahoo.com"
] | emasladojevic@yahoo.com |
bf6fab955be82cb8c2a81a65c3d6b12d35068493 | 3e1584f4bc2f1d4368b10d0f28fcba69d946eb00 | /core/apps/kubeops_api/migrations/0063_auto_20200221_0654.py | a552b6fac34d4eea6b6e19c7ad53a2cf039001be | [
"Apache-2.0"
] | permissive | azmove/KubeOperator | 80d102a41a0009ae85dd2d82c7dc164511de9a58 | 0561ddbc03eded5813a86693af7fc4ee9647f12d | refs/heads/master | 2021-01-08T22:40:51.267027 | 2020-02-21T08:47:43 | 2020-02-21T08:47:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 737 | py | # Generated by Django 2.2.10 on 2020-02-21 06:54
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('kubeops_api', '0062_auto_20200221_0510'),
]
operations = [
migrations.AddField(
model_name='item',
name='users',
field=models.ManyToManyField(to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='clusterhealthhistory',
name='date_type',
field=models.CharField(choices=[('HOUR', 'HOUR'), ('DAY', 'DAY')], default='HOUR', max_length=255),
),
]
| [
"scydeai@qq.com"
] | scydeai@qq.com |
958bc639829a72e3edfb3b8bf551e0d39083e8e7 | 14a9be9ea1e2e3f0102a96c2be9b3a42ad803835 | /src/notabs/settings.py | 63b85861e98c35af7299ca143720c75406556faa | [] | no_license | nowells/notabs | ac5f5de1b42f39df11d394e05c5803e812e04ef8 | 781c066348e153c39d99bb2c50c84eb0c5982c76 | refs/heads/master | 2020-03-30T05:10:30.668757 | 2008-12-12T01:32:47 | 2008-12-12T01:32:47 | 88,607 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 641 | py | import os
SERVER_IDENTIFIER = os.getenv("SERVER_IDENTIFIER")
# import defaults
from notabs.config.base import *
# import overrides
overrides = __import__(
"notabs.config." + SERVER_IDENTIFIER,
globals(),
locals(),
["notabs.config"]
)
# apply imported overrides
for attr in dir(overrides):
# we only want to import settings (which have to be variables in ALLCAPS)
if attr.isupper():
# update our scope with the imported variables. We use globals() instead of locals()
# because locals() is readonly and it returns a copy of itself upon assignment.
globals()[attr] = getattr(overrides, attr)
| [
"nowell@strite.org"
] | nowell@strite.org |
25e6685584de9491b8ae6d8bc05c1c8999b332a7 | 08a021d428a7dae2dfdc490685b02b6af5c889a2 | /suma.py | 06bfd7009a042344771b48dc56cc59bc268001cc | [] | no_license | denylsonroque/trabajo1 | 0785690b005fc3bedc9e7e2a0500456fd38ebf4a | e6ff459630bb878d11519263791fc266dab7d32c | refs/heads/master | 2021-01-10T11:55:39.349256 | 2016-03-05T17:58:38 | 2016-03-05T17:58:38 | 53,214,793 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 102 | py | A = 53
B = 21
C = 18
D = 12
if A + C>= 100 :
print "mayor que 100"
else:
print "menor que 100"
| [
"csdgalcasa@gmail.com"
] | csdgalcasa@gmail.com |
a36515d1cca24d17b73be2b84c3ca3931489f8d9 | ab10071d226c5f6b9d9700715845d1641c9a99d4 | /report.py | ef000aeda42f6150a1cea3eb7604ce52de814fb4 | [
"MIT"
] | permissive | s0ko1ex/soc_recon | 62713a271209ef9acf8bf60eb34d0dfa6706890d | bb876d05d7b466c2cb7eef6b2f1f6280aeee8054 | refs/heads/master | 2021-10-16T15:00:34.561131 | 2019-01-10T13:05:56 | 2019-01-10T13:05:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 931 | py | import os
from operator import itemgetter
import fpdf
def gen_report(target, rep):
print("[=] Creating PDF...")
class PPDF(fpdf.FPDF):
def footer(self):
self.set_y(-15)
self.set_font("Arial", style="I", size=8)
self.cell(0, 10, "soc_recon report", align="C")
pdf = PPDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.add_font("DejaVu", "", "/usr/share/fonts/TTF/DejaVuSansCondensed.ttf", uni=True)
pdf.set_font("DejaVu", size=12)
for k in rep.keys():
mc = sorted(rep[k], key=itemgetter(1), reverse=True)[0]
pdf.cell(0, 10,
"User %s is connected to %s with ID %s. Probability is %s" % (target, k, mc[0], mc[1]),
border=0, ln=1)
if "reports" not in os.listdir("."):
os.mkdir("reports")
os.chdir("reports")
pdf.output(str(target) + "_report.pdf")
os.chdir("..")
print("[+] Done")
| [
"bakunin.t@protonmail.com"
] | bakunin.t@protonmail.com |
c1cb1a8d764cff27cf807edb91dbe3bbd2d2c376 | dd7e61a36fcafb117797553f9f6f2abdbe0c73f0 | /001_运算符/08_operator_precedence.py | 80caa68fbbcbc39472f8ddf5a1e70cda2bda759b | [] | no_license | wenotes/python_base_notes | 549adc5fcb8c2e120c69ad9faca1804b41ed95b8 | 4894282d364f4a7fdaee1f9dc1f343275e3c7718 | refs/heads/master | 2020-04-26T22:47:01.140921 | 2019-07-15T07:12:00 | 2019-07-15T07:12:00 | 173,883,215 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 615 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/6/21 23:47
# @Author : SNCKnight
# @File : 08_operator_precedence.py
# @Software: PyCharm
"""运算符优先级
一般用()控制运算优先级
** 指数 (最高优先级)
~ + - 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
* / % // 乘,除,取模和取整除
+ - 加法减法
>> << 右移,左移运算符
& 位 'AND'
^ | 位运算符
<= < > >= 比较运算符
<> == != 等于运算符
= %= /= //= -= += *= **= 赋值运算符
is is not 身份运算符
in not in 成员运算符
and or not 逻辑运算符
"""
| [
"17875571919@163.com"
] | 17875571919@163.com |
d5878957969dab6e3b0c1396ba2694995bb6c42d | 05e81499a7d8f13cac52c4608d2103b47557baee | /SPECK/SPECK32/Model2/SPECK_Test_2.py | 5edc1a7ba32ac9d585b7715e672871fef9265146 | [] | no_license | mhgharieb/Speed_up_MILP_with_Matsui | 851a8cacdd1893edbffbd851daaaad69772363d0 | 62db0910837bbe915cd44327e310ec3276685b58 | refs/heads/master | 2020-03-28T13:23:12.603785 | 2018-08-28T02:16:04 | 2018-08-28T02:16:04 | 148,390,821 | 3 | 1 | null | 2018-09-11T23:02:39 | 2018-09-11T23:02:39 | null | UTF-8 | Python | false | false | 3,114 | py | '''
Created on 20180201
@author: Administrator
'''
from CryptoMIP import *
n = 16 # word size (one branch)
alpha = 7 # right cyclic rotation by alpha bits
beta = 2 # left cyclic rotation by beta bits
opti = [0, 1, 3, 5, 9, 13, 18, 24, 30]
class SPECK(Cipher):
def genVars_input_of_round(self, r):
assert (r >= 1)
return ['L' + str(j) + '_r' + str(r) for j in range(0, n)] + \
['R' + str(j) + '_r' + str(r) for j in range(0, n)]
# Actually, you do not need to implement this
# Merely for readability
def genVars_afterAddition_of_round(self, r):
return self.genVars_input_of_round(r + 1)[0:n]
def genMyObjectiveFun_to_Round(self, start, end):
terms = []
for k in range(start, end + 1):
terms = terms + [self.activeMarker + str(j) + '_r' + str(k) for j in range(1, self.sboxPerRoud)]
return BasicTools.plusTerm(terms)
def genConstraints_Additional(self, r):
C = ConstraintGenerator.nonZeroActive(self.genVars_input_of_round(1))
C = C + [self.genMyObjectiveFun_to_Round(1, r) + ' - xobj = 0']
return C
def genConstraints_of_Round(self, r):
L_in = self.genVars_input_of_round(r)[0:n]
R_in = self.genVars_input_of_round(r)[n:2 * n]
L_out = self.genVars_input_of_round(r + 1)[0:n]
R_out = self.genVars_input_of_round(r + 1)[n:2 * n]
Seq_AM = self.genVars_ActiveMarkers_of_Round(r)
X = BasicTools.rightCyclicRotation(L_in, alpha)
Y = BasicTools.leftCyclicRotation(R_in, beta)
constraints = []
constraints = constraints + ConstraintGenerator.moduloAddition_differential_Constraints(X, R_in, L_out, Seq_AM)
constraints = constraints + ConstraintGenerator.xorConstraints(Y, L_out, R_out)
return constraints
def genObjectiveFun_to_Round(self, r):
return "xobj"
def genModel(self, ofile, r):
V = set([])
C = list([])
for i in range(1, r + 1):
C = C + self.genConstraints_of_Round(i)
C = C + self.genConstraints_Additional(r)
V = BasicTools.getVariables_From_Constraints(C)
V.remove('xobj')
myfile = open(ofile, 'w')
print('Minimize', file = myfile)
print(self.genObjectiveFun_to_Round(r), file = myfile)
print('\n', file = myfile)
print('Subject To', file = myfile)
for c in C:
print(c, file = myfile)
print('\n', file = myfile)
print('Generals', file = myfile)
print('xobj', file = myfile)
print('\n', file = myfile)
print('Binary', file = myfile)
for v in V:
print(v, file = myfile)
myfile.close()
def traceSol(self, f, r):
F = SolFilePaser(f)
for i in range(1, r + 1):
x = self.genVars_input_of_round(i)
print(F.getBitPatternsFrom(x))
def main():
mySPECK = SPECK(n)
for i in range(1, 10):
mySPECK.genModel(str(i) + ".lp", i)
if __name__ == '__main__':
main()
| [
"zhangyingjie@iie.ac.cn"
] | zhangyingjie@iie.ac.cn |
bf7c87602127e69b89708f20b431b391f0bf3a0e | f7b7fbada98ff1cc39629c1e694d80b2a458af64 | /Python/gestion.py | c55d1c09bcc2aefe9ab5065c52564c9750a5b98f | [] | no_license | josesureda/proyecto-integrador | 94f9da6d8bcaefc14d52033fff687e1cf66741ca | e471c808382423905fe60a5df4d95e6f5de45ab9 | refs/heads/master | 2021-01-20T11:16:58.290326 | 2015-10-15T13:14:30 | 2015-10-15T13:14:30 | 44,315,688 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,434 | py |
import csv
import numpy as np
with open('matrix.txt') as f:
base = [map(int, row) for row in csv.reader(f)]
with open('initialMarking.txt') as f:
marking = [map(int, row) for row in csv.reader(f)]
with open('backwards.txt') as f:
backwards = [map(int, row) for row in csv.reader(f)]
initialMarking = np.array(marking)
m0 = np.transpose(initialMarking)
mexp= np.tile(m0,4)
matrix = np.matrix(base)
back = np.matrix(backwards)
matrixand = np.logical_and(mexp,back)
result = mexp-back
#result2 = np.all(result,-1)
print(back)
print(initialMarking)
print(matrix)
#print(mexp)
#print(mexp-back)
#matrix.append([0] *4)
#print(matrix)
#print(matrixand)
#print(result2)
n = np.logical_not(initialMarking)
print(n)
m = np.dot(n,back)
d = np.logical_not(m)
print(m)
print("Disparo:")
print(d)
v = np.dot(matrix,np.transpose(d))
v2 = np.dot(d,np.transpose(matrix))
print(v2)
m1 = initialMarking + v2
print(m1)
tiro = np.matrix("0,1,1,1")
print(tiro)
p = np.matrix("1,0,0,0;0,1,-1,-1;0,0,1,-1;0,0,0,1")
print(p)
r = np.dot(tiro,p,)
print(r)
result = r ==1
fin = result.tostring()
eventos = {fin :'10'}
print(eventos[fin])
print(eventos)
# vector de tipo de transicion
typeVector = [0] * 40
# vector de eventos registrados
eventVector = [0] * 40
# vector de transiciones sensibilizadas
sensibilityVector = [0] * 40
# vector de disparos
launchVector = [0] * 40
# vector de politicas
policyVector = [0] * 40
| [
"suredajose@gmail.com"
] | suredajose@gmail.com |
ac3914cafd19b139a71a626a0f464c9712214260 | 979db45722c36212c408d06c99bf8e0cd8dac102 | /propietapi/core/constants/__init__.py | 1278ba3867651b948b419ced9695eea6429d6c68 | [] | no_license | propiet/api.propiet.com | d8121d703a6096b05410b91b64907d912bae3fe8 | 8b125c60648eed9b8ee51915e31ca547157b0d8a | refs/heads/master | 2021-01-21T19:35:06.024751 | 2014-10-03T22:58:38 | 2014-10-03T22:58:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 76 | py | from core.constants.languages import *
from core.constants.property import * | [
"lionel@hoopemedia.com"
] | lionel@hoopemedia.com |
1a3f58ff72525025be7cb6efb9e648ea7861e2ad | d72b15489fd3758a69000f9eeacdc7b08064f418 | /profiles/models.py | ed103b5e7ccd9c849b9a8cc1552219455839b2af | [] | no_license | simpliciob/ebrains | 3f19339432e83c28a8fd4eb7c268005f3767afe1 | a65ae6d9644c4eb57556de6b3ad2e89dbfef7d00 | refs/heads/master | 2020-03-06T17:29:23.729542 | 2018-03-27T13:23:02 | 2018-03-27T13:23:02 | 126,796,868 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 914 | py | from django.db import models
from django.db import models
from django.conf import settings
from .utils import code_generator
from django.core.mail import send_mail
from django.db.models.signals import post_save
from django.core.urlresolvers import reverse
from django.contrib.auth.models import AbstractUser
User=settings.AUTH_USER_MODEL
class Profile(AbstractUser):
is_student=models.BooleanField(default=False)
is_teacher=models.BooleanField(default=False)
is_classTeacher=models.BooleanField(default=False)
is_admin=models.BooleanField(default=False)
school=models.CharField(max_length=50)
class_teacher=models.CharField(max_length=50,blank=True)
REQUIRED_FIELDS=['email']
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('exams:update', kwargs={'pk':self.pk})
# Create your models here.
| [
"bachelorsithole@gmail.com"
] | bachelorsithole@gmail.com |
d5e6e6a4462ba37760f7e0ca982a4d83c593ff39 | da603cd023341129a9ef4d74d860764b02631c3f | /disk_objectstore/__init__.py | d819f8f7affa99d27b85acdd568958c5ccf1a9bc | [
"MIT"
] | permissive | chrisjsewell/disk-objectstore | c800ad4267abe7c3975f93740727ea05b207d30d | c718ffdec3881653acb82beaeed69fadf3cd9e3d | refs/heads/master | 2023-07-18T12:20:02.391818 | 2020-07-20T17:46:14 | 2020-07-20T17:46:14 | 298,001,569 | 0 | 0 | MIT | 2020-09-23T14:45:37 | 2020-09-23T14:45:36 | null | UTF-8 | Python | false | false | 230 | py | """An implementation of an efficient object store that writes directly on disk.
It does not require a server running.
"""
from .container import Container, ObjectType
__all__ = ('Container', 'ObjectType')
__version__ = '0.4.0'
| [
"giovanni.pizzi@epfl.ch"
] | giovanni.pizzi@epfl.ch |
1e64d87dfe87a31900f768f82c81e0725aa124e2 | 1ed281b93e11a53ea4ae2a3798aeb9f58dd664de | /webapp/starter/config/settings/local.py | b7e7a63716f22047acb2f9e1c94ef1b10a5f6274 | [
"MIT"
] | permissive | bartkim0426/django-docker-seul | 5ae2a31f1004ae8292569bcafd2e66ce56f67c7e | 6a75605281403357514d7b30e65d2685bb907b31 | refs/heads/master | 2021-05-09T02:55:04.765647 | 2019-02-11T07:45:09 | 2019-02-11T07:45:09 | 119,226,239 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 917 | py | import os
from .partials import *
DEBUG = True
INSTALLED_APPS += [
'debug_toolbar',
'django_extensions',
]
MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ]
INTERNAL_IPS = ['127.0.0.1', ]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['POSTGRES_NAME'],
'USER': os.environ["POSTGRES_USER"],
'PASSWORD': os.environ["POSTGRES_PASSWORD"],
'HOST': os.environ["POSTGRES_HOST"],
'PORT': os.environ["POSTGRES_PORT"],
}
}
MEDIA_ROOT = str(ROOT_DIR('mediafiles'))
# before collectstatic
# for prevent duplication of STATIC_ROOT and STATICFILES_DIRS
# STATIC_ROOT = str(ROOT_DIR('staticfiles'))
# STATICFILES_DIRS = (
# str(ROOT_DIR.path('static')),
# )
# after collectstatic
STATIC_ROOT = str(ROOT_DIR('static-files'))
STATICFILES_DIRS = (
str(ROOT_DIR.path('staticfiles')),
)
| [
"bartkim0426@gmail.com"
] | bartkim0426@gmail.com |
799f016f71a2e4a7a841bde9fd855d8d0f0f762a | 4aae9b8b520a35f0048597e8e2f8ca1d1e796d46 | /polls/twoFasset.py | 14fc5ec920c204408a5df3f0574a9942687f6fe1 | [] | no_license | abhi-portrait/Major-Project | 2f82e95b65669b6d1ae0598b1a91c10418ba3756 | 283d1ff2427b3cafb7aecf64c1800502d73cd7f5 | refs/heads/master | 2021-01-19T23:58:21.046284 | 2017-04-26T01:09:02 | 2017-04-26T01:09:02 | 89,058,670 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,612 | py | import sys
sys.path.append('/home/abhi/Desktop/Django_Projects/mysite/polls/')
import MySQLdb
import operator
from operator import itemgetter
from SQLHandler import sqlHandler
class twoFasets:
def getCount(self,query):
db = MySQLdb.connect("127.0.0.1","root","","Terrorism")
cursor = db.cursor()
c = 0
try:
cursor.execute(query)
res = cursor.fetchall()
c = res[0][0]
except:
print ("Unable to fetch data 5")
return c
def makeQuery(self,attribute1,attributeVal1,attribute2,attributeVal2):
s = "SELECT COUNT(*) FROM attacks where " + attribute1 + " = '" + attributeVal1 + "' and " + attribute2 + " = '" + attributeVal2 + "' "
return s
def giveScoreSortedList(self,someList,totalCount,mainQueryCount):
if totalCount == 0 or mainQueryCount == 0:
sortedTwoFacetList = list()
sortedTwoFacetList.append("Unable to fetch data 3")
return sortedTwoFacetList
someListLen = len(someList)
for i in range(0,someListLen):
num = someList[i][4] / (mainQueryCount * 1.0)
denomNum = self.getCount(self.makeQuery(someList[i][0],someList[i][2],someList[i][1],someList[i][3]))
denom = denomNum / (totalCount * 1.0)
if denom != 0:
score = num / (denom * 1.0)
someList[i].append(score)
tempList = list()
for i in range(0,someListLen):
if someList[i][4] != 0:
tempList.append(someList[i])
sortedTwoFacetList = sorted(tempList,key=itemgetter(5),reverse = True)
return sortedTwoFacetList
def giveTopResultsList(self,cursor,tableName,attribute,mainAttribute1,mainAttribute1Val,mainAttribute2,mainAttribute2Val):
query = "SELECT " + attribute + ", COUNT(*) AS FREQUENCY FROM " + tableName + " WHERE " + mainAttribute1 + " = " + "'" + mainAttribute1Val + "'" + " and " + mainAttribute2 + " = " + "'" + mainAttribute2Val + "'" + " GROUP BY " + attribute + " ORDER BY COUNT(*) DESC LIMIT 5"
# print query
listType = list()
try:
cursor.execute(query)
res = cursor.fetchall()
for i in res:
a = attribute
b = i[0]
if b != "Unknown":
listType.append(a)
listType.append(b)
except:
print ("Unable to fetch data 2")
return listType
def initialTwoFacetList(self,attackList,cityList,targetList):
initialList = list()
# if len(attackList)<3 or len(cityList)<3 or len(targetList)<3 :
# initialList.append("Unable to fetch data")
# return initialList
attr1Len = len(attackList)
attr2Len = len(cityList)
attr3Len = len(targetList)
for i in range(0,attr1Len,2):
for j in range(0,attr2Len,2):
if (i+1) < attr1Len and (j+1) < attr2Len:
anyList = list()
anyList.append(attackList[i])
anyList.append(cityList[j])
anyList.append(attackList[i+1])
anyList.append(cityList[j+1])
initialList.append(anyList)
for i in range(0,attr1Len,2):
for j in range(0,3,2):
if (i+1) < attr1Len and (j+1) < 3:
anyList = list()
anyList.append(attackList[i])
anyList.append(targetList[j])
anyList.append(attackList[i+1])
anyList.append(targetList[j+1])
initialList.append(anyList)
for i in range(0,attr2Len,2):
for j in range(0,attr3Len,2):
if (i+1) < attr2Len and (j+1) < attr3Len:
anyList = list()
anyList.append(cityList[i])
anyList.append(targetList[j])
anyList.append(cityList[i+1])
anyList.append(targetList[j+1])
initialList.append(anyList)
if len(initialList)>16:
del initialList[16:]
return initialList
def giveTopResultsListWithFrequency(self,cursor,tableName,initList,mainAttribute1,mainAttribute1Val,mainAttribute2,mainAttribute2Val):
initListLen = len(initList)
for i in range(0,initListLen):
# query = "SELECT COUNT(*) as FREQUENCY FROM " + tableName " WHERE " + mainAttribute1 + " = " + "'" + mainAttribute1Val + "'" + " and " + mainAttribute2 + " = " + "'" + mainAttribute2Val + "' and "+ initList[i][0] +" = '" + initList[i][2] + "' and " + initList[i][1] + " = '" + initList[i][3] + "' "
query = "SELECT COUNT(*) as FREQUENCY FROM " + tableName + " WHERE " + mainAttribute1 + " = " + "'" + mainAttribute1Val + "'" + " and " + mainAttribute2 + " = " + "'" + mainAttribute2Val + "'" + " and " + initList[i][0] + " = " + "'" + initList[i][2] + "'" + " and " + initList[i][1] + " = " + "'" + initList[i][3] + "'"
try:
cursor.execute(query)
res = cursor.fetchall()
for j in res:
a = j[0]
if a != "Unknown":
initList[i].append(a)
except:
print ("Unable to fetch data 1")
return initList
def generateTopResultsForThreeAttributes(self,cursor,handler,tableName,mainQueryCount,totalCount,mainAttribute1,mainAttribute1Val,mainAttribute2,mainAttribute2Val,attribute1,attribute2,attribute3):
typeOneList = self.giveTopResultsList(cursor,tableName,attribute1,mainAttribute1,mainAttribute1Val,mainAttribute2,mainAttribute2Val)
typeTwoList = self.giveTopResultsList(cursor,tableName,attribute2,mainAttribute1,mainAttribute1Val,mainAttribute2,mainAttribute2Val)
typeThreeList = self.giveTopResultsList(cursor,tableName,attribute3,mainAttribute1,mainAttribute1Val,mainAttribute2,mainAttribute2Val)
initialListWithoutFrequency = self.initialTwoFacetList(typeOneList,typeTwoList,typeThreeList)
initialListWithFrequency = self.giveTopResultsListWithFrequency(cursor,tableName,initialListWithoutFrequency,mainAttribute1,mainAttribute1Val,mainAttribute2,mainAttribute2Val)
twoFasetList = self.giveScoreSortedList(initialListWithFrequency,totalCount,mainQueryCount)
# # printList(twoFasetList)
# print " 2 Faset Recommendations "
# for i in twoFasetList:
# print i
return twoFasetList
| [
"abhi.25101994@gmail.com"
] | abhi.25101994@gmail.com |
a316a3d8d491341794f77c6543c82c2f0dc91708 | 42efe9195603ab21240b7b64ea66d1cb6259b8df | /rsasecure_login/__init__.py | 3cc0be8d9084b07fdc13d4a00b428aef36aa20ee | [] | no_license | milljm/rsasecure_login | c1328212fc91a710803605e10e8280e45fff72c2 | 98573695d3c1519d27b5e4f9b512cc2eb9affaf8 | refs/heads/master | 2023-05-10T18:59:03.655740 | 2021-05-24T17:40:19 | 2021-05-24T17:40:19 | 367,440,676 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 29 | py | from .__main__ import Client
| [
"jason.miller@inl.gov"
] | jason.miller@inl.gov |
9435b3d1732ef67e999ed2b20434f161d896706d | b1445f68fd8fee4fd3f8c4e2e2a8a5517d07233f | /C4E18 Sessions/Session_1/hello_world.py | 678a3bc12f4d6e271d028839070ba841c7072682 | [] | no_license | thedarkknight513v2/daohoangnam-codes | 4cf8010bca531adc8beda7ec8b8586e8b15ea7cc | 2b986ede3aa4b5855a287067ce903e688244d426 | refs/heads/master | 2020-03-21T10:59:50.338732 | 2018-10-10T10:58:02 | 2018-10-10T10:58:02 | 138,483,066 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 79 | py | print("Hello everyone!")
name = input("What's your name?")
print("Hi", name)
| [
"allmaterials513@gmail.com"
] | allmaterials513@gmail.com |
ecfd17e47b80b4e3c73b5e2d35fd398c5287efa7 | e1a181fcb6bcf40cf447ac47097e4a97ac103e23 | /Práctica 7/Ejercicio5.py | d4e1a8edcdeec8c5070707187aa667a9e9cf50a6 | [] | no_license | SergiEduVila/PROGRAMACION | f0fa9e19441e335d3b62f644169dbabcadce8ff1 | edb9816e680bb3123c05803bfa592fa546301316 | refs/heads/master | 2020-09-14T02:25:02.389166 | 2019-11-20T17:08:27 | 2019-11-20T17:08:27 | 222,984,997 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 776 | py | #Sergi Eduard Vila Sánchez# #Práctica 7 Ejercicio 5#
#Escribe un programa que te pida una frase y una vocal, y pase estos datos como parámetro a una función que se encargará de cambiar todas las vocales de la frase por la vocal seleccionada. Devolverá la función la frase modificada, y el programa principal la imprimirá.#
print("Introduce un texto:")
texto=input()
print("Introduce una vocal ahora:")
vocal=input()
def f(a,b):
a=a.replace("A",b)
a=a.replace("a",b)
a=a.replace("E",b)
a=a.replace("e",b)
a=a.replace("I",b)
a=a.replace("i",b)
a=a.replace("O",b)
a=a.replace("o",b)
a=a.replace("U",b)
a=a.replace("u",b)
return a
print("La frase ahora es:", end=" ")
print(f(texto,vocal))
print(" ")
| [
"noreply@github.com"
] | SergiEduVila.noreply@github.com |
e3c51536fb709ace2edeb5d8f468e4d94fce447e | f18df31d4ba8569b420219f5d52da311a32581d6 | /cloudkittydashboard/enabled/_11_project_rating_panel.py | 7dd8f795c512b7d4e07021ce3f00e1c166a41769 | [
"Apache-2.0"
] | permissive | openstack/cloudkitty-dashboard | 418b54a59a93201c79e422ee4571c9f24b6234e5 | 4ed8863c1b15d489a2a78e767b737402647bc4da | refs/heads/master | 2023-08-23T06:09:10.473334 | 2023-07-12T15:40:17 | 2023-07-12T15:40:17 | 23,157,716 | 25 | 14 | Apache-2.0 | 2022-01-18T10:16:11 | 2014-08-20T17:35:14 | Python | UTF-8 | Python | false | false | 810 | py | # Copyright 2015 Objectif Libre
#
# 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.
PANEL_GROUP = 'rating'
PANEL_DASHBOARD = 'project'
PANEL = 'rating'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'cloudkittydashboard.dashboards.project.rating.panel.Project_rating'
| [
"sheeprine@nullplace.com"
] | sheeprine@nullplace.com |
d2bdb6384c85995a4d33d070cbe4bd13ccc229d3 | f7cb5e3c63779575b61cc00add8e3b79f20f8695 | /hello/serializers.py | 9124090aa4ca6dd370420ef4ae6422e07552079a | [] | no_license | 16francej/crypto-horses-data | 0d50c48069411918062fb5da20ea83550e059a98 | eda5694aaef66df9e2ddf5b031556d53c95c216c | refs/heads/main | 2023-08-22T00:23:19.192091 | 2021-10-23T20:46:04 | 2021-10-23T20:46:04 | 415,417,684 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 601 | py | from django.contrib.auth.models import User, Group
from .models import Horses
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']
class HorseSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Horses
fields = ['id', 'genotype', 'bloodline', 'breed_type', 'horse_type', 'rating']
| [
"francejoshuar1@gmail.com"
] | francejoshuar1@gmail.com |
498e00cf0c38fd2af13ab2a42b197babc1e6547b | c9601493765a63b8d2af99ab1b9c8d432d90f86c | /django/mysite/main/models.py | a4330acdedff02f92de5ee52806f73439365ec0d | [] | no_license | TiesHoenselaar/Projects | e724369fd2bbdc55f77f4f52856cc66d12828c1c | 4997e23812eaacd5d2c76aa2465831a3a760752a | refs/heads/master | 2021-04-09T10:42:53.926002 | 2020-10-10T18:28:45 | 2020-10-10T18:28:45 | 125,439,689 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 359 | py | from django.db import models
from datetime import datetime
# Create your models here.
class Tutorial(models.Model):
tutorial_title = models.CharField(max_length=200)
tutorial_content = models.TextField()
tutorial_published = models.DateTimeField("date published", default=datetime.now())
def __str__(self):
return self.tutorial_title
| [
"tieshoenselaar@gmail.com"
] | tieshoenselaar@gmail.com |
6bdb5beaafe32ee1f40cb067b31a6b248e501259 | c40becbc9dacac8119fdd8a6628d2d5dc48dc96f | /Wprowadzenie_do_Sztucznej_Inteligencji/Lista_2/mnist/mnist_softmax_old.py | c163ca973ba742da565e43f4486598d300d9f6d8 | [] | no_license | brzepkowski/college | 1313ef7e0db1c2f05bbf1589faf76cd2989948ce | a8bcc56eb35ffeb19760ad66b4973f5eb7936b09 | refs/heads/main | 2023-08-02T11:04:29.157599 | 2021-09-15T12:31:44 | 2021-09-15T12:31:44 | 406,747,482 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,718 | py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A very simple MNIST classifier.
See extensive documentation at
http://tensorflow.org/tutorials/mnist/beginners/index.md
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
# Import data
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
FLAGS = None
def main(_):
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
# Create the model
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
# The raw formulation of cross-entropy,
#
# tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
# reduction_indices=[1]))
#
# can be numerically unstable.
#
# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw
# outputs of 'y', and then average across the batch.
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.InteractiveSession()
# Train
tf.global_variables_initializer().run()
for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# Test trained model
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images,
y_: mnist.test.labels}))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
help='Directory for storing input data')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
| [
"incidental.address@gmail.com"
] | incidental.address@gmail.com |
dc5df62772aa2776784f4a98884bd8e5b46d2056 | 5f2608d4a06e96c3a032ddb66a6d7e160080b5b0 | /week4/homework_w4_b1.py | e70dae9bdc972512e2e7c76f7fc0ae5ef2833a01 | [] | no_license | sheikhusmanshakeel/statistical-mechanics-ens | f3e150030073f3ca106a072b4774502b02b8f1d0 | ba483dc9ba291cbd6cd757edf5fc2ae362ff3df7 | refs/heads/master | 2020-04-08T21:40:33.580142 | 2014-04-28T21:10:19 | 2014-04-28T21:10:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 967 | py | import math, random, pandas
def Vol1_s(dimension):
return (math.pi ** (dimension / 2.0)) / math.gamma(dimension / 2.0 + 1.0)
def Vol1_s_est(dimensions, trials):
n_hits = 0
for i in range(trials):
dists = [random.uniform(-1.0, 1.0) for _ in range(dimensions)]
sum_dist = sum(d ** 2 for d in dists)
if sum_dist < 1.0:
n_hits += 1
return n_hits / float(trials) * 2 ** dimensions, n_hits
dimensions = []
result = []
trials = 1000000
print '%i used for all' % trials
for d in range(1, 33):
dimensions.append(str(d) + 'd')
vol_est, n_hits = Vol1_s_est(d, trials)
result.append({ 'estimation of Vol1_s(d)': vol_est,
'Vol1_s(d) (exact)': Vol1_s(d),
'n_hits': n_hits })
print d, n_hits, vol_est
ordered_cols = ['estimation of Vol1_s(d)', 'actual', 'n_hits']
print pandas.DataFrame(result, dimensions, columns=ordered_cols)
| [
"noelevans@gmail.com"
] | noelevans@gmail.com |
8e34dc8454b9c5ff42c1d3ad371c7adfcf1bbbb9 | d98c47a2367c82a9a7af7b0ea21f5caca04b3417 | /project01.py | 0aff0c2da7532a04e9c9c9e25f4290b6587452ea | [] | no_license | jakubrozumek/engeto_pvni_projekt | a2bce6bb0135132e42e3f5226c6905fda1f899d1 | 706618997e751f18a6fdb67d5984d4cf13ecc125 | refs/heads/master | 2023-04-02T07:53:24.723012 | 2021-04-14T21:49:16 | 2021-04-14T21:49:16 | 354,520,449 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,972 | py | TEXTS = ['''
Situated about 10 miles west of Kemmerer,
Fossil Butte is a ruggedly impressive
topographic feature that rises sharply
some 1000 feet above Twin Creek Valley
to an elevation of more than 7500 feet
above sea level. The butte is located just
north of US 30N and the Union Pacific Railroad,
which traverse the valley. ''',
'''At the base of Fossil Butte are the bright
red, purple, yellow and gray beds of the Wasatch
Formation. Eroded portions of these horizontal
beds slope gradually upward from the valley floor
and steepen abruptly. Overlying them and extending
to the top of the butte are the much steeper
buff-to-white beds of the Green River Formation,
which are about 300 feet thick.''',
'''The monument contains 8198 acres and protects
a portion of the largest deposit of freshwater fish
fossils in the world. The richest fossil fish deposits
are found in multiple limestone layers, which lie some
100 feet below the top of the butte. The fossils
represent several varieties of perch, as well as
other freshwater genera and herring similar to those
in modern oceans. Other fish such as paddlefish,
garpike and stingray are also present.'''
]
pwds = {'bob': '123', 'ann': 'pass123', 'mike': 'password123', 'liz': 'pass123'}
separator = 43 * '-'
user = input('username: ')
password = input('password: ')
if password == pwds.get(user):
print(f"""{separator}
Welcome to the app, {user}.
We have 3 texts to be analyzed.
{separator}""")
else:
print('Incorrect username or password, exiting...')
quit()
text_nr = input('Enter a number between 1 and 3 to select: ')
if text_nr.isnumeric():
if int(text_nr) not in range(1, 4):
print('Incorrect number entered, exiting...')
quit()
else:
print('Entered value is not a number, exiting...')
quit()
stripped_text = TEXTS[int(text_nr) - 1].replace(',', '').replace('.', '').split()
title_count = 0
upper_count = 0
lower_count = 0
number_count = 0
number_sum = 0
for word in stripped_text:
if word.islower() and word.isalpha():
lower_count += 1
if word.isupper() and word.isalpha():
upper_count += 1
if word.isnumeric():
number_count += 1
number_sum += int(word)
if word.istitle() and word.isalpha():
title_count += 1
print(separator)
print(f"""There are {len(stripped_text)} words in the selected text
There are {title_count} titlecase words.
There are {upper_count} uppercase words.
There are {lower_count} lowercase words.
There are {number_count} numeric strings.
The sum of all numbers {number_sum}.""")
lengths = {}
for wrd in stripped_text:
if len(wrd) not in lengths:
lengths[len(wrd)] = 1
else:
lengths[len(wrd)] += 1
lengths = sorted(lengths.items())
print(separator)
print(f"{'LEN|':<4}{'OCCURENCES':^20}{'|NR.':<3}")
print(separator)
for i in lengths:
print(f"{(str(i[0]) + '|'):>4} {'*' * i[1]:<18} {('|' + str(i[1])):<3}")
| [
"jakub.rozumek@hotmail.com"
] | jakub.rozumek@hotmail.com |
9893c7b1e2d409993936cf8a1bc833b58608c7f5 | 76f4b3b02d535bd1794760582cb1d2c89073105b | /testclient.py | b7ff06c23529c5ca800addcf646ed9df68b8912a | [] | no_license | jalexis91/tictactoeaiui | 4cf74a343d917b61036902498ce4bfd527e86377 | 69ce634c19686efc9e3117b0062899eb4e29ab29 | refs/heads/master | 2021-01-10T22:03:27.552461 | 2015-11-24T01:35:31 | 2015-11-24T01:35:31 | 35,315,955 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,657 | py | # ECEN 404
# Team 2
# Matthew Fischer
import socket
from threading import Thread
from Adafruit_PWM_Servo_Driver import PWM
from socketIO_client import SocketIO, BaseNamespace
import time
base = 15 # channel number for base
shld = 14 # channel number for shoulder
elbow = 13 # channel number for elbow
wrist = 12 # channel number for wrist
pinch = 11 # channel number for the wrist
#lastmove[9] # keeps hold of moves made by the robot to prevent playing in the same position on accident
basePos = 0 #Keeps track of the position of the base servo
shldPos = 0 #Keeps track of the position of the shld servo
elbowPos = 0 #Keeps track of the position of the elbow servo
wristPos = 0 #Keeps track of the position of the wrist servo
pinchPos = 600 #Keeps track of the position of the pinch servo
def setServoPulse(channel,pulse):
pulseLength = 1000000
pulseLength /= 100
pulseLength /= 4096
pulse *=1000
pulse /= pulseLength
pwm.setPWM(channel, 0, pulse)
def stamp(shldPos):
s = shldPos
for i in range(0, 60, 5):
s = s - 5
pwm.setPWM(shld, 0, s)
time.sleep(.1)
time.sleep(1)
for j in range(0, 60, 5):
s = s + 5
pwm.setPWM(shld, 0, s)
time.sleep(.1)
pwm.setPWM(shld,0, shldPos)
def start():
# this is the starting position for the arm to move to during startup
print('Initiate Start-up')
## for k in range(700,625,-10):
## pwm.setPWM(elbow, 0, k)
## time.sleep(.1)
## for j in range(400,645,5):
## pwm.setPWM(shld, 0, j)
## time.sleep(.1)
## for i in range(600,250,-10):
## pwm.setPWM(base, 0, i)
## time.sleep(.1)
## pwm.setPWM(wrist,0, 250)
## time.sleep(1)
## pwm.setPWM(pinch, 0, 600)
## time.sleep(1)
pwm.setPWM(base, 0, 250)
pwm.setPWM(shld, 0, 640)
pwm.setPWM(elbow, 0, 625)
pwm.setPWM(wrist, 0, 250)
basePos = 250
shldPos = 64
elbowPos = 625
wristPos = 250
def moveRest(basePos, shldPos, elbowPos, wristPos, pinchPos):
print('Returning Home')
print 'BasePos', basePos
print 'Shoulder Pos', shldPos
print 'Elbow Pos', elbowPos
print 'Wrist Pos', wristPos
# Shoulder position reset **********************************************************
if shldPos < 640:
print('Shoulder Position is less than Rest Position')
for i in range(shldPos, 640, 10):
pwm.setPWM(shld, 0, i)
time.sleep(.1)
else:
print('Shoulder Position is greater than Rest Position')
for i in range(shldPos, 640, -10): #it should not be able to get here technically
pwm.setPWM(shld, 0, i)
time.sleep(.1)
# Elbow Position reset **************************************************************
if elbowPos < 625:
print('Elbow Position is less than Rest Position')
for j in range(elbowPos, 625, 10):
pwm.setPWM(elbow, 0, j)
time.sleep(.1)
else:
print('Elbow Position is greater than Rest Position')
for i in range(elbowPos, 625, -10):
pwm.setPWM(elbow, 0, i)
time.sleep(.1)
# Base Position Reset ***************************************************************
for k in range(basePos, 250, -10):
pwm.setPWM(base,0, k)
time.sleep(.1)
pwm.setPWM(wrist, 0, 250)
#i Shouldnt have to update pinch ever
def move1():
# moves to position 1 of the game board
print('Moving to position 1!')
w = 380 #posotion for the wirst
pwm.setPWM(wrist, 0, w)
wristPos = w
time.sleep(.1)
for i in range(0, 45, 5): #trying to move all the servos at the same time for step 1
b = 250 + i
pwm.setPWM(base, 0, b)
s = 645 - i
pwm.setPWM(shld, 0, s)
e = 625 - i
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
elbowPos = e
for i in range(0, 40, 5): #trying to move all the servos at the same time for step 2
b = 290 + i
pwm.setPWM(base, 0, b)
s = 605 - i
pwm.setPWM(shld, 0, s)
time.sleep(.1)
shldPos = s
for i in range(0, 260, 10): #trying to move all the servos at the same time for step 3
b = 325 + i
pwm.setPWM(base, 0, b)
time.sleep(.1)
basePos = b
stamp(shldPos)
moveRest(basePos,shldPos,elbowPos,wristPos,pinchPos)
def move2():
# moves to position 2 of the game board
print('Moving to position 2!')
w = 380 #posotion for the wirst
pwm.setPWM(wrist, 0, w)
time.sleep(.1)
wristPos = w
for i in range(0, 45, 5): #trying to move all the servos at the same time for step 1
b = 250 + i
pwm.setPWM(base, 0, b)
s = 645 - i
pwm.setPWM(shld, 0, s)
e = 625 - i
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
elbowPos = e
for i in range(0, 40, 5): #trying to move all the servos at the same time for step 2
b = 290 + i
pwm.setPWM(base, 0, b)
s = 605 - i
pwm.setPWM(shld, 0, s)
time.sleep(.1)
shldPos = s
for i in range(0, 300, 5): #trying to move all the servos at the same time for step 3
b = 325 + i
pwm.setPWM(base, 0, b)
time.sleep(.1)
basePos = b
moveRest(basePos,shldPos,elbowPos,wristPos,pinchPos)
def move3():
# moves to position 3 of the game board
print('Moving to position 2!')
w = 380 #posotion for the wirst
pwm.setPWM(wrist, 0, w)
time.sleep(.1)
wristPos = w
for i in range(0, 50, 10): #trying to move all the servos at the same time for step 1
b = 250 + i
pwm.setPWM(base, 0, b)
s = 645 - i
pwm.setPWM(shld, 0, s)
e = 625 - i
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
elbowPos = e
for i in range(0, 30, 5): #trying to move all the servos at the same time for step 2
b = 290 + i
pwm.setPWM(base, 0, b)
s = 605 - i
pwm.setPWM(shld, 0, s)
time.sleep(.1)
shldPos = s
for i in range(0, 350, 5): #trying to move all the servos at the same time for step 3
b = 325 + i
pwm.setPWM(base, 0, b)
time.sleep(.1)
basePos = b
moveRest(basePos,shldPos,elbowPos,wristPos,pinchPos)
def move4():
# moves to position 4 of the game board
print('Moving to position 4!')
pwm.setPWM(wrist, 0, 440)
time.sleep(.1)
wristPos = 440
for i in range(0, 80, 5): #trying to move all the servos at the same time for step 1
b = 250 + i
pwm.setPWM(base, 0, b)
s = 645 - i
pwm.setPWM(shld, 0, s)
e = 625 + i
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
elbowPos = e
shldPos = s
for i in range(0, 240, 5): #trying to move all the servos at the same time for step 3
b = 325 + i
pwm.setPWM(base, 0, b)
time.sleep(.1)
basePos = b
moveRest(basePos,shldPos,elbowPos,wristPos,pinchPos)
def move5():
# moves to position 5 of the game board
print('Moving to position 5!')
pwm.setPWM(wrist,0, 440) ## sets the position of the wrist
wristPos = 440
#Stage 1
for i in range(0, 80, 10):
b = 250 + i
s = 645 - i
e = 625 + i
pwm.setPWM(base, 0, b)
pwm.setPWM(shld, 0, s)
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
shldPos = s
#stage 2
for i in range(0, 20, 10):
b = 320 + i
e = 695 + i
pwm.setPWM(base, 0, b)
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
elbowPos = e
#stage 3
for i in range(0, 300, 10):
b = 330 + i
pwm.setPWM(base, 0, b)
time.sleep(.1)
basePos = b
#Here i need to call the stamp function whenever that is actally made
#time.sleep(2)
#not i return to rest
moveRest(basePos,shldPos,elbowPos,wristPos,pinchPos)
def move6():
# moves to position 6 of the game board
print('Moving to position 6!')
pwm.setPWM(wrist,0, 440) ## sets the position of the wrist
wristPos = 440
#Stage 1
for i in range(0, 80, 10):
b = 250 + i
s = 645 - i
e = 625 + i
pwm.setPWM(base, 0, b)
pwm.setPWM(shld, 0, s)
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
elbowPos = e
shldPos = s
#stage 2
for i in range(0, 360, 10):
b = 330 + i
pwm.setPWM(base, 0, b)
time.sleep(.1)
basePos = b
#Here i need to call the stamp function whenever that is actally made
time.sleep(2)
#not i return to rest
moveRest(basePos,shldPos,elbowPos,wristPos,pinchPos)
def move7():
# moves to position 7 of the game board
print('Moving to position 7!')
pwm.setPWM(wrist, 0, 440)
wristPos = 440
#stage 1
for i in range(0, 50, 5):
b = 250 + i
s = 645 - i
e = 625 + i
pwm.setPWM(base, 0, b)
pwm.setPWM(shld, 0, s)
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
shldPos = s
#stage 2
for i in range(0, 110, 5):
b = 295 + i
e = 670 + i
pwm.setPWM(base, 0, b)
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
elbowPos = e
#stage 3
for i in range(0, 150, 10):
b = 400 + i
pwm.setPWM(base, 0, b)
time.sleep(.1)
basePos = b
#wait for action...
time.sleep(2)
moveRest(basePos,shldPos,elbowPos,wristPos,pinchPos)
def move8():
print('Moving to position 8!')
pwm.setPWM(wrist, 0, 475)
wristPos = 475
#stage 1
for i in range(0, 40, 10):
b = 250 + i
s = 645 - i
e = 625 + i
pwm.setPWM(base, 0, b)
pwm.setPWM(shld, 0, s)
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
shldPos = s
#stage 2
for i in range(0, 150, 5):
b = 280 + i
e = 655 + i
pwm.setPWM(base, 0, b)
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
elbowPos = e
#stage 3
for i in range(0, 200, 10):
b = 425 + i
pwm.setPWM(base, 0, b)
time.sleep(.1)
basePos = b
#wait for action...
#time.sleep(2)
moveRest(basePos,shldPos,elbowPos,wristPos,pinchPos)
def move9():
# moves to position 9 of the game board
print('Moving to position 9!')
pwm.setPWM(wrist, 0, 455)
time.sleep(.5)
wristPos = 455
for i in range(0, 40, 5): #tring to move all the servos at the same time for step 1
b = 250 + i
pwm.setPWM(base, 0, b)
s = 645 - i
pwm.setPWM(shld, 0, s)
e = 625 + i
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
shldPos = s
for i in range(0, 130, 5): #tring to move all the servos at the same time for step 2
b = 285 + i
pwm.setPWM(base, 0, b)
e = 660 + i
pwm.setPWM(elbow, 0, e)
time.sleep(.1)
elbowPos = e
for i in range(0, 300, 10): #tring to move all the servos at the same time for step 3
b = 410 + i
pwm.setPWM(base, 0, b)
time.sleep(.1)
basePos = b
moveRest(basePos,shldPos,elbowPos,wristPos,pinchPos)
def on_aimove(*args):
print 'got ai move: ', args[0] # gets first arg (i.e. the move we want)
#while 1:
x = args[0] #int(input("Please enter a position number (1-9)"))
if x == "11":
move1()
elif x == "12":
move2()
elif x == "13":
move3()
elif x == "21":
move4()
elif x == "22":
move5()
elif x == "23":
move6()
elif x == "31":
move7()
elif x == "32":
move8()
elif x == "33":
move9()
else:
print("please print a valid number next time!")
socketIO.emit('robot_move_complete') # send msg to img processor when done
# making move so that it knows to start looking for moves again
pwm = PWM(0x40)
pwm.setPWMFreq(100)
start()
socketIO = SocketIO('Localhost', 3000, BaseNamespace)
socketIO.on('aimove', on_aimove)
socketIO.wait()
| [
"jalexis91@users.noreply.github.com"
] | jalexis91@users.noreply.github.com |
6b2c4292022e50ca3fd008d63133334d3a19ce05 | 4e657a4449e1fa07b03cfc12c7352d226cbb434a | /app/db/database.py | cafbe35b3734dcd0f62a756e6e883e24196f549a | [
"MIT"
] | permissive | jmonts/random-dose-of-knowledge | d190d9912e30b83a8fb5d2ffaa80fb324b7a26fe | da827ecb00b09a1d01a546a4950d63dc18e3ba95 | refs/heads/main | 2023-04-23T11:02:07.292941 | 2021-05-04T07:26:07 | 2021-05-04T07:26:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 490 | py | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = 'sqlite:///db/random-knowledge.db'
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={'check_same_thread': False})
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
| [
"dimitris.effrosynidis@gmail.com"
] | dimitris.effrosynidis@gmail.com |
b577dd27a9532277f72cb9fe6c733b59a779cf15 | 30e65ac99e1e44e03b5dbbd6091539a8b947b91f | /main/views.py | d000db035decd8ceb88bc0c76c069d775bfe7db9 | [] | no_license | its-rose/BBoard_on_Django | 37aaa9c2a02bed56d4ed056b06b0ec6b42c7e1b6 | 96a1f328f53df2ceeedb3f3201193906d15750dc | refs/heads/master | 2023-02-10T08:28:53.935707 | 2021-01-12T05:42:13 | 2021-01-12T05:42:13 | 328,883,690 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,586 | py | from django.shortcuts import render, get_object_or_404, redirect, HttpResponseRedirect
from django. http import HttpResponse, Http404
from django.template import TemplateDoesNotExist
from django.template.loader import get_template
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import UpdateView, CreateView, DeleteView
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy
from django.contrib.auth.views import PasswordChangeView
from django.views.generic.base import TemplateView
from django.core.signing import BadSignature
from django.contrib.auth import logout
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q
from .models import AdvUser, SubRubric, Bb, Comment
from .forms import ChangeUserInfoForm, RegisterUserForm, SearchForm
from .forms import BbForm, AIFormSet, UserCommentForm, GuestCommentForm
from .utilities import signer
def other_page(request, page):
try:
template = get_template('main/' + page + '.html')
except TemplateDoesNotExist:
raise Http404
return HttpResponse(template.render(request=request))
def index(request):
bbs = Bb.objects.filter(is_active=True)[:10]
context = {'bbs': bbs}
return render(request, 'main/index.html', context)
class BBLoginView(LoginView):
template_name = 'main/login.html'
class BBLogoutView(LoginRequiredMixin, LogoutView):
template_name = 'main/logout.html'
@login_required
def profile(request):
bbs = Bb.objects.filter(author=request.user.pk)
context = {'bbs': bbs}
return render(request, 'main/profile.html', context)
class ChangeUserInfoView(SuccessMessageMixin, LoginRequiredMixin, UpdateView):
model = AdvUser
template_name = 'main/change_user_info.html'
form_class = ChangeUserInfoForm
success_url = reverse_lazy('main:profile')
success_message = 'Личные данные пользователя изменены'
def dispatch(self, request, *args, **kwargs):
self.user_id = request.user.pk
return super().dispatch(request, *args, **kwargs)
def get_object(self, queryset=None):
if not queryset:
queryset = self.get_queryset()
return get_object_or_404(queryset, pk=self.user_id)
class BBPasswordChangeView(SuccessMessageMixin, LoginRequiredMixin, PasswordChangeView):
template_name = 'main/password_change.html'
success_url = reverse_lazy('main:profile')
success_message = 'Пароль пользователя изменен.'
class RegisterUserView(CreateView):
model = AdvUser
template_name = 'main/register_user.html'
form_class = RegisterUserForm
success_url = reverse_lazy('main:register_done')
class RegisterDoneView(TemplateView):
template_name = 'main/register_done.html'
def user_activate(request, sign):
try:
username = signer.unsign(sign)
except BadSignature:
return render(request, 'main/bad_signature.html', context={'username': username})
user = get_object_or_404(AdvUser, username=username)
if user.is_activated:
template = 'main/user_is_activated.html'
else:
template = 'main/activation_done.html'
user.is_active = True
user.is_activated = True
user.save()
return render(request, template, context={'username': username})
class DeleteUserView(LoginRequiredMixin, DeleteView):
model = AdvUser
template_name = 'main/delete_user.html'
success_url = reverse_lazy('main:index')
def dispatch(self, request, *args, **kwargs):
self.user_id = request.user.pk
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
logout(request) # Необходимо сделать выход перед удалением
messages.add_message(request, messages.SUCCESS, f'Пользователь {request.user.username} удален')
return super().post(request, *args, **kwargs)
def get_object(self, queryset=None):
if not queryset:
queryset = self.get_queryset()
return get_object_or_404(queryset, pk=self.user_id)
# Bb
def by_rubric(request, pk):
rubric = get_object_or_404(SubRubric, pk=pk)
bbs = Bb.objects.filter(is_active=True, rubric=pk)
if 'keyword' in request.GET:
keyword = request.GET['keyword']
q = Q(title__icontains=keyword) | Q(content__icontains=keyword)
bbs = bbs.filter(q)
else:
keyword = ''
form = SearchForm(initial={'keyword': keyword})
paginator = Paginator(bbs, 2)
if 'page' in request.GET:
page_num=request.GET['page']
else:
page_num = 1
page = paginator.get_page(page_num)
context = {'rubric': rubric, 'page': page, 'bbs': page.object_list, 'form': form}
return render(request, 'main/by_rubric.html', context)
def detail(request, rubric_pk, pk):
bb = get_object_or_404(Bb, pk=pk)
ais = bb.additionalimage_set.all()
comments = Comment.objects.filter(bb=pk, is_active=True)
initial = {'bb': bb.pk}
if request.user.is_authenticated:
initial['author'] = request.user.username
form_class = UserCommentForm
else:
form_class = GuestCommentForm
form = form_class(initial=initial)
if request.method == 'POST':
if request.user.is_superuser and request.POST.get('comment_delete', None):
comment_pk = request.POST.get('comment_delete', None)
comment = Comment.objects.get(pk=comment_pk)
comment.delete()
messages.add_message(request, messages.SUCCESS, 'Комментарий удален')
return HttpResponseRedirect(f'/{rubric_pk}/{pk}')
else:
c_form = form_class(request.POST)
if c_form.is_valid():
c_form.save()
messages.add_message(request, messages.SUCCESS, 'Комментарий добавлен')
return HttpResponseRedirect(f'/{rubric_pk}/{pk}')
else:
form = c_form
messages.add_message(request, messages.WARNING, 'Комментарий не добавлен')
context = {'bb': bb, 'ais': ais, 'comments': comments, 'form': form}
return render(request, 'main/detail.html', context)
@login_required
def profile_bb_detail(request, rubric_pk, pk):
bb = get_object_or_404(Bb, pk=pk)
ais = bb.additionalimage_set.all()
context = {'bb': bb, 'ais': ais}
return render(request, 'main/profile_bb_detail.html', context)
@login_required
def profile_bb_add(request):
if request.method == 'POST':
form = BbForm(request.POST, request.FILES)
if form.is_valid():
bb = form.save()
formset = AIFormSet(request.POST, request.FILES, instance=bb)
if formset.is_valid():
formset.save()
messages.add_message(request, messages.SUCCESS, 'Объявление добавлено')
return redirect('main:profile')
else:
form = BbForm(initial={'author': request.user.pk})
formset = AIFormSet()
context = {'form': form, 'formset': formset}
return render(request, 'main/profile_bb_add.html', context)
@login_required
def profile_bb_change(request, pk):
bb = get_object_or_404(Bb, pk=pk)
if request.method == 'POST':
form = BbForm(request.POST, request.FILES, instance=bb)
if form.is_valid():
bb = form.save()
formset = AIFormSet(request.POST, request.FILES, instance=bb)
if formset.is_valid():
formset.save()
messages.add_message(request, messages.SUCCESS, 'Объявление отредактировано')
return redirect('main:profile')
else:
form = BbForm(instance=bb)
formset = AIFormSet(instance=bb)
context = {'form': form, 'formset': formset}
return render(request, 'main/profile_bb_change.html', context)
@login_required
def profile_bb_delete(request, pk):
bb = get_object_or_404(Bb, pk=pk)
if request.method == 'POST':
bb.delete()
messages.add_message(request, messages.SUCCESS, 'Объявление удалено')
return redirect('main:profile')
else:
context = {'bb': bb}
return render(request, 'main/profile_bb_delete.html', context) | [
"seitakhunova@gmail.com"
] | seitakhunova@gmail.com |
ce1d12f180f5431372d250abd42e79630dd28233 | 06f60140118911e917b81cd421e1c2e8af5e6c06 | /tests/__init__.py | e4df8b00f9b840ae87da7e1f43425910802a5f3f | [] | no_license | tf198/annex-librarian | b58a4b298891077fca4890bf850ecb8ec1ad86c5 | a730a817040b328284663be35a86e14a91e9edf0 | refs/heads/master | 2021-01-02T09:45:09.605568 | 2017-12-20T07:25:20 | 2017-12-20T07:25:20 | 99,289,033 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,169 | py | import os
import logging
import shutil
import subprocess
import tempfile
import sys
import unittest
from librarian import Librarian, progress
progress.ENABLED = False
PYTHON_VERSION = int(sys.version[0])
#from . import trace_resources
#trace_resources.enable()
debug = os.environ.get('DEBUG')
if debug is not None:
logging.basicConfig(level=getattr(logging, debug.upper(), logging.INFO))
logging.info("Enabled logging")
def create_repo(repo):
subprocess.check_output(['git', '-C', repo, 'init'])
subprocess.check_output(['git', '-C', repo, 'annex', 'init', 'testing'])
l = Librarian(repo)
for i in range(3):
d = os.path.join(repo, 'dir_{0}'.format(i))
os.mkdir(d)
filename = os.path.join(d, 'test_%s.txt' % i)
with open(filename, 'w') as f:
f.write("Hello %d" % i)
l.annex.git_raw('annex', 'add', filename)
l.annex.git_raw('commit', '-m', 'Added %d' % i)
return l
def clone_repo(origin, repo):
subprocess.check_output(['git', 'clone', origin, repo], stderr=subprocess.STDOUT)
subprocess.check_output(['git', '-C', repo, 'annex', 'init', 'testing'])
l = Librarian(repo)
return l
def destroy_repo(repo):
# annex protects itself well!
objects = os.path.join(repo, '.git', 'annex', 'objects')
if os.path.exists(objects):
for root, dirs, files in os.walk(objects):
for d in dirs:
os.chmod(os.path.join(root, d), 0o755)
shutil.rmtree(repo)
class RepoBase(object):
@classmethod
def setUpClass(cls):
cls.origin = tempfile.mkdtemp()
create_repo(cls.origin)
@classmethod
def tearDownClass(cls):
destroy_repo(cls.origin)
def setUp(self):
self.repo = tempfile.mkdtemp()
def tearDown(self):
destroy_repo(self.repo)
def create_repo(self):
return create_repo(self.repo)
def clone_repo(self):
return clone_repo(self.origin, self.repo)
if PYTHON_VERSION == 2:
def assertRaisesRegex(self, *args, **kwargs):
return self.assertRaisesRegexp(*args, **kwargs)
RepoBase.assertRaisesRegex = assertRaisesRegex
| [
"tris.git@shoddynet.org"
] | tris.git@shoddynet.org |
06436cbb4348355e1508294f584296dbfbbbea71 | c7223040804a0750ecc4e8961de2a4fbb201a40a | /prime_number.py | 9dcfa447ec220d8060d9d7ca2e918601734c641b | [] | no_license | Resham1458/Prime_Numbers | ed47eb506164d0b0e2878a92416fd61f3a9612e8 | 7d8a6b0e9087d2186a11ccdb051aa37249138d3b | refs/heads/master | 2021-06-23T22:34:41.434973 | 2017-08-31T17:27:49 | 2017-08-31T17:27:49 | 102,026,448 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 325 | py | print("List of prime numbers between 2 and 100: ")
#creating list of all numbers from 2 to 100:
for a in range(2, 101):
num = a
if num > 1:
# checking for factors
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num, "is a prime number")
| [
"noreply@github.com"
] | Resham1458.noreply@github.com |
40f0018b88acec9d2cd0ee9d0c21f120bd1b39f5 | ead829087d9c9908aefdc84ee83b6645fb1fa23f | /shop/urls.py | f884ee31b00649c3a5f66ce1452bbbe0766b9389 | [] | no_license | sofinetimihai/shopping_cart_python | ee6a67f757a4c13a0157a037a25c1ae8e32f769f | f38a744a6dab0ff2edd5f38b35495546a756954e | refs/heads/master | 2020-07-23T15:52:53.952448 | 2019-09-10T17:44:05 | 2019-09-10T17:44:05 | 207,619,113 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 396 | py | from django.urls import path, re_path
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'', views.product_list, name='product_list'),
url(r'^category/(?P<categoryid>\d+)/$', views.product_list_by_category, name='product_list_by_category'),
url(r'^produs/(?P<id>\d+)/$', views.product_detail, name='product_detail'),
#re_path(r'^.*$', views.home),
]
| [
"sofinetimihai@gmail.com"
] | sofinetimihai@gmail.com |
e28276b1a48f2713b95c9518fb95e2cb7d2b741f | 1ddf91e1e34f920fcd96885765346f1c755760a6 | /bi-kodovi/nedelje/9/kodovi/1.5.FindInsertionPoint.py | dad74ad67470c86bc22e91cf24010abe51bfd0a1 | [] | no_license | djinx/bioinformatika | e5952616c05bd3a535e54f0c84ddbd3d2b425d44 | e244bd38379cf22e7807ad687551c3ee3d35eb4c | refs/heads/master | 2020-03-25T11:04:29.814182 | 2018-08-30T11:07:43 | 2018-08-30T11:07:43 | 143,718,109 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 339 | py | def find_insertion_point(path, distance):
current_distance = 0
previous_vertex = path[0][0]
for i in range(1, len(path)):
v = path[i][0]
e = path[i][1]
current_distance += e
next_vertex = v
if distance <= current_distance:
return (previous_vertex, next_vertex, e, current_distance - distance)
previous_vertex = v | [
"key13043@gmail.com"
] | key13043@gmail.com |
c2642282ea51a48b961b7ef526e5151b32458b24 | a2a0a66861e1c2a49fc7e2253acc0923e9131b63 | /A Set/281A.py | a1f931f85abc256d7ad1736ffbb5e2d66d5e615c | [] | no_license | notmycall/codeforces-solutions | e94664822cce38b6fbc0ed6be93724177c6cbff1 | fe8d35affd65fe342856ed70a505296f33fc0e7d | refs/heads/master | 2023-06-23T09:42:44.710572 | 2021-07-20T22:54:23 | 2021-07-20T22:54:23 | 387,039,080 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 98 | py | w = input()
nw = w[0].upper() + w[1:]
print(nw)
# https://codeforces.com/problemset/problem/281/A | [
"71604243+notmycall@users.noreply.github.com"
] | 71604243+notmycall@users.noreply.github.com |
921bac25f3b96353e1c99bf350af26b2ba46974d | cd8eac578e8402bd329dcf4d639fa1b8434a2772 | /app/extensions/api_docs/cms/banner.py | e0c8e579e6e82071eb8db62b9167c812a78cf813 | [] | no_license | kongkonger/flaskdemo | 1909fc3530c3200fea60a7cfd5d58f6deb5d2c05 | abe53dd4518a4c2cf6642185faf93f2abe54a55d | refs/heads/main | 2023-01-13T20:54:30.208748 | 2020-11-17T14:42:47 | 2020-11-17T14:42:47 | 313,073,435 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 89 | py | # _*_ coding: utf-8 _*_
"""
Created by Allen7D on 2020/6/30.
"""
__author__ = 'Allen7D' | [
"ming159357456@gmail.com"
] | ming159357456@gmail.com |
6f8902a49b355e37d33249b7427e800d12b7938f | ca83eb19e142faf8c57aca0f1f9ecf92e0930f84 | /siap_git/models/linearRegression.py | ccf12ff5e6e81e0882c3abb7738ccce72f5437d0 | [] | no_license | milicanikolic/siap | 8518baff17554de5a1ddadbff107f8a93c90a5da | 5373ef82cfbd91b6ede78226c966b087ba1b1e26 | refs/heads/master | 2020-05-02T08:53:59.278202 | 2019-03-26T21:00:11 | 2019-03-26T21:00:11 | 177,855,160 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,211 | py | import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, r2_score
from sklearn import linear_model
import numpy as np
train = pd.read_csv('datasets/trainDummies.csv')
test = pd.read_csv('datasets/testDummies.csv')
tip_amountTRAIN = train['tip_amount']
tip_amountTEST = test['tip_amount']
newDataTRAIN = train.drop(['tip_amount', 'tpep_pickup_datetime', 'tpep_dropoff_datetime'], axis=1)
newDataTEST = test.drop(['tip_amount', 'tpep_pickup_datetime', 'tpep_dropoff_datetime'], axis=1)
model = linear_model.LinearRegression()
model.fit(newDataTRAIN, tip_amountTRAIN)
predictions = model.predict(newDataTEST)
print('Coefficients: \n', model.coef_)
# The mean squared error
print("Mean squared error: %.2f" % mean_squared_error(tip_amountTEST, predictions))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f' % r2_score(tip_amountTEST, predictions))
print predictions.shape
print predictions
print tip_amountTEST
# Plot outputs
plt.scatter(newDataTEST, tip_amountTEST, color='black')
plt.plot(newDataTEST, predictions, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
| [
"noreply@github.com"
] | milicanikolic.noreply@github.com |
7af7b7b2b077c56d314c8a7de890790b7cd2a523 | 9972988c4f4ccd7fdbafea601782dae94b679e78 | /tests/test.py | 8f7fc6f16dc0d00289c64bafe01422ece4e4f123 | [
"MIT"
] | permissive | chenshoubiao/ButterSalt | b67e9dec730350e64520064940fe69621a927418 | 7120c5135448cb3c9760925f23d2efc8316458d8 | refs/heads/master | 2021-01-22T03:22:58.791300 | 2017-05-25T01:58:45 | 2017-05-25T01:58:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,787 | py | import ButterSalt
import unittest
class ButterSaltTestCase(unittest.TestCase):
def setUp(self):
ButterSalt.app.config['TESTING'] = True
ButterSalt.app.config['WTF_CSRF_ENABLED'] = False
ButterSalt.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
ButterSalt.app.config['SQLALCHEMY_ECHO'] = False
self.app = ButterSalt.app.test_client()
ButterSalt.db.create_all()
def login(self, username, password):
return self.app.post('/user/login', data=dict(
username=username,
password=password
), follow_redirects=True)
def logout(self):
return self.app.get('/user/logout', follow_redirects=True)
def test_login_logout(self):
rv = self.login('admin', 'default')
assert '/user/logout' in str(rv.data)
assert 'Logged in successfully.' in str(rv.data)
rv = self.logout()
assert 'Please log in to access this page.' in str(rv.data)
assert '/user/logout' not in str(rv.data)
def test_index(self):
self.login('admin', 'default')
rv = self.app.get('/', follow_redirects=True)
assert 'id="tgt" name="tgt" type="text" value="" placeholder="Required"' in str(rv.data)
assert '/user/logout' in str(rv.data)
def test_deployment(self):
self.login('admin', 'default')
rv = self.app.get('/deployment/operation', follow_redirects=True)
assert '<table class="table table-hover">' in str(rv.data)
assert '/user/logout' in str(rv.data)
def test_salt_jobs(self):
self.login('admin', 'default')
rv = self.app.get('/salt/jobs/', follow_redirects=True)
assert '<table class="table table-striped">' in str(rv.data)
assert '/user/logout' in str(rv.data)
def test_execution_command_testping(self):
self.login('admin', 'default')
rv = self.app.post('/', data=dict(
tgt='HXtest3',
fun='test.ping',
), follow_redirects=True)
assert '['HXtest3']' in str(rv.data)
def test_execution_command_testarg(self):
self.login('admin', 'default')
rv = self.app.post('/', data=dict(
tgt='HXtest3',
fun='test.arg',
arg="/proc lol"
), follow_redirects=True)
assert '<th> Arguments </th>' in str(rv.data)
assert '__kwarg__' not in str(rv.data)
def test_execution_command_testkwarg(self):
self.login('admin', 'default')
rv = self.app.post('/', data=dict(
tgt='HXtest3',
fun='test.arg',
arg="/proc lol",
kwarg='lol=wow'
), follow_redirects=True)
assert '__kwarg__' in str(rv.data)
if __name__ == '__main__':
unittest.main()
| [
"lfzyx.me@gmail.com"
] | lfzyx.me@gmail.com |
b0dcb0c0e52e193bf5ff6a59c70f397782bba2cb | 24acfe3b34cec28c01c8ba3423cdada3ef667353 | /ConstrTable/application/migrations/0001_initial.py | 05bd0535d8c91076c2300317655eb65588463be2 | [] | no_license | Ordus161/Constract-v1-on-Django | 6ba8e0132080bebaa68c8283da191a82ffd79830 | 528382c31ab14d344b5453bc30af5c576c69c430 | refs/heads/master | 2023-09-04T11:53:07.094107 | 2021-08-25T17:43:03 | 2021-08-25T17:43:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,119 | py | # Generated by Django 3.2.6 on 2021-08-25 16:44
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ConstructionSite',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('address', models.CharField(blank=True, db_index=True, max_length=150, verbose_name='Адрес')),
('numb', models.IntegerField(validators=[django.core.validators.MinValueValidator(1)], verbose_name='Номер объекта')),
],
options={
'verbose_name': 'Объект',
'verbose_name_plural': 'Объекты',
'ordering': ['numb'],
},
),
migrations.CreateModel(
name='Photo',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('bill', models.ImageField(blank=True, upload_to='photos/%Y/%m/%d', verbose_name='Фото')),
],
options={
'verbose_name': 'Чек',
'verbose_name_plural': 'Чеки',
},
),
migrations.CreateModel(
name='Application',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150, verbose_name='Наименование')),
('brand', models.TextField(blank=True, verbose_name='Бренд')),
('quantity', models.IntegerField(validators=[django.core.validators.MinValueValidator(1)], verbose_name='Количество')),
('link', models.URLField(blank=True, max_length=500, verbose_name='Ссылка')),
('item', models.IntegerField(blank=True, validators=[django.core.validators.MinValueValidator(1)], verbose_name='Артикул')),
('shop', models.TextField(blank=True, verbose_name='Магазин')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Создано')),
('updated_at', models.DateTimeField(auto_now=True, verbose_name='Обновлено')),
('is_executed', models.BooleanField(default=False, verbose_name='Выполнено')),
('area', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='application.constructionsite', verbose_name='Объект')),
('photo', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='application.photo', verbose_name='Фото')),
],
options={
'verbose_name': 'Заявка',
'verbose_name_plural': 'Заявки',
'ordering': ['-created_at'],
},
),
]
| [
"abond6600@gmail.com"
] | abond6600@gmail.com |
d3133b99a152d5f56731feb8fda1d1307d73b447 | 18041bb704499cdde8fe72f865613746400a5988 | /whoknowsCGI.py | 3c3e4fa7768c0d3929b6e94a1f980ae5b6635acf | [] | no_license | owen694/introweb | 2b0b98a1990fdec5d3c98bac83baab7bde30f811 | 8e40c06940bad5693563bc26e5354134290bfd71 | refs/heads/master | 2020-03-18T15:28:31.391585 | 2018-06-11T02:36:36 | 2018-06-11T02:36:36 | 134,910,398 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 573 | py |
#!/usr/bin/python
import cgi
import itertools
def htmlTop():
print '''Content-type:text/html\n\n
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title> Process Name </title>
</head>
<body>
'''
def htmlTail():
print '''
</body>
</html>'''
def main():
htmlTop()
htmlTail()
if __name__ == "__main__":
try:
main()
except:
cgi.print_exception()
| [
"angel@Valeriyas-MacBook-Air.local"
] | angel@Valeriyas-MacBook-Air.local |
e7be49dbc740b1357c53555b1c8370e37846f83e | dbde9338e87117397c2a7c8969df614f4dd4eacc | /examples/tensorflow/qat_conversion/benchmark.py | e31fb0226a4869184f24d64386ded4940317fec9 | [
"Apache-2.0",
"MIT",
"Intel"
] | permissive | leonardozcm/neural-compressor | 9f83551007351e12df19e5fae3742696613067ad | 4a49eae281792d987f858a27ac9f83dffe810f4b | refs/heads/master | 2023-08-16T17:18:28.867898 | 2021-09-03T06:44:25 | 2021-09-03T06:54:30 | 407,043,747 | 0 | 0 | Apache-2.0 | 2021-09-16T07:57:10 | 2021-09-16T06:12:32 | null | UTF-8 | Python | false | false | 1,017 | py | import tensorflow as tf
from tensorflow import keras
import numpy as np
class dataloader(object):
def __init__(self, batch_size=100):
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Normalize the input image so that each pixel value is between 0 to 1.
self.train_images = train_images / 255.0
self.test_images = test_images / 255.0
self.train_labels = train_labels
self.test_labels = test_labels
self.batch_size = batch_size
self.i = 0
def __iter__(self):
while self.i < len(self.test_images):
yield self.test_images[self.i: self.i + self.batch_size], self.test_labels[self.i: self.i + self.batch_size]
self.i = self.i + self.batch_size
from lpot.experimental import Benchmark, common
evaluator = Benchmark('mnist.yaml')
evaluator.model = common.Model('quantized_model')
evaluator.b_dataloader = dataloader()
evaluator('accuracy')
| [
"feng.tian@intel.com"
] | feng.tian@intel.com |
8cffae1caed4f348b156a25034e81b9c31782903 | 46ae8264edb9098c9875d2a0a508bc071201ec8b | /res/scripts/client/gui/battle_control/requestsavatarrequestscontroller.py | f867089a8ae0ffd0381a8948555605e3e5e292d7 | [] | no_license | Difrex/wotsdk | 1fc6156e07e3a5302e6f78eafdea9bec4c897cfb | 510a34c67b8f4c02168a9830d23f5b00068d155b | refs/heads/master | 2021-01-01T19:12:03.592888 | 2016-10-08T12:06:04 | 2016-10-08T12:06:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,880 | py | # Embedded file name: scripts/client/gui/battle_control/requests/AvatarRequestsController.py
from collections import namedtuple
import BigWorld
import AccountCommands
from debug_utils import LOG_DEBUG, LOG_WARNING
from ids_generators import Int32IDGenerator
from helpers import i18n
from messenger import MessengerEntry, g_settings
from gui.shared.utils.requesters.abstract import RequestsByIDProcessor
from gui.shared.utils.requesters.RequestsController import RequestsController
from gui.shared.rq_cooldown import RequestCooldownManager, REQUEST_SCOPE
from gui.battle_control.requests.settings import AVATAR_REQUEST_TYPE, DEFAULT_COOLDOWN
class _AvatarCooldownManager(RequestCooldownManager):
def __init__(self):
super(_AvatarCooldownManager, self).__init__(REQUEST_SCOPE.CLUB)
def lookupName(self, rqTypeID):
rqName = AVATAR_REQUEST_TYPE.getKeyByValue(rqTypeID)
return i18n.makeString('#system_messages:battle/request/%s' % str(rqName))
def getDefaultCoolDown(self):
return DEFAULT_COOLDOWN
def _showSysMessage(self, msg):
MessengerEntry.g_instance.gui.addClientMessage(g_settings.htmlTemplates.format('battleErrorMessage', ctx={'error': msg}))
class _AvatarRequester(RequestsByIDProcessor):
class _Response(namedtuple('_Response', ['code', 'errStr', 'data'])):
def isSuccess(self):
return AccountCommands.isCodeValid(self.code)
def __init__(self):
super(_AvatarRequester, self).__init__(Int32IDGenerator())
def getSender(self):
return BigWorld.player().prebattleInvitations
def _doCall(self, method, *args, **kwargs):
requestID = self._idsGenerator.next()
def _callback(code, errStr, data):
ctx = self._requests.get(requestID)
self._onResponseReceived(requestID, self._makeResponse(code, errStr, data, ctx))
method(callback=_callback, *args, **kwargs)
return requestID
def _makeResponse(self, code = 0, errMsg = '', data = None, ctx = None):
response = self._Response(code, errMsg, data)
if not response.isSuccess():
LOG_WARNING('Avatar request error', ctx, response)
return response
class AvatarRequestsController(RequestsController):
def __init__(self):
super(AvatarRequestsController, self).__init__(_AvatarRequester(), _AvatarCooldownManager())
self.__handlers = {AVATAR_REQUEST_TYPE.SEND_INVITES: self.sendInvites}
def fini(self):
self.__handlers.clear()
super(AvatarRequestsController, self).fini()
def sendInvites(self, ctx, callback = None):
return self._requester.doRequestEx(ctx, callback, 'sendInvitation', ctx.getDatabaseIDs())
def _getHandlerByRequestType(self, requestTypeID):
return self.__handlers.get(requestTypeID)
def _getRequestTimeOut(self):
return 30.0 | [
"m4rtijn@gmail.com"
] | m4rtijn@gmail.com |
89d47b2ad358b6d5ee042bbeabc1a06b5424b1d6 | 670432640f1b5ee99f8786e9e9af0d5c58201c6f | /MyTitanicSolution.py | 80643d746f1be2e84c0c439b143f2626d16a9445 | [] | no_license | ViruTyagi/MLBeginner | b10d314040f10e772bdc2f13d365b1f1e9f89882 | c9fb5fe6f05cdb376dee69214f6da41e4d953503 | refs/heads/master | 2022-11-30T00:17:24.663616 | 2020-08-02T14:26:15 | 2020-08-02T14:26:15 | 284,476,670 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,066 | py | #importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#importing dataset's
train = pd.read_csv("/home/virutyagi/Projects/KaggleProjects/Titanic Problem/train.csv")
test = pd.read_csv("/home/virutyagi/Projects/KaggleProjects/Titanic Problem/test.csv")
train.head(5)
test.head(5)
#diceing and sliceing
X = train.iloc[:,[2,4,5,6,7,9,11]].values
y = train.iloc[:,1].values
X_test = test.iloc[:,[1,3,4,5,6,8,10]].values
#visualization
plt.scatter(X[y==0,2],X[y==0,0],color = 'r')
plt.scatter(X[y==1,2],X[y==1,0],color = 'g')
plt.show()
#handling missing values
from sklearn.preprocessing import Imputer
imp = Imputer()
tesst = X[:,2].reshape(-1,1)
tesst = imp.fit_transform(tesst)
X[:,2] = tesst.ravel()
X_test[:,[2,5]] = imp.fit_transform(X_test[:,[2,5]])
del(tesst)
train1 = pd.DataFrame(X[:,[1,6]])
train1.describe()
test1 = pd.DataFrame(X_test[:,[1,6]])
test1.describe()
train1[1] = train1[1].fillna("S")
X[:,[1,6]] = train1
#converting categorical values into
from sklearn.preprocessing import LabelEncoder
lab = LabelEncoder()
X[:,1] = lab.fit_transform(X[:,1])
X[:,6] = lab.fit_transform(X[:,6])
X_test[:,1] = lab.fit_transform(X_test[:,1])
X_test[:,6] = lab.fit_transform(X_test[:,6])
from sklearn.preprocessing import OneHotEncoder
one = OneHotEncoder(categorical_features = [1,6])
X = one.fit_transform(X)
X_test = one.fit_transform(X_test)
X = X.toarray()
X_test = X_test.toarray()
from sklearn.tree import DecisionTreeClassifier
DT = DecisionTreeClassifier()
DT.fit(X,y)
DT.score(X,y)
y_test = DT.predict(X_test)
DT.score(X_test,y_test)
from sklearn.linear_model import LogisticRegression
log_reg = LogisticRegression()
log_reg.fit(X,y)
log_reg.score(X,y)
y_test1 = log_reg.predict(X_test)
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(X,y)
y_test1 = knn.predict(X_test)
Predictedvalue = pd.DataFrame(y_test1)
train.describe()
#storing predicted values into the csv file
test['Survived'] = Predictedvalue
test.to_csv('/home/virutyagi/Desktop/Submission.csv')
| [
"noreply@github.com"
] | ViruTyagi.noreply@github.com |
b83df84070532acf73d7b9c8fa53c3568f2de255 | 016747529a09dd12ef9979e778d0bd700c6e54c6 | /Primitve_Scrapers/Old Scrapers/TW_Rescrape.py | f6b91a2717043d5a91cd38b85f656f3198e3f03e | [] | no_license | goobyme/WebScrapers | c8cdc1627c73ea8f86a64d510f7816b89898e7c4 | 5e6bbdd0761236ee4886db991b40d202347eb22c | refs/heads/master | 2021-09-07T07:56:01.236791 | 2018-02-19T18:36:58 | 2018-02-19T18:36:58 | 116,184,649 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,846 | py | import requests
import bs4
import pandas
import threading
import os
import openpyxl
os.chdir('/mnt/c/Users/Liberty SBF/PycharmProjects')
# os.chdir('C:\\Users\\Liberty SBF\\PycharmProjects')
SEARCHPAGE = 'https://www.transwestern.com/bio?email='
THREADCOUNT = 20
employees = []
init_proto_profile_list = []
elist_lock = threading.Lock()
llist_lock = threading.Lock()
def webdl(url):
"""Downloads web-page (using requests rather than urllib) """
print('Downloading...%s' % url)
r = requests.get(url)
try:
r.raise_for_status()
return r
except requests.HTTPError:
try:
print('Download failed for %s' % url)
return None
except BlockingIOError:
return None
def excelreader(file_name):
wb = openpyxl.load_workbook(file_name)
sheet = wb.get_sheet_by_name('contacts(1)')
email_list = []
for i in range(2, sheet.max_row):
email = sheet.cell(row=i, column=3)
email_list.append(email.value)
return email_list
def personparsing(page):
e = {}
headers = {1:'Name', 2:'Title', 3:'Department'}
i = 1
soup = bs4.BeautifulSoup(page.text, 'lxml')
parent_el = soup.find_all('div', {'class': 'twoThirdColumn_bio desktopONLYBio'})
try:
elements = parent_el[0].find_all('span')
for element in elements:
e[headers[i]] = element.get_text()
i += 1
except IndexError:
return None
return e
def threadbot(thread_id):
sublist = []
while True:
llist_lock.acquire()
if len(init_proto_profile_list) > 0:
try:
link = init_proto_profile_list[0]
init_proto_profile_list.remove(link)
finally:
llist_lock.release()
print('Thread %s parsing %s' % (thread_id, link))
sublist.append(personparsing(webdl(link)))
else:
llist_lock.release()
print('Thread %s completed parsing' % thread_id)
break
elist_lock.acquire()
try:
global employees
employees += sublist
print('Thread %s wrote to list' % thread_id)
finally:
elist_lock.release()
def main():
global init_proto_profile_list
global employees
threads = []
email_list = excelreader('Transwestern.xlsx')
for email in email_list:
page = SEARCHPAGE + email
link_list.append(page)
for i in range(THREADCOUNT):
thread = threading.Thread(target=threadbot, args=(i+1, ))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
to_save = filter(None, employees)
data_frame = pandas.DataFrame.from_records(to_save)
data_frame.to_csv('TW_Additional.csv')
print('Done')
if __name__ == "__main__":
main()
| [
"goobyme@gmail.com"
] | goobyme@gmail.com |
eb60232c371e9145aaafc3825d814eda33f275f5 | c1bf05a038c892928d126fd5e48473757d10add8 | /python/bottage/module-2/python-env/write_to_a_file.py | d5c8d74a69a12ee51ddbd2721be01ee80717c280 | [] | no_license | heithof3/notes | b893f2ce1880c16b822f1cd710939f7e41f97fee | 0b224309b260cd23ecf30ff8e039f6fd75cf316d | refs/heads/main | 2023-06-20T10:49:18.682686 | 2021-07-13T17:22:13 | 2021-07-13T17:22:13 | 385,675,339 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 177 | py | file_builder = open("logger.txt", "w+")
for i in range(100):
file_builder.write(f"I'm on line {i + 1}\n")
# file_builder.write("Hey, I'm in a file!")
file_builder.close() | [
"heith.robbins@gmail.com"
] | heith.robbins@gmail.com |
9dc8a590b4ee4efceec3e1f291cbcefaf98c0bc1 | a331d1ad87846738ddf2684f09008688c855fdd9 | /venv/Scripts/easy_install-script.py | 4b8fe8d9108f89ab119d600f27d14f8c9c6625dd | [
"MIT"
] | permissive | eyespied/Reincarnation | 086ae91b971be6ebd9f5dbf289f1a91a8afdee78 | d5dc819b9b9490764ace33f2ef89f9bc268c4ca5 | refs/heads/master | 2021-01-08T10:14:56.302820 | 2020-04-25T12:11:25 | 2020-04-25T12:11:25 | 241,999,398 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 457 | py | #!C:\Users\James\Documents\GitHub\Reincarnation\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install'
__requires__ = 'setuptools==40.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==40.8.0', 'console_scripts', 'easy_install')()
)
| [
"jc704@kent.ac.uk"
] | jc704@kent.ac.uk |
1e322b9340bde3dac33558b3897bfef9ce871bd7 | 1ee10e1d42b59a95a64d860f0477a69b016d1781 | /Lecture_09/Lecture Code/3-pipeline_text_generation.py | c1c3ebf2a71d9e21e8fada4b70c2de73687de274 | [] | no_license | KushalIsmael/NLP | 5564070a573d251d7222dda85b8025ae1f9c3c6f | d4ce567a009e149b0cb1781d3a341d25aa438916 | refs/heads/master | 2023-08-18T14:07:48.646386 | 2021-10-28T19:09:25 | 2021-10-28T19:09:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 295 | py | from transformers import pipeline
generator = pipeline("text-generation")
print(generator("In this course, we will teach you how to"))
print(generator("I am tired of listening to this brownbag session about natural language processing.",
num_return_sequences = 1, max_length = 100 )) | [
"amir.h.jafari@okstate.edu"
] | amir.h.jafari@okstate.edu |
6f659e416c442bdd95e9e23a6436a0b97c3965d0 | bd71fd307eb1c8b62c7f0223e320cf9f8a2163e0 | /utils.py | 973881e78d70942cee9384babbd1e029c4816dc8 | [] | no_license | shaghayeghelc/moonshot-NLU | 0aeaf17a0063eab2e931e9259e65f1a59b6f0934 | fe22fe17c53b5c483aaaa40c6f813af14dd7d454 | refs/heads/master | 2022-12-14T06:07:17.678390 | 2019-02-03T17:15:23 | 2019-02-03T17:15:23 | 168,778,379 | 0 | 0 | null | 2022-12-08T01:34:55 | 2019-02-02T00:42:49 | Python | UTF-8 | Python | false | false | 1,967 | py | #!usr/bin/env python3
# Importing Packages
import nltk
import pickle
import re
import numpy as np
# nltk.download('stopwords')
nltk.download('stopwords', download_dir='/opt/python/current/app')
nltk.data.path.append('/opt/python/current/app')
from nltk.corpus import stopwords
def text_prepare_en(text):
""" Tokenization- Preprocessing """
replace_by_space_re = re.compile('[/(){}\[\]\|@,;]')
bad_symbols_re = re.compile('[^0-9a-z #+_]')
stopwords_set = set(stopwords.words('english'))
text = text.lower()
text = replace_by_space_re.sub(' ', text)
text = bad_symbols_re.sub('', text)
text = ' '.join([x for x in text.split() if x and x not in stopwords_set])
return text.strip()
def text_prepare_fr(text):
""" Tokenization- Preprocessing """
replace_by_space_re = re.compile('[/(){}\[\]\|@,;]')
bad_symbols_re = re.compile('[^0-9a-z #+_]')
stopwords_set = set(stopwords.words('french'))
text = text.lower()
text = replace_by_space_re.sub(' ', text)
text = bad_symbols_re.sub('', text)
text = ' '.join([x for x in text.split() if x and x not in stopwords_set])
return text.strip()
def load_embeddings(embeddings_path):
embeddings = dict()
for line in open(embeddings_path, encoding = 'utf-8'):
row = line.strip().split('\t')
embeddings[row[0]] = np.array(row[1:], dtype = np.float32)
embeddings_dim = embeddings[list(embeddings)[0]].shape[0]
return embeddings, embeddings_dim
def question_to_vec(question, embeddings, dim):
""" Transforms a string to an embedding. """
vec = []
for word in question.split():
if word in embeddings:
vec.append(embeddings[word])
if vec == []:
return np.zeros(dim)
result = np.array(vec).mean(axis=0)
return result
def unpickle_file(filename):
""" unpickling the file."""
with open(filename, 'rb') as f:
return pickle.load(f)
| [
"SHARON.SHAHROKHI.TEHRANI@cbc.ca"
] | SHARON.SHAHROKHI.TEHRANI@cbc.ca |
419d31478ef06ebf26b599d043b4c191b73b935e | 35d79c16dba08ec78103ef52d0f49aed978d6efe | /main.py | 8bd8f5a1e612fb21c52bf9b899b18eb17b56c3c4 | [] | no_license | KaleabTessera/Mountain_Climbing_SARSA_Semi_Gradient | 60e4ecc61b9f242a3d3a4ee464e60f09a35c7801 | 2478144f07bdf1d9adf4e12c7c45c8ccd8e721f5 | refs/heads/master | 2022-12-13T23:03:34.649644 | 2019-09-17T09:40:36 | 2019-09-17T09:40:36 | 208,964,533 | 1 | 1 | null | 2022-12-08T06:10:11 | 2019-09-17T05:13:16 | Python | UTF-8 | Python | false | false | 3,687 | py | import gym
from gym import wrappers
import random
import numpy as np
from value_function import ValueFunction
from collections import defaultdict
from collections import namedtuple
import itertools
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
EpisodeStats = namedtuple("Stats", ["episode_lengths", "episode_rewards"])
def plot_average_performance(episode_stats, algor_name, num_runs):
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot()
plt.xlabel("Episode")
plt.ylabel("Episode Length")
ax.set_title(f"Episode Length over Time (averaged over {num_runs} runs)")
average = episode_stats.mean()
average.plot(ax=ax)
fig.savefig(algor_name + "_normal_y_scale.png")
ax.set_yscale('log')
fig.savefig(algor_name + "_log_y_scale.png")
plt.show(block=False)
def SARSA_semi_gradient(env, value_function, num_episodes, discount_factor=1.0, epsilon=0.1, alpha=0.1, print_=False, record_animation=False):
# Keeps track of useful statistics
stats = EpisodeStats(
episode_lengths=np.zeros(num_episodes),
episode_rewards=np.zeros(num_episodes))
q = value_function.__call__
for i_episode in range(num_episodes):
if(print_ and ((i_episode + 1) % 100 == 0)):
print("\rEpisode {}/{}.".format(i_episode + 1, num_episodes), end="")
# Exploit and record animation once we have learned q value
if(i_episode == num_episodes-1 and record_animation):
epsilon = 0
state = env.reset()
action = value_function.act(state, epsilon)
for j in itertools.count():
next_state, reward, done, info = env.step(action)
# Update stats per episode
stats.episode_rewards[i_episode] += reward
stats.episode_lengths[i_episode] = j
if(done):
target = reward
value_function.update(target, state, action)
break
else:
# Estimate q-value at next state-action
next_action = value_function.act(next_state, epsilon)
q_new = q(next_state, next_action)
target = reward + discount_factor * q_new
value_function.update(target, state, action)
state = next_state
action = next_action
return stats
def run_sarsa_semi_gradient(num_episodes=500, num_runs=1):
env = gym.make('MountainCar-v0')
env._max_episode_steps = 10000
episode_lengths_total = pd.DataFrame([])
for i in range(num_runs):
print(f"\n Run {i+1} of {num_runs} \n")
value_function = ValueFunction(alpha=0.1, n_actions=env.action_space.n)
stats = SARSA_semi_gradient(
env, value_function, num_episodes, print_=True)
episode_lengths_total = episode_lengths_total.append(
pd.DataFrame(stats.episode_lengths).T)
env.close()
plot_average_performance(
episode_lengths_total, "SARSA_Semi-Gradient_for_Mountain_Car_Environment", num_runs)
def animate_environment(num_episodes=500):
print(" \n Animating the last episode")
env = gym.make("MountainCar-v0")
env._max_episode_steps = 10000
env = gym.wrappers.Monitor(env, './video/', video_callable=lambda episode_id: episode_id==num_episodes-1,force = True)
value_function = ValueFunction(alpha=0.1, n_actions=env.action_space.n)
stats = SARSA_semi_gradient(
env, value_function, num_episodes, print_=True, record_animation=True)
env.close()
def main():
run_sarsa_semi_gradient(num_episodes=500,num_runs=1)
animate_environment(num_episodes=500)
if __name__ == "__main__":
main()
| [
"kaleabtessera@gmail.com"
] | kaleabtessera@gmail.com |
179f9840aa26538a158c13d517312dc7f541b21f | 7dd5c83b626bb6090584dda4595b1f83d7f7ed50 | /API_for_Linux/image_2_style_gan/perceptual_model.py | 8114b015740b60d730f9f842d5827648a790b46d | [] | no_license | Scania-S730-8x4/2020_team_project | 3a5f82d0dc5983ae7978a1db9ac92921125c1c03 | 41ba7b890eeb407cdadd605d82b81505095468a0 | refs/heads/main | 2023-02-13T11:32:03.345259 | 2021-01-14T06:18:23 | 2021-01-14T06:18:23 | 328,287,747 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,229 | py | import torch
from torchvision import models
class VGG16_for_Perceptual(torch.nn.Module):
def __init__(self,requires_grad=False,n_layers=[2,4,14,21]):
super(VGG16_for_Perceptual,self).__init__()
vgg_pretrained_features=models.vgg16(pretrained=True).features
self.slice0=torch.nn.Sequential()
self.slice1=torch.nn.Sequential()
self.slice2=torch.nn.Sequential()
self.slice3=torch.nn.Sequential()
for x in range(n_layers[0]): #relu1_1
self.slice0.add_module(str(x),vgg_pretrained_features[x])
for x in range(n_layers[0],n_layers[1]): #relu1_2
self.slice1.add_module(str(x),vgg_pretrained_features[x])
for x in range(n_layers[1],n_layers[2]): #relu3_2
self.slice2.add_module(str(x),vgg_pretrained_features[x])
for x in range(n_layers[2],n_layers[3]): #relu4_2
self.slice3.add_module(str(x),vgg_pretrained_features[x])
if not requires_grad:
for param in self.parameters():
param.requires_grad=False
def forward(self,x):
h0=self.slice0(x)
h1=self.slice1(h0)
h2=self.slice2(h1)
h3=self.slice3(h2)
return h0,h1,h2,h3
| [
"noreply@github.com"
] | Scania-S730-8x4.noreply@github.com |
107d863547d1cb0701cdbcba7b81836f6e66fb62 | 4bfe9046ea7c14ef21b6a0a8d971830ba9e87769 | /test_01.py | 0f5aa83c3466e08c98d7b72fbf3d8cbd9352fcbb | [] | no_license | chenyanqa/example_tests_one | 8f0476b92a22dd55e5bf4b8d607f4170e78e6abc | fe61b2eb84e5bb96d1de274be02ec5675d46316d | refs/heads/master | 2021-09-07T00:12:46.625371 | 2018-02-14T00:15:21 | 2018-02-14T00:15:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 424 | py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
m = 0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if(i != j) and (j !=k) and (k != i): #三个数互不相等的表达式
a = 100*i + 10*j +k
print('无重复的三位数为:%s' %(a))
m= m+1
print('总个数为:%s' %(m)) | [
"879167367@qq.com"
] | 879167367@qq.com |
283ba6ade2023d49e634443512795246d7363fa6 | 10eac9cb1196996a895026d955497d7f962c2f16 | /projects/comapny_profiles/apps.py | c6e2472eab09fd0ba013dadcd981a5700daef345 | [] | no_license | naresh143naresh/W2S | d784b32290ad87626735e78006f2d7980730ad83 | c2110a313e21f11f7751e63a4695d8767b29778c | refs/heads/master | 2023-07-13T10:47:39.891423 | 2021-08-17T17:32:25 | 2021-08-17T17:32:25 | 397,334,204 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 163 | py | from django.apps import AppConfig
class ComapnyProfilesConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'comapny_profiles'
| [
"joldrasinaresh143@gmail.com"
] | joldrasinaresh143@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.