content
stringlengths
0
894k
type
stringclasses
2 values
import time import re import argparse import os import yaml def get_arg_parser(): parser = argparse.ArgumentParser() parser.add_argument('--log_dir', help='Full path of log directory', required=False, default='./') return...
python
# Run these tests from ipython in the main package directory: # `run tests\python_example_package_tests.py` import unittest import python_example_package class TestAdd(unittest.TestCase): def test_basic(self): print "I RAN!" def test_add(self): self.assertEqual( python_ex...
python
from time import localtime activities = {8: 'Sleeping', 9: 'Commuting', 17: 'Working', 18: 'Commuting', 20: 'Eating', 22: 'Resting' } time_now = localtime() hour = time_now.tm_hour for activity_time in sorted(activities.keys()): if hour < acti...
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
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import xmltodict from wechatpy.enterprise.events import EVENT_TYPES from wechatpy.enterprise.messages import MESSAGE_TYPES from wechatpy.messages import UnknownMessage from wechatpy.utils import to_text def parse_message(xml): if n...
python
"""Predict a flower name from an image using a trained model. Returns the flower name and class probability. """ import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from workspace_utils import active_session import logging impo...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2017 theloop, 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 req...
python
""" The viewer is just a frameset that loads a menu and a folder. """ def generateHtml(pathUrl): html = f"""<html> <head><title>ABF Browser</title></head> <frameset cols='300px,100%' border='5'> <frame name='menu' src='/ABFmenu/{pathUrl}' frameborder='0' /> <frame name='content' src='/ABFexperiment/{pathUr...
python
# Copyright (c) 2020 Attila Gobi # SPDX-License-Identifier: BSD-3-Clause """ Solution for https://adventofcode.com/2020/day/4 >>> passports = parse("day04/test.txt") >>> solve1(passports) 2 >>> solve2(passports) 2 """ import sys import re def parse(fn): ret = [] current = {} with open(fn, "rt") as f: ...
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from enum import Enum __all__ = [ 'ConnectionAliasAssociationAssociationStatus', 'ConnectionAliasState', ] class ConnectionAliasAssociationA...
python
import itertools from aoc_cqkh42 import BaseSolution class Solution(BaseSolution): def part_a(self): self.sequence(40) return len(self.data) def part_b(self): self.sequence(10) return len(self.data) def iteration(self): g = itertools.groupby(self.data) d ...
python
from os import path from setuptools import setup # read the contents of your README file this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='football-data-connector', version='0.9.1', ...
python
'''File contains the trainer class Complete the functions train() which will train the network given the dataset and hyperparams, and the function __init__ to set your network topology for each dataset ''' import numpy as np import sys import pickle import nn from util import * from layers import * class Trainer: ...
python
#!/usr/bin/python class FilterModule(object): def filters(self): return { 'amend_list_items': self.amend_list_items } def amend_list_items(self, orig_list, prefix="", postfix=""): return list(map(lambda listelement: prefix + str(listelement) + postfix...
python
from django import template from django.utils.translation import gettext as _ register = template.Library() @register.simple_tag def pagetitle(title, **kwargs): if "page" in kwargs and kwargs["page"] > 1: title += " (%s)" % (_("page: %(page)s") % {"page": kwargs["page"]}) if "parent" in kwargs: ...
python
from pydantic.class_validators import root_validator from pydantic.main import BaseModel from .types import TopicID class InputTopic(BaseModel): default: str @root_validator def check_lang(cls, obj): default_lang = obj["default"] if default_lang == "default" or default_lang not in obj: ...
python
import os, datetime import pandas as pd from download.box import LifespanBox import sys verbose = True #verbose = False snapshotdate = datetime.datetime.today().strftime('%m_%d_%Y') #Two types of files to curate...the so called raw data from which scores are generated and the scores themeselves. #connect to Box (to...
python
# !/usr/bin/env python3 # coding=utf-8 import sys import argparse import os import struct parser = argparse.ArgumentParser(description='Cisco VxWorks firmware extractor') parser.add_argument('-i', '--input-firmware-path', metavar='input_firmware_path', help...
python
from discord import File from discord.ext import commands from shavatar import generate from src.internal.bot import Bot from src.internal.context import Context class Avatar(commands.Cog): """Generate an avatar with SHAvatar.""" def __init__(self, bot: Bot): self.bot = bot @commands.command(na...
python
import pathlib from os import listdir from __utils import * import pandas as pd import pandas as pd from math import floor from time import time # This is a wrapper script for analysis of predictions produced in stage 2-model # # Arguments: # REGION name of region # PRED_DIR path ...
python
from gna.configurator import NestedDict from gna.expression.preparse import open_fcn from gna.expression.operation import * from gna.env import env import re import inspect class VTContainer_v01(OrderedDict): _order=None def __init__(self, *args, **kwargs): super(VTContainer_v01, self).__init__(*args,...
python
import time from print_running_function import print_running_function # Hackish method to import from another directory # Useful while xendit-python isn't released yet to the public import importlib.machinery loader = importlib.machinery.SourceFileLoader("xendit", "../xendit/__init__.py") xendit = loader.lo...
python
command = input() all_students = {} while command[0].isupper(): command = command.split(":") key = command[2] value = command[0] + " - " + command[1] all_students.setdefault(key, []).append(value) command = input() searched_course = command.replace("_", " ") print("\n".join(all_students[searched...
python
import sys import random n = int(sys.argv[1]) k = n+n*(n+1)//2 # 10**5 # print('%d %d'%(n, k)) for i in range(n): print ('A %d %d'%(i+1, random.randint(10**8,10**9))) k -= 1 for i in range(n): for j in range(i, n): print('Q %d %d'%(i+1, j+1)) k -= 1 if k <= 1: break if k <= 1: ...
python
import subprocess from flask import Flask, redirect, url_for, request, render_template app = Flask(__name__) @app.route('/') def hello_world(): # put application's code here return render_template("index.html") @app.route('/success/<command>') def success(command): return subprocess.Popen(command, shell=...
python
# coding: utf-8 from models.models import Group from models.models import Person from random import randrange def test_edit_group_name(app): if app.object.count_group() == 0: app.object.create_group_form(Group(name="test")) old_groups = app.object.get_group_list() index = randrange(len(old_groups...
python
import numpy as np import matplotlib.pyplot as plt import spams import cv2 # %load_ext autoreload # %autoreload 2 # %matplotlib inline from pathlib import Path import os import sys import random import warnings import pandas as pd from tqdm import tqdm from itertools import chain import math from vahadane import vaha...
python
from .models import ThingDescription, DirectoryNameToURL, TargetToChildName, TypeToChildrenNames, DynamicAttributes from flask_pymongo import PyMongo mongo = PyMongo() def clear_database() -> None: """Drop collections in the mongodb database in order to initialize it. """ ThingDescription.drop_collec...
python
### channel configuration CHANNEL_NAME = 'ThreatWire' CHANNEL_PLAYLIST_ID = 'PLW5y1tjAOzI0Sx4UU2fncEwQ9BQLr5Vlu' ITEMS_TO_SCAN = 5 FG_YOUTUBE = 'https://www.youtube.com/channel/UC3s0BtrBJpwNDaflRSoiieQ' # channel link FG_AUTHOR = {'name':'Shannon Morse','email':'shannon@hak5.org'} ### data storage and history ITEMS...
python
import cv2 import numpy as np import core.image as im import core.hc_extender as hc_ext import matplotlib.pyplot as plt from drawnow import drawnow def trans(img, hcc): ''' trans(img, hcc): 2D to 1D Transformed by Hilbert Curve img <-- nxn matrix hcc <-- Hibert curve coordinat...
python
"""Base OAuthBackend with token and session validators.""" from typing import List, Optional from fastapi.security import OAuth2 from starlette.authentication import AuthCredentials, AuthenticationBackend, UnauthenticatedUser from starlette.requests import Request from fastapi_aad_auth._base.state import Authenticati...
python
""" Hello World """ from .agents import * from .app import * from .core import * from .renderers import * from .sims import * from .simulation import * from .styles import * from .sys import *
python
from asmpatch.batchbuilder import BatchBuilder from asmpatch.util import TemporyFolderBuilder import os os.makedirs("./build", exist_ok=True) import subprocess #TODO: cache, autofind, config file batch = BatchBuilder() batch.set_end_offset(int("805954bc", 16)) #TODO: auto find end offset via elf file. Also auto ad...
python
import unittest from jpake.tests import test_jpake from jpake.tests import test_parameters loader = unittest.TestLoader() suite = unittest.TestSuite(( loader.loadTestsFromModule(test_jpake), loader.loadTestsFromModule(test_parameters), ))
python
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from tensorflow.python.framework import graph_util from tensorflow.python.platform import gfile tf.logging.set_verbosity(tf.logging.ERROR) mnist = input_data.read_data_sets("./MNIST_data/", one_hot=True) learning_rate = 0.001 trai...
python
from pathlib import Path from mmvae_hub.utils.setup.flags_utils import BaseFlagsSetup from mmvae_hub.base.BaseFlags import parser as parser # DATASET NAME parser.add_argument('--exp_str_prefix', type=str, default='mnistsvhntext', help="prefix of the experiment directory.") # DATA DEPENDENT # to be set by experiment...
python
from .. import db, flask_bcrypt class Company(db.Model): """User Model for storing user related details""" __tablename__ = "companies" id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(255), unique=False, nullable=False) address = db.Column(db.String(255...
python
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
python
import pytest pytestmark = [pytest.mark.django_db] def test_item(stripe): result = stripe.get_items() assert result == [ { 'price_data': { 'currency': 'usd', 'product_data': { 'name': 'Cutting and Sewing', }, ...
python
from .simple_spread.simple_spread import env, parallel_env, raw_env # noqa: F401
python
import csv import numpy as np from os.path import join from os.path import dirname def load_synthetic(data_file_name): """ This is almost completely stolen from sklearn! Loads data from data/data_file_name. Parameters ---------- data_file_name : String. Name of csv file to be loaded from ...
python
''' @package: pyAudioLex @author: Jim Schwoebel @module: ls_freq #ls = list item marker ''' from nltk.tokenize import word_tokenize from nltk.tag import pos_tag, map_tag from collections import Counter def ls_freq(importtext): text=word_tokenize(importtext) tokens=nltk.pos_tag(text) c=Counter(token for ...
python
#!/usr/bin/python # Copyright 2017 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 agr...
python
#Genre Year #Comparison of movie genres to year. By Bradley Brian #imports import matplotlib.pyplot as plt import pandas as pd import numpy as np #data = pd.read_csv('movies_initial.csv') #Function def genreselect(): print('------Please Select a genre------') print("") print("[1] Action") print("[2] Advent...
python
import logging from optparse import make_option from django.core.management.base import NoArgsCommand from django.db import connection from mailer.models import Message class Command(NoArgsCommand): help = "Attempt to resend any deferred mail." base_options = ( make_option('-c', '--cron', default=0,...
python
"""Import all hardware interfaces""" from .gpio_implementations import * from .hardware_interfaces import * from .hpwm_implementations import * from .i2c_implementations import * from .spi_implementations import *
python
class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) == 1: return True jump = 0 current_bound = next_bound = nums[0] i = 1 while True: jump += 1 if curren...
python
#!/usr/bin/env python3 import os import requests, shutil, socket from datetime import datetime, timedelta from time import sleep from pathlib import Path import localconfig from camera import Camera from common import fmt_bytes, get_data_from_pic_stem, get_score class Task: def is_due(self, dt0, dt1): ""...
python
"""Support for P2000 sensors.""" import datetime import logging import feedparser import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_ICON, CONF_LATITUDE, CONF_LONGITUDE, ...
python
# used for testing """ get the coordinates of cards and marks used to get the range for function mark_crd() check whether the calculation is correct change some parameters in "card.py" "anti.py" if necessary Check line 40 and 41, annotate line 37 if you would like test the image from your phone, if you only want to te...
python
from torchctr.datasets.criteo import get_criteo # step 1: download dataset get_criteo('datasets') # step 2: read data
python
''' | Filename : util_lstm_seqlabel.py | Description : Utility functions for the lstm_seqlabel.py file. | Author : Pushpendre Rastogi | Created : Mon Oct 26 20:01:22 2015 (-0400) | Last-Updated: Wed Dec 16 03:49:16 2015 (-0500) | By: Pushpendre Rastogi | Update #: 44 ''' import collections imp...
python
"""Implementation of Eiger Meta Writer This module is a subclass of the odin_data MetaWriter and handles Eiger specific meta messages, writing them to disk. Matt Taylor, Diamond Light Source """ import numpy as np import time import re import ast from odin_data.meta_writer.meta_writer import MetaWriter import _versi...
python
import os def join_muspath(name: str): return os.path.join("assets", "audio", "music", name) menu1 = join_muspath("menu1.ogg") menu2 = join_muspath("menu2.ogg") piano1 = join_muspath("piano1.ogg") MENU = [menu1, menu2, piano1]
python
from unittest import TestCase from . import db_conn, es_conn, APP_DIR, DATABASE_URL from .queries import CREATE_TEST_TABLE, DROP_TEST_TABLE from .writer import Writer from .scanner import Scanner import os import subprocess import time from importlib import import_module from click.testing import CliRunner from .comman...
python
""" ******************************************************************************** pyconmech ******************************************************************************** .. currentmodule:: pyconmech This library provides python wrappers for efficient evaluation of construction mechanics. .. toctree:: :maxd...
python
from src.utils.general import pd_utils from datetime import date import logging import pandas as pd pd.set_option('display.width', None) class LCReviewer: """ LC Reviewer help review LC """ def __init__(self): self.df = pd_utils.pd_read_csv('../../data/files/lc_record.csv') self.revie...
python
from localground.apps.site.api import serializers from localground.apps.site import models from localground.apps.site.api.views.abstract_views import \ MediaList, MediaInstance class MapImageList(MediaList): ext_whitelist = ['jpg', 'jpeg', 'gif', 'png'] serializer_class = serializers.MapImageSerializerCre...
python
import pytest from rasa.shared.nlu.training_data import util from rasa.nlu.config import RasaNLUModelConfig import rasa.shared.nlu.training_data.loading from rasa.nlu.train import Trainer, Interpreter from rasa.utils.tensorflow.constants import ( EPOCHS, MASKED_LM, NUM_TRANSFORMER_LAYERS, TRANSFORMER_S...
python
"""Define _TSP Models Time Series Predictions (TSPs) are attempt to predict what will happen based on what has happened before. While there are a plethora of ways to do this, the teaspoon module foucsses on using the last few observations to predict the next and mechanisms to combine several of these predictions. """ ...
python
class AccessDeniedError(Exception): pass
python
#!/usr/bin/env python3 import numpy as np import json, logging import pylab as plt from frbpa.utils import get_phase, get_params logging_format = '%(asctime)s - %(funcName)s -%(name)s - %(levelname)s - %(message)s' logging.basicConfig(level=logging.INFO, format=logging_format) def make_obs_phase_plot(data_json, perio...
python
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer from RecoMuon.TrackingTools.MuonServiceProxy_cff import MuonServiceProxy from DQMOffline.Muon.gemEfficiencyAnalyzerCosmicsDefault_cfi import gemEfficiencyAnalyzerCosmicsDefault as _gemEfficiencyAnalyzerCosmicsDefault gemE...
python
# -*- coding: utf-8 -*- """ This module implements various utilities for WSGI applications. Most of them are used by the request and response wrappers but especially for middleware development it makes sense to use them without the wrappers. """ import re import os import sys import pkgutil from ._compat i...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2021 Alibaba Group Holding Ltd. # # 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-...
python
import pandas as pd from bokeh.models import ColumnDataSource from bokeh.models import TableColumn, DataTable from .base import TableView from ..models import concurrent_requests class OverviewTable(TableView): def __init__(self, df, df_downloads): super().__init__(df) self.df_downloads = df_down...
python
import os import json from flask import Flask from flask_bootstrap import Bootstrap from oidc_rp.client import Client client_config = {} with open('../client.json', 'r') as f: client_config = json.loads(f.read()) client = Client(client_config) app = Flask(__name__) # SECRET_KEY ## Insert your secret key # To ge...
python
#!/usr/bin/python #------------------------------------------------------------------------------- #License GPL v3.0 #Author: Alexandre Manhaes Savio <alexsavio@gmail.com> #Grupo de Inteligencia Computational <www.ehu.es/ccwintco> #Universidad del Pais Vasco UPV/EHU #Use this at your own risk! #2012-07-26 #-----------...
python
import unittest from mock import Mock, patch import repstruct.dataset as dataset import repstruct.configuration as configuration class TestDataSet(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def __assertProperties(self, instance): t = type(instance) ...
python
# -*- coding: utf-8 -*- from django.db import models, migrations import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('heroes', '0001_initial'), ('actions', '0001_initial'), ] operations = [ migrations.AddField( model_name='metaa...
python
""" *Demon* The managers of the brain with a policy and foresight. They have the power to interpret fractums. """ from fractum import Fractum from abc import ABCMeta from dataclasses import dataclass @dataclass class Demon( Fractum, metaclass=ABCMeta, ): depth: int age: float gamma: ...
python
# -*- coding: utf-8; -*- # # Copyright (c) 2014 Georgi Valkov. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice...
python
""" Módulo que contêm as views de usuário """ from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm from core.funco...
python
#!/usr/bin/env python #-*- coding: utf-8 -*- from terminals import MTerminal from sys import argv """Summary of module 'launcher' here. This is a entry of entire laserjet program class Launcher launches 'Batch' task or 'Play' task depends on options. - Batch options (e.g.:'-exec', '-sync', '-fetch', '-in...
python
# -*- test-case-name: admin.test.test_packaging -*- # Copyright ClusterHQ Inc. See LICENSE file for details. """ Helper utilities for Flocker packaging. """ import platform import sys import os from subprocess import check_output, check_call, CalledProcessError, call from tempfile import mkdtemp from textwrap import...
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
python
#!/usr/bin/env python import getopt, getpass, os, subprocess, sys import github def _shell(cmd): print '$ {}'.format(cmd) subprocess.check_output(cmd, shell = True) print def main(args): username = None password = None fetchGists = False # Parse options opts, _ = getopt.getopt(args, 'gau:', ['gists', 'auth',...
python
"""CreateAnimalTable Migration.""" from masoniteorm.migrations import Migration class CreateAnimalTable(Migration): def up(self): """ Run the migrations. """ with self.schema.create("animals") as table: table.increments("id") table.string("name") ...
python
from typing import Dict, Any, Union import requests import logging from requests.exceptions import HTTPError, ConnectionError from zulip_bots.custom_exceptions import ConfigValidationError GIPHY_TRANSLATE_API = 'http://api.giphy.com/v1/gifs/translate' GIPHY_RANDOM_API = 'http://api.giphy.com/v1/gifs/random' class G...
python
import os import tbs.logger.log as logger import tbs.helper.filedescriptor as fd def checkRoot(message): """ Check if the user is root otherwise error out """ if os.geteuid() != 0: logger.log(message, logger.LOG_ERROR) raise Exception("You need root privileges to do this operation.") de...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ acq400.py interface to one acq400 appliance instance - enumerates all site services, available as uut.sX.knob - simple property interface allows natural "script-like" usage - eg:: uut1.s0.set_arm = 1 - equivalent to running this on a logged in shell session ...
python
import click import utils @click.command() @click.option('--test', '-t', default=None) def cli(test): if test is not None: data = test else: data = utils.load('day-5.txt') if __name__ == '__main__': cli()
python
# chat/routing.py from django.conf.urls import url from . import consumers websocket_urlpatterns = [ url(r'^ws/performance$', consumers.PerformanceConsumer), url(r'^ws/collect$', consumers.CollectionConsumer), ]
python
from django.core.files.base import ContentFile from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from s3file.middleware import S3FileMiddleware class TestS3FileMiddleware: def test_get_files_from_storage(self): content = b'test_get_files_...
python
from __future__ import annotations import uuid from enum import Enum, auto from io import StringIO from threading import Lock from typing import Dict, List, Optional, Sequence, Union import networkx as nx NODE_TYPES = {} class DuplicateKeyError(Exception): pass def register_node(node_subclass): """Decora...
python
from . import CommonViewsTestCase from .base import BaseAuthInfoViewsTestCase # Create your tests here. class AuthInfoViewsTestCase(CommonViewsTestCase): registered_user = { 'username': 'username_000', 'password': 'password_000', } base_action_test_case = BaseAuthInfoViewsTestCase # ...
python
from scrapy.exceptions import IgnoreRequest class TranslationResult(IgnoreRequest): """A translation response was received""" def __init__(self, response, *args, **kwargs): self.response = response super(TranslationResult, self).__init__(*args, **kwargs) class TranslationError(Exception): ...
python
import zutils class zbrick: def __init__(self): self.c = ' ' self.fcolor = zutils.CL_FG self.bcolor = zutils.CL_BG self.attr = 0 def str(self): return str(c) def copy_from(self, other): self.c = other.c self.fcolor = other.fcolor self.bcolor = other.bcolor self.attr = other.attr def equ...
python
# -*- coding: utf-8 -*- import base64 import os import tempfile from unittest import TestCase from test_apps import htauth_app HTPASSWD = 'test_user:$apr1$/W2gsTdJ$J5A3/jiOC/hph1Gcb.0yN/' class HTAuthAppTestCase(TestCase): def setUp(self): _, self.htpasswd_path = tempfile.mkstemp() f = open(sel...
python
import os from django.conf.urls import url from django.utils._os import upath here = os.path.dirname(upath(__file__)) urlpatterns = [ url(r'^custom_templates/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': os.path.join(here, 'custom_templates')}), ]
python
import gym import numpy as np import cv2 from collections import deque class Environment(object): def __init__(self, env_name, resized_width, resized_height, agent_history_length, replay_size, alpha, action_repeat=4): self._env = gym.make(env_name) self._width = resized_width ...
python
from collections import defaultdict from copy import deepcopy from geopy.geocoders import Nominatim import Util import twitter import json import time import string import stop_words geolocator = Nominatim() STOP_WORDS = stop_words.get_stop_words('english') api = twitter.Api(consumer_key='b170h2arKC4VoITriN5jIjFRN', ...
python
import pytest from pji.utils import duplicates @pytest.mark.unittest class TestUtilsCollection: def test_duplicates(self): assert duplicates([1, 2, 3]) == set() assert duplicates({1, 2, 3}) == set() assert duplicates((1, 2, 3)) == set() assert duplicates([1, 2, 3, 2, 3]) == {2, 3}...
python
# Copyright 2016 Andy Chu. 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 """ cmd_parse.py - Parse high level shell comman...
python
#import pandas as pd import plotly.express as px import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import covid countries = covid.getCountries() df = covid.getNewData() #print(df) external_stylesheets = ['https://codepen.io/chriddyp/pen/bW...
python
from django.contrib.auth.models import User from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils import timezone class Comment(models.Model): author = models.ForeignKey(User, null=True, related_n...
python
from setuptools import setup, find_packages classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Topic :: Software Development :: Build Tools", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", ] setup( name="koronavirus", pa...
python
import datetime import json from django.core.urlresolvers import resolve from django.test import TestCase from rest_framework.serializers import ValidationError from rest_framework.test import APITestCase from .models import Appointment from .serializers import DATE_ERROR_MESSAGE, TIME_ERROR_MESSAGE from .views impor...
python
# labvirus.py # BOJ 14502 # Book p.341 n, m = map(int, input().split()) data = [] tmp = [[0] * m for _ in range(n)] for _ in range(n): data.append(list(map(int, input().split()))) dx = (-1, 0, 1, 0) dy = (0, 1, 0, -1) res = 0 def dfs_virus(x, y): for i in range(4): nx = x + dx[i] ny = y...
python
import os import sys import click from modules import az, logging_util from modules.cli.args import Arguments from modules.cli.parser import Parser from modules.cli.validator import Validator from modules.entities.criteria import Criteria from modules.exceptions import AzException, NoArgsException @click.command()...
python