content stringlengths 5 1.05M |
|---|
"""
A subclass of MutableAttr that has defaultdict support.
"""
from collections import Mapping
from attrdict.mixins import MutableAttr
__all__ = ['AttrDefault']
class AttrDefault(MutableAttr):
"""
An implementation of MutableAttr with defaultdict support
"""
def __init__(self, default_factory=None... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import setting
from crawl_zillow.scheduler import ZipcodeScheduler
scheduler = ZipcodeScheduler()
input_data_queue = scheduler.get_todo(
limit=2, get_html_kwargs={"zillow_only": True})
scheduler.do(input_data_queue, multiprocess=False, use_browser=True)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
class AlipayOpenSpMerchantInconsistentApproveRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._back_c... |
# you can write to stdout for debugging purposes, e.g.
# print "this is a debug message"
def solution(A):
n = len(A)
count = 0
layers = [0]*n
current_layer = 0
for i in range(n):
b_r = i + A[i]
b_l = i - A[i]
if b_r >= n or b_r < i:
b_r = n-1
if b_l < 0:... |
from typing import Dict
from typing import List
from pydantic import BaseModel
from stories import arguments
from stories import story
# Constants.
representations = {
"int_error": "value is not a valid integer",
"list_of_int_error": "value is not a valid integer",
"int_field_repr": "int",
"str_fi... |
#!python
#!/usr/bin/env python
#Python script:
import sys
import numpy as np
from pybdm import BDM
from pybdm import options
import warnings
warnings.filterwarnings("ignore")
options.set(raise_if_zero=False)
options.set(warn_if_missing_ctm=False)
file = sys.argv[1]
with open(file, 'r') as file:
data = file.read()... |
# Generated by Django 2.2 on 2019-06-06 15:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('users', '0001_initial'),
('events', '0002_conference_organizer'),
('proposals', '0001_init... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 11 13:48:05 2020
@author: Pablo
"""
from modules_api.Term import Term
def generateFakeTerm():
myterm= Term()
myterm.source =''
myterm.term_id="9999999"
myterm.term="empresario"
myterm.context= "el empresario de la empresa le... |
""" This is the Bokeh charts testing interface.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with thi... |
from . import gps_controller
from . import serial_controller
import logging
import sys
LOGGER = logging.getLogger(__name__)
GPS_TYPE_SERIAL='serial'
def create_gps_controller(gps_type):
try:
controller = None
if gps_type == 'serial':
controller = serial_controller.SerialGPSController... |
# encoding: utf-8
import discord
import praw
import pickle
import datetime
import time
import threading
from conf import *
from discord.ext import commands
class Profile:
"""gets information about TGRP characters."""
def __init__(self, bot):
self.bot = bot
self.profile_dir = cog_dir + "p... |
from typing import Union
import troposphere.ssm as ssm
import yaml
from troposphere import AWSObject
from serverless.aws.resources import Resource
class ResourceManager(yaml.YAMLObject):
yaml_tag = "!Resources"
def __init__(self, service, description):
super().__init__()
self.description = ... |
from utility import *
from collections import OrderedDict
def dispDict(x, prefix=""):
s = ""
if (type(x) == dict) or (type(x) == OrderedDict):
s += "\n" + prefix + "{"
for k, v in x.items():
s += "\n\t" + prefix + k + " : " + dispDict(v, prefix + "\t")
s += "\n" + prefix + ... |
def FrequencyArray(text, k):
array = []
for i in range(0, 4**k):
array.append(0) #der Wert für alle 4**k Möglichkeiten (in dem Fall 16) im array wird auf 0 gesetzt
for i in range(0,len(text)-k+1):
pattern=text[i:i+k]
x=patternToNumber(pattern)
array[x]=array[x]+1 #wird das pattern gefunden, so an der ... |
# import mastodon
#
#
# class StatusListener(mastodon.StreamListener):
# def on_update(self, status):
# print(status)
#
#
# # mastodon.Mastodon.create_app(
# # 'mnm',
# # to_file='mnm.txt',
# # api_base_url='https://mastodon.xyz',
# # )
#
# m = mastodon.Mastodon(client_id='mnm.txt', a... |
# --- coding:utf-8 ---
# author: Cyberfish time:2021/7/23
def rule_response(content, intents, database, DST):
greet, thank, bye = '', '', ''
responds = set()
if len(intents) == 0:
return '实在是不好意思,我没听懂您想问啥,抱歉!', DST
for intent in intents:
if intent == 'greet-none':
greet = '你好... |
from abc import ABCMeta
from abc import abstractmethod
from camp_real_engine.abstract.abc_visitor import Visitee
class ABCProductRoot(object):
__metaclass__ = ABCMeta
class ABCProduct(object):
__metaclass__ = ABCMeta
class ABCProductReal(object):
__metaclass__ = ABCMeta
class ABCProductVar(object):
__m... |
# -*- coding: utf-8 -*-
import tornado.httpclient
import tornado.gen
import datetime
import logger
@tornado.gen.coroutine
def async_http_fetch(url, timeout=5, post_body=None, method='GET', headers=None, validate_cert=None):
http_request = tornado.httpclient.HTTPRequest(
url=url,
method=method,
... |
import tensorflow.compat.v1 as tf
import sys
import os
import cv2
import math
# Disable tensorflow compilation warnings
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow.compat.v1 as tf
label_lines = [line.rstrip() for line
in tf.gfile.GFile("tf_files/retrained_labels.txt")]
with tf.g... |
from typing import Type, Sequence, Union, Optional, List, Callable
import dash
from dash.dependencies import Output, Input, State
from dash.development.base_component import Component
import dash_html_components as html
class DashPythonComponent:
app: Optional[dash.Dash] = None
_callback_output_ids: List[str... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# a tale of two cities
chart = ["abode", "accomplishments", "annihilation", "anxiety", "ball", "banquets", "barber", "boxes", "buildings", "card-towers", "causes", "chosen", "confidence", "construction", "contention", "contrivances", "conversation", "copy", "counterweight"... |
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from app.models import MyUser
class MyBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
user = MyUser.objects.filter(Q(phone=username)|Q(username=username)).first()
i... |
s = 0
for i in range(10, 500000):
ls = list(str(i))
ns = 0
for j in ls:
ns += int(j)**5
if ns == i:
s += ns
print(s) |
import os
import sys
import argparse
import csv
HR = "################################################################################"
################################################################################
# Print Debug
################################################################################
d... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2014 Fabio Niephaus <fabio.niephaus@gmail.com>,
# Dean Jackson <deanishe@deanishe.net>
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2014-08-16
#
"""Self-updating from GitHub.
.. versionadded:: 1.9
.. note::
This module is n... |
"""
Simple app demostrating how to load files to the Google App Engine Blobstore.
"""
import urllib
import webapp2
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
class MainHandler(webapp2.RequestHandler):
"""Displays the upload form with the action fiel... |
from prime import prime
from itertools import combinations
list_of_primes = []
for i in range(1000, 10001):
if prime(i):
list_of_primes.append(i)
for x in combinations(list_of_primes, 3):
if "".join(sorted(str(x[0]))) == "".join(sorted(str(x[1]))):
if "".join(sorted(str(x[1]))) == "".join(sorted(str(x[2])))... |
# setup
lista = []
x = input(str("Dime tu palabra: "))
hazte = "Hazte un " + x
que = "Un que?"
un = "Un " + x
temp_string = ""
for i in range(1, 1000):
for j in range(1,i + 1):
temp_string += hazte + ";"
for j in range(1,i + 1):
temp_string += que + ";"
for j in range(1,i + 1):
t... |
import json
import sys
import time
from os import path
from typing import Optional, Tuple, List, Dict
from uuid import uuid4 as uuid
from flask import Flask, render_template, Blueprint, url_for
from flask_sockets import Sockets
from gevent import monkey
# noinspection PyPackageRequirements
from geventwebsocket.websoc... |
"""Enable multiple processes to send logs to a central server through ZeroMQ.
Thanks to Zachary Voase: https://github.com/zacharyvoase/logbook-zmqpush
Slightly modified to support Logbook 0.4.1.
"""
import errno
import json
import socket
import zmq
import logbook.queues
from logbook.base import LogRecord
class ZeroM... |
import datetime
from app.core.db import db
from models import *
from app.core.bcrypt import bcrypt
from flask import Blueprint, render_template, request, session, redirect, url_for
user_views = Blueprint('user', __name__,
template_folder='../../templates',
static_folder=... |
from django.conf.urls import patterns, url
from plan import views
urlpatterns = patterns('',
url(r'^$', views.index, name='plan'),
url(r'^(?P<plan_number>[\d\-A-Z]+)/$', views.details, name='details'),
url(r'^like_plan/$', views.like_plan, name='like_plan'),
) |
from sanic import Sanic
from sanic.response import json
from sanic_openapi import swagger_blueprint, doc
import default_setting
from models.create_db import create_tables
from resources.users import user_bp
app = Sanic("my_sanic_app")
app.config.from_object(default_setting)
app.blueprint(swagger_bluepri... |
AP_IF = 0
STA_IF = 1
class WLAN:
def __init__(self, t):
pass
def active(self, v):
pass
def connect(self, name, pwd):
pass |
import matplotlib.pyplot as plt
from multiprocessing import Process, Queue
import time
class Plotter:
def __init__(self):
self.queue = Queue(10)
self.process = Process(target=self.plot_data)
self.process.start()
def plot_data(self):
self.fig=plt.gcf()
self.fig.show()... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "sepp.heid@t-online.de"
__doc__ = """ """
import argparse
import os
import sys
from pptx import Presentation
from pptx.exc import PackageNotFoundError
from pptx.util import Inches
from poorscrum import SPRINT_FILE, BURNDOWN_SAVE_NAME, read_fields, __version... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 5 22:27:41 2019
@author: Abhishek Mukherjee
"""
cube = lambda x: x**3 # complete the lambda function
def fibonacci(n):
# return a list of fibonacci numbers
x=list(range(0,n))
if n==1:
x[0]=0
return [x[0]]
elif... |
import os
os.system("rar a Videocard.rar '/home/cathaylife04/smartphone/iphone11/static/data/Videocard'")
|
####
# This is the script for storing the schema of your TerminusDB
# database for your project.
# Use 'terminusdb commit' to commit changes to the database and
# use 'terminusdb sync' to change this file according to
# the exsisting database schema
####
from typing import List
from terminusdb_client.woqlschema impor... |
TIMEOUT = 10
import threading
import tempfile
import os.path
errors = []
class Worker(threading.Thread):
def __init__(self, function, args):
threading.Thread.__init__(self)
self.function = function
self.args = args
def run(self):
self.function(*self.args)
for name, func, ar... |
from django.db import models
# from django.contrib.auth.models import User
# Create your models here.
class UserArtist(models.Model):
userid = models.ForeignKey("auth.User", on_delete=models.SET_NULL, blank=True, null=True, db_column="userid")
artistid = models.ForeignKey("artists.Artist", on_delete=models.SE... |
from flask import redirect, render_template, request, session, url_for
from flask_babel import lazy_gettext as _l
from flask_login import current_user
from app import user_api_client
from app.main import main
from app.main.forms import (
ContactMessageStep,
ContactNotify,
SetUpDemoOrgDetails,
SetUpDemo... |
from software_defined_assets.weather_assets import weather_assets
from dagster import materialize
from dagster.core.test_utils import instance_for_test
def test_airport_weather_assets():
with instance_for_test() as instance:
assert materialize(weather_assets, instance=instance).success
|
"""
Utils for working with AWS.
"""
import boto3
import os
def delete_all_from_s3(directory, bucket):
"""Deletes everything from the corresponding directory on S3."""
prefix = directory[1:] if directory[0] == "/" else directory
# TODO: switch the prefix to above once we're okay deleting old
# checkpoi... |
import datetime, json, grequests, traceback
from commands import *
async def direct():
await ainput()
gid = 739585686377857097
cid = {739585686377857097: 739585828791124051, 699314655973212242: 741144497588535378}
while True:
command = (await ainput(">>> ")).strip()
if command.startswith("gg "):
... |
from appscript import *
finder = app("Finder")
finder.activate()
w = finder.Finder_windows[1].target.get()
w.files[its.name_extension.isin(["htm", "html"])].select() |
"""
NOTE:
the below code is to be maintained Python 2.x-compatible
as the whole Cookiecutter Django project initialization
can potentially be run in Python 2.x environment.
TODO: ? restrict Cookiecutter Django project initialization to Python 3.x environments only
"""
project_slug = '{{ cookiecutter.proje... |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return {
"appName": {{ data.appName }},
"equipe": {{ data.equipe }},
"login": {{ data.login }},
"email": {{ data.email }},
}
@app.route('/healthcheck')
def healthcheck():
return "working"
if __na... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 manfred <manfred.lotz@posteo.de>
#
# Distributed under terms of the MIT license.
import os
import re
import urls
def find_urls(line: str):
regex = re.compile('((https?):((//)|(\\\\))+([\w\d:#@%/;$()~_?\+-=\\\.&](#!)?)*)', re.DOT... |
import sys, os
from flask import Flask, flash, request, redirect, url_for, jsonify, send_file
from flask_cors import CORS, cross_origin
import tweepy
from tweepy import OAuthHandler
from data.twitter_data import twitter_api_call
from dotenv import load_dotenv
sys.path = os.getcwd()
load_dotenv('.env')
app = Flask(_... |
import os
from hwtBuildsystem.fileUtils import which
class QuartusConfig():
HOME = None
_DEFAULT_HOME_LINUX = '/opt/intelFPGA'
@classmethod
def getHome(cls):
if cls.HOME is not None:
return cls.HOME
try:
quartusHomes = os.listdir(cls._DEFAULT_HOME_LINUX)
... |
import itertools
from pipefy.Pipefy import PositionalArg
accumulate = PositionalArg(itertools.accumulate)
chain = PositionalArg(itertools.chain)
chain_from_iterable = PositionalArg(itertools.chain.from_iterable)
combinations = PositionalArg(itertools.combinations)
combinations_with_replacement = PositionalArg(
i... |
import matplotlib.pyplot as plt
from lib.random_walk1 import RandomWalk
''' Movimento molecular. Simula o percurso de um grão de pólem na superfície de um agota de água. '''
while True:
# Cria um passeio aleatório e plota os pontos.
rw = RandomWalk(5000)
rw.fill_walk()
# Define o tamanho da janela d... |
import geopandas as gpd
import logging
import pandas as pd
import sys
from collections import defaultdict
from copy import deepcopy
from itertools import chain
from operator import attrgetter, itemgetter
from pathlib import Path
from shapely.geometry import Point
from shapely.ops import polygonize, unary_union
filepat... |
from . import models
from django.contrib import admin
class TodoListAdmin(admin.ModelAdmin):
list_display = ("title", "created", "due_date")
class CategoryAdmin(admin.ModelAdmin):
list_display = ("name",)
admin.site.register(models.TodoList, TodoListAdmin)
admin.site.register(models.Category, CategoryAdm... |
#!/usr/bin/env python3
import argparse, subprocess, requests, json, sys, base64, binascii, time, hashlib, re, copy, logging, configparser
import dns.resolver, dns.tsigkeyring, dns.update
LOGGER = logging.getLogger('acme_dns_tiny')
LOGGER.addHandler(logging.StreamHandler())
def get_crt(config, log=LOGGER):
def _b6... |
import json
import os
import pathlib
import shutil
from unittest.mock import patch
import pytest
from django.conf import settings
from django.contrib.auth.models import User
from django.test import override_settings
from core.models import Url
from core.serializers import UrlSerializer
from core.utils import dataregi... |
# -*- coding: utf-8 -*-
import gzip
import json
import re
import scrapy
from locations.hours import OpeningHours
from locations.items import GeojsonPointItem
class DollarGeneralSpider(scrapy.Spider):
name = "dollar_general"
item_attributes = {"brand": "Dollar General", "brand_wikidata": "Q145168"}
allow... |
from flask import Blueprint
users = Blueprint('users', __name__, url_prefix='/api/v0/user')
from . import view |
###############################################################################
# Copyright 2013-2014 The University of Texas at Austin #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #... |
"""
Generate static documentation for your Elm application.
"""
import sys
from setuptools import find_packages, setup
setup(
name='elm-doc',
version='1.0.0b4',
url='https://github.com/ento/elm-doc',
license='BSD 3-clause',
author='Marica Odagaki',
author_email='ento.entotto@gmail.com',
de... |
import unittest
import re
from ..identifiers import *
class TestIdentifierUtilities(unittest.TestCase):
def test_generate_mac_address_random(self):
mac = generate_mac_address()
self.assertRegex(mac, '^([0-9a-f]{2}:){5}[0-9a-f]{2}$')
def test_generate_mac_address_oui(self):
oui = 'ab... |
# generated by datamodel-codegen:
# filename: location_2D.json
from __future__ import annotations
from pydantic import BaseModel
class Location2D(BaseModel):
map: str
x: float
y: float
yaw: float
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ngsv-tools
# http://github.com/xcoo/ngsv-tools
# Copyright (C) 2012-2013, Xcoo, 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
#... |
from flask import Flask
import speech_recognition as sr
from ffmpy import FFmpeg
from os import path
import os
import uuid
from flask import request
app = Flask(__name__)
@app.route("/")
def hello():
return "Try GET /transcribe?videoUrl=path_to_video"
@app.route("/health-check")
def health():
return "Stron... |
from .base_type import BaseType
from .base_metric import BaseMetric
from wallarm_api import WallarmAPI
class NorthStarMetric(BaseType):
class CountNSM(BaseMetric):
def __init__(self) -> None:
super().__init__("North Star Metric", 2)
def value(self) -> int:
requests_count =... |
from django.test import TestCase
from djangorestframework.views import View
from djangorestframework.compat import apply_markdown
# We check that docstrings get nicely un-indented.
DESCRIPTION = """an example docstring
====================
* list
* list
another header
--------------
code block
indented
# hash... |
#!/usr/bin/env python
from gnuradio import gr
from gnuradio import audio
from gnuradio import trellis, digital, filter, blocks
from gnuradio import eng_notation
import math
import sys
import random
import fsm_utils
try:
from gnuradio import analog
except ImportError:
sys.stderr.write("Error: Program requires ... |
from builtins import str
from builtins import int
from past.builtins import basestring
import numpy as np
__all__ = ['isfloat', 'isint', 'isstr',
'res_doc_type', 'res_top_type', 'res_word_type']
#
# Rudimentary type-checking fns
#
def isfloat(x):
"""
Returns True if `x` is an instance of a f... |
def plainTextStyle():
return """
QPlainTextEdit
{
background-color: #b1b1b1;
color: #202020;
border: 1px solid #031582;
selection-background-color: #505050;
selection-color: #ACDED5;
}
QMenu
{
background: #F2F2F2;
color: #0E185F;
border: 1px solid #000;
selection-background-color: #ACDED5;
}
"""
def pushBut... |
import csv
import itertools
import os
import random
from collections import namedtuple
import numpy as np
import tensorflow as tf
from gtd.utils import flatten
from gtd.chrono import verboserate
from keras.utils.np_utils import to_categorical
from strongsup.case_weighter import get_case_weighter
from strongsup.decomp... |
from vizdoommaze.envs.vizdoomenv import VizdoomEnv
class VizdoomMazeTwo7(VizdoomEnv):
def __init__(self):
super(VizdoomMazeTwo7, self).__init__(40) |
des = ('Desafio-006 número dobro triplo raiz')
print ('{}.'.format(des))
#Desafio-06 >>> Crie um programa que leia um número e mostre o seu dobro, seu triplo e sua rais quadrada.
n1 = int(input('Digite um número: '))
do = n1*2
tr = n1*3
rz = n1**(1/2)
print ('O dobro do número que você digitou é {}. \nE seu triplo é {... |
#
# PySNMP MIB module MSERIES-PORT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MSERIES-PORT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:05:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
from webclient.models import *
from django.contrib import admin
from django import forms
from django.utils.html import format_html
admin.site.register(Image)
#admin.site.register(ImageLabel)
admin.site.register(ImageSourceType)
admin.site.register(CategoryType)
admin.site.register(ImageFilter)
admin.... |
class Source:
'''
news_Source class to define News Source Objects
'''
def __init__(self,id,name,description,url,category,country):
self.id =id
self.name =name
self.description =description
self.url =url
self.category =category
self.country =country
class... |
from django.shortcuts import render, reverse
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.detail import DetailView
from .models import Video
def index(request):
return render(request, 'videos/index.html')
class CreateVideo(CreateView):
model = Video
fields = ['... |
#!/usr/bin/env python3
from collections import Counter
import re
with open('aoc05_input.txt') as f:
a5 = f.read().splitlines()
pattern = re.compile(r'(\d+),(\d+) -> (\d+),(\d+)')
lines = [[int(x) for x in pattern.fullmatch(l).groups()] for l in a5]
hvlines = [l for l in lines if l[0] == l[2] or l[1] == l[3]]
d... |
#!/home/suffian/Envs/microblog_tutoriak/bin/python
import os
import sys
if sys.platform == 'win32':
pybabel = 'flask\\Scripts\\[ybabel'
else:
pybabel = '/home/suffian/Envs/microblog_tutoriak/bin/pybabel'
os.system(pybabel + ' compile -d app/translations')
|
from django.urls import path, re_path
from fake_admin.views import FakeAdminView
urlpatterns = [
path('login/', FakeAdminView.as_view(), name='login'),
re_path(r'^.*$', FakeAdminView.as_view(), name='index'),
]
|
import logging, solr
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from web.lib.base import BaseController, render
log = logging.getLogger(__name__)
class Four0FourController(BaseController):
def index(self):
r... |
g = int(input().strip())
for _ in range(g):
n = int(input().strip())
s = [int(x) for x in input().strip().split(' ')]
x = 0
for i in s:
x ^= i
if len(set(s))==1 and 1 in s:
#here x=0 or 1
if x:#odd no. of ones
print("Second")
else:#even no. of... |
# Copyright 2019 NullConvergence
#
# 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 writi... |
from rdkit import Chem
import numpy
import copy
import pandas as pd
def _CalculateEntropy(Probability):
"""
**Internal used only**
Calculation of entropy (Information content) for probability given
"""
res = 0.0
for i in Probability:
if i != 0:
res = res - i * n... |
"""
The main package for regression tests.
"""
__all__ = [
'Test',
'TestSettings',
'files_in_dir',
'on_linux',
'on_macos',
'on_windows',
]
# Ensure that packages in the 'deps' directory can be found during import.
import os
import sys
# Insert the path to the beginning of import paths to p... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
... |
import enum
import json
# Status Type
class StatusType(enum.Enum):
success = "SUCCESS"
fail = "FAIL"
# Token Type
class TokenType(enum.Enum):
accessToken = "ACCESSTOKEN"
refreshToken = "REFRESHTOKEN"
# Create response data
def ResponseModal(status, data, message):
if data is not None:
... |
"""Flask config class."""
import os
class Config():
|
from sys import modules
from unittest import TestCase
from unittest.mock import Mock, patch
modules_to_patch = [
"pitop.camera.camera",
"atexit",
"numpy",
"pitop.common",
]
for module in modules_to_patch:
modules[module] = Mock()
from pitop import DriveController, EncoderMotor
# Avoid getting the... |
# -*- coding: utf-8 -*-
import logging
from logging.config import fileConfig
import os
DEFAULT_FORMAT = "%(asctime)s %(levelname)s [%(module)s %(funcName)s:%(lineno)d] %(messages)s"
DEFAULT_DATEFMT = "%Y-%m-%dT%H:%M:%S"
'''
Configure logging; if a config file (logging.ini) is not found in the current directory,
a d... |
import pandas as pd; import numpy as np
from pyg_base._inspect import getargs
from pyg_base._types import is_ts, is_str, is_df, is_pd, is_series, is_array, is_tuple, is_dict
from pyg_base._decorators import wrapper
from pyg_base._as_list import as_tuple
__all__ = ['loop', 'loops', 'len0', 'pd2np', 'shape', 'loop_all']... |
try:
hours=float(input("Enter hours worked: "))
rate=float(input("Enter rate: "))
total=0;
def extra():
extra_hour=hours-40
extra_rate=extra_hour*rate
computepay(hours,rate,extra_rate)
def computepay(h,r,extra):
total=h*r+extra
print("Total: ",total)
if hours > 40:
extra();
else:
computepay(hou... |
from typing import Any, Dict, Type
from pait.model.core import PaitCoreModel
from pait.model.response import PaitBaseResponseModel, PaitJsonResponseModel
from pait.plugin.base import BaseAsyncPlugin, BasePlugin, PluginProtocol
from pait.util import get_pait_response_model
class AutoCompleteJsonRespPluginProtocolMixi... |
# This notebook follows the video course: https://youtu.be/rfscVS0vtbw
#%%
# adding two numbers
num1 = float(input('Please enter a number:'))
num2 = float(input('Please enter another number'))
# how could I handle the wrong input, e.g. text? we'll see
result = num1 + num2
print(result)
#%%
is_male = False
is_tall = ... |
import unittest
from mayatdd import server
class ServerTest(unittest.TestCase):
def setUp(self):
self.server = None
self.port = 6778
self.server = server.Server(self.port)
def testConnect(self):
'''
validate that server-client connection is happening and ... |
"""Extract features from training images to hd5f db
Modified from:
https://gurus.pyimagesearch.com/topic/transfer-learning-example-dogs-and-cats/
"""
import os
import random
import cv2
import numpy as np
from tqdm import tqdm
from keras.applications import VGG16
from keras.applications import imagenet_utils
from s... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# If you are using a code grep query service and want to resolve
# certain global symbols to local directories,
# add them as REPOS below. We ... |
import ast
import shutil
import os
from pathlib import Path
import unittest
import tests.plugins
from obscurepy.obfuscator import Obfuscator
from obscurepy.handlers.classdef_handler import ClassDefHandler
class ObfuscatorTest(unittest.TestCase):
def setUp(self):
self.fixture = Obfuscator('tests/my_modul... |
# The MIT License (MIT)
#
# Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
#
# 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 ... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @author jsbxyyx
# @since 1.0
from seata.exception.ShouldNeverHappenException import ShouldNeverHappenException
from seata.rm.datasource.ColumnUtils import ColumnUtils
from seata.rm.datasource.undo.UndoExecutor import UndoExecutor
from seata.sqlparser.util.JdbcConstants im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.