Beispiel #1
0
def post_process_csv_data(data):
    """Apply color, card type, and CMC to cards."""
    for x in data:
        # Each x is a list of the form [cardname, color, cardtype, CMC]
        db(db.Cards.Name == x[0]).update(
            Color=x[1].replace('MONO_', ''),
            Cardtype=x[2],
            CMC=x[3])
Beispiel #2
0
def update(filename):
    '''Change the cube list to reflect the contents of FILENAME.
    FILENAME: a list of cardnames, one per line. No quantity data - multiples
    must be listed separately for each instance. This matches CubeTutor's output
    as of August 2014.
    
    This function:
    1. Iterates through the list and builds a {name: quantity} dictionary.
    2. Iterates through the cards table, setting quantities to 0 on all cards
    not appearing in the dictionary.
    3. Iterates through the dictionary, creating or updating rows as needed.

    This function does not add, update, or change card attributes (color etc.).
    '''

    log.debug("Reading from %s", filename)
    with open(filename, 'r') as f:
        cardData = f.readlines()
    log.info("cardData indicates a %s-card cube.", len(cardData))

    # Step 1

    newCards = {} # empty dictionary to hold name:qty keypairs
    for i in range(len(cardData)):
        cardData[i] = cardData[i].strip()
        if cardData[i] in newCards:    # Duplicate cardname found...
            newCards[cardData[i]] += 1 # so increment the quantity.
        else:
            newCards[cardData[i]] = 1  # Otherwise add a key with qty=1.
    log.warning("newCards indicates a %s-card cube.", sum(newCards.values()))

    # Step 2

    cut_cards = added_cards = 0 # Count number of changed cards for logging.
    for row in db().select(db.Cards.Name, db.Cards.Quantity):
        if row.Name not in newCards and row.Quantity != 0: # Card has been cut
            db(db.Cards.Name == row.Name).update(Quantity = 0)
            cut_cards += row.Quantity
        else:
            added_cards -= row.Quantity
            # This subtracts out the existing records' quantities. The total
            # number of added cards is the sum of this (negative or 0) and the
            # update_or_insert quantity sum in step 3.

    log.warning("Cutting %s cards...", cut_cards)

    # Step 3

    for cardname in newCards:
        db.Cards.update_or_insert(db.Cards.Name == cardname, Name = cardname,
                                  Quantity = newCards[cardname])
        added_cards += newCards[cardname]

    log.warning("Adding %s cards...", added_cards)

    db.commit()

    return
Beispiel #3
0
    def on_game_log(self, gameId):
        """Return parsed game log for game with id=gameId.

        Args:
          gameId (int): ID of target game.

        Returns:
          dict: Prepared game log data.

        """
        gameData = db(db.Games.id == gameId).select().first()
        events = db(db.Events.game_id == gameId).select()
        return parseLog.prepare(gameData, events)
Beispiel #4
0
    def on_log_list(self):
        """Retrieve list of available game logs.

        Returns:
          list: Each list item is a dict with keys (name, id).

        """
        return db(db.Games.id > 0).select().as_list()
Beispiel #5
0
	def get_user_feed(self, user_id):
		return db().query(	'select '
					'(select name from user where id=actor_user_id) as actor, '
					'(select name from user where id=target_user_id) as target, '
					'amount, note '
					'from user_payment p '
					'where actor_user_id=$user_id or target_user_id=$user_id', 
				{'user_id': user_id}) 
Beispiel #6
0
def get_current_ratings():
    '''Return a dict with a key for each active cardname, and values of tuples
    like (mu, sigma).'''
    active_cards_with_ratings = db(db.Cards.Quantity > 0).select(db.Cards.Name,
        db.Transactions.mu.coalesce(DEFAULT_MU).with_alias('mu'),
        db.Transactions.sigma.coalesce(DEFAULT_SIGMA).with_alias('sigma'),
        left=db.Transactions.on(db.Cards.id == db.Transactions.card_id),
        orderby=db.Transactions.timestamp)

    # Only retains most recent timestamp due to select being ordered by same
    acwrdict = {row['Cards.Name']:(row['mu'], row['sigma'])
                for row in active_cards_with_ratings}
    return acwrdict
Beispiel #7
0
 def delete(self, __id):
     db().delete(self.className, where="id=$id", vars={"id": __id})
Beispiel #8
0
 def update(self, __id, **kwargs):
     if "id" in kwargs:
         del kwargs["id"]
     db().update(self.className, where="id=$id", vars={"id": __id}, **kwargs)
Beispiel #9
0
 def get_by_user_id(self, user_id):
     ret = db().select(self.className, {"user_id": user_id}, where="user_id=$user_id")
     return single_result(ret)
Beispiel #10
0
 def load(self, __id):
     ret = db().select(self.className, where="id=$id", vars={"id": __id})
     return single_result(ret)
Beispiel #11
0
 def list(self):
     return db().select(self.className, order="id DESC")
Beispiel #12
0
async def run(logger):
    logger.debug("Loading settings from file...")
    config = load_config()
    logger.debug("Loaded settings from file!")
    token = config['token']
    intents = discord.Intents.default()
    intents.members = True
    logger.debug("Checking version...")
    #figure out what we're logging in as
    tokenfilename, database, ver = get_release_level()
    logger.debug(f"Logging in as '{ver}'")
    if ver == 'stable':
        if config['owner_id'] == "538193752913608704" and (
                os.path.exists('devtoken.txt')
                or os.path.exists('betatoken.txt')
        ) and not "--nologin" in sys.argv:
            print(
                "You're attempting to start the production version of Maximilian when you have other versions available.\nAre you sure you want to do this? \nIf you're certain this won't break anything, enter 'Yes, do as I say!' below.\n"
            )
            if input() == "Yes, do as I say!":
                print("\nOk, starting Maximilian.\n")
                await asyncio.sleep(1)
            else:
                print("You need to type 'Yes, do as I say!' exactly as shown.")
                os._exit(5)
        commit = ''
    else:
        token = common.token().get(tokenfilename)
        logger.debug("Getting latest commit hash...")
        commit = get_latest_commit()
        logger.debug("Done getting latest commit hash.")
    logger.debug("Setting up some stuff")
    bot = commands.Bot(
        command_prefix=core.get_prefix,
        owner_id=int(config['owner_id']),
        intents=intents,
        activity=discord.Activity(
            type=discord.ActivityType.playing,
            name=f" v0.6.2{f'-{commit}' if commit else ''} ({ver})"))
    #set up some important stuff
    bot.database = database
    bot.logger = logger
    if parse_version(discord.__version__).major < 2:
        bot.logger.debug("using dpy 1.x")
        bot.IS_DPY_2 = False
    else:
        bot.IS_DPY_2 = True
        bot.logger.debug("using dpy 2.x")
        bot.logger.warning(
            "It looks like Maximilian is using discord.py 2.x. Use of dpy2 is not recommended for now due to some serious bugs."
        )
        await asyncio.sleep(1)
    try:
        #experimental i18n, not used at the moment
        #initialize_i18n(bot)
        pass
    except:
        if '--i18n-errors' in sys.argv:
            traceback.print_exc()
        logger.critical(
            'i18n initialization failed! Does the translation file exist?')
        os._exit(53)
    await wrap_event(bot)
    #show version information
    bot.logger.warning(
        f"Starting maximilian-{ver} v0.6.2{f'-{commit}' if commit else ''}{' with Jishaku enabled ' if '--enablejsk' in sys.argv else ' '}(running on Python {sys.version_info.major}.{sys.version_info.minor} and discord.py {discord.__version__}) "
    )
    #parse additional arguments (ip, enablejsk, noload)
    bot.noload = []
    bot.logger.debug("Parsing command line arguments...")
    parse_arguments(bot, sys.argv)
    bot.logger.debug("Done parsing command line arguments.")
    bot.guildlist = []
    bot.prefixes = {}
    bot.responses = []
    bot.start_time = time.time()
    bot.dbinst = common.db(bot, config['dbp'])
    bot.logger.debug("Done setting up stuff.")
    #try to connect to database, exit if it fails
    bot.logger.info(
        f"Attempting to connect to database '{bot.database}' on '{bot.dbip}'..."
    )
    try:
        bot.dbinst.connect(bot.database)
        bot.logger.info("Connected to database successfully.")
        bot.dbdisabled = False
    except pymysql.err.OperationalError:
        bot.logger.critical(
            f"Couldn't connect to database! \nMaybe try running setup.sh again?"
        )
        os._exit(96)
    #make sure all tables exist
    try:
        bot.dbinst.ensure_tables()
    except pymysql.OperationalError:
        bot.logger.error(
            "Unable to create one or more tables! Does `maximilianbot` not have the CREATE permission?"
        )
    #now that we've got most stuff set up, load extensions
    load_extensions(bot)
    #and log in
    print("Logging in...")
    if not "--nologin" in sys.argv:
        await bot.start(token)
Beispiel #13
0
#	(at your option) any later version.
#
#	Meters is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with meters.  If not, see <http://www.gnu.org/licenses/>.

import time
import flask
import common
import sys

db = common.db()
readings_collection = db.database.readings
deleted_collection = db.database.deleted_readings
app = flask.Flask(__name__)


@app.route("/get")
def get():
    start_date, end_date, message = common.get_dates(flask.request.args)
    if message:
        return common.format_error(message)
    day_query = {"date": {"$gte": start_date, "$lte": end_date}}
    return common.format_success(
        list(
            readings_collection.find(
                {
Beispiel #14
0
 def load_by_card_number(self, card_number):
     ret = db().select(self.className, {"card_number": card_number}, where="card_number=$card_number")
     return single_result(ret)
Beispiel #15
0
vrms = 1
fs = 50
f1 = 5
f2 = 20
ns = 100
nrep = 1

u, t = forcing.randomPeriodic(vrms, fs, f1, f2, ns, nrep)

npt.assert_allclose(np.linalg.norm(t), 11.6335721083)
npt.assert_allclose(np.linalg.norm(u), 10.0498756211)

U = np.fft.fft(u)
idx = len(U) // 2

U_plot = db(np.abs(U[0:idx]))
freq = np.fft.fftfreq(len(U), d=1 / fs)
freq = freq[0:idx]

fig1 = plt.figure()
plt.clf()
plt.plot(freq, U_plot, '*k')
plt.axvline(f1, color='k', linestyle='--')
plt.axvline(f2, color='k', linestyle='--')
plt.title('Frequency content for randomPeriodic signal')
plt.xlabel('Frequency (Hz)')
plt.ylabel('FFT basis periodic random (dB)')
plt.grid()

amp = 1
fs = 100
Beispiel #16
0
        def load_by_username(self, username):
		ret = db().select(self.className, {'username': username}, where="username=$username")
		return single_result(ret)
Beispiel #17
0
 def new(self, **kwargs):
     if "id" in kwargs:
         del kwargs["id"]
     return db().insert(self.className, **kwargs)