code
stringlengths
1
199k
from merc.actor import Actor from merc.collision import Collision from merc.player import Player from pprint import pprint import sys import json import numpy import itertools from PIL import Image, ImageDraw, ImageColor class Game: NUM_TWEENS = 10 def __init__(self, data): """ `data` should contain the JSON outp...
"""Train ILSVRC2017 Data using homemade scripts.""" import cv2 import os import math import tensorflow as tf from multiprocessing import Process, Queue import os import sys FILE_DIR = os.path.dirname(__file__) sys.path.append(FILE_DIR + '/../') import config as cfg from img_dataset.ilsvrc2017_cls_multithread import ils...
import xml.sax import xml.sax.handler import types try: _StringTypes = [types.StringType, types.UnicodeType] except AttributeError: _StringTypes = [types.StringType] START_ELEMENT = "START_ELEMENT" END_ELEMENT = "END_ELEMENT" COMMENT = "COMMENT" START_DOCUMENT = "START_DOCUMENT" END_DOCUMENT = "END_DOCUMENT" PR...
from django.conf import settings IMAGE_URL = getattr(settings, 'AWARDS_IMAGE_URL', 'icons/awards/{slug}.png')
import unittest import random from gameboard.gameboard import Gameboard, Direction from gameboard.coordinate import Coordinate class TestBoard(unittest.TestCase): def setUp(self): self.board = Gameboard() def test_64_squares(self): self.assertEqual(len(self.board._squares),64) def test_index...
import sip sip.setapi('QVariant', 2) import math from PyQt4 import QtCore, QtGui, QtNetwork from lib.Point import Point from lib.tileOperations import * TDIM = 256 class LightMaps(QtGui.QWidget): def __init__(self, parent = None): super(LightMaps, self).__init__(parent) self.pressed = False ...
import logging from wtforms import Form, SelectField, SelectMultipleField, validators import savant.comparisons import savant.sets import savant.diffs class DiffForm(Form): diffs = SelectMultipleField('Diffs', [validators.Required()], choices=[]) class DiffNamingForm(DiffForm): action = SelectField('Action', [v...
""" IEEE 48-bit EUI (MAC address) logic. Supports numerous MAC string formats including Cisco's triple hextet as well as bare MACs containing no delimiters. """ import struct as _struct import re as _re try: from socket import AF_LINK except ImportError: AF_LINK = 48 from netaddr.core import AddrFormatError fro...
import random class Tree: def __init__(self, world, screen, x, y): self.world, self.pygame = world, world.pygame self.screen = screen model = random.choice(['tree.png', 'tree_1.png']) self.image = self.pygame.image.load("./images/houses/" + model) self.x, self.y = x, y de...
"""Integration with the Rachio Iro sprinkler system controller.""" from abc import abstractmethod from contextlib import suppress from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from home...
import os from twisted.trial import unittest from lisa.server.plugins.PluginManager import PluginManagerSingleton class LisaPluginTestCase(unittest.TestCase): def setUp(self): self.pluginManager = PluginManagerSingleton.get() def test_a_install_plugin_ok(self): answer = self.pluginManager.instal...
class Item(object): def __init__(self, uid, name, time): self._uid = uid self._name = name self._time = time @property def name(self): return self._name @property def uid(self): return self._uid def display(self, size): delta = size - len(self._nam...
from marshmallow import Schema, fields, post_load, EXCLUDE from ..resource import Resource from collections import namedtuple class Plan(Resource): """ https://dev.chartmogul.com/v1.0/reference#plans """ _path = "/plans{/uuid}" _root_key = 'plans' _many = namedtuple('Plans', [_root_key, "current...
import os import os.path from django.db import transaction from bibliotik import manage_bibliotik from bibliotik.models import BibliotikTransTorrent, BibliotikTorrent from home.models import LogEntry, DownloadLocation def sync_instance_db(instance): b_torrents = instance.get_b_torrents_by_hash() t_torrents = in...
"""change the edges in loopdaigram so that there are no names with colons (:) """ def replace_colon(s, replacewith='__'): """replace the colon with something""" return s.replace(":", replacewith) def clean_edges(arg): if isinstance(arg, basestring): # Python 3: isinstance(arg, str) return replace_co...
from utils import weighted_random_subreddit t_channel = '@pythondaily' subreddit = weighted_random_subreddit({ 'flask': 3, 'Python': 6, 'django': 4, 'MachineLearning': 1, 'djangolearning': 1, 'IPython': 5, 'pystats': 4, 'JupyterNotebooks': 3 }) def send_post(submission, r2t): info = ...
import numpy as np import astropy.units as u import astropy.coordinates as coord from astropy.coordinates import frame_transform_graph from astropy.coordinates.matrix_utilities import matrix_transpose __all__ = ["JhelumBonaca19"] class JhelumBonaca19(coord.BaseCoordinateFrame): """ A Heliocentric spherical coor...
import optparse class CLI: pass CLI.parser = optparse.OptionParser() CLI.parser.add_option("-q", "--queries", dest="queries", help="Queries csv file", metavar="FILE") CLI.parser.add_option("-l", "--logs", dest="logs", help="Path to log files containing directory", metavar="DIR") CLI.parser.add_option("-r", "--results...
import re from main import sc __author__ = 'minh' class Utils: def __init__(self): pass not_allowed_chars = '[\/*?"<>|\s\t]' numeric_regex = r"\A((\\-)?[0-9]{1,3}(,[0-9]{3})+(\\.[0-9]+)?)|((\\-)?[0-9]*\\.[0-9]+)|((\\-)?[0-9]+)|((\\-)?[0" \ r"-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?)\Z" ...
from avatar.templatetags.avatar_tags import avatar_url from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse from tastypie import fields from tastypie.resources import ModelResource from accounts.models import UserProfile from main.api.authentication i...
from csacompendium.indicators.models import ResearchOutcomeIndicator from csacompendium.utils.pagination import APILimitOffsetPagination from csacompendium.utils.permissions import IsOwnerOrReadOnly from csacompendium.utils.viewsutils import DetailViewUpdateDelete, get_http_request from rest_framework.filters import Dj...
""" Terrain module providing step overlapping data containers """ import threading world = threading.local() # pylint: disable=invalid-name def pick(func): """ Picks the given function and add it to the world object """ setattr(world, func.__name__, func) return func world.pick = pick
from goprocam import GoProCamera, constants gpCam = GoProCamera.GoPro() gpCam.downloadAll() gpCam.delete("all")
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "badguys.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from __future__ import print_function import sys import time import os import ctypes import threading if sys.version_info[0] >= 3: long = int unicode = str xrange = range class WinMM (object): def __init__ (self, prefix = ''): import ctypes.wintypes self.__winmm = ctypes.windll.winmm self.__mciSendString = se...
import sys file_name = sys.argv[1] with open(file_name) as open_file: for line in open_file.readlines(): a, b, n = map(int, line.split()) output = "" for i in xrange(1, n + 1): out = "" spacing = " " if i == 1: spacing = "" if i % a == 0: out += "F" if i % b == 0: out += "B" output ...
MYSQL_DB = 'edxapp' MYSQL_USER = 'root' MYSQL_PSWD = '' MONGO_DB = 'edxapp' MONGO_DISCUSSION_DB = 'cs_comments_service_development'
from __future__ import print_function import boto3 import time from botocore.exceptions import ClientError from datetime import datetime def get_unix_timestamp(): """ Generate a Unix timestamp string. """ d = datetime.now() t = time.mktime(d.timetuple()) return str(int(t)) def lambda_handler(eve...
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount.models import SocialApp, SocialToken import oauth2 as oauth import urllib, urllib2, json class TwitterAccount(P...
import json import os import consul import sys import time from alertaclient.api import Client CONSUL_HOST = os.environ.get('CONSUL_HOST', '127.0.0.1') CONSUL_PORT = int(os.environ.get('CONSUL_PORT', 8500)) client = consul.Consul(host=CONSUL_HOST, port=CONSUL_PORT, token=None, scheme='http', consistency='default', dc=N...
from enum import Enum class AccessKeyName(str, Enum): key1 = "key1" key2 = "key2" class CheckNameReason(str, Enum): unavailable = "Unavailable" invalid = "Invalid"
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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,...
from django.apps import AppConfig class TelegramBotConfig(AppConfig): name = 'frekenbot'
import mosek import sys def streamprinter(msg): sys.stdout.write (msg) sys.stdout.flush () if len(sys.argv) <= 1: print ("Missing argument, syntax is:") print (" simple inputfile [ solutionfile ]") else: # Create the mosek environment. env = mosek.Env () # Create a task object linked with ...
import cv2 import time import numpy as np MAX_TARGETS = 3 TOP = 0 BOTTOM = 1 LEFT = 0 RIGHT = 1 def __init_tracker(frame): running_average_image = np.float32(frame) running_average_in_display_color_depth = frame.copy() difference = frame.copy() last_target_count = 1 last_target_change_time = 0.0 ...
from django.contrib import admin from tsj.models import * admin.site.register(Company) admin.site.register(Resident) admin.site.register(House) admin.site.register(ServiceCompany) admin.site.register(MeterType) admin.site.register(MeterReadingHistory) admin.site.register(Employer) admin.site.register(Notification)
from __future__ import print_function import aaf import aaf.mob import aaf.define import aaf.iterator import aaf.dictionary import aaf.storage import aaf.component import aaf.util from aaf.util import AUID, MobID import unittest import os cur_dir = os.path.dirname(os.path.abspath(__file__)) sandbox = os.path.join(cur_d...
import hashlib from datetime import datetime from flask import request from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from . import db, login_manager @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(UserMixin...
from datetime import datetime, timedelta import time from openerp import pooler from openerp.osv import fields, osv from openerp.tools.translate import _ class is_api(osv.osv): _name = 'is_api' _description = u'Fonctions générales' def get_usagers_structure(self, cr, uid, structure_id, context=None): ...
import os import sys import pathlib import asyncio import logging import importlib import pyuavcan compiled_dsdl_dir = pathlib.Path(__file__).resolve().parent / ".demo_dsdl_compiled" sys.path.insert(0, str(compiled_dsdl_dir)) try: import sirius_cyber_corp # This is our vendor-specific root namespace. Custom data t...
import string from pyparsing import ( Literal, White, Word, alphanums, CharsNotIn, Forward, Group, SkipTo, Optional, OneOrMore, ZeroOrMore, pythonStyleComment) class Parser(object): left_bracket = Literal("{").suppress() right_bracket = Literal("}").suppress() semicolon = Literal(";").suppress() ...
from PyQt4.QtCore import Qt from PyQt4 import QtCore, QtGui class GetCoverTask(QtCore.QObject): coverLoaded = QtCore.pyqtSignal(QtGui.QImage) def __init__(self, coverPath): super(GetCoverTask, self).__init__() self._coverPath = coverPath def run(self): image = QtGui.QImage(self._cove...
import os import json import tensorflow as tf import numpy as np def load_data(taxonomy): data_list= list(filter(lambda x:x[-3:]=='npy', os.listdir(taxonomy))) result=[] for data_file in data_list: result.append(np.load('%s/%s' %(taxonomy, data_file))) if len(result)%1000== 0: print("%s: %d/%d" %(taxonomy, le...
import os STIR_ROOT = os.path.normpath(os.path.dirname(__file__)) STIR_APP = os.path.normpath(os.path.join(STIR_ROOT, "application")) STIR_LIB = os.path.normpath(os.path.join(STIR_ROOT, "library"))
import logging import socket from unipath import Path class BaseConfig(object): DEBUG = False TESTING = False LOG_LEVEL = logging.INFO SITE_ROOT = Path(__file__).absolute().parent STDNET_DB_URL = "redis://localhost:6379?db=0" GEOIP_DB_URL_IPV4 = "http://geolite.maxmind.com/download/geoip/databas...
from os.path import join, isfile from os import walk import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command def read_file(filename): with open(filename) as fp: return fp.read().strip() def read_requirements(filename): return [line.strip() for line i...
import functools from pluss.app import app from pluss.util.cache import Cache RATE_LIMIT_CACHE_KEY_TEMPLATE = 'pluss--remoteip--ratelimit--1--%s' def ratelimited(func): """Includes the wrapped handler in the global rate limiter (60 calls/min).""" @functools.wraps(func) def wrapper(*args, **kwargs): ...
from collections import OrderedDict from nicepy.utils import ljust_all, pretty_repr def get_failed_msg(compare_method, values, expected_values, names=None, expected_names=None): failed_list = [] names = names or map(str, range(len(values))) expected_names = expected_names or [''] * len(names) for value,...
""" Generate random MAC address Inspired by http://www.linux-kvm.com/sites/default/files/macgen.py """ from sys import argv import random DEFAULT_OUI = '00-16-3e' # Xensource, Inc. def random_mac(oui=None): """returns a random MAC address, with optional +oui+ override""" mac_parts = [oui or DEFAULT_OUI] fo...
from data import formats class Player(): def __init__(self, name, position, team, champion=''): self.name = name self.position = position self.team = team self.champion = champion def __str__(self): return formats.player.format(name=self.name, position=self.position, ...
""" Authentication, Authorization, Accouting @requires: U{B{I{gluon}} <http://web2py.com>} @copyright: (c) 2010-2012 Sahana Software Foundation @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Sof...
from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'todo/index.html')
from stard.services import BaseService class Service(BaseService): def init_service(self): self.children = {self.service('child')}
import sys import logging import time import subprocess import shlex import os import StringIO import tempfile from watchdog.observers import Observer from watchdog.events import FileCreatedEvent, RegexMatchingEventHandler class CreatedFilesHandler(RegexMatchingEventHandler): def on_created(self, event): if...
import sys import re if (len(sys.argv) != 2): print('Invalid number of arguments!') sys.exit() input_file = open(sys.argv[1]) puzzle_input = input_file.readlines() input_file.close() regex_happiness = re.compile(r'(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+).') happiness = {} possibili...
from datetime import date, time NO_TITLE = u"__NO_TITLE__" NO_AUTHOR_NAME = 'None' NO_CATEGORY_NAME = 'None' NON_EXISTENT_ARTICLE_TITLE = 'NON_EXISTENT' NO_DATE = date(1970, 01, 01) NO_TIME = time(0, 0) NO_URL = u"__NO_URL__" UNFINISHED_TAG = u"unfinished" GHOST_LINK_TAG = u"ghost link" GHOST_LINK_TITLE = u"__GHOST_LIN...
""" Mock object library for Python. Mock objects can be used when unit testing to remove a dependency on another production class. They are typically used when the dependency would either pull in lots of other classes, or significantly slow down the execution of the test. They are also used to create exceptional condit...
""" Paging capabilities for IPython.core Authors: * Brian Granger * Fernando Perez Notes ----- For now this uses ipapi, so it can't be in IPython.utils. If we can get rid of that dependency, we could move it there. ----- """ from __future__ import print_function import os import re import sys import tempfile from io i...
from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured import os FREEZE_ROOT = getattr(settings, 'FREEZE_ROOT', os.path.abspath(os.path.join(settings.MEDIA_ROOT, '../freeze/')) ) if not os.path.isabs(FREEZE_ROOT): raise ImproperlyConfigu...
from flask_restful import marshal_with, reqparse from flask import abort, g from flask import Blueprint as FlaskBlueprint from flask_restful import fields from sqlalchemy.orm.session import make_transient import logging import uuid from pebbles.models import db, BlueprintTemplate, Plugin from pebbles.forms import Bluep...
from ..workdays import * from datetime import datetime, timedelta from time import strptime import math import traceback tests=[] def test( fn ): tests.append(fn) return fn def runTests(): for t in tests: print t try: t() except Exception as e: print e traceba...
"""Team Password Manager API To simplify usage of Team Password Manager API. You can authenticate with username and password >>> import tpm >>> URL = "https://mypasswordmanager.example.com" >>> USER = 'MyUser' >>> PASS = 'Secret' >>> tpmconn = tpm.TpmApiv5(URL, username=USER, password=PASS) Or with ...
import ast import os import requests import models from config import config, sqla from gevent.pool import Pool from helpers import random_str, down base_path = config.get('photo', 'path') base_path = os.path.join(base_path, 'celebrity') cookies = { 'bid': '' } def create_down(str_urls, douban_id, category): ...
""" :module: watchdog.observers.inotify :synopsis: ``inotify(7)`` based emitter implementation. :author: Sebastien Martini <seb@dbzteam.org> :author: Luke McCarthy <luke@iogopro.co.uk> :author: yesudeep@google.com (Yesudeep Mangalapilly) :author: Tim Cuthbertson <tim+github@gfxmonk.net> :platforms: Linux 2.6.13+. .. AD...
from solution1 import multiplicationTable as f qa = [ (5, [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]), (2, [[1, 2], [2, 4]]), (4, [[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4,...
import time import serial import string import sys import mysql.connector from mysql.connector import errorcode, pooling from db import * import datetime import multiprocessing as mp from multiprocessing import Queue from multiprocessing.managers import SyncManager from os import system, devnull from subprocess import ...
import os from flask import current_app from flask.cli import FlaskGroup, run_command from opsy.db import db from opsy.app import create_app, create_scheduler from opsy.utils import load_plugins DEFAULT_CONFIG = '%s/opsy.ini' % os.path.abspath(os.path.curdir) def create_opsy_app(info): return create_app(config=os.e...
""" sprintkit.services ================== Implementations of most Developer Sandbox Services. :Copyright: (c) 2011 by Sprint. :License: MIT, see LICENSE for more details. """ from ConfigParser import SafeConfigParser from datetime import datetime from hashlib import md5 import json import os import time import urlparse...
import sys import os import cv2 import numpy as np class Detector: def detect(self, src): raise NotImplementedError("Every Detector must implement the detect method.") class SkinDetector(Detector): """ Implements common color thresholding rules for the RGB, YCrCb and HSV color space. The values ...
from datetime import datetime from django.test import TestCase from django.contrib.auth.models import User from apps.mountains.models import Mountain, Climb class ClimbTest(TestCase): def setUp(self): User.objects.create( username = "test_user", email = "test@testemail.com", ...
import os.path import pytest import abclinuxuapi from abclinuxuapi import shared @pytest.fixture def bp_url(): return "http://www.abclinuxu.cz/blog/bystroushaak/2015/2/bolest-proxy" @pytest.fixture def do_that_fucking_monkey_patch(monkeypatch): def mock_download(*args, **kwargs): fn = os.path.join(os.pa...
from django.conf.urls import url from .views import list_products app_name = "producto" urlpatterns = [ url(r'list-productos/$', list_products, name='list_products'), ]
import ClientAPI class AnimationState: # # Constructor # def __init__(self): assert False # # Property Getters # def _get_Time(self): return self._state.State.Time def __getattr__(self, attrname): if attrname in self._getters: return self._getters[...
from classes import wunderpy_wrapper from classes import grocerylist from classes import grocerystore wp = wunderpy_wrapper.wunderpy_wrapper('../data/tokens.csv') obj = wp.get_task_positions_obj(wp.WUNDERLIST_GROCERY) grocery_store = grocerystore.groceryStore('../data/store_order_zehrs.csv', '../data/ingredient_categor...
'''Test framework for pyglet. Reads details of components and capabilities from a requirements document, runs the appropriate unit tests. How to Run the Tests -------------------- :: python tests/test.py top app graphics clock resource # these all run automatically python tests/test.py font media text pyth...
"""A clone of the Music Player Daemon (MPD) that plays music from a Beets library. Attempts to implement a compatible protocol to allow use of the wide range of MPD clients. """ from __future__ import division, absolute_import, print_function import re from string import Template import traceback import random import t...
import sys def solve(): moveList = sys.stdin.read().strip() moves = {} houseGrid = [] houseGrid.append([1]) moves['^'] = [-1, 0] moves['v'] = [1, 0] moves['<'] = [0, -1] moves['>'] = [0, 1] santa = {} santa['x'] = 0 santa['y'] = 0 robo = {} robo['x'] = 0 robo['y'] = 0 santaList = [(0,0)] isSanta = True ...
from testUtils import Utils from Cluster import Cluster from WalletMgr import WalletMgr from TestHelper import TestHelper import random Print=Utils.Print errorExit=Utils.errorExit args=TestHelper.parse_args({"-p","-d","-s","-c","--kill-sig","--kill-count","--keep-logs" ,"--dump-error-details...
from pathlib import Path import numpy as np import xarray as xr import holoviews as hv from postladim import ParticleFile hv.extension("bokeh") tstep = 40 # Time step to show output_file = "line_hv.png" scale = 5 # Figure size factor ladim_dir = Path("../../") grid_file = ladim_dir / "examples/data/ocean_avg_0014.n...
import os import random import time from flask import Flask, request, render_template, session, flash, redirect, \ url_for, jsonify from flask.ext.mail import Mail, Message from flask.ext.sqlalchemy import SQLAlchemy from celery import Celery app = Flask(__name__) app.config['SECRET_KEY'] = 'top-secret!' app.config...
import re from jinja2 import Markup, escape, evalcontextfilter from app import app _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}') @app.template_filter('nl2br') @evalcontextfilter def nl2br(eval_ctx, value): result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') for p in _paragra...
import django_tables2 as tables from django_tables2 import RequestConfig from django_tables2.utils import A # alias for Accessor from django.shortcuts import render import inspect class DtTemplate(tables.Table): #name_first = tables.Column(verbose_name="First Name") #name_last = tables.LinkColumn('track:runn...
""" MultiQC modules base class, contains helper functions """ from __future__ import print_function from collections import OrderedDict import io import json import mimetypes import os import random import logging from multiqc import config logger = logging.getLogger(__name__) letters = 'abcdefghijklmnopqrstuvwxyz' cla...
import pyperclip import os import re import subprocess def get_extension(file_name): if file_name.find('.')!=-1: ext = file_name.split('.') return (ext[1]) else: return 'txt' def cut(str, len1): return str[len1 + 1:] #to remove first line which is meant for reading from which file d...
from Tkinter import * import Pmw class YasaraControl(Frame): """A yasara controller for comparison use""" def __init__(self, parent, yasara): Frame.__init__(self, parent, height=200,width=160) self.yasara = yasara c=Button(self,text='Align', command=self.align) c.grid(row=1,colum...
import numpy as np from model import GAN, discriminator_pixel, discriminator_image, discriminator_patch1, discriminator_patch2, generator, discriminator_dummy import utils import os from PIL import Image import argparse from keras import backend as K parser=argparse.ArgumentParser() parser.add_argument( '--ratio_ga...
from __future__ import unicode_literals class User(object): def __init__(self, app, id, name, adapter): self.app = app self.id = id self.name = name self.chat = adapter.create_chat_with(self.id) self.storage = app.get_storage('communication:{}:users:{}'.format( ad...
from __future__ import unicode_literals from django.db import models, migrations import django.contrib.auth.models import django.utils.timezone from django.conf import settings import django.core.validators import forum.models class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_co...
import os import sys import scandir import pymmh3 as mmh3 import misc def log_paths_dict(d, record_key = 'input', nest_depth = 1, sep = ':', cl_args_list = sys.argv): ''' Records contents of dictionary d at record_key on nest_depth. Assumes unnested elements of d follow human-name: file-pa...
from unittest import TestCase from nose.tools import eq_ from mock import Mock from datetime import datetime from tests.constants import STRING, NUMBER, DATE from tests.asserters import eq_obj from danmaku.cores.danmaku_process import generate_danmaku from danmaku.cores.danmaku_process import process_recieve_data from ...
from ..abstractdriver import AbstractDriver import numpy as np import os class FreeCADDriver(AbstractDriver): def __init__(self, debug=False): super(FreeCADDriver, self).__init__() self._debug = debug self._program_name = "FreeCAD" def get_program_name(self): return self._program...
import subprocess import praw import datetime import pyperclip from hashlib import sha1 from flask import Flask from flask import Response from flask import request from cStringIO import StringIO from base64 import b64encode from base64 import b64decode from ConfigParser import ConfigParser import OAuth2Util import os ...
""" By Simon Harms. Copyright 2015 Simon Harms, MIT LICENSE Name: Stack2 Summary: Stack Version 2 """ class Stack: """ Python Stack V2 with view and change. """ def __init__(self): """ Initialize the Stack. """ self.__storage = [] def is_empty(self): """ ...
from ritoapi.endpoints.match_v3 import MatchV3 import threading def _load_matches(match_v3, sample_region, sample_match_id, count): for i in range(count): data = match_v3.matches(sample_region, sample_match_id) assert(data['gameId'] == sample_match_id) def test_matches_stress(sample_api_key, sample_...
import os from conans.tools import unzip import shutil from conans.util.files import rmdir, mkdir from conans.client.remote_registry import RemoteRegistry from conans import tools from conans.errors import ConanException def _handle_remotes(registry_path, remote_file, output): registry = RemoteRegistry(registry_pat...
import unittest import mechanize from links import links class LinksTest(unittest.TestCase): """Test para 'links.py'""" def test_obtener_parametros_de_la_url(self): url_unlam = 'http://www.unlam.edu.ar/index.php' url_unlam_con_parametros = 'http://www.unlam.edu.ar/index.php?seccion=-1&accion=bus...
from .attribute import html_attribute from .element import VoidElement class Image(VoidElement): """An HTML image (<img>) element. Images must have an alternate text description that describes the contents of the image, if the image can not be displayed. In some cases the alternate text can be empty. Fo...
from django.db import models from botManager.models import Bot class Activist(models.Model): identifier = models.CharField(max_length=200) name = models.CharField(max_length=200) username = models.CharField(max_length=200) reg_date = models.DateTimeField('Date registered', auto_now_add=True) bot = m...
import os from pynsett.discourse import Discourse from pynsett.drt import Drs from pynsett.extractor import Extractor from pynsett.knowledge import Knowledge _path = os.path.dirname(__file__) text = "John Smith is not blond" drs = Drs.create_from_natural_language(text) drs.plot() print(drs)
from participantCollection import ParticipantCollection import string import re import datetime import pyperclip currentMonthTotalDays = 31 currentMonthURL = "https://www.reddit.com/r/pornfree/comments/5lefq1/stay_clean_january_this_thread_updated_daily/" currentMonthIndex = datetime.date.today().month currentMonthPenu...