content stringlengths 5 1.05M |
|---|
# Generated by Django 2.1.11 on 2020-02-18 19:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('qa', '0050_auto_20200131_1020'),
]
operations = [
migrations.AddField(
model_name='test',
name='wrap_high',
... |
class Solution:
def breakPalindrome(self, palindrome: str) -> str:
"""
:type palindrome: str
:rtype: str
"""
for i in range(len(palindrome)):
if palindrome[i] == 'a':
continue
if (i == int(len(palindrome) / 2)):
continue... |
import os
import sublime
from . import GitWindowCommand, git_root
class GitOpenConfigFileCommand(GitWindowCommand):
def run(self):
working_dir = git_root(self.get_working_dir())
config_file = os.path.join(working_dir, '.git/config')
if os.path.exists(config_file):
self.window.... |
# -*- coding: utf-8 -*-
__all__ = ["logger", "as_tensor_variable", "deprecation_warning", "deprecated"]
import logging
import warnings
from functools import wraps
from aesara_theano_fallback import aesara as theano
logger = logging.getLogger("exoplanet")
def as_tensor_variable(x, dtype="float64", **kwargs):
t... |
"""Begin Imports"""
# Internal imports
from package.package_manager import PackageManager
from package.package_manager import Package
from package.pacman_wrapper import invoke_pacman
# Python stdlib imports
import requests
"""End Imports"""
def send_aur_rpc(arguments):
aur_req = requests.get(f"https://aur.archl... |
def delete_duplicates(a_list):
"""This function recives a list, it returns a new list based on the
original list but without the duplicate elements of it"""
new_list = []
for i in a_list:
if not i in new_list:
new_list.append(i)
return new_list
def main():
print "Please, i... |
import unittest
from app.models import User
class TestUser(unittest.TestCase):
"""
Test class to test the behaviour of the User class
"""
def setUp(self):
"""
Set up method that will run before every test
"""
self.new_user = User(
username='nyambura',
... |
"""
此模块提供了异常类。
"""
__all__ = [
'Error',
'ApiNotAvailable',
'ApiError',
'HttpFailed',
'ActionFailed',
'NetworkError',
'TimingError',
]
class Error(Exception):
"""`aiocqhttp` 所有异常的基类。"""
pass
class ApiNotAvailable(Error):
"""OneBot API 不可用。"""
pass
class ApiError(Error, ... |
import unittest
from event_reporter import EventReporter
import fakeredis
import os
class EventReporterTest(unittest.TestCase):
def setUp(self):
self.conn = fakeredis.FakeStrictRedis()
self.conn.flushdb()
# override with your own UA to verify test results in GA
self.my_ua = os.get... |
import firebase_admin
import random
from firebase_admin import credentials
from firebase_admin import firestore
# Use a service account
cred = credentials.Certificate('db-service-account.json')
firebase_admin.initialize_app(cred)
db = firestore.client()
# Settings
collection_name = 'dict-nl'
batch_size = 499
d = op... |
# Common code
import numpy as np
# Common formula, All Models
def Cost_waiting(f, y, t01, t02, t11, t12, fbar, Pw, epsilon):
# Cost of waiting
if (f >= fbar):
t0 = t02
t1 = t12
else:
t0 = t01
t1 = t11
Cw = Pw * (t0 + t1 * (epsilon/f)) * y
return C... |
"""
Board representation of No Dice Einstein.
"""
COLOR = {
"red": 'R',
"blue": 'B'
}
VALUE = {
1: '1',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6'
}
MOVE = {
"U": "up",
"D": "down",
"L": "left",
"R": "right",
"X": "diagonal"
}
class Piece:
def __init__(self, row, c... |
"""
Copyright 2018-present Open Networking Foundation
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 agre... |
import graphene
class ResponseField(graphene.Interface):
"""Response interface"""
is_success = graphene.Boolean(default_value=True)
error_message = graphene.String()
|
# An English text needs to be encrypted using the following encryption scheme.
# First, the spaces are removed from the text. Let be the length of this text.
# Then, characters are written into a grid, whose rows and columns have the following constraints:
#
# , where is floor function and is ceil function
# For exa... |
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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.... |
import time
class Timeouts():
def __init__(self):
self.timeouts = dict()
def add(self, command, length):
ctime = time.time()
if command not in self.timeouts or ctime > self.timeouts[command]:
self.timeouts[command] = ctime + length
def is_timeout(self, command):
if command in self.timeouts:
if time.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
# 脚本库
class OpsJobJobScriptInfo(models.Model):
job_name = models.CharField(max_length=32) # job name
script_name = models.CharField(max_length=32) # script_name
script_content = mode... |
from copy import deepcopy
from src.cards import start_card, cards
# Default values
# DO NOT CHANGE THE WIDTH AND HEIGHT, as the entire game is made to render the items to the screen using these values, especially the images
window_width = 1500
window_height = 800
game_width = 1200
game_height = 800
cell_width = 4... |
#!/usr/bin/env python3.7
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import time
start = time.time()
sys.stdin.reconfigure(errors='surrogateescape')
sys.stdout.reconfigure(errors='surrogateescape')
for line in sys.stdin:
seconds = time.time() - start
sy... |
#!/usr/bin/env python
from pyrf.devices.thinkrf import WSA
from pyrf.connectors.twisted_async import TwistedConnector
from pyrf.sweep_device import SweepDevice
import sys
import time
import math
from matplotlib.pyplot import plot, figure, axis, xlabel, ylabel, show
import numpy as np
from twisted.internet import re... |
from enum import Enum, unique
from typing import List
from shotgrid_leecher.utils.functional import try_or
@unique
class QueryStringType(Enum):
STR = str
INT = int
FLOAT = float
@staticmethod
def from_param(type_name: str) -> "QueryStringType":
if not type_name:
return QueryS... |
from regression_tests import *
class TestBasic(Test):
"""Related to:
#41: https://github.com/avast/retdec/issues/41
#169: https://github.com/avast/retdec/issues/169
#391: https://github.com/avast/retdec/pull/391
"""
settings=TestSettings(
input='Test.exe'
)
def test(self):
... |
from __future__ import absolute_import
from .lib import Sedflux3D
|
import os, platform, collections
import socket, subprocess,sys
import threading
from datetime import datetime
class myThread (threading.Thread):
def __init__(self,startLastOctet,endLastOctet):
threading.Thread.__init__(self)
self.startLastOctet = startLastOctet
self.endLastOctet = endLastOctet
def run(... |
#
# PySNMP MIB module ChrComAtmVplTpVp-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ChrComAtmVplTpVp-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:19:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
import numpy as np
import torch
import torch.nn as nn
# import torch.nn.functional as F
from dp.modules.backbones.resnet import ResNetBackbone
from dp.modules.decoders.OrdinalRegression import OrdinalRegressionLayer
from dp.modules.encoders.SceneUnderstandingModule import SceneUnderstandingModule
from dp.modules.losse... |
# The MIT License (MIT)
#
# Copyright (c) 2018 Carter Nelson for Adafruit Industries
#
# 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 ri... |
import csv
from django.core.management.base import BaseCommand
from nationalparks.models import FederalSite
def determine_site_type(name, website):
""" The name (or website) of a Federal Site in this list provides an
indication of what type of site it might be. This extracts that out. """
name_fragment... |
import pyexcel
sheet = pyexcel.get_sheet(file_name="test.csv")
sheet
|
from copy import deepcopy
import pytest
import random
import bigchaindb
from bigchaindb.core import Bigchain
from contextlib import contextmanager
from bigchaindb.common.crypto import generate_key_pair
from tests.pipelines.stepping import create_stepper
###############################################################... |
import pandas as pd
import requests
from LeapOfThought.common.file_utils import cached_path
from tqdm import tqdm
import pandas as pd
# This is mainly for testing and debugging ...
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 2000)
pd.set_option('disp... |
from .empty2d import EmptyWorld2D
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: orderbook/orderbook.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflecti... |
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
# !wget https://thispersondoesnotexist.com/image -O 'image.png'
import matplotlib.pyplot as plt
import cv2
# load
image = cv2.imread("image.png")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# show
plt.imshow(image)
# show without edge blur
plt.imshow(image, interpolation='nearest')
|
import threading
def create_thread(obj):
obj_thread = threading.Thread(target=obj.run, daemon=True)
obj_thread.start()
while obj_thread.isAlive():
obj_thread.join(1)
obj_response = obj.get_response()
return obj_response
|
import os # NOQA
import sys # NOQA
import re
import fileinput
from utils import Point, parse_line
def printgrid():
for y in range(min_y - 1, max_y + 1):
print ''.join(grid.get(Point(x, y), '.') for x in range(min_x - 1, max_x + 2))
print
grid = {}
min_y = 1e10
max_y = -1e10
min_x = 1e10
max_x =... |
# -*- coding: utf-8 -*-
"""
Solution to Project Euler problem 109 - Darts
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
import numpy as np
def run():
target = 100
poss_d = np.concatenate([2 * np.arange(1, 21), [50]])
poss = np.concatenate(
[np.arange(1, 21), 2 * np.... |
class Files():
completion_error='school_invalid_data.csv'
student_donwload='/student_attendance_allDistricts_'
student_block='/student_attendance_allBlocks_'
student_cluster='/student_attendance_allClusters_'
student_school='/student_attendance_allSchools_'
student_districtwise='/student_att... |
#cronjob syntax running on server: 0 8 * * * python3 homework-10-gruen-apirequest.py
#API key: yourapikey
#Place in decimal degrees: NYC = {'Latitude': 40.7142700 , 'Longitude': -74.0059700}
import requests
weather_response = requests.get ('https://api.forecast.io/forecast/yourapikey/40.7142700,-74.0059700')
wea... |
from car import Car
my_new_car = Car('audi', 'a4', 2015)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
|
version=".92B"
date="7/31/2018"
import sys, os, subprocess, shutil
import pandas
from os import listdir
from os.path import isfile, join
def find_charge_range(input_pin_files): #This function is called to return information on the max an min charges considered among a collection of percolator 'pin' input files
al... |
import json
def error(e, msg="", ex=False) :
print("ERROR {} : {}".format(msg, e))
if ex : exit()
def loads(data, cry=True) :
data = None
try :
data = json.loads(data)
if cry : print("LOADS SUCCESS.")
except Exception as e :
error(e, "LOADS")
finally :
retur... |
import torch.nn as nn
import math
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, retain_activation=True, activation='ReLU'):
super(ConvBlock, self).__init__()
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, p... |
import sys
LOCATIONS = "abcdefg"
VALID_DIGITS = {
2: [{"c", "f"}],
3: [{"a", "c", "f"}],
4: [{"b", "c", "d", "f"}],
5: [
{"a", "c", "d", "e", "g"},
{"a", "c", "d", "f", "g"},
{"a", "b", "d", "f", "g"},
],
6: [
{"a", "b", "d", "e", "f", "g"},
{"a", "b", "c... |
import cv2
images=cv2.imread('rumahkita3.jpeg')
resize=cv2.resize(images,(824,464))
cv2.imwrite('rumahkita3-resized.jpeg',resize)
|
#!/usr/bin/python3
import sys
import funcs
import json
import auth
def main():
while True:
args = input( "-> " )
splitters = [x.strip() for x in args.split( ' ' ) ]
print( splitters )
fname = splitters[:-1]
try:
arg = json.loads(splitters[-1])
print( str(funcs.parse(fname, arg)))
except Exception ... |
#!/usr/bin/env python
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree.
import tempfile
import unittest
from nuclide_certificates_generator import NuclideCertificatesGenerator
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Implementation of Neighbor Based Node Embeddings (NBNE).
Call function with a networkx graph:
>>> train_model(graph, num_permutations, output_filename)
For details read the paper:
Fast Node Embeddings: Learning Ego-Centric Representations
Tiago Pimentel, Adr... |
#
# This source file is part of appleseed.
# Visit https://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2014-2018 The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.AccountRecord import AccountRecord
class AlipayUserAccountSearchResponse(AlipayResponse):
def __init__(self):
super(AlipayUserAccountSearch... |
from os.path import join, dirname
from setuptools import setup
setup(
name = 'xmppgcm',
packages = ['xmppgcm'], # this must be the same as the name above
version = '0.2.4',
description = 'Client Library for Firebase Cloud Messaging using XMPP',
long_description = open(join(dirname(__file__), 'README.txt')).r... |
input = """
p6|p9|p6|not_p22:-p19,p23.
p2|p24|p15:-not p23.
p1|p12|p2|not_p16:-not p23,not p3.
p3|p20|p18:-p1,not p22.
p3|not_p20|p18:-p13,not p22,not p14.
p15|p4|p3|p1:-p12,p5.
p3|p20|p18|p3:-p1,not p22.
not_p2|not_p24|p9:-p1,p12,not p11.
p15|p11|p24|p3.
not_p4:-not p4.
not_p23|p7|p21|p5:-p13,not p3.
p1|p15... |
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
result = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
self.dfs(grid,i,j)
... |
from flask import Blueprint, render_template, request
from .database import db
from .model import Item
bp = Blueprint('admin',__name__)
@bp.route('/admin', methods=('GET','POST'))
def admin():
if request.method == 'POST':
id = request.form['delete']
Item.query.filter(Item.id==id).delete()
... |
# -*- coding: utf-8
from django.core.management.base import BaseCommand
from django.conf import settings
from django.core.exceptions import *
from apps.subject.models import Department, Professor, Lecture, Course, ClassTime, ExamTime
#from otl.apps.timetable.models import ClassTime, ExamTime, Syllabus
#from optparse im... |
import settings
import handlers.base_handler
import csv
class CartogramHandler(handlers.base_handler.BaseCartogramHandler):
def get_name(self):
return "Bangladesh"
def get_gen_file(self):
return "{}/bangladesh_processedmap.json".format(settings.CARTOGRAM_DATA_DIR)
def validate_values... |
#from TestingTemplate import Test
import sys
sys.path.append('../../ExVivo')
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
def calcStress(disp,force,dims):
#Cauchy Stress
stretch = (disp - disp[0])/dims1['length'] + 1
stress = force/(dims1['width']*dims1['thickness'])*stretc... |
# Jorge Castanon, October 2015
# Data Scientist @ IBM
# run in terminal sitting on YOUR-PATH-TO-REPO:
# ~/Documents/spark-1.5.1/bin/spark-submit mllib-scripts/cluster-words.py
# Replace this line with:
# /YOUR-SPARK-HOME/bin/spark-submit mllib-scripts/cluster-words.py
import numpy as np
import math
from pyspark.cont... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
# file : middleware/mymiddleware.py
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
import re
class MyMiddleWare(MiddlewareMixin):
def process_request(self, request):
print("中间件方法 process_request 被调用")
def process_view(self, request, callback, callback_args,... |
from . import vocab
from . import tokenizers
from . import batchify
from .vocab import *
__all__ = ['batchify', 'tokenizers'] + vocab.__all__
|
from sqlalchemy import schema
from sqlalchemy.orm import Session
from fastapi import Depends, APIRouter, HTTPException, status
from fastapi.security.oauth2 import OAuth2PasswordRequestForm
from .. import db, models, schemas, utils, oauth2
router = APIRouter(
tags=["Authentication"],
)
@router.post("/login", re... |
import tensorflow as tf
from tensorflow.python.framework import ops
_op = tf.load_op_library('local_cluster.so')
def LocalCluster(neighbour_idxs, hierarchy_idxs, row_splits):
'''
.Input("neighbour_idxs: int32") //change to distances!!
.Input("hierarchy_idxs: int32")
.Input("global_idxs: int32")
.... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from auxlib.ish import dals
log = logging.getLogger(__name__)
def test_dals():
test_string = """
This little piggy went to the market.
This little piggy stayed home.
This little piggy ... |
from typing import Any, Optional
from great_expectations.core.usage_statistics.anonymizers.base import BaseAnonymizer
from great_expectations.datasource import (
BaseDatasource,
Datasource,
LegacyDatasource,
PandasDatasource,
SimpleSqlalchemyDatasource,
SparkDFDatasource,
SqlAlchemyDatasour... |
import unittest
import pickle
import numpy as np
import mockredis
from mock import patch
from datasketch.lsh import MinHashLSH
from datasketch.minhash import MinHash
from datasketch.weighted_minhash import WeightedMinHashGenerator
def fake_redis(**kwargs):
redis = mockredis.mock_redis_client(**kwargs)
redis.c... |
"""
Package providing a module to parse the content from tabbed tree files
"""
__version__ = '0.2.0'
|
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_django-user-verification
------------
Tests for verification `generators`.
"""
# Third Party Stuff
from django.test import TestCase
from nose.tools import ok_
# Local Stuff
from verification.generators import NumberGenerator
class TestNumberGenerator(TestCa... |
#(c) 2016-2018 by Authors
#This file is a part of Flye program.
#Released under the BSD license (see LICENSE file)
"""
Modifies repeat graph using the Tresle output
"""
import logging
from itertools import izip, chain
from collections import defaultdict
import flye.utils.fasta_parser as fp
from flye.repeat_graph.gra... |
a = 1
b = 2
c = 3
dd = 4
efg = 6666
|
# https://codeforces.com/problemset/problem/1535/A
t = int(input())
cases = [list(map(int, input().split())) for _ in range(t)]
for case in cases:
top = sorted(case, reverse=True)[:2]
if max(case[0], case[1]) in top and max(case[2], case[3]) in top:
print('YES')
else:
print('NO') |
from PIL import Image
from skimage import measure
import numpy as np
from shapely.geometry import Polygon, MultiPolygon
import json
def create_sub_masks(mask_image):
width, height = mask_image.size
# Initialize a dictionary of sub-masks indexed by RGB colors
sub_masks = {}
for x in range(width):
... |
"""
18 / 18 test cases passed.
Runtime: 28 ms
Memory Usage: 14.9 MB
"""
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
ans = []
while columnNumber != 0:
columnNumber -= 1
ans.append(chr(65 + columnNumber % 26))
columnNumber //= 26
retu... |
"""
2019.08.19, testing the first nasbench search space.
I should finish this within a weekend and should deploy this as soon as possible.
"""
from copy import copy
from functools import partial
import itertools
import logging
import os
from collections import deque, OrderedDict
import IPython
from search_policies.c... |
""""Hacs base setup task."""
# pylint: disable=abstract-method
from __future__ import annotations
from datetime import timedelta
from timeit import default_timer as timer
from homeassistant.core import HomeAssistant
from ..base import HacsBase
from ..enums import HacsStage
from ..mixin import LogMixin
class HacsTa... |
import unittest
import json
from ... import create_app
from ...api.v1.model.sales import Sales
class TestInvalidData(unittest.TestCase):
def setUp(self):
self.test = create_app('testing').test_client()
self.content_type = 'application/json'
payload = {'password': 'admin', 'email_address': 'admin@gmail.c... |
from django.utils.formats import localize
from rest_framework.serializers import (
HyperlinkedIdentityField,
SerializerMethodField,
ValidationError,
)
from rest_framework import serializers
from django.contrib.auth import get_user_model
from ...sale.model... |
from glob import glob
import pickle as pkl
import copy
import math
import os
import random
import numpy as np
from tqdm import tqdm
from collections import defaultdict
from config import cfg
if __name__ == '__main__':
preds_list = []
all_paths = list(glob(cfg.cache + '*.pkl'))
for path in all_paths:
... |
from uuid import UUID
from jose import jwt
from pydantic import BaseModel
from settings import Config
class TokenData(BaseModel):
player_uuid: UUID
game_uuid: UUID
def decode_token(token: str) -> TokenData:
config = Config()
return TokenData(
**jwt.decode(
token, config.jwt_to... |
import pkgutil
import os
import sys
from collections import defaultdict
from multiprocessing import Pool
def tree():
"""Tree data structure.
See https://gist.github.com/hrldcpr/2012250
"""
return defaultdict(tree)
def get_datapath(package, resource):
"""Rewrite of pkgutil.get_data() that just r... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-08 00:06
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateM... |
ThoughtPrefix = '.'
def isThought(message):
return message and message.startswith(ThoughtPrefix)
def removeThoughtPrefix(message):
if isThought(message):
return message[len(ThoughtPrefix):]
else:
return message
def findAvatarName(id):
info = base.cr.identifyAvatar(id)
return info... |
from rest_framework.generics import CreateAPIView
from rest_framework.renderers import TemplateHTMLRenderer, JSONRenderer
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from djvue.views import FileUploadView
from .serializers import LoginSerializer, Profil... |
# coding: utf-8
r"""
>>> from django.contrib.comments.models import Comment
>>> from django.contrib.auth.models import User
>>> u = User.objects.create_user('commenttestuser', 'commenttest@example.com', 'testpw')
>>> c = Comment(user=u, comment=u'\xe2')
>>> c
<Comment: commenttestuser: â...>
>>> print c
commenttestuse... |
from config import palette
from colorthief import ColorThief
def runPalette(name, root):
"""
Prints the most used colors (in plural) of an image.
Args:
name (str): File name
root (str): Superior path to file; the folder in which the file
is stored
"""
if palet... |
from __future__ import absolute_import
from optparse import make_option
import sys
from behave.configuration import options as behave_options
from behave.__main__ import main as behave_main
from django.core.management.base import BaseCommand
from behave_django.environment import monkey_patch_behave
from behave_django... |
from contextlib import contextmanager
import pg8000
from translators import sql_translator
from translators.sql_translator import NGSI_ISO8601, NGSI_DATETIME, \
NGSI_GEOJSON, NGSI_TEXT, NGSI_STRUCTURED_VALUE, TIME_INDEX, \
METADATA_TABLE_NAME, FIWARE_SERVICEPATH, TENANT_PREFIX
import geocoding.geojson.wktcodec
... |
"""The top level package for the Tetris OpenAI Gym Environment."""
from .tetris_env import TetrisEnv
from ._registration import make
from .wrappers import wrap
# define the outward facing API of this module (none, gym provides the API)
__all__ = [
TetrisEnv.__name__,
make.__name__,
wrap.__name__,
]
|
# coding: utf-8
"""
UltraCart Rest API V2
UltraCart REST API Version 2
OpenAPI spec version: 2.0.0
Contact: support@ultracart.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class ItemPricing(object):
... |
# Copyright 2017 - Nokia
#
# 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, sof... |
#
# import tree: please see __init.py__
#
from .stdlib import *
from ..meta.decorator import *
from ..meta.listify import *
from ..meta.meta import *
from ..debug.trace import *
from ..debug.profile import *
from ..debug.debug import *
from ..debug.jupyter import *
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from tqdm import tqdm
from epimargin.estimators import analytical_MPVS
from epimargin.etl.commons import download_data
from epimargin.etl.covid19india import (get_time_series, load_all_data,
replace_district_n... |
import os
from dataclasses import dataclass
from pathlib import Path
from re import search
import sys
import logging
from typing import List, MutableMapping, Optional, Tuple
FORMAT = "%(levelname)s: %(message)s"
class DocumentLogAdapter(logging.LoggerAdapter):
def __init__(
self, logger: logging.Logger, ... |
import time
def animate_sentence(word):
for word in word_list:
for char in word:
print(char,end='',flush=True)
time.sleep(0.2)
print(" ",end='',flush=True)
word_list=["Welcome","to","the","World","of","Code"]
animate_sentence(word_list)
|
import re
from API.models import Project
def get_proposal_from_visit(visit):
visit_pattern = '([A-Za-z0-9_]+)(\-[0-9]+)'
p = re.fullmatch(visit_pattern, visit)
try:
return p.group(1)
except AttributeError:
return ""
def get_project_from_visit(visit):
proposal = get_proposal_from_vi... |
"""sc-githooks - Checks on Git commits
Copyright (c) 2021 Scott Lau
Portions Copyright (c) 2021 InnoGames GmbH
Portions Copyright (c) 2021 Emre Hasegeli
"""
from githooks.config import config
from githooks.base_check import BaseCheck, Severity
from githooks.git import Commit
class CommitCheck(BaseCheck):
"""Par... |
# -*- coding: utf-8 -*-
from distutils.core import setup
import py2exe
setup(name="main",
version="1.0",
console=[{"script": "main.py"}]
) |
from fastapi.testclient import TestClient
from fastapi import status
from tests.test_auth import TestAuth
class TestUser:
def test_post(self, client: TestClient):
payload = {
"username": "testuser",
"password": "12345",
"email": "testuser@example.com",
"firs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.