content
stringlengths
0
894k
type
stringclasses
2 values
""" stanCode Breakout Project Adapted from Eric Roberts's Breakout by Sonja Johnson-Yu, Kylie Jue, Nick Bowman, and Jerry Liao. YOUR DESCRIPTION HERE Click mouse to start the game. When no live is remained or all bricks are cleared, game is over. """ from campy.gui.events.timer import pause from breakoutgraphics impo...
python
#!/usr/bin/env python ''' jRAT Rat Config Decoder ''' __description__ = 'jRAT Rat Config Extractor' __author__ = 'Kevin Breen http://techanarchy.net http://malwareconfig.com' __version__ = '0.3' __date__ = '2015/04/03' #Standard Imports Go Here import os import sys from base64 import b64decode import string from zip...
python
import json import uuid from datetime import datetime from sqlalchemy.dialects.postgresql import UUID from app import db # person_team = db.Table( # "person_team", # db.Column( # "person_id", # UUID, # db.ForeignKey("person.id", ondelete="CASCADE"), # primary_key=True, # )...
python
#!/usr/bin/env python # # Code to build the catalogue cache # # Usage: python build_cache.py # from __future__ import print_function from sys import stdout __author__ = "Yu Feng and Martin White" __version__ = "1.0" __email__ = "yfeng1@berkeley.edu or mjwhite@lbl.gov" from imaginglss import DECALS import numpy from...
python
#Summe der Zahlen von 1 bis 5 summe=0 for i in [1,2,3,4,5]: summe=summe+i #Beginn eines Blocks print("Summe von 1 bis ", i,":",summe) #Ende eines Blocks print("Ende der Rechnung")
python
# -*- coding: utf-8 -*- """ Miscellaneous utilities and tools """ import errno import functools import keyword import logging import os import re import shutil import sys import traceback from contextlib import contextmanager from pathlib import Path from pkg_resources import parse_version from . import __version__ ...
python
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from odahuflow.sdk.models.base_model_ import Model from odahuflow.sdk.models import util class ExternalUrl(Model): """NOTE: This class is auto generated by the sw...
python
from bs4 import BeautifulSoup, SoupStrainer import re import requests import json strained = SoupStrainer('a', href=re.compile('saskatchewan.kijiji.ca/f.*QQ')) soup = BeautifulSoup(requests.get('http://saskatchewan.kijiji.ca').text) category_dict = {} for a in soup.findAll(strained): category_id = None category =...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import datetime from django.conf import settings from django.db import connection, DatabaseError, transaction import djang...
python
# src/chara/character.py import enum class C_type(enum.Enum): PLAYER = 0 NPC = 1 OPPONENT = 2 BOSS = 3 class Character(): def __init__(self,name,c_type): types = Character.__ty() self.name = name self.c_type = types[c_type] # temporary function def identity(self):...
python
from peewee import IntegerField, Model, CompositeKey, ForeignKeyField from data.db import database from data.user import User class Buddies(Model): buddy1 = ForeignKeyField(User, to_field="id") buddy2 = ForeignKeyField(User, to_field="id") class Meta: database = database primary_key = Com...
python
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
python
""" Financial Modeling Prep Model """ __docformat__ = "numpy" import pandas as pd import FundamentalAnalysis as fa from gamestonk_terminal import config_terminal as cfg def get_rating(ticker: str) -> pd.DataFrame: """Get ratings for a given ticker. [Source: Financial Modeling Prep] Parameters ----------...
python
#!/usr/bin/env python """tests for :mod:`online_pomdp_planning.mcts`""" from functools import partial from math import log, sqrt from typing import Dict import pytest from online_pomdp_planning.mcts import ( ActionNode, DeterministicNode, MuzeroInferenceOutput, ObservationNode, backprop_running_q...
python
from itertools import product import torch import dgl from dgl.data import citation_graph from dgl.contrib.data import load_data from dgl import DGLGraph from runtime.dgl.gcn import GCN, GCNSPMV from runtime.dgl.gat import GAT, GATSPMV from runtime.dgl.rgcn import RGCN, RGCNSPMV from runtime.dgl.train import train_ru...
python
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import threading from datetime import date, datetime, timedelta from psycopg2 import sql from odoo import api, fields, models, tools, SUPERUSER_ID from odoo.osv import expression from odoo.tools.translate...
python
import sys from schemas.input_conf import personal_info from settings.base_conf import KOBO_PERSONAL_INFO_CSV_MAP ''' json_structure - the json attributes that are to be extracted from the source json mapping_format - see oldcuris_elastic_map for an example. import it here input_format - default input of source json...
python
""" Test Metadata Tool """ from __future__ import unicode_literals, absolute_import from tmt.base import Tree __all__ = ["Tree"]
python
import os import matplotlib.pyplot as plt from typing import List, Union, Tuple, Dict import torch import pickle current_dir = os.path.dirname(os.path.realpath(__file__)) CATEGORY = List[Union[int, float]] RUN_STATS = Dict[str, Union[int, float]] def plot_score_and_acc_over_docs( dir_name: str, stats: List[Tu...
python
from molsysmt._private_tools.exceptions import * from molsysmt.forms.common_gets import * import numpy as np from molsysmt.molecular_system import molecular_system_components from molsysmt._private_tools.files_and_directories import tmp_filename form_name='file:dcd' is_form = { 'file:dcd':form_name } inf...
python
import mongolib class a(): def aa(self): a=mongolib.mongodb() a.log_collect(msg='1gaejiusfuadaifuagusuifhiau afdu gaudf uisg uagsi gaug asyaigasydg aug iug ') a.log_collect(msg='2') a.log_input() a.log_output() aaaa=a() aaaa.aa()
python
import inspect import operator import re from datetime import datetime from decimal import Decimal from enum import Enum from functools import reduce import pymongo from bson import ObjectId from pymongo.collection import Collection, ReturnDocument from pymongo.errors import CollectionInvalid from appkernel.configura...
python
# Generated by Django 3.0.11 on 2021-01-22 10:13 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('cars', '0001_initial'), ('users', '0002_auto_20210122_0713'), ...
python
import math N = int(input()) sqN = math.floor(math.sqrt(N)) yaku1 = 1 yaku2 = 1 for i in range(sqN, 0, -1): if N % i == 0: yaku1 = i yaku2 = N // i break print(yaku1+yaku2-2)
python
import asyncio import pytest import unittest from unittest.mock import MagicMock, patch from app import Application @pytest.mark.asyncio async def test_func1(): app = Application() func2_stub = MagicMock(return_value='future result!') func2_coro = asyncio.coroutine(func2_stub) async with patch.object...
python
#先引入后面分析、可视化等可能用到的库 import tushare as ts import pandas as pd import numpy as np import matplotlib.pyplot as plt from sqlalchemy import create_engine import psycopg2 #正常显示画图时出现的中文和负号 from pylab import mpl mpl.rcParams['font.sans-serif']=['SimHei'] mpl.rcParams['axes.unicode_minus']=False #设置token token = '7dc39867da...
python
# Copyright (c) 2019 leosocy. All rights reserved. # Use of this source code is governed by a MIT-style license # that can be found in the LICENSE file. import io import os from setuptools import setup import edcc # Package meta-data. NAME = "edcc" DESCRIPTION = "EDCC: An efficient and accurate algorithm for palmpr...
python
from toolkit.modules.make_follow_sets import follow_sets from toolkit.modules.make_first_sets import first_sets from toolkit.modules.grammar import is_terminal from tabulate import tabulate def parsing_table(pgrammar, fs, fls, error_recovery=True): """ Input: pgrammar: parsed grammar fs: first...
python
class MemcacheError(Exception): pass class MemcacheServerError(Exception): def __init__(self, server: str, message: str) -> None: self.server = server super().__init__(message)
python
watchdog_config = """ # SDSLabs Watchdog configuration START UsePAM yes PasswordAuthentication no AuthorizedKeysCommand /opt/watchdog/bin/watchdog auth -u %u -t %t -p %k AuthorizedKeysCommandUser root # SDSLabs Watchdog configuration END """ modified_options = [ 'AuthorizedKeysCommand', 'AuthorizedKeysCommandUser...
python
#!/usr/bin/env python #author mark_purcell@ie.ibm.com #NOTE: FOR GOFLEX OPERATIONS DONT CHANGE THE CONTENTS OF THIS FILE #REQUEST BUG FIXES OR ENHANCEMENTS AS NECESSARY class GoFlexMessageFormatter(): def __init__(self): pass def request_meter_data(self, meter, from_date, to_date): return {...
python
from .gradient_penalty import * from .wasserstain_div import *
python
# -*- coding: utf-8 -*- import sys from formalchemy import templates __doc__ = """ There is two configuration settings available in a global config object. - encoding: the global encoding used by FormAlchemy to deal with unicode. Default: utf-8 - engine: A valide :class:`~formalchemy.templates.TemplateEngine` - dat...
python
''' Copyright (c) 2021-2022 OVGU LIA Author: Harish Kumar Pakala This source code is licensed under the Apache License 2.0 (see LICENSE.txt). This source code may use other Open Source software components (see LICENSE.txt). ''' try: import queue as Queue except ImportError: import Queue as Queue class DataMan...
python
# Последовательность треугольных чисел образуется путем сложения натуральных чисел. К примеру, 7-ое треугольное число # равно 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. Первые десять треугольных чисел: # # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # # Перечислим делители первых семи треугольных чисел: # # 1: 1 # 3: 1, 3 # 6: 1,...
python
from django.conf import settings if settings.WITH_WQDB: from wq.db import rest from wq.db.patterns import serializers as patterns from .models import Note rest.router.register_model( Note, serializer=patterns.NaturalKeyModelSerializer, fields="__all__", )
python
# Introduction to Python # Structure of if statements """ if condition: Statements elif condition: Statements else: Statements """ #Grade of a student marks = 90 # No braces in Python, Indectation does the job if marks > 90: print("Grade O") elif marks > 80: print("Grade E") elif marks > 70: ...
python
class DeprecatedEnv(ImportError): pass
python
#!/usr/bin/env python # coding: utf-8 # ## Case Challenge Part I (Individual Assignment 1) # After three years serving customers across the San Francisco Bay Area, the executives at # Apprentice Chef have decided to take on an analytics project to better understand how much # revenue to expect from each customer withi...
python
from flocx_ui.api import schema from flocx_ui.api.utils import generic_provider_request as generic_request from flocx_ui.api.utils import validate_data_with def post(path, **kwargs): """An alias for generic_request with the type set to 'POST' :param path: A url path :param **kwargs: The keyword arguments ...
python
import bluesky.plan_stubs as bps import bluesky.plans as bp import bluesky.preprocessors as bpp import numpy as np import pytest from ophyd.sim import SynAxis, hw import nabs.plans as nbp from nabs.simulators import validate_plan hw = hw() class LimitedMotor(SynAxis): def check_value(self, value, **kwargs): ...
python
def test_list_devices(client): devices = client.devices() assert len(devices) > 0 assert any(map(lambda device: device.serial == "emulator-5554", devices)) def test_version(client): version = client.version() assert type(version) == int assert version != 0
python
import numpy as np from gutfit import model, parameterlist def matrix_diag3(d1,d2,d3): return np.array([[d1, 0.0, 0.0], [0.0, d2, 0.0], [0.0, 0.0, d3]]) # Generic Rotations # def matrix_rot23(th23): return np.array([[1.0, 0.0 , 0.0], [0.0, np.cos(th23), np.sin(th23)], ...
python
import argparse import json import logging import random import numpy as np import torch from decouple import config from tqdm import tqdm from GPT2.config import GPT2Config from GPT2.encoder import get_encoder from GPT2.model import GPT2LMHeadModel from GPT2.utils import load_weight # import os # import torch.nn....
python
# # PySNMP MIB module SUN-T300-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SUN-T300-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:04:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
python
# ****************************************************************************** # Copyright 2017-2018 Intel Corporation # # 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.apa...
python
def foo(): print "hello every body"
python
from relevanceai.base import _Base from relevanceai.api.endpoints.centroids import CentroidsClient class ClusterClient(_Base): def __init__(self, project, api_key): self.project = project self.api_key = api_key self.centroids = CentroidsClient(project=project, api_key=api_key) supe...
python
import requests import urllib from bs4 import BeautifulSoup from os import path, makedirs import wget class Crawler: """ Class for crawl by page ulr-like 'http(s)://page_path/page_name_{number}/ and download pictures """ def __init__(self, url_pattern, page_number, css_alt=None): self.url_patt...
python
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) # # 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 appli...
python
#!/usr/bin/env python3 # Povolene knihovny: copy, math # Import jakekoli jine knihovny neprojde vyhodnocovaci sluzbou. # To, ze jsou nejake knihovny povolene, neznamena, ze je nutne je pouzit. # IB002 Domaci uloha 9. # # V teto uloze se budeme zabyvat binarnimi vyhledavacimi stromy. # # V prvni casti bude Vasi uloho...
python
class Item: def __init__(self, name, tag, desc, intro): self.name = name self.tag = tag self.desc = desc self.intro = intro def __str__(self): return f"=> {self.name} - {self.desc}" def getItem(self, player): player.inventory.append(self) def getIntro(self): return self.intro # so t...
python
# pylint: skip-file
python
# Copyright 2020 Google LLC. 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 a...
python
import logging def get_logger(log_filename=None, module_name=__name__, level=logging.INFO): # select handler if log_filename is None: handler = logging.StreamHandler() elif type(log_filename) is str: handler = logging.FileHandler(log_filename, 'w') else: raise ValueError("log_f...
python
from view import View from tkinter import Tk class Controller: def __init__(self, model): self.model = model self.view = View(self.model.graph.width(), self.model.graph.height(), self.model.graph_path) def run(self): self.view.draw_mode...
python
#! /usr/bin/env python # -*- Mode: Python -*- # -*- coding: ascii -*- """ Dump layer name list layer containing the mesh """ import lwsdk __lwver__ = "11" class HistoryData(): def __init__(self): self.string = '' self.select_contains = False self.select_others = False class DumpLayerN...
python
# SPDX-License-Identifier: Apache-2.0 # # The OpenSearch Contributors require contributions made to # this file be licensed under the Apache-2.0 license or a # compatible open source license. import os import unittest from unittest.mock import Mock, call, patch from ci_workflow.ci_check_manifest_component import CiCh...
python
from plugins.adversary.app.operation.operation import Step, OPVar, OPHost, OPRat, OPSoftware from plugins.adversary.app.commands import * from plugins.adversary.app.custom import * class WebServerInstall(Step): """ Description: This step prepares the installation of a PHP webserver. Requi...
python
from django.apps import AppConfig from django.db.models.signals import post_save, post_delete from django.conf import settings class SyncConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'sync' def ready(self): try: from .signals import init_signals ...
python
# -*- coding: utf-8 -*- """Launch small HTTP server for TimeoutTest test case Should work with Python 2 and 3. """ import sys import time try: from SimpleHTTPServer import SimpleHTTPRequestHandler as RequestHandler except ImportError: from http.server import CGIHTTPRequestHandler as RequestHandler try: ...
python
""" PPO with tensorflow implementation The goal of RL is to find an optimal behavior strategy for the agent to obtain optimal rewards. The policy gradient methods target at modeling and optimizing the policy directly. The policy loss is defined as L = E [log pi (a|s)] * AF where, 'L' is the policy loss, 'E' is the...
python
#!/usr/bin/python # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "Licen...
python
import math as m import numpy as np from matplotlib import pyplot as plt from BDPoisson1D import dirichlet_non_linear_poisson_solver_amr from BDFunction1D import Function from BDFunction1D.Functional import Functional class TestFunction(Function): """ Some known differentiable function """ def evalu...
python
#!/usr/bin/env python import glob for name in glob.glob('dir/*'): print name
python
""" Image conversion functions. """ # Copyright (c) 2020 Ben Zimmer. All rights reserved. from typing import Tuple import numpy as np from PIL import Image # Some functions for colorizing single channel black and white image (PIL "L" mode) # or the alpha channels of text_scala output. # ~~~~ function from text_...
python
import pandas as pd def generate_train(playlists): # define category range cates = {'cat1': (10, 50), 'cat2': (10, 78), 'cat3': (10, 100), 'cat4': (40, 100), 'cat5': (40, 100), 'cat6': (40, 100),'cat7': (101, 250), 'cat8': (101, 250), 'cat9': (150, 250), 'cat10': (150, 250)} cat_pids = {} ...
python
''' Copyright (C) 2018 PyElo. 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, sublice...
python
# -*- coding: utf-8 -*- import unittest from gilded_rose import Item, GildedRose class GildedRoseTest(unittest.TestCase): def test_foo_quality_never_below_zero(self): items = [Item("foo", 0, 0)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEqual("foo", it...
python
#!/usr/bin/env python import gpt_2_simple as gpt2 import sys if len(sys.argv) > 1: prompt = sys.argv[1] else: prompt = "prompt: So, what's new around here?" print(prompt) sys.exit(1) sess = gpt2.start_tf_sess() gpt2.load_gpt2(sess) single_text = gpt2.generate( sess, return_as_list=True, ...
python
# Please refrain from specifying a micro version if possible. # --------------------------------------------------------------------------- # VERSION = (1, 1) # --------------------------------------------------------------------------- # def _get_version(vt): ...
python
# GUI Application automation and testing library # Copyright (C) 2006-2018 Mark Mc Mahon and Contributors # https://github.com/pywinauto/pywinauto/graphs/contributors # http://pywinauto.readthedocs.io/en/latest/credits.html # All rights reserved. # # Redistribution and use in source and binary forms, with or without # ...
python
# Make sure to have CoppeliaSim running, with followig scene loaded: # # scenes/messaging/ikMovementViaRemoteApi.ttt # # Do not launch simulation, then run this script from zmqRemoteApi import RemoteAPIClient print('Program started') client = RemoteAPIClient() sim = client.getObject('sim') tipHandle = sim.getObject...
python
import attr from .document import Document from .has_settings import HasSettings from .templated import Templated import exam_gen.util.logging as logging log = logging.new(__name__, level="DEBUG") @attr.s class GradeData(): points = attr.ib(default=None) children = attr.ib(factory=dict) comment = attr....
python
import sys def op(arg1, arg2): if (len(sys.argv) != 3): raise Exception("InputError: only numbers\n\n") if (arg1.isdigit() and arg2.isdigit()): arg1 = int(arg1) arg2 = int(arg2) else: raise Exception("InputError: only numbers\n\n") print("Sum: ", arg1 + arg2) print("Difference: ", arg1 - arg2) print("Pr...
python
def xprop(layout, data, prop, enabled=True, **kwargs): attrs = getattr(data.bl_rna, prop)[1] name = attrs.get('name', prop) lay = layout.row().split(percentage=0.33) lay.label(name + ':') lay = lay.row(align=True) lay_l = lay.row(align=True) lay_r = lay if not enabled: lay = lay....
python
#!/usr/bin/env python from distutils.core import setup setup(name='pyledsign', version='1.01', description='pyledsign - control led signs from python', author='Kerry Schwab', author_email='sales@brightsigns.com', url='http://www.python.org/tbd/', packages=['pyledsign'], )
python
from django.conf import settings from django.http import Http404 from django.shortcuts import redirect, render from .models import Link def redirect_(request, key): try: link = Link.find_by_key(key.lower()) except Link.DoesNotExist: raise Http404("Link does not exist.") return redirect(...
python
# Generated by Django 2.1 on 2018-08-08 04:35 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ] operations = [ migrations.CreateModel(...
python
"""Tests the DNC class implementation.""" import sonnet as snt import tensorflow as tf import unittest from numpy.testing import assert_array_equal from .. dnc import dnc def suite(): """Create testing suite for all tests in this module.""" suite = unittest.TestSuite() suite.addTest(DNCTest('test_const...
python
# Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ # Author : henrytine # Date : 2020-08-19 ##################################################################################################### # # Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tr...
python
import pymysql import urllib.request from bs4 import BeautifulSoup import requests def connectDatabase(): """Create database connection""" global db db = pymysql.connect(host='localhost', user='root', password='', db='vg_dapi', cursorclass=pymysql.cursors.DictCursor,charset='utf8')...
python
from mycroft import MycroftSkill, intent_file_handler class RoomBooking(MycroftSkill): def __init__(self): MycroftSkill.__init__(self) @intent_file_handler('booking.room.intent') def handle_booking_room(self, message): amount = message.data.get('amount') building = message.data.ge...
python
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class DialogEvent: def __init__(self, bubble: bool = False, name: str = "", value: object = None): self.bubble = bubble self.name = name self.value: object = value
python
import traceback from twisted.internet import reactor def stack(): print("The Python Stack.") traceback.print_stack() reactor.callWhenRunning(stack) reactor.run()
python
import os import sys import codecs import difflib sys.path.insert(0, os.path.dirname(__file__)) from logger import log def restore_file_case(text_file, orig_file, debug=False): text_io = codecs.open(text_file, 'r', encoding='utf8') orig_io = codecs.open(orig_file, 'r', encoding='utf8') for line in text...
python
"""Test for our weighted graph.""" # {'A': {'B': 7, 'C': 9}, 'B': {'D': 2, 'E': 4}, 'C': {'F':6}} """Test our graph implementation.""" import pytest from weighted_graph import Weighted @pytest.fixture def new_weighted_graph(): """Graph for testing.""" from weighted_graph import Weighted empty_graph = Weig...
python
import os.path from unittest import TestCase from pkg_resources import require, DistributionNotFound from subprocess import call from sys import platform, executable, exit from src.info import AppInfo try: REQUIRED = open(os.path.join(AppInfo.root_dir, "requirements.txt")).read() except Exception as e: raise E...
python
# Copyright The PyTorch Lightning team. # # 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 i...
python
#!/usr/bin/env python import discord import configparser from libs import raid_combat # Setup the config and Discord client config = configparser.RawConfigParser() config.read('config.conf') client = discord.Client() # create the dict of combat managers for each server combat_managers = {} @client.event async def ...
python
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = 'mykey' secretkey = 'mysecret' Driver = get_driver(Provider.AURORACOMPUTE) conn = Driver(key=apikey, secret=secretkey)
python
# Copyright 2019 Atalaya Tech, Inc. # 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, ...
python
# app/chats/forms.py
python
from django.views.generic import UpdateView, ListView import pyperclip from django.http import HttpResponse from django.template.loader import render_to_string from django.http.response import Http404 from django.shortcuts import render from .models import Image, Categories, Location # modal window settings class Moda...
python
from os import environ def assert_in(file, files_to_check): if file not in files_to_check: raise AssertionError("{} does not exist in the list".format(str(file))) return True def assert_in_env(check_list: list): for item in check_list: assert_in(item, environ.keys()) return True
python
from django.contrib import messages from django.shortcuts import redirect from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from misago.admin.views import generic from misago.users.forms.admin import RankForm from misago.users.models import Rank class RankAdmin(generic.AdminBase...
python
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
python
#!/usr/bin/python """ This work targets for emulating fog computing infrastructure and fog service and network evaluation. Original author Tzu-Chiao Yeh (@tz70s), 2017@National Taiwan University, Dependable Distributed System and Network Lab. Checkout the License for using, modifying and publishing. """ import docker...
python
# Generated by Django 3.2.4 on 2021-09-09 13:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("accounts", "0005_add_field_last_modified_20210621_1058"), ] operations = [ migrations.AddField( model_name="govdepartment", ...
python
# -*- coding: utf-8 -*- """Shared utility functions for interacting with the data model.""" import logging logger = logging.getLogger(__name__) import os from binascii import hexlify def generate_random_digest(num_bytes=28, urandom=None, to_hex=None): """Generates a random hash and returns the hex digest as a u...
python